




from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...utils import logging


if TYPE_CHECKING:
							from ...feature_extraction_utils import FeatureExtractionMixin
							from ...tokenization_utils_base import PreTrainedTokenizerBase
							from ...utils import TensorType

UpperCAmelCase_		:					str          =  logging.get_logger(__name__)

UpperCAmelCase_		:					Tuple          =  {
    "openai/whisper-base": "https://huggingface.co/openai/whisper-base/resolve/main/config.json",
}

# fmt: off
UpperCAmelCase_		:					str          =  [
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
    705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377,
    1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211,
    4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786,
    11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791,
    17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409,
    34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361
]
UpperCAmelCase_		:					Union[str, Any]          =  [
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
    893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627,
    3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647,
    7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793,
    14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675,
    22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865,
    42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362
]




class 		__A   (      UpperCamelCase__      ):
						UpperCamelCase      =       """whisper"""
						UpperCamelCase      =       ["""past_key_values"""]
						UpperCamelCase      =       {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}

						def __init__(		self :Any     ,			__snake_case :Any=5_18_65     ,			__snake_case :Optional[int]=80     ,			__snake_case :str=6     ,			__snake_case :List[str]=4     ,			__snake_case :List[Any]=6     ,			__snake_case :Any=4     ,			__snake_case :Union[str, Any]=15_36     ,			__snake_case :List[Any]=15_36     ,			__snake_case :str=0.0     ,			__snake_case :Optional[Any]=0.0     ,			__snake_case :int=5_02_57     ,			__snake_case :Optional[int]=True     ,			__snake_case :List[str]=True     ,			__snake_case :str="gelu"     ,			__snake_case :Optional[Any]=2_56     ,			__snake_case :Union[str, Any]=0.0     ,			__snake_case :Any=0.0     ,			__snake_case :Optional[int]=0.0     ,			__snake_case :str=0.02     ,			__snake_case :Union[str, Any]=False     ,			__snake_case :int=15_00     ,			__snake_case :List[Any]=4_48     ,			__snake_case :Optional[int]=5_02_56     ,			__snake_case :Tuple=5_02_56     ,			__snake_case :Any=5_02_56     ,			__snake_case :Dict=None     ,			__snake_case :int=[2_20, 5_02_56]     ,			__snake_case :List[Any]=False     ,			__snake_case :Optional[Any]=2_56     ,			__snake_case :Tuple=False     ,			__snake_case :int=0.05     ,			__snake_case :List[Any]=10     ,			__snake_case :Optional[int]=2     ,			__snake_case :Tuple=0.0     ,			__snake_case :Union[str, Any]=10     ,			__snake_case :Dict=0     ,			__snake_case :List[Any]=7     ,			**__snake_case :List[str]     ,			):
										'''simple docstring'''

										__magic_name__						:						Any										=vocab_size
										__magic_name__						:						Optional[Any]										=num_mel_bins
										__magic_name__						:						Union[str, Any]										=d_model
										__magic_name__						:						List[Any]										=encoder_layers
										__magic_name__						:						str										=encoder_attention_heads
										__magic_name__						:						List[str]										=decoder_layers
										__magic_name__						:						List[str]										=decoder_attention_heads
										__magic_name__						:						int										=decoder_ffn_dim
										__magic_name__						:						Tuple										=encoder_ffn_dim
										__magic_name__						:						Tuple										=dropout
										__magic_name__						:						List[Any]										=attention_dropout
										__magic_name__						:						Any										=activation_dropout
										__magic_name__						:						List[Any]										=activation_function
										__magic_name__						:						Union[str, Any]										=init_std
										__magic_name__						:						Tuple										=encoder_layerdrop
										__magic_name__						:						Optional[Any]										=decoder_layerdrop
										__magic_name__						:						List[str]										=use_cache
										__magic_name__						:						Any										=encoder_layers
										__magic_name__						:						str										=scale_embedding  # scale factor will be sqrt(d_model) if True
										__magic_name__						:						Optional[int]										=max_source_positions
										__magic_name__						:						str										=max_target_positions

										# Audio Classification-specific parameters. Feel free to ignore for other classes.
										__magic_name__						:						Any										=classifier_proj_size
										__magic_name__						:						Tuple										=use_weighted_layer_sum

										# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
										__magic_name__						:						Any										=apply_spec_augment
										__magic_name__						:						Optional[Any]										=mask_time_prob
										__magic_name__						:						str										=mask_time_length
										__magic_name__						:						List[str]										=mask_time_min_masks
										__magic_name__						:						List[str]										=mask_feature_prob
										__magic_name__						:						Dict										=mask_feature_length
										__magic_name__						:						Dict										=mask_feature_min_masks

										__magic_name__						:						Tuple										=median_filter_width

										super().__init__(
										    pad_token_id=__snake_case     ,			bos_token_id=__snake_case     ,			eos_token_id=__snake_case     ,			is_encoder_decoder=__snake_case     ,			decoder_start_token_id=__snake_case     ,			suppress_tokens=__snake_case     ,			begin_suppress_tokens=__snake_case     ,			**__snake_case     ,			)




