





'''simple docstring'''







import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()
class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_       ,							unittest.TestCase      ):






				"""simple docstring"""







				__a            =KandinskyVaaImgaImgPipeline
				__a            =['image_embeds', 'negative_image_embeds', 'image']
				__a            =[
				    'image_embeds',
				    'negative_image_embeds',
				    'image',
				]
				__a            =[
				    'generator',
				    'height',
				    'width',
				    'strength',
				    'guidance_scale',
				    'num_inference_steps',
				    'return_dict',
				    'guidance_scale',
				    'num_images_per_prompt',
				    'output_type',
				    'return_dict',
				]
				__a            =False




				@property
				def   UpperCamelCase__   (  self     :					int					):
								return 32




				@property
				def   UpperCamelCase__   (  self     :					int					):
								return 32




				@property
				def   UpperCamelCase__   (  self     :					Any					):
								return self.time_input_dim




				@property
				def   UpperCamelCase__   (  self     :					Dict					):
								return self.time_input_dim * 4




				@property
				def   UpperCamelCase__   (  self     :					int					):
								return 1_00




				@property
				def   UpperCamelCase__   (  self     :					List[Any]					):
								torch.manual_seed(0					)

								_a								= {
								    "in_channels": 4,
								    # Out channels is double in channels because predicts mean and variance
								    "out_channels": 8,
								    "addition_embed_type": "image",
								    "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
								    "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
								    "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
								    "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
								    "layers_per_block": 1,
								    "encoder_hid_dim": self.text_embedder_hidden_size,
								    "encoder_hid_dim_type": "image_proj",
								    "cross_attention_dim": self.cross_attention_dim,
								    "attention_head_dim": 4,
								    "resnet_time_scale_shift": "scale_shift",
								    "class_embed_type": None,
								}

								_a								= UNetaDConditionModel(**__a					)
								return model




				@property
				def   UpperCamelCase__   (  self     :					Any					):
								return {
								    "block_out_channels": [32, 64],
								    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
								    "in_channels": 3,
								    "latent_channels": 4,
								    "layers_per_block": 1,
								    "norm_num_groups": 8,
								    "norm_type": "spatial",
								    "num_vq_embeddings": 12,
								    "out_channels": 3,
								    "up_block_types": [
								        "AttnUpDecoderBlock2D",
								        "UpDecoderBlock2D",
								    ],
								    "vq_embed_dim": 4,
								}




				@property
				def   UpperCamelCase__   (  self     :					List[Any]					):
								torch.manual_seed(0					)
								_a								= VQModel(**self.dummy_movq_kwargs					)
								return model




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= self.dummy_unet
								_a								= self.dummy_movq

								_a								= {
								    "num_train_timesteps": 10_00,
								    "beta_schedule": "linear",
								    "beta_start": 0.00085,
								    "beta_end": 0.012,
								    "clip_sample": False,
								    "set_alpha_to_one": False,
								    "steps_offset": 0,
								    "prediction_type": "epsilon",
								    "thresholding": False,
								}

								_a								= DDIMScheduler(**__a					)

								_a								= {
								    "unet": unet,
								    "scheduler": scheduler,
								    "movq": movq,
								}

								return components




				def   UpperCamelCase__   (  self     :					Optional[Any]					,				__a     :					Any					,				__a     :					Union[str, Any]=0					):
								_a								= floats_tensor((1, self.text_embedder_hidden_size)					,				rng=random.Random(__a					)					).to(__a					)
								_a								= floats_tensor((1, self.text_embedder_hidden_size)					,				rng=random.Random(seed + 1					)					).to(
								    __a					)
								# create init_image
								_a								= floats_tensor((1, 3, 64, 64)					,				rng=random.Random(__a					)					).to(__a					)
								_a								= image.cpu().permute(0					,				2					,				3					,				1					)[0]
								_a								= Image.fromarray(np.uinta(__a					)					).convert("RGB"					).resize((2_56, 2_56)					)

								if str(__a					).startswith("mps"					):
												_a								= torch.manual_seed(__a					)
								else:
												_a								= torch.Generator(device=__a					).manual_seed(__a					)
								_a								= {
								    "image": init_image,
								    "image_embeds": image_embeds,
								    "negative_image_embeds": negative_image_embeds,
								    "generator": generator,
								    "height": 64,
								    "width": 64,
								    "num_inference_steps": 10,
								    "guidance_scale": 7.0,
								    "strength": 0.2,
								    "output_type": "np",
								}
								return inputs




				def   UpperCamelCase__   (  self     :					Dict					):
								_a								= "cpu"

								_a								= self.get_dummy_components()

								_a								= self.pipeline_class(**__a					)
								_a								= pipe.to(__a					)

								pipe.set_progress_bar_config(disable=__a					)

								_a								= pipe(**self.get_dummy_inputs(__a					)					)
								_a								= output.images

								_a								= pipe(
								    **self.get_dummy_inputs(__a					)					,				return_dict=__a					,				)[0]

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

								assert image.shape == (1, 64, 64, 3)

								_a								= np.array(
								    [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263]					)
								assert (
								    np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2
								), f' expected_slice {expected_slice}, but got {image_slice.flatten()}'
								assert (
								    np.abs(image_from_tuple_slice.flatten() - expected_slice					).max() < 1e-2
								), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'


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






				"""simple docstring"""







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




				def   UpperCamelCase__   (  self     :					int					):
								_a								= load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/kandinskyv22/kandinskyv22_img2img_frog.npy"					)

								_a								= load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png"					)
								_a								= "A red cartoon frog, 4k"

								_a								= KandinskyVaaPriorPipeline.from_pretrained(
								    "kandinsky-community/kandinsky-2-2-prior"					,				torch_dtype=torch.floataa					)
								pipe_prior.to(__a					)

								_a								= KandinskyVaaImgaImgPipeline.from_pretrained(
								    "kandinsky-community/kandinsky-2-2-decoder"					,				torch_dtype=torch.floataa					)
								_a								= pipeline.to(__a					)

								pipeline.set_progress_bar_config(disable=__a					)

								_a								= torch.Generator(device="cpu"					).manual_seed(0					)
								_a	,					_a								= pipe_prior(
								    __a					,				generator=__a					,				num_inference_steps=5					,				negative_prompt=""					,				).to_tuple()

								_a								= pipeline(
								    image=__a					,				image_embeds=__a					,				negative_image_embeds=__a					,				generator=__a					,				num_inference_steps=1_00					,				height=7_68					,				width=7_68					,				strength=0.2					,				output_type="np"					,				)

								_a								= output.images[0]

								assert image.shape == (7_68, 7_68, 3)

								assert_mean_pixel_difference(__a					,				__a					)







