





'''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

a        =						logging.get_logger(__name__)

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase      )						->					Dict:

   '''simple docstring'''







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

def 						__magic_name__       (							__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase      )						->					int:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE      							=       to_pil_image(__UpperCAmelCase      )
   __SCREAMING_SNAKE_CASE      							=       pil_image.size
   __SCREAMING_SNAKE_CASE      							=       pytesseract.image_to_data(__UpperCAmelCase							,	lang=__UpperCAmelCase							,	output_type="""dict"""							,	config=__UpperCAmelCase      )
   __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(__UpperCAmelCase      ) if not word.strip()]
   __SCREAMING_SNAKE_CASE      							=       [word for idx, word in enumerate(__UpperCAmelCase      ) if idx not in irrelevant_indices]
   __SCREAMING_SNAKE_CASE      							=       [coord for idx, coord in enumerate(__UpperCAmelCase      ) if idx not in irrelevant_indices]
   __SCREAMING_SNAKE_CASE      							=       [coord for idx, coord in enumerate(__UpperCAmelCase      ) if idx not in irrelevant_indices]
   __SCREAMING_SNAKE_CASE      							=       [coord for idx, coord in enumerate(__UpperCAmelCase      ) if idx not in irrelevant_indices]
   __SCREAMING_SNAKE_CASE      							=       [coord for idx, coord in enumerate(__UpperCAmelCase      ) 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(__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase							,	__UpperCAmelCase      ):
      __SCREAMING_SNAKE_CASE      							=       [x, y, x + w, y + h]
      actual_boxes.append(__UpperCAmelCase      )

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

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

   return words, normalized_boxes







class __a (   SCREAMING_SNAKE_CASE__			):
   __UpperCamelCase   : int	      =	['pixel_values']





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

      '''simple docstring'''

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

      __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				:			int				,lowerCamelCase				:			List[str]				,lowerCamelCase				:			Any				,lowerCamelCase				:			Optional[Any] = PILImageResampling.BILINEAR				,lowerCamelCase				:			str = None				,**lowerCamelCase				:			Dict				,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       get_size_dict(snake_case__    )
      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(snake_case__				,size=snake_case__				,resample=snake_case__				,data_format=snake_case__				,**snake_case__    )





   def      UpperCAmelCase__     (					self				:			Dict				,lowerCamelCase				:			Optional[int]				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			Optional[Any] = None				,**lowerCamelCase				:			Optional[int]				,):

      '''simple docstring'''

      return rescale(snake_case__				,scale=snake_case__				,data_format=snake_case__				,**snake_case__    )





   def      UpperCAmelCase__     (					self				:			Optional[Any]				,lowerCamelCase				:			Optional[Any]				,lowerCamelCase				:			Dict				,lowerCamelCase				:			Union[str, Any]				,lowerCamelCase				:			Dict = None				,**lowerCamelCase				:			Tuple				,):

      '''simple docstring'''

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





   def      UpperCAmelCase__     (					self				:			List[Any]				,lowerCamelCase				:			Any				,lowerCamelCase				:			str = None				,lowerCamelCase				:			Dict = None				,lowerCamelCase				:			Optional[Any]=None				,lowerCamelCase				:			List[Any] = None				,lowerCamelCase				:			Optional[int] = None				,lowerCamelCase				:			int = None				,lowerCamelCase				:			List[str] = None				,lowerCamelCase				:			Optional[int] = None				,lowerCamelCase				:			int = None				,lowerCamelCase				:			int = None				,lowerCamelCase				:			str = None				,lowerCamelCase				:			List[Any] = None				,lowerCamelCase				:			Optional[Any] = ChannelDimension.FIRST				,**lowerCamelCase				:			List[str]				,):

      '''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(snake_case__    )
      __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(snake_case__    )

      if not valid_images(snake_case__    ):
         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(snake_case__    ) 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(snake_case__				,snake_case__				,snake_case__    )
            words_batch.append(snake_case__    )
            boxes_batch.append(snake_case__    )

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

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

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

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

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

      if apply_ocr:
         __SCREAMING_SNAKE_CASE      							=       words_batch
         __SCREAMING_SNAKE_CASE      							=       boxes_batch
      return data












'''simple docstring'''

import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import ChineseCLIPImageProcessor