class 		__A   (      UpperCamelCase__      ):

						@property
						def      A__    (		self :List[Any]			):
										'''simple docstring'''

										__magic_name__						:						int										=OrderedDict(
										    [
										        ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}),
										    ]			)
										if self.use_past:
														__magic_name__						:						int										={0: """batch"""}
										else:
														__magic_name__						:						Union[str, Any]										={0: """batch""", 1: """decoder_sequence"""}

										if self.use_past:
														self.fill_with_past_key_values_(__snake_case     ,			direction="""inputs"""			)

										return common_inputs

						def      A__    (		self :List[str]     ,			__snake_case :Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]     ,			__snake_case :int = -1     ,			__snake_case :int = -1     ,			__snake_case :bool = False     ,			__snake_case :Optional["TensorType"] = None     ,			__snake_case :int = 2_20_50     ,			__snake_case :float = 5.0     ,			__snake_case :int = 2_20     ,			):
										'''simple docstring'''

										__magic_name__						:						List[Any]										=OrderedDict()
										__magic_name__						:						Optional[int]										=OnnxConfig.generate_dummy_inputs(
										    self     ,			preprocessor=preprocessor.feature_extractor     ,			batch_size=__snake_case     ,			framework=__snake_case     ,			sampling_rate=__snake_case     ,			time_duration=__snake_case     ,			frequency=__snake_case     ,			)
										__magic_name__						:						List[Any]										=encoder_inputs["""input_features"""].shape[2]
										__magic_name__						:						Tuple										=encoder_sequence_length // 2 if self.use_past else seq_length

										__magic_name__						:						Union[str, Any]										=super().generate_dummy_inputs(
										    preprocessor.tokenizer     ,			__snake_case     ,			__snake_case     ,			__snake_case     ,			__snake_case			)

										__magic_name__						:						Optional[Any]										=encoder_inputs.pop("""input_features"""			)
										__magic_name__						:						Dict										=decoder_inputs.pop("""decoder_input_ids"""			)

										if "past_key_values" in decoder_inputs:
														__magic_name__						:						Optional[int]										=decoder_inputs.pop("""past_key_values"""			)

										return dummy_inputs


						@property
						def      A__    (		self :Union[str, Any]			):
										'''simple docstring'''

										return 1E-3










