





"""simple docstring"""
import json
import os
import tempfile

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


if is_torch_available():
  import numpy as np
  import torch

if is_vision_available():
  from PIL import Image



def   __lowerCamelCase     (							a_  :	Union[str, Any]				,     a_  :	Dict=False				,     a_  :	int=False				,     a_  :	str=False							)    ->   Tuple:
      assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

      __SCREAMING_SNAKE_CASE     :Optional[int]	       =						[]
      for i in range(image_processor_tester.batch_size							):
            if equal_resolution:
                  __SCREAMING_SNAKE_CASE     :Optional[int]	       =						image_processor_tester.max_resolution
            else:
                  # To avoid getting image width/height 0
                  __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						image_processor_tester.min_resolution
                  if getattr(a_				,     '''size_divisor'''				,     a_							):
                        # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
                        __SCREAMING_SNAKE_CASE     :Optional[int]	       =						max(image_processor_tester.size_divisor				,     a_							)
                  __SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE     :List[Any]	       =						np.random.choice(np.arange(a_				,     image_processor_tester.max_resolution							)				,     2							)
            image_inputs.append(
                np.random.randint(2_55				,     size=(image_processor_tester.num_channels, width, height)				,     dtype=np.uinta							)							)

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

      if torchify:
            __SCREAMING_SNAKE_CASE     :Tuple	       =						[torch.from_numpy(a_							) for image in image_inputs]

      return image_inputs



def   __lowerCamelCase     (							a_  :	Tuple				,     a_  :	Dict=10				,     a_  :	str=10				,     a_  :	Optional[int]=False				,     a_  :	Optional[int]=False							)    ->   Dict:
      __SCREAMING_SNAKE_CASE     :Tuple	       =						[]
      for i in range(image_processor_tester.num_frames							):
            video.append(np.random.randint(2_55				,     size=(image_processor_tester.num_channels, width, height)				,     dtype=np.uinta							)							)

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

      if torchify:
            __SCREAMING_SNAKE_CASE     :int	       =						[torch.from_numpy(a_							) for frame in video]

      return video



def   __lowerCamelCase     (							a_  :	Optional[Any]				,     a_  :	Dict=False				,     a_  :	int=False				,     a_  :	List[str]=False							)    ->   Any:
      assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

      __SCREAMING_SNAKE_CASE     :List[str]	       =						[]
      for i in range(image_processor_tester.batch_size							):
            if equal_resolution:
                  __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						image_processor_tester.max_resolution
            else:
                  __SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE     :Optional[int]	       =						np.random.choice(
                      np.arange(image_processor_tester.min_resolution				,     image_processor_tester.max_resolution							)				,     2							)
                  __SCREAMING_SNAKE_CASE     :Tuple	       =						prepare_video(
                      image_processor_tester=a_				,     width=a_				,     height=a_				,     numpify=a_				,     torchify=a_				,     )
            video_inputs.append(a_							)

      return video_inputs







