




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        lowerCamelCase_							(      unittest.TestCase					):


 '''simple docstring'''







 def __init__(							self  :		List[Any]				,				_lowerCAmelCase  :		Dict				,				_lowerCAmelCase  :		Any=7				,				_lowerCAmelCase  :		Union[str, Any]=3				,				_lowerCAmelCase  :		Optional[int]=18				,				_lowerCAmelCase  :		int=30				,				_lowerCAmelCase  :		List[str]=400				,				_lowerCAmelCase  :		Optional[Any]=True				,				_lowerCAmelCase  :		Optional[Any]=None				,				_lowerCAmelCase  :		int=True				,				_lowerCAmelCase  :		str=None				,				_lowerCAmelCase  :		Optional[Any]=True				,				_lowerCAmelCase  :		Dict=[0.4814_5466, 0.457_8275, 0.4082_1073]				,				_lowerCAmelCase  :		str=[0.2686_2954, 0.2613_0258, 0.2757_7711]				,				_lowerCAmelCase  :		int=True				,				):
       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       lowerCAmelCase_  (							self  :		Union[str, Any]						):
       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       lowerCAmelCase_  (							self  :		Union[str, Any]				,				_lowerCAmelCase  :		Optional[Any]=False				,				_lowerCAmelCase  :		Any=False				,				_lowerCAmelCase  :		Optional[Any]=False						):
       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        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE       ,   unittest.TestCase					):


 '''simple docstring'''







 lowercase_				    =    ChineseCLIPImageProcessor if is_vision_available() else None



 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_							=			ChineseCLIPImageProcessingTester(self				,				do_center_crop=_lowerCAmelCase						)



 @property
 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       return self.image_processor_tester.prepare_image_processor_dict()



 def       lowerCAmelCase_  (							self  :		List[Any]						):
       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       lowerCAmelCase_  (							self  :		str						):
       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       lowerCAmelCase_  (							self  :		str						):
       pass



 def       lowerCAmelCase_  (							self  :		List[str]						):
       # Initialize image_processing
       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       lowerCAmelCase_  (							self  :		str						):
       # Initialize image_processing
       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       lowerCAmelCase_  (							self  :		int						):
       # Initialize image_processing
       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        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE       ,   unittest.TestCase					):


 '''simple docstring'''







 lowercase_				    =    ChineseCLIPImageProcessor if is_vision_available() else None



 def       lowerCAmelCase_  (							self  :		str						):
       SCREAMING_SNAKE_CASE_							=			ChineseCLIPImageProcessingTester(self				,				num_channels=4				,				do_center_crop=_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			3



 @property
 def       lowerCAmelCase_  (							self  :		List[str]						):
       return self.image_processor_tester.prepare_image_processor_dict()



 def       lowerCAmelCase_  (							self  :		Any						):
       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       lowerCAmelCase_  (							self  :		List[Any]						):
       pass




 def       lowerCAmelCase_  (							self  :		List[str]						):
       # Initialize image_processing
       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'],
           )				,				)





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]