import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
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 		__A   (      UpperCamelCase__       ,    unittest.TestCase      ):
						UpperCamelCase      =       KandinskyInpaintPipeline
						UpperCamelCase      =       ["""prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image"""]
						UpperCamelCase      =       [
						    """prompt""",
						    """negative_prompt""",
						    """image_embeds""",
						    """negative_image_embeds""",
						    """image""",
						    """mask_image""",
						]
						UpperCamelCase      =       [
						    """generator""",
						    """height""",
						    """width""",
						    """latents""",
						    """guidance_scale""",
						    """negative_prompt""",
						    """num_inference_steps""",
						    """return_dict""",
						    """guidance_scale""",
						    """num_images_per_prompt""",
						    """output_type""",
						    """return_dict""",
						]
						UpperCamelCase      =       False

						@property
						def      A__    (		self :Union[str, Any]			):
										'''simple docstring'''

										return 32

						@property
						def      A__    (		self :Optional[Any]			):
										'''simple docstring'''

										return 32

						@property
						def      A__    (		self :List[Any]			):
										'''simple docstring'''

										return self.time_input_dim

						@property
						def      A__    (		self :Dict			):
										'''simple docstring'''

										return self.time_input_dim * 4

						@property
						def      A__    (		self :List[Any]			):
										'''simple docstring'''

										return 1_00

						@property
						def      A__    (		self :Dict			):
										'''simple docstring'''

										__magic_name__						:						Dict										=XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base"""			)
										return tokenizer

						@property
						def      A__    (		self :str			):
										'''simple docstring'''

										torch.manual_seed(0			)
										__magic_name__						:						str										=MCLIPConfig(
										    numDims=self.cross_attention_dim     ,			transformerDimensions=self.text_embedder_hidden_size     ,			hidden_size=self.text_embedder_hidden_size     ,			intermediate_size=37     ,			num_attention_heads=4     ,			num_hidden_layers=5     ,			vocab_size=10_05     ,			)

										__magic_name__						:						Tuple										=MultilingualCLIP(__snake_case			)
										__magic_name__						:						Optional[int]										=text_encoder.eval()

										return text_encoder

						@property
						def      A__    (		self :Dict			):
										'''simple docstring'''

										torch.manual_seed(0			)

										__magic_name__						:						Optional[Any]										={
										    """in_channels""": 9,
										    # Out channels is double in channels because predicts mean and variance
										    """out_channels""": 8,
										    """addition_embed_type""": """text_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""": """text_image_proj""",
										    """cross_attention_dim""": self.cross_attention_dim,
										    """attention_head_dim""": 4,
										    """resnet_time_scale_shift""": """scale_shift""",
										    """class_embed_type""": None,
										}

										__magic_name__						:						Union[str, Any]										=UNetaDConditionModel(**__snake_case			)
										return model

						@property
						def      A__    (		self :List[str]			):
										'''simple docstring'''

										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      A__    (		self :Tuple			):
										'''simple docstring'''

										torch.manual_seed(0			)
										__magic_name__						:						Dict										=VQModel(**self.dummy_movq_kwargs			)
										return model

						def      A__    (		self :Optional[Any]			):
										'''simple docstring'''

										__magic_name__						:						List[str]										=self.dummy_text_encoder
										__magic_name__						:						Optional[Any]										=self.dummy_tokenizer
										__magic_name__						:						Optional[Any]										=self.dummy_unet
										__magic_name__						:						Tuple										=self.dummy_movq

										__magic_name__						:						List[str]										=DDIMScheduler(
										    num_train_timesteps=10_00     ,			beta_schedule="""linear"""     ,			beta_start=0.00085     ,			beta_end=0.012     ,			clip_sample=__snake_case     ,			set_alpha_to_one=__snake_case     ,			steps_offset=1     ,			prediction_type="""epsilon"""     ,			thresholding=__snake_case     ,			)

										__magic_name__						:						str										={
										    """text_encoder""": text_encoder,
										    """tokenizer""": tokenizer,
										    """unet""": unet,
										    """scheduler""": scheduler,
										    """movq""": movq,
										}

										return components

						def      A__    (		self :str     ,			__snake_case :Optional[Any]     ,			__snake_case :int=0			):
										'''simple docstring'''

										__magic_name__						:						Union[str, Any]										=floats_tensor((1, self.cross_attention_dim)     ,			rng=random.Random(__snake_case			)			).to(__snake_case			)
										__magic_name__						:						Dict										=floats_tensor((1, self.cross_attention_dim)     ,			rng=random.Random(seed + 1			)			).to(__snake_case			)
										# create init_image
										__magic_name__						:						str										=floats_tensor((1, 3, 64, 64)     ,			rng=random.Random(__snake_case			)			).to(__snake_case			)
										__magic_name__						:						int										=image.cpu().permute(0     ,			2     ,			3     ,			1			)[0]
										__magic_name__						:						str										=Image.fromarray(np.uinta(__snake_case			)			).convert("""RGB"""			).resize((2_56, 2_56)			)
										# create mask
										__magic_name__						:						Dict										=np.ones((64, 64)     ,			dtype=np.floataa			)
										__magic_name__						:						Any										=0

										if str(__snake_case			).startswith("""mps"""			):
														__magic_name__						:						Dict										=torch.manual_seed(__snake_case			)
										else:
														__magic_name__						:						Tuple										=torch.Generator(device=__snake_case			).manual_seed(__snake_case			)
										__magic_name__						:						List[Any]										={
										    """prompt""": """horse""",
										    """image""": init_image,
										    """mask_image""": mask,
										    """image_embeds""": image_embeds,
										    """negative_image_embeds""": negative_image_embeds,
										    """generator""": generator,
										    """height""": 64,
										    """width""": 64,
										    """num_inference_steps""": 2,
										    """guidance_scale""": 4.0,
										    """output_type""": """np""",
										}
										return inputs

						def      A__    (		self :List[str]			):
										'''simple docstring'''

										__magic_name__						:						Tuple										="""cpu"""

										__magic_name__						:						List[Any]										=self.get_dummy_components()

										__magic_name__						:						Union[str, Any]										=self.pipeline_class(**__snake_case			)
										__magic_name__						:						Tuple										=pipe.to(__snake_case			)

										pipe.set_progress_bar_config(disable=__snake_case			)

										__magic_name__						:						Tuple										=pipe(**self.get_dummy_inputs(__snake_case			)			)
										__magic_name__						:						List[Any]										=output.images

										__magic_name__						:						Any										=pipe(
										    **self.get_dummy_inputs(__snake_case			)     ,			return_dict=__snake_case     ,			)[0]

										__magic_name__						:						int										=image[0, -3:, -3:, -1]
										__magic_name__						:						str										=image_from_tuple[0, -3:, -3:, -1]

										print(f"image.shape {image.shape}"			)

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

										__magic_name__						:						Optional[Any]										=np.array(
										    [0.8326919, 0.73790467, 0.20918581, 0.9309612, 0.5511791, 0.43713328, 0.5513321, 0.49922934, 0.59497786]			)

										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()}"


						def      A__    (		self :Dict			):
										'''simple docstring'''

										super().test_inference_batch_single_identical(expected_max_diff=3E-3			)




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

						def      A__    (		self :List[Any]			):
										'''simple docstring'''

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


						def      A__    (		self :Union[str, Any]			):
										'''simple docstring'''

										__magic_name__						:						List[str]										=load_numpy(
										    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
										    """/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy"""			)

										__magic_name__						:						int										=load_image(
										    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png"""			)
										__magic_name__						:						List[Any]										=np.ones((7_68, 7_68)     ,			dtype=np.floataa			)
										__magic_name__						:						Any										=0

										__magic_name__						:						int										="""a hat"""

										__magic_name__						:						int										=KandinskyPriorPipeline.from_pretrained(
										    """kandinsky-community/kandinsky-2-1-prior"""     ,			torch_dtype=torch.floataa			)
										pipe_prior.to(__snake_case			)

										__magic_name__						:						Dict										=KandinskyInpaintPipeline.from_pretrained(
										    """kandinsky-community/kandinsky-2-1-inpaint"""     ,			torch_dtype=torch.floataa			)
										__magic_name__						:						int										=pipeline.to(__snake_case			)
										pipeline.set_progress_bar_config(disable=__snake_case			)

										__magic_name__						:						Union[str, Any]										=torch.Generator(device="""cpu"""			).manual_seed(0			)
										__magic_name__					,			__magic_name__						:						Dict										=pipe_prior(
										    __snake_case     ,			generator=__snake_case     ,			num_inference_steps=5     ,			negative_prompt=""""""     ,			).to_tuple()

										__magic_name__						:						Optional[Any]										=pipeline(
										    __snake_case     ,			image=__snake_case     ,			mask_image=__snake_case     ,			image_embeds=__snake_case     ,			negative_image_embeds=__snake_case     ,			generator=__snake_case     ,			num_inference_steps=1_00     ,			height=7_68     ,			width=7_68     ,			output_type="""np"""     ,			)

										__magic_name__						:						Optional[int]										=output.images[0]

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

										assert_mean_pixel_difference(__snake_case     ,			__snake_case			)




