



from typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


_lowerCamelCase   :				Dict     			=						logging.get_logger(__name__)  # pylint: disable=invalid-name


class   lowercase      (       a__       ):




							def __init__(  self				:   Optional[int]		,							_UpperCamelCase				:   int		,							_UpperCamelCase				:   int		,							_UpperCamelCase				:   int		,							_UpperCamelCase				:   Tuple		,							_UpperCamelCase				:   Optional[Any]		,							_UpperCamelCase				:   Tuple		,							_UpperCamelCase				:   Dict		,							_UpperCamelCase				:   int		,							_UpperCamelCase				:   int		,							)   ->			Union[str, Any]:



												'''simple docstring'''

												super().__init__()

												if hasattr(scheduler.config		,							"steps_offset" ) and scheduler.config.steps_offset != 1:
																	SCREAMING_SNAKE_CASE           =    (
																	    F"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
																	    F" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
																	    '''to update the config accordingly as leaving `steps_offset` might led to incorrect results'''
																	    ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'''
																	    ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'''
																	    ''' file'''
																	)
																	deprecate("steps_offset!=1"		,							"1.0.0"		,							_lowerCamelCase		,							standard_warn=_lowerCamelCase )
																	SCREAMING_SNAKE_CASE           =    dict(scheduler.config )
																	SCREAMING_SNAKE_CASE           =    1
																	SCREAMING_SNAKE_CASE           =    FrozenDict(_lowerCamelCase )

												if hasattr(scheduler.config		,							"skip_prk_steps" ) and scheduler.config.skip_prk_steps is False:
																	SCREAMING_SNAKE_CASE           =    (
																	    F"The configuration file of this scheduler: {scheduler} has not set the configuration"
																	    ''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make'''
																	    ''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to'''
																	    ''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face'''
																	    ''' Hub, it would be very nice if you could open a Pull request for the'''
																	    ''' `scheduler/scheduler_config.json` file'''
																	)
																	deprecate("skip_prk_steps not set"		,							"1.0.0"		,							_lowerCamelCase		,							standard_warn=_lowerCamelCase )
																	SCREAMING_SNAKE_CASE           =    dict(scheduler.config )
																	SCREAMING_SNAKE_CASE           =    True
																	SCREAMING_SNAKE_CASE           =    FrozenDict(_lowerCamelCase )

												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(
												    segmentation_model=_lowerCamelCase		,							segmentation_processor=_lowerCamelCase		,							vae=_lowerCamelCase		,							text_encoder=_lowerCamelCase		,							tokenizer=_lowerCamelCase		,							unet=_lowerCamelCase		,							scheduler=_lowerCamelCase		,							safety_checker=_lowerCamelCase		,							feature_extractor=_lowerCamelCase		,							)




							def 		__snake_case(  self				:   Optional[Any]		,							_UpperCamelCase				:   List[Any] = "auto" )   ->			Dict:



												'''simple docstring'''

												if slice_size == "auto":
																	# half the attention head size is usually a good trade-off between
																	# speed and memory
																	SCREAMING_SNAKE_CASE           =    self.unet.config.attention_head_dim // 2
												self.unet.set_attention_slice(_lowerCamelCase )




							def 		__snake_case(  self				:   Dict )   ->			Optional[int]:



												'''simple docstring'''

												self.enable_attention_slicing(_lowerCamelCase )




							def 		__snake_case(  self				:   Dict )   ->			List[str]:



												'''simple docstring'''

												if is_accelerate_available():
																	from accelerate import cpu_offload
												else:
																	raise ImportError("Please install accelerate via `pip install accelerate`" )

												SCREAMING_SNAKE_CASE           =    torch.device("cuda" )

												for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
																	if cpu_offloaded_model is not None:
																						cpu_offload(_lowerCamelCase		,							_lowerCamelCase )




							@property
							# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
							def 		__snake_case(  self				:   List[Any] )   ->			Union[str, Any]:



												'''simple docstring'''

												if self.device != torch.device("meta" ) or not hasattr(self.unet		,							"_hf_hook" ):
																	return self.device
												for module in self.unet.modules():
																	if (
																	    hasattr(_lowerCamelCase		,							"_hf_hook" )
																	    and hasattr(module._hf_hook		,							"execution_device" )
																	    and module._hf_hook.execution_device is not None
																	):
																						return torch.device(module._hf_hook.execution_device )
												return self.device





							@torch.no_grad()
							def __call__(  self				:   int		,							_UpperCamelCase				:   List[Any]		,							_UpperCamelCase				:   Tuple		,							_UpperCamelCase				:   List[str]		,							_UpperCamelCase				:   List[str] = 512		,							_UpperCamelCase				:   Union[str, Any] = 512		,							_UpperCamelCase				:   Optional[Any] = 50		,							_UpperCamelCase				:   Union[str, Any] = 7.5		,							_UpperCamelCase				:   List[str] = None		,							_UpperCamelCase				:   Dict = 1		,							_UpperCamelCase				:   Tuple = 0.0		,							_UpperCamelCase				:   Tuple = None		,							_UpperCamelCase				:   Optional[Any] = None		,							_UpperCamelCase				:   Any = "pil"		,							_UpperCamelCase				:   Tuple = True		,							_UpperCamelCase				:   Union[str, Any] = None		,							_UpperCamelCase				:   int = 1		,							**_UpperCamelCase				:   Tuple		,							)   ->			Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    self.segmentation_processor(
												    text=[text]		,							images=[image]		,							padding="max_length"		,							return_tensors="pt" ).to(self.device )
												SCREAMING_SNAKE_CASE           =    self.segmentation_model(**_lowerCamelCase )
												SCREAMING_SNAKE_CASE           =    torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy()
												SCREAMING_SNAKE_CASE           =    self.numpy_to_pil(_lowerCamelCase )[0].resize(image.size )

												# Run inpainting pipeline with the generated mask
												SCREAMING_SNAKE_CASE           =    StableDiffusionInpaintPipeline(
												    vae=self.vae		,							text_encoder=self.text_encoder		,							tokenizer=self.tokenizer		,							unet=self.unet		,							scheduler=self.scheduler		,							safety_checker=self.safety_checker		,							feature_extractor=self.feature_extractor		,							)
												return inpainting_pipeline(
												    prompt=_lowerCamelCase		,							image=_lowerCamelCase		,							mask_image=_lowerCamelCase		,							height=_lowerCamelCase		,							width=_lowerCamelCase		,							num_inference_steps=_lowerCamelCase		,							guidance_scale=_lowerCamelCase		,							negative_prompt=_lowerCamelCase		,							num_images_per_prompt=_lowerCamelCase		,							eta=_lowerCamelCase		,							generator=_lowerCamelCase		,							latents=_lowerCamelCase		,							output_type=_lowerCamelCase		,							return_dict=_lowerCamelCase		,							callback=_lowerCamelCase		,							callback_steps=_lowerCamelCase		,							)





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase   :				int     			=						logging.get_logger(__name__)

_lowerCamelCase   :				Union[str, Any]     			=						{
    '''microsoft/unispeech-sat-base-100h-libri-ft''': (
        '''https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'''
    ),
    # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}


class   lowercase      (       a       ):
							lowercase__  :    Tuple									=							"""unispeech-sat"""




							def __init__(  self				:   str		,							_UpperCamelCase				:   Tuple=32		,							_UpperCamelCase				:   Union[str, Any]=768		,							_UpperCamelCase				:   Tuple=12		,							_UpperCamelCase				:   List[str]=12		,							_UpperCamelCase				:   Tuple=3_072		,							_UpperCamelCase				:   List[str]="gelu"		,							_UpperCamelCase				:   Tuple=0.1		,							_UpperCamelCase				:   Any=0.1		,							_UpperCamelCase				:   Union[str, Any]=0.1		,							_UpperCamelCase				:   Dict=0.0		,							_UpperCamelCase				:   Tuple=0.0		,							_UpperCamelCase				:   Tuple=0.1		,							_UpperCamelCase				:   Optional[Any]=0.1		,							_UpperCamelCase				:   Tuple=0.0_2		,							_UpperCamelCase				:   Optional[int]=1e-5		,							_UpperCamelCase				:   Union[str, Any]="group"		,							_UpperCamelCase				:   Optional[int]="gelu"		,							_UpperCamelCase				:   Tuple=(512, 512, 512, 512, 512, 512, 512)		,							_UpperCamelCase				:   List[str]=(5, 2, 2, 2, 2, 2, 2)		,							_UpperCamelCase				:   Optional[int]=(10, 3, 3, 3, 3, 2, 2)		,							_UpperCamelCase				:   Optional[int]=False		,							_UpperCamelCase				:   Dict=128		,							_UpperCamelCase				:   Optional[int]=16		,							_UpperCamelCase				:   Tuple=False		,							_UpperCamelCase				:   Union[str, Any]=True		,							_UpperCamelCase				:   Optional[Any]=0.0_5		,							_UpperCamelCase				:   Union[str, Any]=10		,							_UpperCamelCase				:   Union[str, Any]=2		,							_UpperCamelCase				:   str=0.0		,							_UpperCamelCase				:   List[Any]=10		,							_UpperCamelCase				:   Optional[int]=0		,							_UpperCamelCase				:   Any=320		,							_UpperCamelCase				:   List[Any]=2		,							_UpperCamelCase				:   str=0.1		,							_UpperCamelCase				:   str=100		,							_UpperCamelCase				:   int=256		,							_UpperCamelCase				:   Optional[Any]=256		,							_UpperCamelCase				:   List[Any]=0.1		,							_UpperCamelCase				:   str="mean"		,							_UpperCamelCase				:   int=False		,							_UpperCamelCase				:   Optional[Any]=False		,							_UpperCamelCase				:   Any=256		,							_UpperCamelCase				:   str=(512, 512, 512, 512, 1_500)		,							_UpperCamelCase				:   List[Any]=(5, 3, 3, 1, 1)		,							_UpperCamelCase				:   Union[str, Any]=(1, 2, 3, 1, 1)		,							_UpperCamelCase				:   Any=512		,							_UpperCamelCase				:   str=0		,							_UpperCamelCase				:   int=1		,							_UpperCamelCase				:   Any=2		,							_UpperCamelCase				:   Optional[Any]=504		,							**_UpperCamelCase				:   str		,							)   ->			int:



												'''simple docstring'''

												super().__init__(**_UpperCamelCase		,							pad_token_id=_UpperCamelCase		,							bos_token_id=_UpperCamelCase		,							eos_token_id=_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    hidden_size
												SCREAMING_SNAKE_CASE           =    feat_extract_norm
												SCREAMING_SNAKE_CASE           =    feat_extract_activation
												SCREAMING_SNAKE_CASE           =    list(_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    list(_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    list(_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    conv_bias
												SCREAMING_SNAKE_CASE           =    num_conv_pos_embeddings
												SCREAMING_SNAKE_CASE           =    num_conv_pos_embedding_groups
												SCREAMING_SNAKE_CASE           =    len(self.conv_dim )
												SCREAMING_SNAKE_CASE           =    num_hidden_layers
												SCREAMING_SNAKE_CASE           =    intermediate_size
												SCREAMING_SNAKE_CASE           =    hidden_act
												SCREAMING_SNAKE_CASE           =    num_attention_heads
												SCREAMING_SNAKE_CASE           =    hidden_dropout
												SCREAMING_SNAKE_CASE           =    attention_dropout
												SCREAMING_SNAKE_CASE           =    activation_dropout
												SCREAMING_SNAKE_CASE           =    feat_proj_dropout
												SCREAMING_SNAKE_CASE           =    final_dropout
												SCREAMING_SNAKE_CASE           =    layerdrop
												SCREAMING_SNAKE_CASE           =    layer_norm_eps
												SCREAMING_SNAKE_CASE           =    initializer_range
												SCREAMING_SNAKE_CASE           =    vocab_size
												SCREAMING_SNAKE_CASE           =    num_clusters
												SCREAMING_SNAKE_CASE           =    do_stable_layer_norm
												SCREAMING_SNAKE_CASE           =    use_weighted_layer_sum

												if (
												    (len(self.conv_stride ) != self.num_feat_extract_layers)
												    or (len(self.conv_kernel ) != self.num_feat_extract_layers)
												    or (len(self.conv_dim ) != self.num_feat_extract_layers)
												):
																	raise ValueError(
																	    "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
																	    " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
																	    F" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,"
																	    F" `len(config.conv_kernel) = {len(self.conv_kernel )}`." )

												# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
												SCREAMING_SNAKE_CASE           =    apply_spec_augment
												SCREAMING_SNAKE_CASE           =    mask_time_prob
												SCREAMING_SNAKE_CASE           =    mask_time_length
												SCREAMING_SNAKE_CASE           =    mask_time_min_masks
												SCREAMING_SNAKE_CASE           =    mask_feature_prob
												SCREAMING_SNAKE_CASE           =    mask_feature_length
												SCREAMING_SNAKE_CASE           =    mask_feature_min_masks

												# parameters for pretraining with codevector quantized representations
												SCREAMING_SNAKE_CASE           =    num_codevectors_per_group
												SCREAMING_SNAKE_CASE           =    num_codevector_groups
												SCREAMING_SNAKE_CASE           =    contrastive_logits_temperature
												SCREAMING_SNAKE_CASE           =    feat_quantizer_dropout
												SCREAMING_SNAKE_CASE           =    num_negatives
												SCREAMING_SNAKE_CASE           =    codevector_dim
												SCREAMING_SNAKE_CASE           =    proj_codevector_dim
												SCREAMING_SNAKE_CASE           =    diversity_loss_weight

												# ctc loss
												SCREAMING_SNAKE_CASE           =    ctc_loss_reduction
												SCREAMING_SNAKE_CASE           =    ctc_zero_infinity

												# SequenceClassification-specific parameter. Feel free to ignore for other classes.
												SCREAMING_SNAKE_CASE           =    classifier_proj_size

												# XVector-specific parameters. Feel free to ignore for other classes.
												SCREAMING_SNAKE_CASE           =    list(_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    list(_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    list(_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    xvector_output_dim





							@property
							def 		__snake_case(  self				:   Tuple )   ->			str:



												'''simple docstring'''

												return functools.reduce(operator.mul		,							self.conv_stride		,							1 )




