




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					):
							def __init__(		self		:Any						, __magic_name__		:Optional[int]						, __magic_name__		:Optional[Any]=7						, __magic_name__		:str=3						, __magic_name__		:Optional[int]=18						, __magic_name__		:str=30						, __magic_name__		:List[Any]=400						, __magic_name__		:Any=True						, __magic_name__		:Dict=None						, __magic_name__		:Any=True						, __magic_name__		:Dict=None						, __magic_name__		:List[Any]=True						, __magic_name__		:Optional[int]=[0.48145466, 0.4578275, 0.40821073]						, __magic_name__		:Any=[0.26862954, 0.26130258, 0.27577711]						, __magic_name__		:int=True						, ):







								'''simple docstring'''







								a									=				size if size is not None else {"""height""": 224, """width""": 224}
								a									=				crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
								a									=				parent
								a									=				batch_size
								a									=				num_channels
								a									=				image_size
								a									=				min_resolution
								a									=				max_resolution
								a									=				do_resize
								a									=				size
								a									=				do_center_crop
								a									=				crop_size
								a									=				do_normalize
								a									=				image_mean
								a									=				image_std
								a									=				do_convert_rgb
							def  lowerCamelCase__				(		self		:Any							):







								'''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  lowerCamelCase__				(		self		:Dict						, __magic_name__		:List[Any]=False						, __magic_name__		:Any=False						, __magic_name__		:Union[str, Any]=False							):







								'''simple docstring'''







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

								if equal_resolution:
									a									=				[]
									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:
									a									=				[]
									for i in range(self.batch_size							):
										a							,					a									=				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
									a									=				[Image.fromarray(np.moveaxis(__magic_name__						, 0						, -1							)							) for x in image_inputs]

								if torchify:
									a									=				[torch.from_numpy(__magic_name__							) for x in image_inputs]

								return image_inputs







@require_torch
@require_vision
class 						__lowerCAmelCase      (      _a ,			unittest.TestCase					):
							UpperCamelCase__   	=    ChineseCLIPImageProcessor if is_vision_available() else None
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								a									=				ChineseCLIPImageProcessingTester(self						, do_center_crop=__magic_name__							)
							@property
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								return self.image_processor_tester.prepare_image_processor_dict()
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								a									=				self.image_processing_class(**self.image_processor_dict							)
								self.assertTrue(hasattr(__magic_name__						, """do_resize"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """size"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """do_center_crop"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """center_crop"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """do_normalize"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """image_mean"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """image_std"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """do_convert_rgb"""							)							)
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				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}							)

								a									=				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		:Tuple							):







								'''simple docstring'''







								pass
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







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

								# Test not batched input
								a									=				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
								a									=				image_processing(__magic_name__						, 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		:List[str]							):







								'''simple docstring'''







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

								# Test not batched input
								a									=				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
								a									=				image_processing(__magic_name__						, 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		:Optional[int]							):







								'''simple docstring'''







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

								# Test not batched input
								a									=				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
								a									=				image_processing(__magic_name__						, 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      (      _a ,			unittest.TestCase					):
							UpperCamelCase__   	=    ChineseCLIPImageProcessor if is_vision_available() else None
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								a									=				ChineseCLIPImageProcessingTester(self						, num_channels=4						, do_center_crop=__magic_name__							)
								a									=				3
							@property
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								return self.image_processor_tester.prepare_image_processor_dict()
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								a									=				self.image_processing_class(**self.image_processor_dict							)
								self.assertTrue(hasattr(__magic_name__						, """do_resize"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """size"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """do_center_crop"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """center_crop"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """do_normalize"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """image_mean"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """image_std"""							)							)
								self.assertTrue(hasattr(__magic_name__						, """do_convert_rgb"""							)							)
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								pass





							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







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

								# Test not batched input
								a									=				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
								a									=				image_processing(__magic_name__						, 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 					SCREAMING_SNAKE_CASE_  (       unittest.TestCase ):
       """simple docstring"""


       def 				UpperCamelCase__						(				self	:Any):



          """simple docstring"""

          _lowercase              =0





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

          _lowercase              =AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32')
          self.assertIsInstance(snake_case,      snake_case)





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



          """simple docstring"""

          with tempfile.TemporaryDirectory() as tmpdirname:
             _lowercase              =Path(snake_case) / 'preprocessor_config.json'
             _lowercase              =Path(snake_case) / 'config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'},      open(snake_case,      'w'),      )
             json.dump({'model_type': 'clip'},      open(snake_case,      'w'))

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
             self.assertIsInstance(snake_case,      snake_case)





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



          """simple docstring"""

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

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
             self.assertIsInstance(snake_case,      snake_case)





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



          """simple docstring"""

          with tempfile.TemporaryDirectory() as tmpdirname:
             _lowercase              =CLIPConfig()

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

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

             config_dict.pop('image_processor_type')
             _lowercase              =CLIPImageProcessor(**snake_case)

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

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)

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

          self.assertIsInstance(snake_case,      snake_case)





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

          with tempfile.TemporaryDirectory() as tmpdirname:
             _lowercase              =Path(snake_case) / 'preprocessor_config.json'
             json.dump(
                 {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'},      open(snake_case,      'w'),      )

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
             self.assertIsInstance(snake_case,      snake_case)





       def 				UpperCamelCase__						(				self	:int):



          """simple docstring"""

          with self.assertRaisesRegex(
              snake_case,      'clip-base is not a local folder and is not a valid model identifier'):
             _lowercase              =AutoImageProcessor.from_pretrained('clip-base')





       def 				UpperCamelCase__						(				self	:Dict):



          """simple docstring"""

          with self.assertRaisesRegex(
              snake_case,      r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'):
             _lowercase              =AutoImageProcessor.from_pretrained(snake_case,      revision='aaaaaa')





       def 				UpperCamelCase__						(				self	:List[Any]):



          """simple docstring"""

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





       def 				UpperCamelCase__						(				self	:Optional[Any]):



          """simple docstring"""

          with self.assertRaises(snake_case):
             _lowercase              =AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor')
          # If remote code is disabled, we can't load this config.
          with self.assertRaises(snake_case):
             _lowercase              =AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor',      trust_remote_code=snake_case)

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

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





       def 				UpperCamelCase__						(				self	:Optional[Any]):



          """simple docstring"""

          try:
             AutoConfig.register('custom',      snake_case)
             AutoImageProcessor.register(snake_case,      snake_case)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(snake_case):
                AutoImageProcessor.register(snake_case,      snake_case)

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

                _lowercase              =CustomImageProcessor.from_pretrained(snake_case)

             # 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(snake_case)
                _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
                self.assertIsInstance(snake_case,      snake_case)

          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 				UpperCamelCase__						(				self	:str):



          """simple docstring"""

          class 					SCREAMING_SNAKE_CASE_  (       _a ):
                 """simple docstring"""


                 __lowerCAmelCase    :		Union[str, Any]					=True

          try:
             AutoConfig.register('custom',      snake_case)
             AutoImageProcessor.register(snake_case,      snake_case)
             # If remote code is not set, the default is to use local
             _lowercase              =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.
             _lowercase              =AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor',      trust_remote_code=snake_case)
             self.assertEqual(image_processor.__class__.__name__,      'NewImageProcessor')
             self.assertTrue(image_processor.is_local)

             # If remote is enabled, we load from the Hub
             _lowercase              =AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor',      trust_remote_code=snake_case)
             self.assertEqual(image_processor.__class__.__name__,      'NewImageProcessor')
             self.assertTrue(not hasattr(snake_case,      '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]


