


'''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


A__:    Union[str, Any]					    =       logging.get_logger(__name__)  # pylint: disable=invalid-name







class A__       (						UpperCAmelCase__      ):






      def __init__( self			:List[Any]     ,						SCREAMING_SNAKE_CASE			:WhisperForConditionalGeneration     ,						SCREAMING_SNAKE_CASE			:WhisperProcessor     ,						SCREAMING_SNAKE_CASE			:AutoencoderKL     ,						SCREAMING_SNAKE_CASE			:CLIPTextModel     ,						SCREAMING_SNAKE_CASE			:CLIPTokenizer     ,						SCREAMING_SNAKE_CASE			:UNetaDConditionModel     ,						SCREAMING_SNAKE_CASE			:Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]     ,						SCREAMING_SNAKE_CASE			:StableDiffusionSafetyChecker     ,						SCREAMING_SNAKE_CASE			:CLIPImageProcessor     ,						)       ->					Any:




             '''simple docstring'''
             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=SCREAMING_SNAKE_CASE     ,						speech_processor=SCREAMING_SNAKE_CASE     ,						vae=SCREAMING_SNAKE_CASE     ,						text_encoder=SCREAMING_SNAKE_CASE     ,						tokenizer=SCREAMING_SNAKE_CASE     ,						unet=SCREAMING_SNAKE_CASE     ,						scheduler=SCREAMING_SNAKE_CASE     ,						feature_extractor=SCREAMING_SNAKE_CASE     ,						)






      def __UpperCAmelCase       ( self			:str     ,						SCREAMING_SNAKE_CASE			:Optional[Union[str, int]] = "auto"	)       ->					List[str]:




             '''simple docstring'''
             if slice_size == "auto":
                    _a    : int     					=self.unet.config.attention_head_dim // 2
             self.unet.set_attention_slice(SCREAMING_SNAKE_CASE	)






      def __UpperCAmelCase       ( self			:Tuple	)       ->					List[str]:




             '''simple docstring'''
             self.enable_attention_slicing(SCREAMING_SNAKE_CASE	)






      @torch.no_grad()
      def __call__( self			:List[Any]     ,						SCREAMING_SNAKE_CASE			:int     ,						SCREAMING_SNAKE_CASE			:List[str]=1_6_0_0_0     ,						SCREAMING_SNAKE_CASE			:int = 5_1_2     ,						SCREAMING_SNAKE_CASE			:int = 5_1_2     ,						SCREAMING_SNAKE_CASE			:int = 5_0     ,						SCREAMING_SNAKE_CASE			:float = 7.5     ,						SCREAMING_SNAKE_CASE			:Optional[Union[str, List[str]]] = None     ,						SCREAMING_SNAKE_CASE			:Optional[int] = 1     ,						SCREAMING_SNAKE_CASE			:float = 0.0     ,						SCREAMING_SNAKE_CASE			:Optional[torch.Generator] = None     ,						SCREAMING_SNAKE_CASE			:Optional[torch.FloatTensor] = None     ,						SCREAMING_SNAKE_CASE			:Optional[str] = "pil"     ,						SCREAMING_SNAKE_CASE			:bool = True     ,						SCREAMING_SNAKE_CASE			:Optional[Callable[[int, int, torch.FloatTensor], None]] = None     ,						SCREAMING_SNAKE_CASE			:int = 1     ,						**SCREAMING_SNAKE_CASE			:int     ,						)       ->					Optional[Any]:




             '''simple docstring'''
             _a    : Union[str, Any]     					=self.speech_processor.feature_extractor(
                 SCREAMING_SNAKE_CASE     ,						return_tensors="""pt"""     ,						sampling_rate=SCREAMING_SNAKE_CASE	).input_features.to(self.device	)
             _a    : Any     					=self.speech_model.generate(SCREAMING_SNAKE_CASE     ,						max_length=4_8_0_0_0_0	)

             _a    : Dict     					=self.speech_processor.tokenizer.batch_decode(SCREAMING_SNAKE_CASE     ,						skip_special_tokens=SCREAMING_SNAKE_CASE     ,						normalize=SCREAMING_SNAKE_CASE	)[
                 0
             ]

             if isinstance(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	):
                    _a    : List[Any]     					=1
             elif isinstance(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	):
                    _a    : Union[str, Any]     					=len(SCREAMING_SNAKE_CASE	)
             else:
                    raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE	)}"	)

             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(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	) or callback_steps <= 0)
             ):
                    raise ValueError(
                        f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
                        f" {type(SCREAMING_SNAKE_CASE	)}."	)

             # get prompt text embeddings
             _a    : Dict     					=self.tokenizer(
                 SCREAMING_SNAKE_CASE     ,						padding="""max_length"""     ,						max_length=self.tokenizer.model_max_length     ,						return_tensors="""pt"""     ,						)
             _a    : Union[str, Any]     					=text_inputs.input_ids

             if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
                    _a    : Union[str, Any]     					=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    : str     					=text_input_ids[:, : self.tokenizer.model_max_length]
             _a    : Dict     					=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    : Any     					=text_embeddings.shape
             _a    : str     					=text_embeddings.repeat(1     ,						SCREAMING_SNAKE_CASE     ,						1	)
             _a    : List[Any]     					=text_embeddings.view(bs_embed * num_images_per_prompt     ,						SCREAMING_SNAKE_CASE     ,						-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    : List[Any]     					=guidance_scale > 1.0
             # get unconditional embeddings for classifier free guidance
             if do_classifier_free_guidance:
                    _a    : List[str]
                    if negative_prompt is None:
                           _a    : str     					=[""""""] * batch_size
                    elif type(SCREAMING_SNAKE_CASE	) is not type(SCREAMING_SNAKE_CASE	):
                           raise TypeError(
                               f"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE	)} !="
                               f" {type(SCREAMING_SNAKE_CASE	)}."	)
                    elif isinstance(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	):
                           _a    : List[Any]     					=[negative_prompt]
                    elif batch_size != len(SCREAMING_SNAKE_CASE	):
                           raise ValueError(
                               f"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE	)}, but `prompt`:"
                               f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                               """ the batch size of `prompt`."""	)
                    else:
                           _a    : int     					=negative_prompt

                    _a    : Tuple     					=text_input_ids.shape[-1]
                    _a    : List[Any]     					=self.tokenizer(
                        SCREAMING_SNAKE_CASE     ,						padding="""max_length"""     ,						max_length=SCREAMING_SNAKE_CASE     ,						truncation=SCREAMING_SNAKE_CASE     ,						return_tensors="""pt"""     ,						)
                    _a    : Tuple     					=self.text_encoder(uncond_input.input_ids.to(self.device	)	)[0]

                    # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
                    _a    : Dict     					=uncond_embeddings.shape[1]
                    _a    : Tuple     					=uncond_embeddings.repeat(1     ,						SCREAMING_SNAKE_CASE     ,						1	)
                    _a    : Tuple     					=uncond_embeddings.view(batch_size * num_images_per_prompt     ,						SCREAMING_SNAKE_CASE     ,						-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    : Optional[Any]     					=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    : List[Any]     					=(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
             _a    : Tuple     					=text_embeddings.dtype
             if latents is None:
                    if self.device.type == "mps":
                           # randn does not exist on mps
                           _a    : List[Any]     					=torch.randn(SCREAMING_SNAKE_CASE     ,						generator=SCREAMING_SNAKE_CASE     ,						device="""cpu"""     ,						dtype=SCREAMING_SNAKE_CASE	).to(
                               self.device	)
                    else:
                           _a    : str     					=torch.randn(SCREAMING_SNAKE_CASE     ,						generator=SCREAMING_SNAKE_CASE     ,						device=self.device     ,						dtype=SCREAMING_SNAKE_CASE	)
             else:
                    if latents.shape != latents_shape:
                           raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"	)
                    _a    : Tuple     					=latents.to(self.device	)

             # set timesteps
             self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE	)

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

             # scale the initial noise by the standard deviation required by the scheduler
             _a    : List[str]     					=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    : Optional[Any]     					="""eta""" in set(inspect.signature(self.scheduler.step	).parameters.keys()	)
             _a    : Optional[int]     					={}
             if accepts_eta:
                    _a    : Optional[int]     					=eta

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

                    # predict the noise residual
                    _a    : Optional[Any]     					=self.unet(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						encoder_hidden_states=SCREAMING_SNAKE_CASE	).sample

                    # perform guidance
                    if do_classifier_free_guidance:
                           _a					,    _a    : Tuple     					=noise_pred.chunk(2	)
                           _a    : Optional[Any]     					=noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

                    # compute the previous noisy sample x_t -> x_t-1
                    _a    : Union[str, Any]     					=self.scheduler.step(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						**SCREAMING_SNAKE_CASE	).prev_sample

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

             _a    : Tuple     					=1 / 0.18_215 * latents
             _a    : Union[str, Any]     					=self.vae.decode(SCREAMING_SNAKE_CASE	).sample

             _a    : int     					=(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    : List[str]     					=image.cpu().permute(0     ,						2     ,						3     ,						1	).float().numpy()

             if output_type == "pil":
                    _a    : Optional[Any]     					=self.numpy_to_pil(SCREAMING_SNAKE_CASE	)

             if not return_dict:
                    return image

             return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE     ,						nsfw_content_detected=SCREAMING_SNAKE_CASE	)






'''simple docstring'''







import pytest

from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs


@pytest.mark.parametrize(
    """kwargs, expected"""    ,[
        ({"""num_shards""": 0, """max_num_jobs""": 1}, []),
        ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10  )]),
        ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase    ,i + 1  ) for i in range(10  )]),
        ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1  )]),
        ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0    ,4  ), range(4    ,7  ), range(7    ,10  )]),
        ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0    ,1  ), range(1    ,2  ), range(2    ,3  )]),
    ]    ,)
def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Union[str, Any]    ,_UpperCAmelCase	:	Dict  )  ->			Optional[Any]:
       _a    : Tuple     					=_distribute_shards(**_UpperCAmelCase  )
       assert out == expected


@pytest.mark.parametrize(
    """gen_kwargs, max_num_jobs, expected"""    ,[
        ({"""foo""": 0}, 10, [{"""foo""": 0}]),
        ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]),
        ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]),
        ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]),
        ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]),
    ]    ,)
def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	List[Any]    ,_UpperCAmelCase	:	Union[str, Any]  )  ->			List[str]:
       _a    : List[str]     					=_split_gen_kwargs(_UpperCAmelCase    ,_UpperCAmelCase  )
       assert out == expected


@pytest.mark.parametrize(
    """gen_kwargs, expected"""    ,[
        ({"""foo""": 0}, 1),
        ({"""shards""": [0]}, 1),
        ({"""shards""": [0, 1, 2, 3]}, 4),
        ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4),
        ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4),
        ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError),
    ]    ,)
def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Optional[Any]    ,_UpperCAmelCase	:	List[Any]  )  ->			Union[str, Any]:
       if expected is RuntimeError:
              with pytest.raises(_UpperCAmelCase  ):
                     _number_of_shards_in_gen_kwargs(_UpperCAmelCase  )
       else:
              _a    : Dict     					=_number_of_shards_in_gen_kwargs(_UpperCAmelCase  )
              assert out == expected


