
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  A							(  self	:    int	):


				'''simple docstring'''


				_snake_case		=			0



	def  A							(  self	:    str	):


				'''simple docstring'''


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



	def  A							(  self	:    Tuple	):


				'''simple docstring'''


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

							_snake_case		=			AutoImageProcessor.from_pretrained(lowercase	)
							self.assertIsInstance(lowercase			,  lowercase	)



	def  A							(  self	:    str	):


				'''simple docstring'''


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

							_snake_case		=			AutoImageProcessor.from_pretrained(lowercase	)
							self.assertIsInstance(lowercase			,  lowercase	)



	def  A							(  self	:    str	):


				'''simple docstring'''


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

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

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

							config_dict.pop('image_processor_type'	)
							_snake_case		=			CLIPImageProcessor(**lowercase	)

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

							_snake_case		=			AutoImageProcessor.from_pretrained(lowercase	)

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

				self.assertIsInstance(lowercase			,  lowercase	)



	def  A							(  self	:    List[Any]	):


				'''simple docstring'''


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

							_snake_case		=			AutoImageProcessor.from_pretrained(lowercase	)
							self.assertIsInstance(lowercase			,  lowercase	)



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


				'''simple docstring'''


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



	def  A							(  self	:    int	):


				'''simple docstring'''


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



	def  A							(  self	:    int	):


				'''simple docstring'''


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



	def  A							(  self	:    Optional[int]	):


				'''simple docstring'''


				with self.assertRaises(lowercase	):
							_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(lowercase	):
							_snake_case		=			AutoImageProcessor.from_pretrained(
							    'hf-internal-testing/test_dynamic_image_processor'			,  trust_remote_code=lowercase	)

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

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



	def  A							(  self	:    Tuple	):


				'''simple docstring'''


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

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

										_snake_case		=			CustomImageProcessor.from_pretrained(lowercase	)

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

				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  A							(  self	:    List[str]	):


				'''simple docstring'''


				class    SCREAMING_SNAKE_CASE__     (	UpperCAmelCase					):





					'''simple docstring'''



					_UpperCAmelCase       :		Union[str, Any]       =					True

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

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

import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch




@require_torch
class    SCREAMING_SNAKE_CASE__     :





	'''simple docstring'''



	@property
	def  A							(  self	:    List[str]	):


				'''simple docstring'''


				return self.get_dummy_input()



	@property
	def  A							(  self	:    Any	):


				'''simple docstring'''


				if self.block_type == "down":
							return (4, 32, 16, 16)
				elif self.block_type == "mid":
							return (4, 32, 32, 32)
				elif self.block_type == "up":
							return (4, 32, 64, 64)

				raise ValueError(f'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.'''	)



	def  A							(  self	:    Union[str, Any]			,  lowercase	:    Any=True			,  lowercase	:    List[Any]=False			,  lowercase	:    List[str]=False			,  lowercase	:    Dict=False			,  ):


				'''simple docstring'''


				_snake_case		=			4
				_snake_case		=			32
				_snake_case		=			(32, 32)

				_snake_case		=			torch.manual_seed(0	)
				_snake_case		=			torch.device(lowercase	)
				_snake_case		=			(batch_size, num_channels) + sizes
				_snake_case		=			randn_tensor(lowercase			,  generator=lowercase			,  device=lowercase	)
				_snake_case		=			{'hidden_states': hidden_states}

				if include_temb:
							_snake_case		=			128
							_snake_case		=			randn_tensor((batch_size, temb_channels)			,  generator=lowercase			,  device=lowercase	)

				if include_res_hidden_states_tuple:
							_snake_case		=			torch.manual_seed(1	)
							_snake_case		=			(randn_tensor(lowercase			,  generator=lowercase			,  device=lowercase	),)

				if include_encoder_hidden_states:
							_snake_case		=			floats_tensor((batch_size, 32, 32)	).to(lowercase	)

				if include_skip_sample:
							_snake_case		=			randn_tensor(((batch_size, 3) + sizes)			,  generator=lowercase			,  device=lowercase	)

				return dummy_input



	def  A							(  self	:    Any	):


				'''simple docstring'''


				_snake_case		=			{
				    'in_channels': 32,
				    'out_channels': 32,
				    'temb_channels': 128,
				}
				if self.block_type == "up":
							_snake_case		=			32

				if self.block_type == "mid":
							init_dict.pop('out_channels'	)

				_snake_case		=			self.dummy_input
				return init_dict, inputs_dict



	def  A							(  self	:    Dict			,  lowercase	:    Optional[int]	):


				'''simple docstring'''


				_snake_case	,					_snake_case		=			self.prepare_init_args_and_inputs_for_common()
				_snake_case		=			self.block_class(**lowercase	)
				unet_block.to(lowercase	)
				unet_block.eval()

				with torch.no_grad():
							_snake_case		=			unet_block(**lowercase	)

				if isinstance(lowercase			,  lowercase	):
							_snake_case		=			output[0]

				self.assertEqual(output.shape			,  self.output_shape	)

				_snake_case		=			output[0, -1, -3:, -3:]
				_snake_case		=			torch.tensor(lowercase	).to(lowercase	)
				assert torch_all_close(output_slice.flatten()			,  lowercase			,  atol=5E-3	)





	@unittest.skipIf(torch_device == 'mps'			,  'Training is not supported in mps'	)
	def  A							(  self	:    Dict	):


				'''simple docstring'''


				_snake_case	,					_snake_case		=			self.prepare_init_args_and_inputs_for_common()
				_snake_case		=			self.block_class(**lowercase	)
				model.to(lowercase	)
				model.train()
				_snake_case		=			model(**lowercase	)

				if isinstance(lowercase			,  lowercase	):
							_snake_case		=			output[0]

				_snake_case		=			torch.device(lowercase	)
				_snake_case		=			randn_tensor(output.shape			,  device=lowercase	)
				_snake_case		=			torch.nn.functional.mse_loss(lowercase			,  lowercase	)
				loss.backward()