





'''simple docstring'''

import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


__lowerCAmelCase							:	str			=logging.get_logger(__name__)  # pylint: disable=invalid-name






class    UpperCAmelCase	(       UpperCamelCase__				):
 def __init__(				self      :List[str]						,       lowercase_      :WhisperForConditionalGeneration						,       lowercase_      :WhisperProcessor						,       lowercase_      :AutoencoderKL						,       lowercase_      :CLIPTextModel						,       lowercase_      :CLIPTokenizer						,       lowercase_      :UNetaDConditionModel						,       lowercase_      :Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]						,       lowercase_      :StableDiffusionSafetyChecker						,       lowercase_      :CLIPImageProcessor						,       )->							int:
     super().__init__()

     if safety_checker is None:
         logger.warning(
             F"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
             " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
             " results in services or applications open to the public. Both the diffusers team and Hugging Face"
             " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
             " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
             " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."							)

     self.register_modules(
         speech_model=lowercase_						,       speech_processor=lowercase_						,       vae=lowercase_						,       text_encoder=lowercase_						,       tokenizer=lowercase_						,       unet=lowercase_						,       scheduler=lowercase_						,       feature_extractor=lowercase_						,       )
 def      UpperCAmelCase_							(				self      :List[str]						,       lowercase_      :Optional[Union[str, int]] = "auto"							)->							List[str]:
     if slice_size == "auto":
         A__				=			self.unet.config.attention_head_dim // 2
     self.unet.set_attention_slice(lowercase_							)
 def      UpperCAmelCase_							(				self      :Union[str, Any]							)->							Optional[int]:
     self.enable_attention_slicing(lowercase_							)



 @torch.no_grad()
 def __call__(				self      :Any						,       lowercase_      :Optional[Any]						,       lowercase_      :str=1_60_00						,       lowercase_      :int = 5_12						,       lowercase_      :int = 5_12						,       lowercase_      :int = 50						,       lowercase_      :float = 7.5						,       lowercase_      :Optional[Union[str, List[str]]] = None						,       lowercase_      :Optional[int] = 1						,       lowercase_      :float = 0.0						,       lowercase_      :Optional[torch.Generator] = None						,       lowercase_      :Optional[torch.FloatTensor] = None						,       lowercase_      :Optional[str] = "pil"						,       lowercase_      :bool = True						,       lowercase_      :Optional[Callable[[int, int, torch.FloatTensor], None]] = None						,       lowercase_      :int = 1						,       **lowercase_      :Dict						,       )->							Any:
     A__				=			self.speech_processor.feature_extractor(
         lowercase_						,       return_tensors="pt"						,       sampling_rate=lowercase_							).input_features.to(self.device							)
     A__				=			self.speech_model.generate(lowercase_						,       max_length=48_00_00							)

     A__				=			self.speech_processor.tokenizer.batch_decode(lowercase_						,       skip_special_tokens=lowercase_						,       normalize=lowercase_							)[
         0
     ]

     if isinstance(lowercase_						,       lowercase_							):
         A__				=			1
     elif isinstance(lowercase_						,       lowercase_							):
         A__				=			len(lowercase_							)
     else:
         raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowercase_							)}"							)

     if height % 8 != 0 or width % 8 != 0:
         raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}."							)

     if (callback_steps is None) or (
         callback_steps is not None and (not isinstance(lowercase_						,       lowercase_							) or callback_steps <= 0)
     ):
         raise ValueError(
             F"`callback_steps` has to be a positive integer but is {callback_steps} of type"
             F" {type(lowercase_							)}."							)

     # get prompt text embeddings
     A__				=			self.tokenizer(
         lowercase_						,       padding="max_length"						,       max_length=self.tokenizer.model_max_length						,       return_tensors="pt"						,       )
     A__				=			text_inputs.input_ids

     if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
         A__				=			self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]							)
         logger.warning(
             "The following part of your input was truncated because CLIP can only handle sequences up to"
             F" {self.tokenizer.model_max_length} tokens: {removed_text}"							)
         A__				=			text_input_ids[:, : self.tokenizer.model_max_length]
     A__				=			self.text_encoder(text_input_ids.to(self.device							)							)[0]

     # duplicate text embeddings for each generation per prompt, using mps friendly method
     A__,	A__,	A__				=			text_embeddings.shape
     A__				=			text_embeddings.repeat(1						,       lowercase_						,       1							)
     A__				=			text_embeddings.view(bs_embed * num_images_per_prompt						,       lowercase_						,       -1							)

     # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
     # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
     # corresponds to doing no classifier free guidance.
     A__				=			guidance_scale > 1.0
     # get unconditional embeddings for classifier free guidance
     if do_classifier_free_guidance:
         A__				=			42
         if negative_prompt is None:
             A__				=			[""] * batch_size
         elif type(lowercase_							) is not type(lowercase_							):
             raise TypeError(
                 F"`negative_prompt` should be the same type to `prompt`, but got {type(lowercase_							)} !="
                 F" {type(lowercase_							)}."							)
         elif isinstance(lowercase_						,       lowercase_							):
             A__				=			[negative_prompt]
         elif batch_size != len(lowercase_							):
             raise ValueError(
                 F"`negative_prompt`: {negative_prompt} has batch size {len(lowercase_							)}, but `prompt`:"
                 F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                 " the batch size of `prompt`."							)
         else:
             A__				=			negative_prompt

         A__				=			text_input_ids.shape[-1]
         A__				=			self.tokenizer(
             lowercase_						,       padding="max_length"						,       max_length=lowercase_						,       truncation=lowercase_						,       return_tensors="pt"						,       )
         A__				=			self.text_encoder(uncond_input.input_ids.to(self.device							)							)[0]

         # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
         A__				=			uncond_embeddings.shape[1]
         A__				=			uncond_embeddings.repeat(1						,       lowercase_						,       1							)
         A__				=			uncond_embeddings.view(batch_size * num_images_per_prompt						,       lowercase_						,       -1							)

         # For classifier free guidance, we need to do two forward passes.
         # Here we concatenate the unconditional and text embeddings into a single batch
         # to avoid doing two forward passes
         A__				=			torch.cat([uncond_embeddings, text_embeddings]							)

     # get the initial random noise unless the user supplied it

     # Unlike in other pipelines, latents need to be generated in the target device
     # for 1-to-1 results reproducibility with the CompVis implementation.
     # However this currently doesn't work in `mps`.
     A__				=			(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
     A__				=			text_embeddings.dtype
     if latents is None:
         if self.device.type == "mps":
             # randn does not exist on mps
             A__				=			torch.randn(lowercase_						,       generator=lowercase_						,       device="cpu"						,       dtype=lowercase_							).to(
                 self.device							)
         else:
             A__				=			torch.randn(lowercase_						,       generator=lowercase_						,       device=self.device						,       dtype=lowercase_							)
     else:
         if latents.shape != latents_shape:
             raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"							)
         A__				=			latents.to(self.device							)

     # set timesteps
     self.scheduler.set_timesteps(lowercase_							)

     # Some schedulers like PNDM have timesteps as arrays
     # It's more optimized to move all timesteps to correct device beforehand
     A__				=			self.scheduler.timesteps.to(self.device							)

     # scale the initial noise by the standard deviation required by the scheduler
     A__				=			latents * self.scheduler.init_noise_sigma

     # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
     # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
     # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
     # and should be between [0, 1]
     A__				=			"eta" in set(inspect.signature(self.scheduler.step							).parameters.keys()							)
     A__				=			{}
     if accepts_eta:
         A__				=			eta

     for i, t in enumerate(self.progress_bar(lowercase_							)							):
         # expand the latents if we are doing classifier free guidance
         A__				=			torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
         A__				=			self.scheduler.scale_model_input(lowercase_						,       lowercase_							)

         # predict the noise residual
         A__				=			self.unet(lowercase_						,       lowercase_						,       encoder_hidden_states=lowercase_							).sample

         # perform guidance
         if do_classifier_free_guidance:
             A__,	A__				=			noise_pred.chunk(2							)
             A__				=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

         # compute the previous noisy sample x_t -> x_t-1
         A__				=			self.scheduler.step(lowercase_						,       lowercase_						,       lowercase_						,       **lowercase_							).prev_sample

         # call the callback, if provided
         if callback is not None and i % callback_steps == 0:
             callback(lowercase_						,       lowercase_						,       lowercase_							)

     A__				=			1 / 0.1_8_2_1_5 * latents
     A__				=			self.vae.decode(lowercase_							).sample

     A__				=			(image / 2 + 0.5).clamp(0						,       1							)

     # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
     A__				=			image.cpu().permute(0						,       2						,       3						,       1							).float().numpy()

     if output_type == "pil":
         A__				=			self.numpy_to_pil(lowercase_							)

     if not return_dict:
         return image

     return StableDiffusionPipelineOutput(images=lowercase_						,       nsfw_content_detected=lowercase_							)










'''simple docstring'''

import os
import re
import shutil
import sys
import tempfile
import unittest

import black


__lowerCAmelCase							:	Any			=os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
__lowerCAmelCase							:	Optional[int]			="    def __init__(self, config):\n        super().__init__()\n        self.transform = BertPredictionHeadTransform(config)\n\n        # The output weights are the same as the input embeddings, but there is\n        # an output-only bias for each token.\n        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n        self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n        self.decoder.bias = self.bias\n\n    def forward(self, hidden_states):\n        hidden_states = self.transform(hidden_states)\n        hidden_states = self.decoder(hidden_states)\n        return hidden_states\n"






class    UpperCAmelCase	(       unittest.TestCase				):
 def      UpperCAmelCase_							(				self      :Tuple							)->							Union[str, Any]:
     A__				=			tempfile.mkdtemp()
     os.makedirs(os.path.join(self.transformer_dir						,       "models/bert/"							)							)
     A__				=			self.transformer_dir
     shutil.copy(
         os.path.join(lowercase_						,       "src/transformers/models/bert/modeling_bert.py"							)						,       os.path.join(self.transformer_dir						,       "models/bert/modeling_bert.py"							)						,       )
 def      UpperCAmelCase_							(				self      :Optional[int]							)->							Tuple:
     A__				=			"src/transformers"
     shutil.rmtree(self.transformer_dir							)
 def      UpperCAmelCase_							(				self      :List[Any]						,       lowercase_      :List[str]						,       lowercase_      :Union[str, Any]						,       lowercase_      :int						,       lowercase_      :Tuple=None							)->							Optional[Any]:
     A__				=			comment + F"\nclass {class_name}(nn.Module):\n" + class_code
     if overwrite_result is not None:
         A__				=			comment + F"\nclass {class_name}(nn.Module):\n" + overwrite_result
     A__				=			black.Mode(target_versions={black.TargetVersion.PYaa}						,       line_length=1_19							)
     A__				=			black.format_str(lowercase_						,       mode=lowercase_							)
     A__				=			os.path.join(self.transformer_dir						,       "new_code.py"							)
     with open(lowercase_						,       "w"						,       newline="\n"							) as f:
         f.write(lowercase_							)
     if overwrite_result is None:
         self.assertTrue(len(check_copies.is_copy_consistent(lowercase_							)							) == 0							)
     else:
         check_copies.is_copy_consistent(f.name						,       overwrite=lowercase_							)
         with open(lowercase_						,       "r"							) as f:
             self.assertTrue(f.read()						,       lowercase_							)
 def      UpperCAmelCase_							(				self      :str							)->							Optional[Any]:
     A__				=			check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead"							)
     self.assertEqual(lowercase_						,       lowercase_							)
 def      UpperCAmelCase_							(				self      :List[str]							)->							Optional[int]:
     # Base copy consistency
     self.check_copy_consistency(
         "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"						,       "BertLMPredictionHead"						,       REFERENCE_CODE + "\n"						,       )

     # With no empty line at the end
     self.check_copy_consistency(
         "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"						,       "BertLMPredictionHead"						,       lowercase_						,       )

     # Copy consistency with rename
     self.check_copy_consistency(
         "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"						,       "TestModelLMPredictionHead"						,       re.sub("Bert"						,       "TestModel"						,       lowercase_							)						,       )

     # Copy consistency with a really long name
     A__				=			"TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"
     self.check_copy_consistency(
         F"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}"						,       F"{long_class_name}LMPredictionHead"						,       re.sub("Bert"						,       lowercase_						,       lowercase_							)						,       )

     # Copy consistency with overwrite
     self.check_copy_consistency(
         "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"						,       "TestModelLMPredictionHead"						,       lowercase_						,       overwrite_result=re.sub("Bert"						,       "TestModel"						,       lowercase_							)						,       )



 def      UpperCAmelCase_							(				self      :Dict							)->							Any:
     A__				=			check_copies.LOCALIZED_READMES["README_zh-hans.md"]

     A__				=			(
         "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
         " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
         " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
         " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."
         " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"
         " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
         " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"
         " method has been applied to compress GPT2 into"
         " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
         " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
         " Multilingual BERT into"
         " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
         " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"
         " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"
         " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"
         " Luong, Quoc V. Le, Christopher D. Manning."
     )
     A__				=			(
         "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
         " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
         " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
         " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
     )
     A__				=			(
         "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
         " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
         " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
         " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."
         " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"
         " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
         " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"
         " method has been applied to compress GPT2 into"
         " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
         " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
         " Multilingual BERT into"
         " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
         " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"
         " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"
         " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"
         " Christopher D. Manning 发布。\n"
     )

     A__,	A__				=			check_copies.convert_to_localized_md(
         lowercase_						,       lowercase_						,       localized_readme["format_model_list"]							)

     self.assertFalse(lowercase_							)
     self.assertEqual(lowercase_						,       lowercase_							)

     A__,	A__				=			check_copies.convert_to_localized_md(
         lowercase_						,       lowercase_						,       localized_readme["format_model_list"]							)

     # Check whether the number of models is equal to README.md after conversion.
     self.assertTrue(lowercase_							)

     A__				=			(
         "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
         " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
         " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
         " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
     )
     A__				=			(
         "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"
         " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
         " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
         " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
     )
     A__				=			(
         "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
         " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
         " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
         " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
     )

     A__,	A__				=			check_copies.convert_to_localized_md(
         lowercase_						,       lowercase_						,       localized_readme["format_model_list"]							)

     # Check if the model link is synchronized.
     self.assertEqual(lowercase_						,       lowercase_							)



