




'''simple docstring'''


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







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


														"""simple docstring"""


														_a      	=							0







							def   __lowerCAmelCase     (    self			:    str   )     ->				str:


														"""simple docstring"""


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







							def   __lowerCAmelCase     (    self			:    List[str]   )     ->				Optional[int]:


														"""simple docstring"""


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

																					_a      	=							AutoImageProcessor.from_pretrained(lowerCAmelCase_   )
																					self.assertIsInstance(lowerCAmelCase_				,     lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    List[str]   )     ->				Any:


														"""simple docstring"""


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

																					_a      	=							AutoImageProcessor.from_pretrained(lowerCAmelCase_   )
																					self.assertIsInstance(lowerCAmelCase_				,     lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Any   )     ->				List[str]:


														"""simple docstring"""


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

																					# Create a dummy config file with image_proceesor_type
																					_a      	=							Path(lowerCAmelCase_   ) / '''preprocessor_config.json'''
																					_a      	=							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
																					_a      	=							AutoImageProcessor.from_pretrained(lowerCAmelCase_   ).to_dict()

																					config_dict.pop('''image_processor_type'''   )
																					_a      	=							CLIPImageProcessor(**lowerCAmelCase_   )

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

																					_a      	=							AutoImageProcessor.from_pretrained(lowerCAmelCase_   )

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

														self.assertIsInstance(lowerCAmelCase_				,     lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    Tuple   )     ->				Dict:


														"""simple docstring"""


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

																					_a      	=							AutoImageProcessor.from_pretrained(lowerCAmelCase_   )
																					self.assertIsInstance(lowerCAmelCase_				,     lowerCAmelCase_   )







							def   __lowerCAmelCase     (    self			:    int   )     ->				str:


														"""simple docstring"""


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







							def   __lowerCAmelCase     (    self			:    Optional[int]   )     ->				int:


														"""simple docstring"""


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







							def   __lowerCAmelCase     (    self			:    List[str]   )     ->				Any:


														"""simple docstring"""


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







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


														"""simple docstring"""


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

														_a      	=							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_   )
																					_a      	=							AutoImageProcessor.from_pretrained(lowerCAmelCase_				,     trust_remote_code=lowerCAmelCase_   )
														self.assertEqual(reloaded_image_processor.__class__.__name__				,     '''NewImageProcessor'''   )







							def   __lowerCAmelCase     (    self			:    List[str]   )     ->				Any:


														"""simple docstring"""


														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:
																												_a      	=							Path(lowerCAmelCase_   ) / '''preprocessor_config.json'''
																												_a      	=							Path(lowerCAmelCase_   ) / '''config.json'''
																												json.dump(
																												    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}				,     open(lowerCAmelCase_				,     '''w'''   )				,     )
																												json.dump({'''model_type''': '''clip'''}				,     open(lowerCAmelCase_				,     '''w'''   )   )

																												_a      	=							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_   )
																												_a      	=							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			:    Optional[int]   )     ->				Any:


														"""simple docstring"""


														class      A       (						_a       ):
																					lowercase_							     =							True

														try:
																					AutoConfig.register('''custom'''				,     lowerCAmelCase_   )
																					AutoImageProcessor.register(lowerCAmelCase_				,     lowerCAmelCase_   )
																					# If remote code is not set, the default is to use local
																					_a      	=							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.
																					_a      	=							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
																					_a      	=							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]







'''simple docstring'''


import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

@slow
@require_torch_gpu
class      A       (						unittest.TestCase       ):







							def   __lowerCAmelCase     (    self			:    int   )     ->				Any:


														"""simple docstring"""


														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()







							def   __lowerCAmelCase     (    self			:    List[Any]   )     ->				int:


														"""simple docstring"""


														_a      	=							StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''   )
														_a      	=							sd_pipe.to(lowerCAmelCase_   )
														sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

														sd_pipe.set_scheduler('''sample_euler'''   )

														_a      	=							'''A painting of a squirrel eating a burger'''
														_a      	=							torch.manual_seed(0   )
														_a      	=							sd_pipe([prompt]				,     generator=lowerCAmelCase_				,     guidance_scale=9.0				,     num_inference_steps=20				,     output_type='''np'''   )

														_a      	=							output.images

														_a      	=							image[0, -3:, -3:, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														_a      	=							np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9]   )

														assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2







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


														"""simple docstring"""


														_a      	=							StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''   )
														_a      	=							sd_pipe.to(lowerCAmelCase_   )
														sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

														sd_pipe.set_scheduler('''sample_euler'''   )

														_a      	=							'''A painting of a squirrel eating a burger'''
														_a      	=							torch.manual_seed(0   )
														_a      	=							sd_pipe([prompt]				,     generator=lowerCAmelCase_				,     guidance_scale=9.0				,     num_inference_steps=20				,     output_type='''np'''   )

														_a      	=							output.images

														_a      	=							image[0, -3:, -3:, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														_a      	=							np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2]   )

														assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5e-1







							def   __lowerCAmelCase     (    self			:    Dict   )     ->				Optional[Any]:


														"""simple docstring"""


														_a      	=							StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''   )
														_a      	=							sd_pipe.to(lowerCAmelCase_   )
														sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_   )

														sd_pipe.set_scheduler('''sample_dpmpp_2m'''   )

														_a      	=							'''A painting of a squirrel eating a burger'''
														_a      	=							torch.manual_seed(0   )
														_a      	=							sd_pipe(
														    [prompt]				,     generator=lowerCAmelCase_				,     guidance_scale=7.5				,     num_inference_steps=15				,     output_type='''np'''				,     use_karras_sigmas=lowerCAmelCase_				,     )

														_a      	=							output.images

														_a      	=							image[0, -3:, -3:, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														_a      	=							np.array(
														    [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8]   )

														assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-2