class       _SCREAMING_SNAKE_CASE:
       SCREAMING_SNAKE_CASE_     :   Dict					=						None




       def 					_UpperCamelCase  (		self							)    ->   Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						self.image_processing_class(**self.image_processor_dict							)
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						json.loads(image_processor.to_json_string()							)
             for key, value in self.image_processor_dict.items():
                   self.assertEqual(obj[key]	,SCREAMING_SNAKE_CASE__							)




       def 					_UpperCamelCase  (		self							)    ->   List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :str	       =						self.image_processing_class(**self.image_processor_dict							)

             with tempfile.TemporaryDirectory() as tmpdirname:
                   __SCREAMING_SNAKE_CASE     :List[str]	       =						os.path.join(SCREAMING_SNAKE_CASE__	,'''image_processor.json'''							)
                   image_processor_first.to_json_file(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE     :List[str]	       =						self.image_processing_class.from_json_file(SCREAMING_SNAKE_CASE__							)

             self.assertEqual(image_processor_second.to_dict()	,image_processor_first.to_dict()							)




       def 					_UpperCamelCase  (		self							)    ->   Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Any	       =						self.image_processing_class(**self.image_processor_dict							)

             with tempfile.TemporaryDirectory() as tmpdirname:
                   __SCREAMING_SNAKE_CASE     :str	       =						image_processor_first.save_pretrained(SCREAMING_SNAKE_CASE__							)[0]
                   check_json_file_has_correct_format(SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						self.image_processing_class.from_pretrained(SCREAMING_SNAKE_CASE__							)

             self.assertEqual(image_processor_second.to_dict()	,image_processor_first.to_dict()							)




       def 					_UpperCamelCase  (		self							)    ->   Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Dict	       =						self.image_processing_class()
             self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)




       @require_torch
       @require_vision
       def 					_UpperCamelCase  (		self							)    ->   Dict:





             """simple docstring"""






             if self.test_cast_dtype is not None:
                   # Initialize image_processor
                   __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						self.image_processing_class(**self.image_processor_dict							)

                   # create random PyTorch tensors
                   __SCREAMING_SNAKE_CASE     :List[Any]	       =						prepare_image_inputs(self.image_processor_tester	,equal_resolution=SCREAMING_SNAKE_CASE__	,torchify=SCREAMING_SNAKE_CASE__							)

                   __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						image_processor(SCREAMING_SNAKE_CASE__	,return_tensors='''pt'''							)
                   # for layoutLM compatiblity
                   self.assertEqual(encoding.pixel_values.device	,torch.device('''cpu'''							)							)
                   self.assertEqual(encoding.pixel_values.dtype	,torch.floataa							)

                   __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						image_processor(SCREAMING_SNAKE_CASE__	,return_tensors='''pt'''							).to(torch.floataa							)
                   self.assertEqual(encoding.pixel_values.device	,torch.device('''cpu'''							)							)
                   self.assertEqual(encoding.pixel_values.dtype	,torch.floataa							)

                   __SCREAMING_SNAKE_CASE     :str	       =						image_processor(SCREAMING_SNAKE_CASE__	,return_tensors='''pt'''							).to('''cpu'''	,torch.bfloataa							)
                   self.assertEqual(encoding.pixel_values.device	,torch.device('''cpu'''							)							)
                   self.assertEqual(encoding.pixel_values.dtype	,torch.bfloataa							)

                   with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                         __SCREAMING_SNAKE_CASE     :Optional[int]	       =						image_processor(SCREAMING_SNAKE_CASE__	,return_tensors='''pt'''							).to(torch.bfloataa	,'''cpu'''							)

                   # Try with text + image feature
                   __SCREAMING_SNAKE_CASE     :Tuple	       =						image_processor(SCREAMING_SNAKE_CASE__	,return_tensors='''pt'''							)
                   encoding.update({'''input_ids''': torch.LongTensor([[1, 2, 3], [4, 5, 6]]							)}							)
                   __SCREAMING_SNAKE_CASE     :List[Any]	       =						encoding.to(torch.floataa							)

                   self.assertEqual(encoding.pixel_values.device	,torch.device('''cpu'''							)							)
                   self.assertEqual(encoding.pixel_values.dtype	,torch.floataa							)
                   self.assertEqual(encoding.input_ids.dtype	,torch.long							)






"""simple docstring"""
# Lint as: python3

import hashlib
from typing import Union



def   __lowerCamelCase     (							a_  :	Union[str, int, bytes]							)    ->   bytes:
      if isinstance(a_				,     a_							):
            # Data already in bytes, returns as it as
            return hash_data
      elif isinstance(a_				,     a_							):
            # We keep the data as it as for it ot be later encoded to UTF-8
            # However replace `\\` with `/` for Windows compatibility
            __SCREAMING_SNAKE_CASE     :str	       =						hash_data.replace('''\\'''				,     '''/'''							)
      elif isinstance(a_				,     a_							):
            __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						str(a_							)
      else:
            # If data is not of the required type, raise error
            raise InvalidKeyError(a_							)

      return hash_data.encode('''utf-8'''							)






class       _SCREAMING_SNAKE_CASE(     A						):




       def __init__(		self	,SCREAMING_SNAKE_CASE__							)    ->   Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Tuple	       =						'''\nFAILURE TO GENERATE DATASET: Invalid key type detected'''
             __SCREAMING_SNAKE_CASE     :int	       =						f'''\nFound Key {hash_data} of type {type(SCREAMING_SNAKE_CASE__							)}'''
             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						'''\nKeys should be either str, int or bytes type'''
             super().__init__(f'''{self.prefix}{self.err_msg}{self.suffix}'''							)






class       _SCREAMING_SNAKE_CASE(     A						):




       def __init__(		self	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__	,SCREAMING_SNAKE_CASE__=""							)    ->   List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :str	       =						key
             __SCREAMING_SNAKE_CASE     :str	       =						duplicate_key_indices
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						fix_msg
             __SCREAMING_SNAKE_CASE     :int	       =						'''Found multiple examples generated with the same key'''
             if len(SCREAMING_SNAKE_CASE__							) <= 20:
                   __SCREAMING_SNAKE_CASE     :Dict	       =						f'''\nThe examples at index {", ".join(SCREAMING_SNAKE_CASE__							)} have the key {key}'''
             else:
                   __SCREAMING_SNAKE_CASE     :List[str]	       =						f'''\nThe examples at index {", ".join(duplicate_key_indices[:20]							)}... ({len(SCREAMING_SNAKE_CASE__							) - 20} more) have the key {key}'''
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						'''\n''' + fix_msg if fix_msg else ''''''
             super().__init__(f'''{self.prefix}{self.err_msg}{self.suffix}'''							)






class       _SCREAMING_SNAKE_CASE:




       def __init__(		self	,SCREAMING_SNAKE_CASE__							)    ->   Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Dict	       =						hashlib.mda(_as_bytes(SCREAMING_SNAKE_CASE__							)							)




       def 					_UpperCamelCase  (		self	,SCREAMING_SNAKE_CASE__							)    ->   int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Tuple	       =						self._split_mda.copy()
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						_as_bytes(SCREAMING_SNAKE_CASE__							)
             mda.update(SCREAMING_SNAKE_CASE__							)
             # Convert to integer with hexadecimal conversion
             return int(mda.hexdigest()	,16							)