




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
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_vision_available, logging


if is_vision_available():
   import PIL


lowerCamelCase__ :   List[Any]					=							logging.get_logger(__name__)





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    ["pixel_values"]



 def __init__(							self  :		Union[str, Any]				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Dict[str, int] = None				,				_lowerCAmelCase  :		float = None				,				_lowerCAmelCase  :		PILImageResampling = PILImageResampling.BILINEAR				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Union[int, float] = 1 / 255				,				_lowerCAmelCase  :		bool = True				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				**_lowerCAmelCase  :		List[str]				,				):
       super().__init__(**_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			size if size is not None else {'shortest_edge': 384}
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			do_resize
       SCREAMING_SNAKE_CASE_							=			size
       # Default value set here for backwards compatibility where the value in config is None
       SCREAMING_SNAKE_CASE_							=			crop_pct if crop_pct is not None else 224 / 256
       SCREAMING_SNAKE_CASE_							=			resample
       SCREAMING_SNAKE_CASE_							=			do_rescale
       SCREAMING_SNAKE_CASE_							=			rescale_factor
       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



 def       lowerCAmelCase_  (							self  :		List[str]				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		Dict[str, int]				,				_lowerCAmelCase  :		float				,				_lowerCAmelCase  :		PILImageResampling = PILImageResampling.BICUBIC				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		Optional[Any]				,				):
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)
       if "shortest_edge" not in size:
             raise ValueError(F"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}"						)
       SCREAMING_SNAKE_CASE_							=			size['shortest_edge']

       if shortest_edge < 384:
             # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
             SCREAMING_SNAKE_CASE_							=			int(shortest_edge / crop_pct						)
             SCREAMING_SNAKE_CASE_							=			get_resize_output_image_size(_lowerCAmelCase				,				size=_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			resize(image=_lowerCAmelCase				,				size=_lowerCAmelCase				,				resample=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)
             # then crop to (shortest_edge, shortest_edge)
             return center_crop(image=_lowerCAmelCase				,				size=(shortest_edge, shortest_edge)				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)
       else:
             # warping (no cropping) when evaluated at 384 or larger
             return resize(
                 _lowerCAmelCase				,				size=(shortest_edge, shortest_edge)				,				resample=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Union[str, Any]				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		Union[int, float]				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		Any				,				):
       return rescale(_lowerCAmelCase				,				scale=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Any				,				_lowerCAmelCase  :		np.ndarray				,				_lowerCAmelCase  :		Union[float, List[float]]				,				_lowerCAmelCase  :		Union[float, List[float]]				,				_lowerCAmelCase  :		Optional[Union[str, ChannelDimension]] = None				,				**_lowerCAmelCase  :		Tuple				,				):
       return normalize(_lowerCAmelCase				,				mean=_lowerCAmelCase				,				std=_lowerCAmelCase				,				data_format=_lowerCAmelCase				,				**_lowerCAmelCase						)




 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		ImageInput				,				_lowerCAmelCase  :		bool = None				,				_lowerCAmelCase  :		Dict[str, int] = None				,				_lowerCAmelCase  :		float = None				,				_lowerCAmelCase  :		PILImageResampling = None				,				_lowerCAmelCase  :		bool = None				,				_lowerCAmelCase  :		float = None				,				_lowerCAmelCase  :		bool = None				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				_lowerCAmelCase  :		Optional[Union[float, List[float]]] = None				,				_lowerCAmelCase  :		Optional[Union[str, TensorType]] = None				,				_lowerCAmelCase  :		ChannelDimension = ChannelDimension.FIRST				,				**_lowerCAmelCase  :		List[str]				,				):
       SCREAMING_SNAKE_CASE_							=			do_resize if do_resize is not None else self.do_resize
       SCREAMING_SNAKE_CASE_							=			crop_pct if crop_pct is not None else self.crop_pct
       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_							=			size if size is not None else self.size
       SCREAMING_SNAKE_CASE_							=			get_size_dict(_lowerCAmelCase				,				default_to_square=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			make_list_of_images(_lowerCAmelCase						)

       if not valid_images(_lowerCAmelCase						):
             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 or resample is None:
             raise ValueError('Size and resample must be specified if do_resize is True.'						)

       if do_resize and size["shortest_edge"] < 384 and crop_pct is None:
             raise ValueError('crop_pct must be specified if size < 384.'						)

       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('Image mean and std must be specified if do_normalize is True.'						)

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

       if do_resize:
             SCREAMING_SNAKE_CASE_							=			[self.resize(image=_lowerCAmelCase				,				size=_lowerCAmelCase				,				crop_pct=_lowerCAmelCase				,				resample=_lowerCAmelCase						) for image in images]

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

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

       SCREAMING_SNAKE_CASE_							=			[to_channel_dimension_format(_lowerCAmelCase				,				_lowerCAmelCase						) for image in images]

       SCREAMING_SNAKE_CASE_							=			{'pixel_values': images}
       return BatchFeature(data=_lowerCAmelCase				,				tensor_type=_lowerCAmelCase						)





import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class        lowerCamelCase_							(      unittest.TestCase					):


 '''simple docstring'''







 def       lowerCAmelCase_  (							self  :		Any						):
       SCREAMING_SNAKE_CASE_							=			0



 def       lowerCAmelCase_  (							self  :		int						):
       SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32'						)
       self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Optional[int]						):
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
             json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
             self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		str						):
       # Ensure we can load the image processor from the feature extractor config
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
             json.dump(
                 {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
             json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
             self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Union[str, Any]						):
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			CLIPConfig()

             # Create a dummy config file with image_proceesor_type
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
             json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

             # remove image_processor_type to make sure config.json alone is enough to load image processor locally
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						).to_dict()

             config_dict.pop('image_processor_type'						)
             SCREAMING_SNAKE_CASE_							=			CLIPImageProcessor(**_lowerCAmelCase						)

             # save in new folder
             model_config.save_pretrained(_lowerCAmelCase						)
             config.save_pretrained(_lowerCAmelCase						)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)

             # make sure private variable is not incorrectly saved
             SCREAMING_SNAKE_CASE_							=			json.loads(config.to_json_string()						)
             self.assertTrue('_processor_class' not in dict_as_saved						)

       self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		str						):
       with tempfile.TemporaryDirectory() as tmpdirname:
             SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)

             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
             self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		List[Any]						):
       with self.assertRaisesRegex(
           _lowerCAmelCase				,				'clip-base is not a local folder and is not a valid model identifier'						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('clip-base'						)



 def       lowerCAmelCase_  (							self  :		List[Any]						):
       with self.assertRaisesRegex(
           _lowerCAmelCase				,				R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase				,				revision='aaaaaa'						)



 def       lowerCAmelCase_  (							self  :		str						):
       with self.assertRaisesRegex(
           _lowerCAmelCase				,				'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'				,				):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('hf-internal-testing/config-no-model'						)



 def       lowerCAmelCase_  (							self  :		Tuple						):
       # If remote code is not set, we will time out when asking whether to load the model.
       with self.assertRaises(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor'						)
       # If remote code is disabled, we can't load this config.
       with self.assertRaises(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
           'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)
       self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)

       # Test image processor can be reloaded.
       with tempfile.TemporaryDirectory() as tmp_dir:
             image_processor.save_pretrained(_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase				,				trust_remote_code=_lowerCAmelCase						)
       self.assertEqual(reloaded_image_processor.__class__.__name__				,				'NewImageProcessor'						)



 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       try:
             AutoConfig.register('custom'				,				_lowerCAmelCase						)
             AutoImageProcessor.register(_lowerCAmelCase				,				_lowerCAmelCase						)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(_lowerCAmelCase						):
                   AutoImageProcessor.register(_lowerCAmelCase				,				_lowerCAmelCase						)

             with tempfile.TemporaryDirectory() as tmpdirname:
                   SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'preprocessor_config.json'
                   SCREAMING_SNAKE_CASE_							=			Path(_lowerCAmelCase						) / 'config.json'
                   json.dump(
                       {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'}				,				open(_lowerCAmelCase				,				'w'						)				,				)
                   json.dump({'model_type': 'clip'}				,				open(_lowerCAmelCase				,				'w'						)						)

                   SCREAMING_SNAKE_CASE_							=			CustomImageProcessor.from_pretrained(_lowerCAmelCase						)

             # Now that the config is registered, it can be used as any other config with the auto-API
             with tempfile.TemporaryDirectory() as tmp_dir:
                   image_processor.save_pretrained(_lowerCAmelCase						)
                   SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(_lowerCAmelCase						)
                   self.assertIsInstance(_lowerCAmelCase				,				_lowerCAmelCase						)

       finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                   del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                   del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]




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





       class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


        '''simple docstring'''







        lowercase_				    =    True

       try:
             AutoConfig.register('custom'				,				_lowerCAmelCase						)
             AutoImageProcessor.register(_lowerCAmelCase				,				_lowerCAmelCase						)
             # If remote code is not set, the default is to use local
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor'						)
             self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)
             self.assertTrue(image_processor.is_local						)

             # If remote code is disabled, we load the local one.
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)
             self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)
             self.assertTrue(image_processor.is_local						)

             # If remote is enabled, we load from the Hub
             SCREAMING_SNAKE_CASE_							=			AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor'				,				trust_remote_code=_lowerCAmelCase						)
             self.assertEqual(image_processor.__class__.__name__				,				'NewImageProcessor'						)
             self.assertTrue(not hasattr(_lowerCAmelCase				,				'is_local'						)						)

       finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                   del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                   del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]