"""simple docstring"""




import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

class       a_      (     unittest.TestCase			):




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()




					@property
					def 						_SCREAMING_SNAKE_CASE						(	self						:     Any     ):
							torch.manual_seed(0     )
							lowerCAmelCase__        =   UNetaDModel(
							    sample_size=(32, 64)  ,						in_channels=1  ,						out_channels=1  ,						layers_per_block=2  ,						block_out_channels=(128, 128)  ,						down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")  ,						up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")  ,						)
							return model




					@property
					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							torch.manual_seed(0     )
							lowerCAmelCase__        =   UNetaDConditionModel(
							    sample_size=(64, 32)  ,						in_channels=1  ,						out_channels=1  ,						layers_per_block=2  ,						block_out_channels=(128, 128)  ,						down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""")  ,						up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""")  ,						cross_attention_dim=10  ,						)
							return model




					@property
					def 						_SCREAMING_SNAKE_CASE						(	self						:     int     ):
							torch.manual_seed(0     )
							lowerCAmelCase__        =   AutoencoderKL(
							    sample_size=(128, 64)  ,						in_channels=1  ,						out_channels=1  ,						latent_channels=1  ,						layers_per_block=2  ,						block_out_channels=(128, 128)  ,						down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")  ,						up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")  ,						)
							lowerCAmelCase__        =   UNetaDModel(
							    sample_size=(64, 32)  ,						in_channels=1  ,						out_channels=1  ,						layers_per_block=2  ,						block_out_channels=(128, 128)  ,						down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")  ,						up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")  ,						)
							return vqvae, unet




					@slow
					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[Any]     ):
							lowerCAmelCase__        =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
							lowerCAmelCase__        =   Mel(
							    x_res=self.dummy_unet.config.sample_size[1]  ,						y_res=self.dummy_unet.config.sample_size[0]  ,						)

							lowerCAmelCase__        =   DDPMScheduler()
							lowerCAmelCase__        =   AudioDiffusionPipeline(vqvae=snake_case__  ,						unet=self.dummy_unet  ,						mel=snake_case__  ,						scheduler=snake_case__     )
							lowerCAmelCase__        =   pipe.to(snake_case__     )
							pipe.set_progress_bar_config(disable=snake_case__     )

							lowerCAmelCase__        =   torch.Generator(device=snake_case__     ).manual_seed(42     )
							lowerCAmelCase__        =   pipe(generator=snake_case__  ,						steps=4     )
							lowerCAmelCase__        =   output.audios[0]
							lowerCAmelCase__        =   output.images[0]

							lowerCAmelCase__        =   torch.Generator(device=snake_case__     ).manual_seed(42     )
							lowerCAmelCase__        =   pipe(generator=snake_case__  ,						steps=4  ,						return_dict=snake_case__     )
							lowerCAmelCase__        =   output[0][0]

							assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
							assert (
							    image.height == self.dummy_unet.config.sample_size[0]
							    and image.width == self.dummy_unet.config.sample_size[1]
							)
							lowerCAmelCase__        =   np.frombuffer(image.tobytes()  ,						dtype="""uint8"""     )[:10]
							lowerCAmelCase__        =   np.frombuffer(image_from_tuple.tobytes()  ,						dtype="""uint8"""     )[:10]
							lowerCAmelCase__        =   np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]     )

							assert np.abs(image_slice.flatten() - expected_slice     ).max() == 0
							assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() == 0

							lowerCAmelCase__        =   Mel(
							    x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]  ,						y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]  ,						)

							lowerCAmelCase__        =   DDIMScheduler()
							lowerCAmelCase__        =   self.dummy_vqvae_and_unet
							lowerCAmelCase__        =   AudioDiffusionPipeline(
							    vqvae=self.dummy_vqvae_and_unet[0]  ,						unet=dummy_vqvae_and_unet[1]  ,						mel=snake_case__  ,						scheduler=snake_case__     )
							lowerCAmelCase__        =   pipe.to(snake_case__     )
							pipe.set_progress_bar_config(disable=snake_case__     )

							np.random.seed(0     )
							lowerCAmelCase__        =   np.random.uniform(-1  ,						1  ,						((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)     )
							lowerCAmelCase__        =   torch.Generator(device=snake_case__     ).manual_seed(42     )
							lowerCAmelCase__        =   pipe(raw_audio=snake_case__  ,						generator=snake_case__  ,						start_step=5  ,						steps=10     )
							lowerCAmelCase__        =   output.images[0]

							assert (
							    image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
							    and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
							)
							lowerCAmelCase__        =   np.frombuffer(image.tobytes()  ,						dtype="""uint8"""     )[:10]
							lowerCAmelCase__        =   np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]     )

							assert np.abs(image_slice.flatten() - expected_slice     ).max() == 0

							lowerCAmelCase__        =   self.dummy_unet_condition
							lowerCAmelCase__        =   AudioDiffusionPipeline(
							    vqvae=self.dummy_vqvae_and_unet[0]  ,						unet=snake_case__  ,						mel=snake_case__  ,						scheduler=snake_case__     )
							lowerCAmelCase__        =   pipe.to(snake_case__     )
							pipe.set_progress_bar_config(disable=snake_case__     )

							np.random.seed(0     )
							lowerCAmelCase__        =   torch.rand((1, 1, 10)     )
							lowerCAmelCase__        =   pipe(generator=snake_case__  ,						encoding=snake_case__     )
							lowerCAmelCase__        =   output.images[0]
							lowerCAmelCase__        =   np.frombuffer(image.tobytes()  ,						dtype="""uint8"""     )[:10]
							lowerCAmelCase__        =   np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]     )

							assert np.abs(image_slice.flatten() - expected_slice     ).max() == 0

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




					def 						_SCREAMING_SNAKE_CASE						(	self						:     List[Any]     ):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							lowerCAmelCase__        =   torch_device

							lowerCAmelCase__        =   DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256"""     )
							lowerCAmelCase__        =   pipe.to(snake_case__     )
							pipe.set_progress_bar_config(disable=snake_case__     )

							lowerCAmelCase__        =   torch.Generator(device=snake_case__     ).manual_seed(42     )
							lowerCAmelCase__        =   pipe(generator=snake_case__     )
							lowerCAmelCase__        =   output.audios[0]
							lowerCAmelCase__        =   output.images[0]

							assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
							assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
							lowerCAmelCase__        =   np.frombuffer(image.tobytes()  ,						dtype="""uint8"""     )[:10]
							lowerCAmelCase__        =   np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]     )

							assert np.abs(image_slice.flatten() - expected_slice     ).max() == 0





"""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 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]     ):
							lowerCAmelCase__        =   0




					def 						_SCREAMING_SNAKE_CASE						(	self						:     List[Any]     ):
							lowerCAmelCase__        =   AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32"""     )
							self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Tuple     ):
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
									lowerCAmelCase__        =   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"""     )     )

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )
									self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							# Ensure we can load the image processor from the feature extractor config
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
									lowerCAmelCase__        =   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"""     )     )

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )
									self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]     ):
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   CLIPConfig()

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

									config_dict.pop("""image_processor_type"""     )
									lowerCAmelCase__        =   CLIPImageProcessor(**snake_case__     )

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

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )

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

							self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Dict     ):
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
									json.dump(
									    {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}  ,						open(snake_case__  ,						"""w"""     )  ,						)

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )
									self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]     ):
							with self.assertRaisesRegex(
							    snake_case__  ,						"""clip-base is not a local folder and is not a valid model identifier"""     ):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained("""clip-base"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							with self.assertRaisesRegex(
							    snake_case__  ,						R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""     ):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__  ,						revision="""aaaaaa"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[Any]     ):
							with self.assertRaisesRegex(
							    snake_case__  ,						"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""  ,						):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Any     ):
							# If remote code is not set, we will time out when asking whether to load the model.
							with self.assertRaises(snake_case__     ):
									lowerCAmelCase__        =   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__     ):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(
									    """hf-internal-testing/test_dynamic_image_processor"""  ,						trust_remote_code=snake_case__     )

							lowerCAmelCase__        =   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__     )
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__  ,						trust_remote_code=snake_case__     )
							self.assertEqual(reloaded_image_processor.__class__.__name__  ,						"""NewImageProcessor"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Dict     ):
							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:
											lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
											lowerCAmelCase__        =   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"""     )     )

											lowerCAmelCase__        =   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__     )
											lowerCAmelCase__        =   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 						_SCREAMING_SNAKE_CASE						(	self						:     List[str]     ):

							class       a_      (     __UpperCamelCase			):
												UpperCamelCase_ :	Tuple			=    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
									lowerCAmelCase__        =   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.
									lowerCAmelCase__        =   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
									lowerCAmelCase__        =   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]




