
import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


lowercase__				:				Dict						=      logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
lowercase__				:				Union[str, Any]						=      direct_transformers_import(Path(__file__).parent)


lowercase__				:				Optional[int]						=      {
    "AutoTokenizer": "PreTrainedTokenizerBase",
    "AutoFeatureExtractor": "FeatureExtractionMixin",
    "AutoImageProcessor": "ImageProcessingMixin",
}






class 							SCREAMING_SNAKE_CASE__     (				SCREAMING_SNAKE_CASE_     ):

							"""simple docstring"""






							_snake_case  		=	['feature_extractor', 'tokenizer']
							# Names need to be attr_class for attr in attributes
							_snake_case  		=	None
							_snake_case  		=	None
							_snake_case  		=	None



							def __init__(	self  ,						*SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )-> str:





													'''simple docstring'''






													for key in kwargs:
																			if key not in self.attributes:
																									raise TypeError(F"Unexpected keyword argument {key}."      )
													for arg, attribute_name in zip(SCREAMING_SNAKE_CASE_  ,						self.attributes      ):
																			if attribute_name in kwargs:
																									raise TypeError(F"Got multiple values for argument {attribute_name}."      )
																			else:
																									__UpperCamelCase  	=      arg

													if len(SCREAMING_SNAKE_CASE_      ) != len(self.attributes      ):
																			raise ValueError(
																			    F"This processor requires {len(self.attributes      )} arguments: {', '.join(self.attributes      )}. Got "
																			    F"{len(SCREAMING_SNAKE_CASE_      )} arguments instead."      )

													# Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
													for attribute_name, arg in kwargs.items():
																			__UpperCamelCase  	=      getattr(self  ,						F"{attribute_name}_class"      )
																			# Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
																			__UpperCamelCase  	=      AUTO_TO_BASE_CLASS_MAPPING.get(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )
																			if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																									__UpperCamelCase  	=      tuple(getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ) for n in class_name if n is not None      )
																			else:
																									__UpperCamelCase  	=      getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )

																			if not isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																									raise ValueError(
																									    F"Received a {type(SCREAMING_SNAKE_CASE_      ).__name__} for argument {attribute_name}, but a {class_name} was expected."      )

																			setattr(self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )



							def __repr__(	self      )-> Any:





													'''simple docstring'''






													__UpperCamelCase  	=      [F"- {name}: {repr(getattr(self  ,						SCREAMING_SNAKE_CASE_      )      )}" for name in self.attributes]
													__UpperCamelCase  	=      '''\n'''.join(SCREAMING_SNAKE_CASE_      )
													return F"{self.__class__.__name__}:\n{attributes_repr}"



							def      A__		(	self  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_ = False  ,						**SCREAMING_SNAKE_CASE_      )-> List[Any]:





													'''simple docstring'''






													os.makedirs(SCREAMING_SNAKE_CASE_  ,						exist_ok=SCREAMING_SNAKE_CASE_      )

													if push_to_hub:
																			__UpperCamelCase  	=      kwargs.pop('''commit_message'''  ,						SCREAMING_SNAKE_CASE_      )
																			__UpperCamelCase  	=      kwargs.pop('''repo_id'''  ,						save_directory.split(os.path.sep      )[-1]      )
																			__UpperCamelCase  	=      self._create_repo(SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )
																			__UpperCamelCase  	=      self._get_files_timestamps(SCREAMING_SNAKE_CASE_      )
													# If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
													# loaded from the Hub.
													if self._auto_class is not None:
																			__UpperCamelCase  	=      [getattr(self  ,						SCREAMING_SNAKE_CASE_      ) for attribute_name in self.attributes]
																			__UpperCamelCase  	=      [(a.init_kwargs if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ) else a) for a in attrs]
																			custom_object_save(self  ,						SCREAMING_SNAKE_CASE_  ,						config=SCREAMING_SNAKE_CASE_      )

													for attribute_name in self.attributes:
																			__UpperCamelCase  	=      getattr(self  ,						SCREAMING_SNAKE_CASE_      )
																			# Include the processor class in the attribute config so this processor can then be reloaded with the
																			# `AutoProcessor` API.
																			if hasattr(SCREAMING_SNAKE_CASE_  ,						'''_set_processor_class'''      ):
																									attribute._set_processor_class(self.__class__.__name__      )
																			attribute.save_pretrained(SCREAMING_SNAKE_CASE_      )

													if self._auto_class is not None:
																			# We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
																			for attribute_name in self.attributes:
																									__UpperCamelCase  	=      getattr(self  ,						SCREAMING_SNAKE_CASE_      )
																									if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																															del attribute.init_kwargs["auto_map"]

													if push_to_hub:
																			self._upload_modified_files(
																			    SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_  ,						commit_message=SCREAMING_SNAKE_CASE_  ,						token=kwargs.get('''use_auth_token'''      )  ,						)



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_ = None  ,						SCREAMING_SNAKE_CASE_ = False  ,						SCREAMING_SNAKE_CASE_ = False  ,						SCREAMING_SNAKE_CASE_ = None  ,						SCREAMING_SNAKE_CASE_ = "main"  ,						**SCREAMING_SNAKE_CASE_  ,						)-> Any:





													'''simple docstring'''






													__UpperCamelCase  	=      cache_dir
													__UpperCamelCase  	=      force_download
													__UpperCamelCase  	=      local_files_only
													__UpperCamelCase  	=      revision

													__UpperCamelCase  	=      kwargs.pop('''use_auth_token'''  ,						SCREAMING_SNAKE_CASE_      )
													if use_auth_token is not None:
																			warnings.warn(
																			    '''The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.'''  ,						SCREAMING_SNAKE_CASE_      )
																			if token is not None:
																									raise ValueError(
																									    '''`token` and `use_auth_token` are both specified. Please set only the argument `token`.'''      )
																			__UpperCamelCase  	=      use_auth_token

													if token is not None:
																			# change to `token` in a follow-up PR
																			__UpperCamelCase  	=      token

													__UpperCamelCase  	=      cls._get_arguments_from_pretrained(SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )
													return cls(*SCREAMING_SNAKE_CASE_      )



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_="AutoProcessor"      )-> Optional[int]:





													'''simple docstring'''






													if not isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																			__UpperCamelCase  	=      auto_class.__name__

													import transformers.models.auto as auto_module

													if not hasattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																			raise ValueError(F"{auto_class} is not a valid auto class."      )

													__UpperCamelCase  	=      auto_class



							@classmethod
							def      A__		(	cls  ,						SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )-> Optional[int]:





													'''simple docstring'''






													__UpperCamelCase  	=      []
													for attribute_name in cls.attributes:
																			__UpperCamelCase  	=      getattr(cls  ,						F"{attribute_name}_class"      )
																			if isinstance(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ):
																									__UpperCamelCase  	=      tuple(getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      ) if n is not None else None for n in class_name      )
																									__UpperCamelCase  	=      kwargs.get('''use_fast'''  ,						SCREAMING_SNAKE_CASE_      )
																									if use_fast and classes[1] is not None:
																															__UpperCamelCase  	=      classes[1]
																									else:
																															__UpperCamelCase  	=      classes[0]
																			else:
																									__UpperCamelCase  	=      getattr(SCREAMING_SNAKE_CASE_  ,						SCREAMING_SNAKE_CASE_      )

																			args.append(attribute_class.from_pretrained(SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_      )      )
													return args



							@property
							def      A__		(	self      )-> Any:





													'''simple docstring'''






													__UpperCamelCase  	=      getattr(self  ,						self.attributes[0]      )
													return getattr(SCREAMING_SNAKE_CASE_  ,						'''model_input_names'''  ,						SCREAMING_SNAKE_CASE_      )





