def crop_str_to_vr_type()

in pathology/transformation_pipeline/ingestion_lib/dicom_gen/dicom_schema_util.py [0:0]


  def crop_str_to_vr_type(self, val: Any) -> Any:
    """Crops string values to VR type max character count definitions.

    Args:
      val: value to crop

    Returns:
      Value either unchangned or cropped.
    Raises:
     DICOMSchemaTagError: Length of tag value violates DICOM Standard VR code
       requirements.
    """
    if not isinstance(
        val, str
    ) or not dicom_standard.dicom_standard_util().is_vr_str_type(self.vr):
      return val
    length_validation = ingest_flags.METADATA_TAG_LENGTH_VALIDATION_FLG.value
    if length_validation == ingest_flags.MetadataTagLengthValidation.NONE:
      return val
    max_str_len = [
        dicom_standard.dicom_standard_util().get_vr_max_chars(self.vr)
    ]
    max_bytes = dicom_standard.dicom_standard_util().get_vr_max_bytes(self.vr)
    if max_bytes > 0:
      max_str_len.append(SchemaDICOMTag._get_byte_char_count(val, max_bytes))
    max_str_len = max(max_str_len)
    # VR Codes: 'OB', 'OV', 'OL', 'OW' do not have defined lengths and return -1
    if max_str_len < 0 or len(val) <= max_str_len:
      return val
    if (
        length_validation
        == ingest_flags.MetadataTagLengthValidation.LOG_WARNING
    ):
      cloud_logging_client.warning(
          'DICOM tag value exceeds DICOM Standard length limits for tag VR'
          ' type.',
          {'tag_value': val, 'tag': str(self)},
      )
      return val
    elif (
        length_validation
        == ingest_flags.MetadataTagLengthValidation.LOG_WARNING_AND_CLIP
    ):
      cropped_val = val[:max_str_len]
      cloud_logging_client.warning(
          'DICOM tag value cropped; value exceeds DICOM Standard length limits'
          ' for tag VR type.',
          {
              'uncropped_tag_value': val,
              'cropped_tag_value': cropped_val,
              'tag': str(self),
          },
      )
      return cropped_val
    msg = (
        'DICOM tag value exceeds DICOM Standard length limits for tag VR type.'
    )
    cloud_logging_client.error(
        msg,
        {'tag_value': val, 'tag': str(self)},
    )
    raise DICOMSchemaTagError(self, msg)