class __a (   unittest.TestCase			):





   def __init__(					self				:			List[Any]				,lowerCamelCase				:			List[Any]				,lowerCamelCase				:			List[str]=7				,lowerCamelCase				:			List[str]=3				,lowerCamelCase				:			List[str]=18				,lowerCamelCase				:			Any=30				,lowerCamelCase				:			Optional[Any]=400				,lowerCamelCase				:			Optional[Any]=True				,lowerCamelCase				:			Optional[Any]=None				,lowerCamelCase				:			Optional[int]=True				,lowerCamelCase				:			int=None				,lowerCamelCase				:			str=True				,lowerCamelCase				:			Dict=[0.48_145_466, 0.4_578_275, 0.40_821_073]				,lowerCamelCase				:			List[str]=[0.26_862_954, 0.26_130_258, 0.27_577_711]				,lowerCamelCase				:			Tuple=True				,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       size if size is not None else {"""height""": 224, """width""": 224}
      __SCREAMING_SNAKE_CASE      							=       crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
      __SCREAMING_SNAKE_CASE      							=       parent
      __SCREAMING_SNAKE_CASE      							=       batch_size
      __SCREAMING_SNAKE_CASE      							=       num_channels
      __SCREAMING_SNAKE_CASE      							=       image_size
      __SCREAMING_SNAKE_CASE      							=       min_resolution
      __SCREAMING_SNAKE_CASE      							=       max_resolution
      __SCREAMING_SNAKE_CASE      							=       do_resize
      __SCREAMING_SNAKE_CASE      							=       size
      __SCREAMING_SNAKE_CASE      							=       do_center_crop
      __SCREAMING_SNAKE_CASE      							=       crop_size
      __SCREAMING_SNAKE_CASE      							=       do_normalize
      __SCREAMING_SNAKE_CASE      							=       image_mean
      __SCREAMING_SNAKE_CASE      							=       image_std
      __SCREAMING_SNAKE_CASE      							=       do_convert_rgb





   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      return {
          "do_resize": self.do_resize,
          "size": self.size,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
          "do_normalize": self.do_normalize,
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_convert_rgb": self.do_convert_rgb,
      }





   def      UpperCAmelCase__     (					self				:			int				,lowerCamelCase				:			Union[str, Any]=False				,lowerCamelCase				:			str=False				,lowerCamelCase				:			str=False    ):

      '''simple docstring'''

      assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

      if equal_resolution:
         __SCREAMING_SNAKE_CASE      							=       []
         for i in range(self.batch_size    ):
            image_inputs.append(
                np.random.randint(
                    255				,size=(self.num_channels, self.max_resolution, self.max_resolution)				,dtype=np.uinta    )    )
      else:
         __SCREAMING_SNAKE_CASE      							=       []
         for i in range(self.batch_size    ):
            __SCREAMING_SNAKE_CASE							,     __SCREAMING_SNAKE_CASE      							=       np.random.choice(np.arange(self.min_resolution				,self.max_resolution    )				,2    )
            image_inputs.append(np.random.randint(255				,size=(self.num_channels, width, height)				,dtype=np.uinta    )    )

      if not numpify and not torchify:
         # PIL expects the channel dimension as last dimension
         __SCREAMING_SNAKE_CASE      							=       [Image.fromarray(np.moveaxis(lowerCamelCase				,0				,-1    )    ) for x in image_inputs]

      if torchify:
         __SCREAMING_SNAKE_CASE      							=       [torch.from_numpy(lowerCamelCase    ) for x in image_inputs]

      return image_inputs







@require_torch
@require_vision
class __a (   _snake_case,   unittest.TestCase			):
   __UpperCamelCase   : int	      =	ChineseCLIPImageProcessor if is_vision_available() else None





   def      UpperCAmelCase__     (					self				:			Any    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       ChineseCLIPImageProcessingTester(self				,do_center_crop=lowerCamelCase    )





   @property
   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      return self.image_processor_tester.prepare_image_processor_dict()





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class(**self.image_processor_dict    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_resize"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""size"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_center_crop"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""center_crop"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_normalize"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""image_mean"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""image_std"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_convert_rgb"""    )    )





   def      UpperCAmelCase__     (					self				:			List[Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class.from_dict(self.image_processor_dict    )
      self.assertEqual(image_processor.size				,{"""height""": 224, """width""": 224}    )
      self.assertEqual(image_processor.crop_size				,{"""height""": 18, """width""": 18}    )

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class.from_dict(self.image_processor_dict				,size=42				,crop_size=84    )
      self.assertEqual(image_processor.size				,{"""shortest_edge""": 42}    )
      self.assertEqual(image_processor.crop_size				,{"""height""": 84, """width""": 84}    )





   def      UpperCAmelCase__     (					self				:			Dict    ):

      '''simple docstring'''

      pass





   def      UpperCAmelCase__     (					self				:			List[str]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class(**self.image_processor_dict    )
      # create random PIL images
      __SCREAMING_SNAKE_CASE      							=       self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase    )
      for image in image_inputs:
         self.assertIsInstance(lowerCamelCase				,Image.Image    )

      # Test not batched input
      __SCREAMING_SNAKE_CASE      							=       image_processing(image_inputs[0]				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)

      # Test batched
      __SCREAMING_SNAKE_CASE      							=       image_processing(lowerCamelCase				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)





   def      UpperCAmelCase__     (					self				:			Optional[int]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class(**self.image_processor_dict    )
      # create random numpy tensors
      __SCREAMING_SNAKE_CASE      							=       self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase				,numpify=lowerCamelCase    )
      for image in image_inputs:
         self.assertIsInstance(lowerCamelCase				,np.ndarray    )

      # Test not batched input
      __SCREAMING_SNAKE_CASE      							=       image_processing(image_inputs[0]				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)

      # Test batched
      __SCREAMING_SNAKE_CASE      							=       image_processing(lowerCamelCase				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)





   def      UpperCAmelCase__     (					self				:			str    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class(**self.image_processor_dict    )
      # create random PyTorch tensors
      __SCREAMING_SNAKE_CASE      							=       self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase				,torchify=lowerCamelCase    )
      for image in image_inputs:
         self.assertIsInstance(lowerCamelCase				,torch.Tensor    )

      # Test not batched input
      __SCREAMING_SNAKE_CASE      							=       image_processing(image_inputs[0]				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)

      # Test batched
      __SCREAMING_SNAKE_CASE      							=       image_processing(lowerCamelCase				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)







@require_torch
@require_vision
class __a (   _snake_case,   unittest.TestCase			):
   __UpperCamelCase   : Optional[int]	      =	ChineseCLIPImageProcessor if is_vision_available() else None





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       ChineseCLIPImageProcessingTester(self				,num_channels=4				,do_center_crop=lowerCamelCase    )
      __SCREAMING_SNAKE_CASE      							=       3





   @property
   def      UpperCAmelCase__     (					self				:			Dict    ):

      '''simple docstring'''

      return self.image_processor_tester.prepare_image_processor_dict()





   def      UpperCAmelCase__     (					self				:			int    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class(**self.image_processor_dict    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_resize"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""size"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_center_crop"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""center_crop"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_normalize"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""image_mean"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""image_std"""    )    )
      self.assertTrue(hasattr(lowerCamelCase				,"""do_convert_rgb"""    )    )





   def      UpperCAmelCase__     (					self				:			Tuple    ):

      '''simple docstring'''

      pass





   def      UpperCAmelCase__     (					self				:			Union[str, Any]    ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE      							=       self.image_processing_class(**self.image_processor_dict    )
      # create random PIL images
      __SCREAMING_SNAKE_CASE      							=       self.image_processor_tester.prepare_inputs(equal_resolution=lowerCamelCase    )
      for image in image_inputs:
         self.assertIsInstance(lowerCamelCase				,Image.Image    )

      # Test not batched input
      __SCREAMING_SNAKE_CASE      							=       image_processing(image_inputs[0]				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              1,
              self.expected_encoded_image_num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)

      # Test batched
      __SCREAMING_SNAKE_CASE      							=       image_processing(lowerCamelCase				,return_tensors="""pt"""    ).pixel_values
      self.assertEqual(
          encoded_images.shape				,(
              self.image_processor_tester.batch_size,
              self.expected_encoded_image_num_channels,
              self.image_processor_tester.crop_size["""height"""],
              self.image_processor_tester.crop_size["""width"""],
          )				,)





