


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


snake_case__						:   List[Any]			 = logging.get_logger(__name__)  # pylint: disable=invalid-name



class 						snake_case_(				a__	):






     def __init__(		self     :    Dict    , UpperCamelCase_     :    WhisperForConditionalGeneration    , UpperCamelCase_     :    WhisperProcessor    , UpperCamelCase_     :    AutoencoderKL    , UpperCamelCase_     :    CLIPTextModel    , UpperCamelCase_     :    CLIPTokenizer    , UpperCamelCase_     :    UNetaDConditionModel    , UpperCamelCase_     :    Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]    , UpperCamelCase_     :    StableDiffusionSafetyChecker    , UpperCamelCase_     :    CLIPImageProcessor    , ):
           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=UpperCamelCase_    , speech_processor=UpperCamelCase_    , vae=UpperCamelCase_    , text_encoder=UpperCamelCase_    , tokenizer=UpperCamelCase_    , unet=UpperCamelCase_    , scheduler=UpperCamelCase_    , feature_extractor=UpperCamelCase_    , )






     def    lowerCamelCase__   (		self     :    Dict    , UpperCamelCase_     :    Optional[Union[str, int]] = "auto" ):
           if slice_size == "auto":
                 lowerCAmelCase    :		List[Any]				=      self.unet.config.attention_head_dim // 2
           self.unet.set_attention_slice(UpperCamelCase_ )






     def    lowerCamelCase__   (		self     :    Tuple ):
           self.enable_attention_slicing(UpperCamelCase_ )






     @torch.no_grad()
     def __call__(		self     :    str    , UpperCamelCase_     :    List[str]    , UpperCamelCase_     :    Union[str, Any]=1_6_0_0_0    , UpperCamelCase_     :    int = 5_1_2    , UpperCamelCase_     :    int = 5_1_2    , UpperCamelCase_     :    int = 5_0    , UpperCamelCase_     :    float = 7.5    , UpperCamelCase_     :    Optional[Union[str, List[str]]] = None    , UpperCamelCase_     :    Optional[int] = 1    , UpperCamelCase_     :    float = 0.0    , UpperCamelCase_     :    Optional[torch.Generator] = None    , UpperCamelCase_     :    Optional[torch.FloatTensor] = None    , UpperCamelCase_     :    Optional[str] = "pil"    , UpperCamelCase_     :    bool = True    , UpperCamelCase_     :    Optional[Callable[[int, int, torch.FloatTensor], None]] = None    , UpperCamelCase_     :    int = 1    , **UpperCamelCase_     :    str    , ):
           lowerCAmelCase    :		Union[str, Any]				=      self.speech_processor.feature_extractor(
               UpperCamelCase_    , return_tensors='''pt'''    , sampling_rate=UpperCamelCase_ ).input_features.to(self.device )
           lowerCAmelCase    :		int				=      self.speech_model.generate(UpperCamelCase_    , max_length=4_8_0_0_0_0 )

           lowerCAmelCase    :		List[str]				=      self.speech_processor.tokenizer.batch_decode(UpperCamelCase_    , skip_special_tokens=UpperCamelCase_    , normalize=UpperCamelCase_ )[
               0
           ]

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

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

           # get prompt text embeddings
           lowerCAmelCase    :		Optional[Any]				=      self.tokenizer(
               UpperCamelCase_    , padding='''max_length'''    , max_length=self.tokenizer.model_max_length    , return_tensors='''pt'''    , )
           lowerCAmelCase    :		List[str]				=      text_inputs.input_ids

           if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
                 lowerCAmelCase    :		List[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}''' )
                 lowerCAmelCase    :		str				=      text_input_ids[:, : self.tokenizer.model_max_length]
           lowerCAmelCase    :		str				=      self.text_encoder(text_input_ids.to(self.device ) )[0]

           # duplicate text embeddings for each generation per prompt, using mps friendly method
           lowerCAmelCase,					lowerCAmelCase,					lowerCAmelCase    :		Optional[Any]				=      text_embeddings.shape
           lowerCAmelCase    :		Dict				=      text_embeddings.repeat(1    , UpperCamelCase_    , 1 )
           lowerCAmelCase    :		Tuple				=      text_embeddings.view(bs_embed * num_images_per_prompt    , UpperCamelCase_    , -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.
           lowerCAmelCase    :		str				=      guidance_scale > 1.0
           # get unconditional embeddings for classifier free guidance
           if do_classifier_free_guidance:
                 lowerCAmelCase    :		List[str]
                 if negative_prompt is None:
                       lowerCAmelCase    :		Tuple				=      [''''''] * batch_size
                 elif type(UpperCamelCase_ ) is not type(UpperCamelCase_ ):
                       raise TypeError(
                           F'''`negative_prompt` should be the same type to `prompt`, but got {type(UpperCamelCase_ )} !='''
                           F''' {type(UpperCamelCase_ )}.''' )
                 elif isinstance(UpperCamelCase_    , UpperCamelCase_ ):
                       lowerCAmelCase    :		Tuple				=      [negative_prompt]
                 elif batch_size != len(UpperCamelCase_ ):
                       raise ValueError(
                           F'''`negative_prompt`: {negative_prompt} has batch size {len(UpperCamelCase_ )}, but `prompt`:'''
                           F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
                           ''' the batch size of `prompt`.''' )
                 else:
                       lowerCAmelCase    :		Tuple				=      negative_prompt

                 lowerCAmelCase    :		Any				=      text_input_ids.shape[-1]
                 lowerCAmelCase    :		Optional[int]				=      self.tokenizer(
                     UpperCamelCase_    , padding='''max_length'''    , max_length=UpperCamelCase_    , truncation=UpperCamelCase_    , return_tensors='''pt'''    , )
                 lowerCAmelCase    :		Union[str, Any]				=      self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]

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

           # set timesteps
           self.scheduler.set_timesteps(UpperCamelCase_ )

           # Some schedulers like PNDM have timesteps as arrays
           # It's more optimized to move all timesteps to correct device beforehand
           lowerCAmelCase    :		List[str]				=      self.scheduler.timesteps.to(self.device )

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

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

                 # predict the noise residual
                 lowerCAmelCase    :		str				=      self.unet(UpperCamelCase_    , UpperCamelCase_    , encoder_hidden_states=UpperCamelCase_ ).sample

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

                 # compute the previous noisy sample x_t -> x_t-1
                 lowerCAmelCase    :		List[Any]				=      self.scheduler.step(UpperCamelCase_    , UpperCamelCase_    , UpperCamelCase_    , **UpperCamelCase_ ).prev_sample

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

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

           lowerCAmelCase    :		Tuple				=      (image / 2 + 0.5).clamp(0    , 1 )

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

           if output_type == "pil":
                 lowerCAmelCase    :		Union[str, Any]				=      self.numpy_to_pil(UpperCamelCase_ )

           if not return_dict:
                 return image

           return StableDiffusionPipelineOutput(images=UpperCamelCase_    , nsfw_content_detected=UpperCamelCase_ )







'''simple docstring'''





from typing import Dict, Optional

import numpy as np

import datasets


lowercase_		       =  "\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n"

lowercase_		       =  "\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric(\"mean_iou\")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mean_iou': 0.47750000000000004, 'mean_accuracy': 0.5916666666666666, 'overall_accuracy': 0.5263157894736842, 'per_category_iou': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), 'per_category_accuracy': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}\n"

lowercase_		       =  "\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}"




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     if label_map is not None:
          for old_id, new_id in label_map.items():
               _a      =  new_id

    # turn into Numpy arrays
     _a      =  np.array(__A)
     _a      =  np.array(__A)

     if reduce_labels:
          _a      =  255
          _a      =  label - 1
          _a      =  255

     _a      =  label != ignore_index
     _a      =  np.not_equal(__A  ,	__A)
     _a      =  pred_label[mask]
     _a      =  np.array(__A)[mask]

     _a      =  pred_label[pred_label == label]

     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]
     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]
     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]

     _a      =  area_pred_label + area_label - area_intersect

     return area_intersect, area_union, area_pred_label, area_label




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     for result, gt_seg_map in zip(__A  ,	__A):
          _a  ,    _a  ,    _a  ,    _a      =  intersect_and_union(
              __A  ,	__A  ,	__A  ,	__A  ,	__A  ,	__A)
          total_area_intersect += area_intersect
          total_area_union += area_union
          total_area_pred_label += area_pred_label
          total_area_label += area_label
     return total_area_intersect, total_area_union, total_area_pred_label, total_area_label




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     _a  ,    _a  ,    _a  ,    _a      =  total_intersect_and_union(
         __A  ,	__A  ,	__A  ,	__A  ,	__A  ,	__A)

     # compute metrics
     _a      =  {}

     _a      =  total_area_intersect.sum() / total_area_label.sum()
     _a      =  total_area_intersect / total_area_union
     _a      =  total_area_intersect / total_area_label

     _a      =  np.nanmean(__A)
     _a      =  np.nanmean(__A)
     _a      =  all_acc
     _a      =  iou
     _a      =  acc

     if nan_to_num is not None:
          _a      =  {metric: np.nan_to_num(__A  ,	nan=__A) for metric, metric_value in metrics.items()}

     return metrics






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,   _KWARGS_DESCRIPTION						)
class __A			(  datasets.Metric						):



 '''simple docstring'''







 def 					a__  (self       )    ->     List[str]:


      """simple docstring"""



      return datasets.MetricInfo(
          description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
              # 1st Seq - height dim, 2nd - width dim
              {
                  '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''       )       )       ),
                  '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''       )       )       ),
              }       ) ,   reference_urls=[
              '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'''
          ] ,   )



 def 					a__  (self ,   A ,   A ,   A ,   A ,   A = None ,   A = None ,   A = False ,   )    ->     List[Any]:


      """simple docstring"""



      _a      =  mean_iou(
          results=A ,   gt_seg_maps=A ,   num_labels=A ,   ignore_index=A ,   nan_to_num=A ,   label_map=A ,   reduce_labels=A ,   )
      return iou_result