'''simple docstring'''







import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase_					:    Any      	=			get_tests_dir('fixtures')
lowerCAmelCase_					:    Union[str, Any]      	=			get_tests_dir('fixtures/dummy_feature_extractor_config.json')
lowerCAmelCase_					:    Dict      	=			get_tests_dir('fixtures/dummy-config.json')
class 				__SCREAMING_SNAKE_CASE  (unittest.TestCase      ):






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					Optional[int]					):
								_a								= 0




				def   UpperCamelCase__   (  self     :					str					):
								_a								= AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h"					)
								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= AutoFeatureExtractor.from_pretrained(__a					)
								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					List[Any]					):
								with tempfile.TemporaryDirectory() as tmpdirname:
												_a								= WavaVecaConfig()

												# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
												_a								= AutoFeatureExtractor.from_pretrained(__a					).to_dict()

												config_dict.pop("feature_extractor_type"					)
												_a								= WavaVecaFeatureExtractor(**__a					)

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

												_a								= AutoFeatureExtractor.from_pretrained(__a					)

												# 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(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					Tuple					):
								_a								= AutoFeatureExtractor.from_pretrained(__a					)
								self.assertIsInstance(__a					,				__a					)




				def   UpperCamelCase__   (  self     :					Union[str, Any]					):
								with self.assertRaisesRegex(
								    __a					,				"bert-base is not a local folder and is not a valid model identifier"					):
												_a								= AutoFeatureExtractor.from_pretrained("bert-base"					)




				def   UpperCamelCase__   (  self     :					Optional[Any]					):
								with self.assertRaisesRegex(
								    __a					,				r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"					):
												_a								= AutoFeatureExtractor.from_pretrained(__a					,				revision="aaaaaa"					)




				def   UpperCamelCase__   (  self     :					List[Any]					):
								with self.assertRaisesRegex(
								    __a					,				"hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."					,				):
												_a								= AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model"					)




				def   UpperCamelCase__   (  self     :					List[Any]					):
								# If remote code is not set, we will time out when asking whether to load the model.
								with self.assertRaises(__a					):
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					)
								# If remote code is disabled, we can't load this config.
								with self.assertRaises(__a					):
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)

								_a								= AutoFeatureExtractor.from_pretrained(
								    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)
								self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)

								# Test feature extractor can be reloaded.
								with tempfile.TemporaryDirectory() as tmp_dir:
												feature_extractor.save_pretrained(__a					)
												_a								= AutoFeatureExtractor.from_pretrained(__a					,				trust_remote_code=__a					)
								self.assertEqual(reloaded_feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)




				def   UpperCamelCase__   (  self     :					Any					):
								try:
												AutoConfig.register("custom"					,				__a					)
												AutoFeatureExtractor.register(__a					,				__a					)
												# Trying to register something existing in the Transformers library will raise an error
												with self.assertRaises(__a					):
																AutoFeatureExtractor.register(__a					,				__a					)

												# Now that the config is registered, it can be used as any other config with the auto-API
												_a								= CustomFeatureExtractor.from_pretrained(__a					)
												with tempfile.TemporaryDirectory() as tmp_dir:
																feature_extractor.save_pretrained(__a					)
																_a								= AutoFeatureExtractor.from_pretrained(__a					)
																self.assertIsInstance(__a					,				__a					)

								finally:
												if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]
												if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]




				def   UpperCamelCase__   (  self     :					Tuple					):
								class 				__SCREAMING_SNAKE_CASE  (lowerCamelCase_      ):






												"""simple docstring"""







												__a            =True

								try:
												AutoConfig.register("custom"					,				__a					)
												AutoFeatureExtractor.register(__a					,				__a					)
												# If remote code is not set, the default is to use local
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					)
												self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)
												self.assertTrue(feature_extractor.is_local					)

												# If remote code is disabled, we load the local one.
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)
												self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)
												self.assertTrue(feature_extractor.is_local					)

												# If remote is enabled, we load from the Hub
												_a								= AutoFeatureExtractor.from_pretrained(
												    "hf-internal-testing/test_dynamic_feature_extractor"					,				trust_remote_code=__a					)
												self.assertEqual(feature_extractor.__class__.__name__					,				"NewFeatureExtractor"					)
												self.assertTrue(not hasattr(__a					,				"is_local"					)					)

								finally:
												if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]
												if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
