






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	:		List[str]										=   logging.get_logger(__name__)  # pylint: disable=invalid-name







class  _lowercase   (   _A						):
						def __init__(     self				,			a				,			a				,			a				,			a				,			a				,			a				,			a				,			a				,			a				,			):
							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=a				,			speech_processor=a				,			vae=a				,			text_encoder=a				,			tokenizer=a				,			unet=a				,			scheduler=a				,			feature_extractor=a				,			)
						def 						lowercase__					(     self				,			a = "auto"   ):
							if slice_size == "auto":
								snake_case__  :    Tuple							       =self.unet.config.attention_head_dim // 2
							self.unet.set_attention_slice(a   )
						def 						lowercase__					(     self   ):
							self.enable_attention_slicing(a   )



						@torch.no_grad()
						def __call__(     self				,			a				,			a=1_6_0_0_0				,			a = 5_1_2				,			a = 5_1_2				,			a = 5_0				,			a = 7.5				,			a = None				,			a = 1				,			a = 0.0				,			a = None				,			a = None				,			a = "pil"				,			a = True				,			a = None				,			a = 1				,			**a				,			):
							snake_case__  :    Dict							       =self.speech_processor.feature_extractor(
							    a				,			return_tensors="""pt"""				,			sampling_rate=a   ).input_features.to(self.device   )
							snake_case__  :    Optional[Any]							       =self.speech_model.generate(a				,			max_length=4_8_0_0_0_0   )

							snake_case__  :    Optional[int]							       =self.speech_processor.tokenizer.batch_decode(a				,			skip_special_tokens=a				,			normalize=a   )[
							    0
							]

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

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

							# get prompt text embeddings
							snake_case__  :    List[str]							       =self.tokenizer(
							    a				,			padding="""max_length"""				,			max_length=self.tokenizer.model_max_length				,			return_tensors="""pt"""				,			)
							snake_case__  :    List[str]							       =text_inputs.input_ids

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

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

								snake_case__  :    Optional[int]							       =text_input_ids.shape[-1]
								snake_case__  :    str							       =self.tokenizer(
								    a				,			padding="""max_length"""				,			max_length=a				,			truncation=a				,			return_tensors="""pt"""				,			)
								snake_case__  :    List[Any]							       =self.text_encoder(uncond_input.input_ids.to(self.device   )   )[0]

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

							# set timesteps
							self.scheduler.set_timesteps(a   )

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

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

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

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

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

								# compute the previous noisy sample x_t -> x_t-1
								snake_case__  :    Optional[int]							       =self.scheduler.step(a				,			a				,			a				,			**a   ).prev_sample

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

							snake_case__  :    Tuple							       =1 / 0.18215 * latents
							snake_case__  :    Optional[int]							       =self.vae.decode(a   ).sample

							snake_case__  :    Optional[Any]							       =(image / 2 + 0.5).clamp(0				,			1   )

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

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

							if not return_dict:
								return image

							return StableDiffusionPipelineOutput(images=a				,			nsfw_content_detected=a   )













import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


__lowerCamelCase	:		Dict										=   """\
@inproceedings{popovic-2015-chrf,
    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",
    month = sep,
    year = \"2015\",
    address = \"Lisbon, Portugal\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W15-3049\",
    doi = \"10.18653/v1/W15-3049\",
    pages = \"392--395\",
}
@inproceedings{popovic-2017-chrf,
    title = \"chr{F}++: words helping character n-grams\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Second Conference on Machine Translation\",
    month = sep,
    year = \"2017\",
    address = \"Copenhagen, Denmark\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W17-4770\",
    doi = \"10.18653/v1/W17-4770\",
    pages = \"612--618\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

__lowerCamelCase	:		Optional[int]										=   """\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
"""

__lowerCamelCase	:		List[str]										=   """
Produces ChrF(++) scores for hypotheses given reference translations.

Args:
    predictions (list of str): The predicted sentences.
    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
    char_order (int): Character n-gram order. Defaults to `6`.
    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
    eps_smoothing (bool): If `True`, applies epsilon smoothing similar
    to reference chrF++.py, NLTK and Moses implementations. If `False`,
    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.

Returns:
    'score' (float): The chrF (chrF++) score,
    'char_order' (int): The character n-gram order,
    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
    'beta' (int): Determine the importance of recall w.r.t precision

Examples:
    Example 1--a simple example of calculating chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction, references=reference)
        >>> print(results)
        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}

    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2)
        >>> print(results)
        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}

    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2,
        ...                         lowercase=True)
        >>> print(results)
        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
"""







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,				_KWARGS_DESCRIPTION						)
class  _lowercase   (   datasets.Metric						):
      def 						lowercase__					(     self   ):
       if version.parse(scb.__version__   ) < version.parse("""1.4.12"""   ):
        raise ImportWarning(
            """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
            """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""   )
       return datasets.MetricInfo(
           description=_DESCRIPTION				,			citation=_CITATION				,			homepage="""https://github.com/mjpost/sacreBLEU#chrf--chrf"""				,			inputs_description=_KWARGS_DESCRIPTION				,			features=datasets.Features(
               {
                   """predictions""": datasets.Value("""string"""				,			id="""sequence"""   ),
                   """references""": datasets.Sequence(datasets.Value("""string"""				,			id="""sequence"""   )				,			id="""references"""   ),
               }   )				,			codebase_urls=["""https://github.com/mjpost/sacreBLEU#chrf--chrf"""]				,			reference_urls=[
               """https://github.com/m-popovic/chrF""",
           ]				,			)



      def 						lowercase__					(     self				,			a				,			a				,			a = CHRF.CHAR_ORDER				,			a = CHRF.WORD_ORDER				,			a = CHRF.BETA				,			a = False				,			a = False				,			a = False				,			):
       snake_case__  :    str							       =len(references[0]   )
       if any(len(a   ) != references_per_prediction for refs in references   ):
        raise ValueError("""Sacrebleu requires the same number of references for each prediction"""   )
       snake_case__  :    List[Any]							       =[[refs[i] for refs in references] for i in range(a   )]

       snake_case__  :    int							       =CHRF(a				,			a				,			a				,			a				,			a				,			a   )
       snake_case__  :    int							       =sb_chrf.corpus_score(a				,			a   )

       return {
           "score": output.score,
           "char_order": output.char_order,
           "word_order": output.word_order,
           "beta": output.beta,
       }