lowercase__				:				Any						=      copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
				lowercase__				:				str						=      ProcessorMixin.push_to_hub.__doc__.format(
				    object="processor", object_class="AutoProcessor", object_files="processor files"
				)







import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()





class      snake_case_      (					_a      ,			_a      ,			unittest.TestCase				):


							"""simple docstring"""





							__UpperCAmelCase      =StableDiffusionParadigmsPipeline
							__UpperCAmelCase      =TEXT_TO_IMAGE_PARAMS
							__UpperCAmelCase      =TEXT_TO_IMAGE_BATCH_PARAMS
							__UpperCAmelCase      =TEXT_TO_IMAGE_IMAGE_PARAMS
							__UpperCAmelCase      =TEXT_TO_IMAGE_IMAGE_PARAMS




							def 							A__	(			self				):
												torch.manual_seed(0				)
												__lowerCAmelCase       =				UNetaDConditionModel(
												    block_out_channels=(3_2, 6_4)       ,    layers_per_block=2       ,    sample_size=3_2       ,    in_channels=4       ,    out_channels=4       ,    down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')       ,    up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')       ,    cross_attention_dim=3_2       ,    attention_head_dim=(2, 4)       ,    use_linear_projection=_A       ,    )
												__lowerCAmelCase       =				DDIMParallelScheduler(
												    beta_start=0.0_0085       ,    beta_end=0.012       ,    beta_schedule='scaled_linear'       ,    clip_sample=_A       ,    set_alpha_to_one=_A       ,    )
												torch.manual_seed(0				)
												__lowerCAmelCase       =				AutoencoderKL(
												    block_out_channels=[3_2, 6_4]       ,    in_channels=3       ,    out_channels=3       ,    down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']       ,    up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']       ,    latent_channels=4       ,    sample_size=1_2_8       ,    )
												torch.manual_seed(0				)
												__lowerCAmelCase       =				CLIPTextConfig(
												    bos_token_id=0       ,    eos_token_id=2       ,    hidden_size=3_2       ,    intermediate_size=3_7       ,    layer_norm_eps=1e-0_5       ,    num_attention_heads=4       ,    num_hidden_layers=5       ,    pad_token_id=1       ,    vocab_size=1_0_0_0       ,    hidden_act='gelu'       ,    projection_dim=5_1_2       ,    )
												__lowerCAmelCase       =				CLIPTextModel(_A				)
												__lowerCAmelCase       =				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

												__lowerCAmelCase       =				{
												    'unet': unet,
												    'scheduler': scheduler,
												    'vae': vae,
												    'text_encoder': text_encoder,
												    'tokenizer': tokenizer,
												    'safety_checker': None,
												    'feature_extractor': None,
												}
												return components




							def 							A__	(			self       ,    _A       ,    _A=0				):
												if str(_A				).startswith('mps'				):
																	__lowerCAmelCase       =				torch.manual_seed(_A				)
												else:
																	__lowerCAmelCase       =				torch.Generator(device=_A				).manual_seed(_A				)
												__lowerCAmelCase       =				{
												    'prompt': 'a photograph of an astronaut riding a horse',
												    'generator': generator,
												    'num_inference_steps': 1_0,
												    'guidance_scale': 6.0,
												    'output_type': 'numpy',
												    'parallel': 3,
												    'debug': True,
												}
												return inputs




							def 							A__	(			self				):
												__lowerCAmelCase       =				'cpu'  # ensure determinism for the device-dependent torch.Generator
												__lowerCAmelCase       =				self.get_dummy_components()
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline(**_A				)
												__lowerCAmelCase       =				sd_pipe.to(_A				)
												sd_pipe.set_progress_bar_config(disable=_A				)

												__lowerCAmelCase       =				self.get_dummy_inputs(_A				)
												__lowerCAmelCase       =				sd_pipe(**_A				).images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1]
												assert image.shape == (1, 6_4, 6_4, 3)

												__lowerCAmelCase       =				np.array([0.4773, 0.5417, 0.4723, 0.4925, 0.5631, 0.4752, 0.5240, 0.4935, 0.5023]				)

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




							def 							A__	(			self				):
												__lowerCAmelCase       =				'cpu'  # ensure determinism for the device-dependent torch.Generator
												__lowerCAmelCase       =				self.get_dummy_components()
												torch.manual_seed(0				)
												__lowerCAmelCase       =				DDPMParallelScheduler()
												torch.manual_seed(0				)
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline(**_A				)
												__lowerCAmelCase       =				sd_pipe.to(_A				)
												sd_pipe.set_progress_bar_config(disable=_A				)

												__lowerCAmelCase       =				self.get_dummy_inputs(_A				)
												__lowerCAmelCase       =				sd_pipe(**_A				).images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1]
												assert image.shape == (1, 6_4, 6_4, 3)

												__lowerCAmelCase       =				np.array([0.3573, 0.4420, 0.4960, 0.4799, 0.3796, 0.3879, 0.4819, 0.4365, 0.4468]				)

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




							def 							A__	(			self				):
												super().test_inference_batch_consistent(batch_sizes=[1, 2]				)




							def 							A__	(			self				):
												super().test_inference_batch_single_identical(batch_size=2       ,    expected_max_diff=3e-3				)




							def 							A__	(			self				):
												__lowerCAmelCase       =				'cpu'  # ensure determinism for the device-dependent torch.Generator
												__lowerCAmelCase       =				self.get_dummy_components()
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline(**_A				)
												__lowerCAmelCase       =				sd_pipe.to(_A				)
												sd_pipe.set_progress_bar_config(disable=_A				)

												__lowerCAmelCase       =				self.get_dummy_inputs(_A				)
												__lowerCAmelCase       =				'french fries'
												__lowerCAmelCase       =				sd_pipe(**_A       ,    negative_prompt=_A				)
												__lowerCAmelCase       =				output.images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1]

												assert image.shape == (1, 6_4, 6_4, 3)

												__lowerCAmelCase       =				np.array([0.4771, 0.5420, 0.4683, 0.4918, 0.5636, 0.4725, 0.5230, 0.4923, 0.5015]				)

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





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


							"""simple docstring"""





							def 							A__	(			self				):
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()




							def 							A__	(			self       ,    _A=0				):
												__lowerCAmelCase       =				torch.Generator(device=_A				).manual_seed(_A				)
												__lowerCAmelCase       =				{
												    'prompt': 'a photograph of an astronaut riding a horse',
												    'generator': generator,
												    'num_inference_steps': 1_0,
												    'guidance_scale': 7.5,
												    'output_type': 'numpy',
												    'parallel': 3,
												    'debug': True,
												}
												return inputs




							def 							A__	(			self				):
												__lowerCAmelCase       =				'stabilityai/stable-diffusion-2-base'
												__lowerCAmelCase       =				DDIMParallelScheduler.from_pretrained(_A       ,    subfolder='scheduler'				)
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline.from_pretrained(_A       ,    scheduler=_A       ,    safety_checker=_A				)
												pipe.to(_A				)
												pipe.set_progress_bar_config(disable=_A				)
												pipe.enable_attention_slicing()

												__lowerCAmelCase       =				self.get_inputs()
												__lowerCAmelCase       =				pipe(**_A				).images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 5_1_2, 5_1_2, 3)

												__lowerCAmelCase       =				np.array([0.9622, 0.9602, 0.9748, 0.9591, 0.9630, 0.9691, 0.9661, 0.9631, 0.9741]				)

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






