

'''simple docstring'''



from typing import Dict, Iterable, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends


if is_vision_available():
  import PIL

# soft dependency
if is_pytesseract_available():
  import pytesseract

UpperCAmelCase					:			List[str]       =	logging.get_logger(__name__)







def   a__			(    a__ ,       a__ ,       a__		):




     """simple docstring"""


     return [
         int(10_00 * (box[0] / width)		),
         int(10_00 * (box[1] / height)		),
         int(10_00 * (box[2] / width)		),
         int(10_00 * (box[3] / height)		),
     ]







def   a__			(    a__ ,       a__ ,       a__		):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE      = to_pil_image(_SCREAMING_SNAKE_CASE		)
     __SCREAMING_SNAKE_CASE      = pil_image.size
     __SCREAMING_SNAKE_CASE      = pytesseract.image_to_data(_SCREAMING_SNAKE_CASE ,       lang=_SCREAMING_SNAKE_CASE ,       output_type="""dict""" ,       config=_SCREAMING_SNAKE_CASE		)
     __SCREAMING_SNAKE_CASE      = data['text'], data['left'], data['top'], data['width'], data['height']

     # filter empty words and corresponding coordinates
     __SCREAMING_SNAKE_CASE      = [idx for idx, word in enumerate(_SCREAMING_SNAKE_CASE		) if not word.strip()]
     __SCREAMING_SNAKE_CASE      = [word for idx, word in enumerate(_SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __SCREAMING_SNAKE_CASE      = [coord for idx, coord in enumerate(_SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __SCREAMING_SNAKE_CASE      = [coord for idx, coord in enumerate(_SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __SCREAMING_SNAKE_CASE      = [coord for idx, coord in enumerate(_SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]
     __SCREAMING_SNAKE_CASE      = [coord for idx, coord in enumerate(_SCREAMING_SNAKE_CASE		) if idx not in irrelevant_indices]

     # turn coordinates into (left, top, left+width, top+height) format
     __SCREAMING_SNAKE_CASE      = []
     for x, y, w, h in zip(_SCREAMING_SNAKE_CASE ,       _SCREAMING_SNAKE_CASE ,       _SCREAMING_SNAKE_CASE ,       _SCREAMING_SNAKE_CASE		):
          __SCREAMING_SNAKE_CASE      = [x, y, x + w, y + h]
          actual_boxes.append(_SCREAMING_SNAKE_CASE		)

     # finally, normalize the bounding boxes
     __SCREAMING_SNAKE_CASE      = []
     for box in actual_boxes:
          normalized_boxes.append(normalize_box(_SCREAMING_SNAKE_CASE ,       _SCREAMING_SNAKE_CASE ,       _SCREAMING_SNAKE_CASE		)		)

     assert len(_SCREAMING_SNAKE_CASE		) == len(_SCREAMING_SNAKE_CASE		), "Not as many words as there are bounding boxes"

     return words, normalized_boxes







class 		lowerCAmelCase__  ( a   ):



 """simple docstring"""



 lowerCAmelCase__       = ["""pixel_values"""]
 def __init__(						self   :			Tuple   ,				__SCREAMING_SNAKE_CASE   :			Dict = True   ,				__SCREAMING_SNAKE_CASE   :			int = None   ,				__SCREAMING_SNAKE_CASE   :			Any = PILImageResampling.BILINEAR   ,				__SCREAMING_SNAKE_CASE   :			str = True   ,				__SCREAMING_SNAKE_CASE   :			Optional[Any] = 1 / 255   ,				__SCREAMING_SNAKE_CASE   :			str = True   ,				__SCREAMING_SNAKE_CASE   :			Any = None   ,				__SCREAMING_SNAKE_CASE   :			Dict = None   ,				__SCREAMING_SNAKE_CASE   :			int = True   ,				__SCREAMING_SNAKE_CASE   :			List[Any] = None   ,				__SCREAMING_SNAKE_CASE   :			Tuple = ""   ,				**__SCREAMING_SNAKE_CASE   :			Optional[Any]   ,				)    ->					Any:


      """simple docstring"""




      super().__init__(**__UpperCAmelCase     )
      __SCREAMING_SNAKE_CASE      = size if size is not None else {'height': 224, 'width': 224}
      __SCREAMING_SNAKE_CASE      = get_size_dict(__UpperCAmelCase     )

      __SCREAMING_SNAKE_CASE      = do_resize
      __SCREAMING_SNAKE_CASE      = size
      __SCREAMING_SNAKE_CASE      = resample
      __SCREAMING_SNAKE_CASE      = do_rescale
      __SCREAMING_SNAKE_CASE      = rescale_value
      __SCREAMING_SNAKE_CASE      = do_normalize
      __SCREAMING_SNAKE_CASE      = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
      __SCREAMING_SNAKE_CASE      = image_std if image_std is not None else IMAGENET_STANDARD_STD
      __SCREAMING_SNAKE_CASE      = apply_ocr
      __SCREAMING_SNAKE_CASE      = ocr_lang
      __SCREAMING_SNAKE_CASE      = tesseract_config
 def  UpperCAmelCase__						(						self   :			str   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any]   ,				__SCREAMING_SNAKE_CASE   :			str   ,				__SCREAMING_SNAKE_CASE   :			List[str] = PILImageResampling.BILINEAR   ,				__SCREAMING_SNAKE_CASE   :			Tuple = None   ,				**__SCREAMING_SNAKE_CASE   :			int   ,				)    ->					List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = get_size_dict(__UpperCAmelCase     )
      if "height" not in size or "width" not in size:
           raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'     )
      __SCREAMING_SNAKE_CASE      = (size['height'], size['width'])
      return resize(__UpperCAmelCase   ,				size=__UpperCAmelCase   ,				resample=__UpperCAmelCase   ,				data_format=__UpperCAmelCase   ,				**__UpperCAmelCase     )
 def  UpperCAmelCase__						(						self   :			Union[str, Any]   ,				__SCREAMING_SNAKE_CASE   :			List[str]   ,				__SCREAMING_SNAKE_CASE   :			Tuple   ,				__SCREAMING_SNAKE_CASE   :			Tuple = None   ,				**__SCREAMING_SNAKE_CASE   :			int   ,				)    ->					int:


      """simple docstring"""




      return rescale(__UpperCAmelCase   ,				scale=__UpperCAmelCase   ,				data_format=__UpperCAmelCase   ,				**__UpperCAmelCase     )
 def  UpperCAmelCase__						(						self   :			Dict   ,				__SCREAMING_SNAKE_CASE   :			List[Any]   ,				__SCREAMING_SNAKE_CASE   :			Any   ,				__SCREAMING_SNAKE_CASE   :			List[str]   ,				__SCREAMING_SNAKE_CASE   :			int = None   ,				**__SCREAMING_SNAKE_CASE   :			Any   ,				)    ->					Dict:


      """simple docstring"""




      return normalize(__UpperCAmelCase   ,				mean=__UpperCAmelCase   ,				std=__UpperCAmelCase   ,				data_format=__UpperCAmelCase   ,				**__UpperCAmelCase     )


 def  UpperCAmelCase__						(						self   :			Any   ,				__SCREAMING_SNAKE_CASE   :			List[str]   ,				__SCREAMING_SNAKE_CASE   :			Optional[int] = None   ,				__SCREAMING_SNAKE_CASE   :			Optional[int] = None   ,				__SCREAMING_SNAKE_CASE   :			List[Any]=None   ,				__SCREAMING_SNAKE_CASE   :			Optional[Any] = None   ,				__SCREAMING_SNAKE_CASE   :			List[Any] = None   ,				__SCREAMING_SNAKE_CASE   :			Optional[Any] = None   ,				__SCREAMING_SNAKE_CASE   :			Tuple = None   ,				__SCREAMING_SNAKE_CASE   :			Tuple = None   ,				__SCREAMING_SNAKE_CASE   :			Tuple = None   ,				__SCREAMING_SNAKE_CASE   :			Any = None   ,				__SCREAMING_SNAKE_CASE   :			str = None   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any] = None   ,				__SCREAMING_SNAKE_CASE   :			Optional[int] = ChannelDimension.FIRST   ,				**__SCREAMING_SNAKE_CASE   :			str   ,				)    ->					Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = do_resize if do_resize is not None else self.do_resize
      __SCREAMING_SNAKE_CASE      = size if size is not None else self.size
      __SCREAMING_SNAKE_CASE      = get_size_dict(__UpperCAmelCase     )
      __SCREAMING_SNAKE_CASE      = resample if resample is not None else self.resample
      __SCREAMING_SNAKE_CASE      = do_rescale if do_rescale is not None else self.do_rescale
      __SCREAMING_SNAKE_CASE      = rescale_factor if rescale_factor is not None else self.rescale_factor
      __SCREAMING_SNAKE_CASE      = do_normalize if do_normalize is not None else self.do_normalize
      __SCREAMING_SNAKE_CASE      = image_mean if image_mean is not None else self.image_mean
      __SCREAMING_SNAKE_CASE      = image_std if image_std is not None else self.image_std
      __SCREAMING_SNAKE_CASE      = apply_ocr if apply_ocr is not None else self.apply_ocr
      __SCREAMING_SNAKE_CASE      = ocr_lang if ocr_lang is not None else self.ocr_lang
      __SCREAMING_SNAKE_CASE      = tesseract_config if tesseract_config is not None else self.tesseract_config

      __SCREAMING_SNAKE_CASE      = make_list_of_images(__UpperCAmelCase     )

      if not valid_images(__UpperCAmelCase     ):
           raise ValueError(
               """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
               """torch.Tensor, tf.Tensor or jax.ndarray."""     )

      if do_resize and size is None:
           raise ValueError("""Size must be specified if do_resize is True."""     )

      if do_rescale and rescale_factor is None:
           raise ValueError("""Rescale factor must be specified if do_rescale is True."""     )

      if do_normalize and (image_mean is None or image_std is None):
           raise ValueError("""If do_normalize is True, image_mean and image_std must be specified."""     )

      # All transformations expect numpy arrays.
      __SCREAMING_SNAKE_CASE      = [to_numpy_array(__UpperCAmelCase     ) for image in images]

      # Tesseract OCR to get words + normalized bounding boxes
      if apply_ocr:
           requires_backends(self   ,				"""pytesseract"""     )
           __SCREAMING_SNAKE_CASE      = []
           __SCREAMING_SNAKE_CASE      = []
           for image in images:
                __SCREAMING_SNAKE_CASE      = apply_tesseract(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase     )
                words_batch.append(__UpperCAmelCase     )
                boxes_batch.append(__UpperCAmelCase     )

      if do_resize:
           __SCREAMING_SNAKE_CASE      = [self.resize(image=__UpperCAmelCase   ,				size=__UpperCAmelCase   ,				resample=__UpperCAmelCase     ) for image in images]

      if do_rescale:
           __SCREAMING_SNAKE_CASE      = [self.rescale(image=__UpperCAmelCase   ,				scale=__UpperCAmelCase     ) for image in images]

      if do_normalize:
           __SCREAMING_SNAKE_CASE      = [self.normalize(image=__UpperCAmelCase   ,				mean=__UpperCAmelCase   ,				std=__UpperCAmelCase     ) for image in images]

      __SCREAMING_SNAKE_CASE      = [to_channel_dimension_format(__UpperCAmelCase   ,				__UpperCAmelCase     ) for image in images]

      __SCREAMING_SNAKE_CASE      = BatchFeature(data={"""pixel_values""": images}   ,				tensor_type=__UpperCAmelCase     )

      if apply_ocr:
           __SCREAMING_SNAKE_CASE      = words_batch
           __SCREAMING_SNAKE_CASE      = boxes_batch
      return data













"""simple docstring"""





# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__A											=						{
    """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""],
    """processing_mgp_str""": ["""MgpstrProcessor"""],
    """tokenization_mgp_str""": ["""MgpstrTokenizer"""],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __A											=						[
      """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """MgpstrModel""",
      """MgpstrPreTrainedModel""",
      """MgpstrForSceneTextRecognition""",
  ]

if TYPE_CHECKING:
  from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
  from .processing_mgp_str import MgpstrProcessor
  from .tokenization_mgp_str import MgpstrTokenizer

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_mgp_str import (
        MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
        MgpstrForSceneTextRecognition,
        MgpstrModel,
        MgpstrPreTrainedModel,
    )
else:
  import sys

  __A											=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
