






'''simple docstring'''



from typing import List, Optional, Union

import torch
from transformers import (
    XLMRobertaTokenizer,
)

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .text_encoder import MultilingualCLIP


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

__UpperCamelCase   :							Optional[Any]         =   """
    Examples:
        ```py
        >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline
        >>> import torch

        >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\")
        >>> pipe_prior.to(\"cuda\")

        >>> prompt = \"red cat, 4k photo\"
        >>> out = pipe_prior(prompt)
        >>> image_emb = out.image_embeds
        >>> negative_image_emb = out.negative_image_embeds

        >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\")
        >>> pipe.to(\"cuda\")

        >>> image = pipe(
        ...     prompt,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=negative_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ... ).images

        >>> image[0].save(\"cat.png\")
        ```
"""



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Dict,       SCREAMING_SNAKE_CASE__:						Tuple,       SCREAMING_SNAKE_CASE__:						Any=8     )	->      Dict:

   """simple docstring"""
   __a					  =     h // scale_factor**2
   if h % scale_factor**2 != 0:
      new_h += 1
   __a					  =     w // scale_factor**2
   if w % scale_factor**2 != 0:
      new_w += 1
   return new_h * scale_factor, new_w * scale_factor



class 				__SCREAMING_SNAKE_CASE							(				_lowerCAmelCase  ):




      def __init__(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, )				->List[str]:



         '''simple docstring'''
         super().__init__()

         self.register_modules(
             text_encoder=lowerCamelCase			, tokenizer=lowerCamelCase			, unet=lowerCamelCase			, scheduler=lowerCamelCase			, movq=lowerCamelCase			, )
         __a					  =     2 ** (len(self.movq.config.block_out_channels   ) - 1)




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase   )				->List[str]:



         '''simple docstring'''
         if latents is None:
            __a					  =     randn_tensor(lowerCamelCase			, generator=lowerCamelCase			, device=lowerCamelCase			, dtype=lowerCamelCase   )
         else:
            if latents.shape != shape:
               raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""   )
            __a					  =     latents.to(lowerCamelCase   )

         __a					  =     latents * scheduler.init_noise_sigma
         return latents




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase=None			, )				->List[Any]:



         '''simple docstring'''
         __a					  =     len(lowerCamelCase   ) if isinstance(lowerCamelCase			, lowerCamelCase   ) else 1
         # get prompt text embeddings
         __a					  =     self.tokenizer(
             lowerCamelCase			, padding='max_length'			, truncation=lowerCamelCase			, max_length=77			, return_attention_mask=lowerCamelCase			, add_special_tokens=lowerCamelCase			, return_tensors='pt'			, )

         __a					  =     text_inputs.input_ids
         __a					  =     self.tokenizer(lowerCamelCase			, padding='longest'			, return_tensors='pt'   ).input_ids

         if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCamelCase			, lowerCamelCase   ):
            __a					  =     self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]   )
            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.to(lowerCamelCase   )
         __a					  =     text_inputs.attention_mask.to(lowerCamelCase   )

         __a  ,      __a					  =     self.text_encoder(
             input_ids=lowerCamelCase			, attention_mask=lowerCamelCase   )

         __a					  =     prompt_embeds.repeat_interleave(lowerCamelCase			, dim=0   )
         __a					  =     text_encoder_hidden_states.repeat_interleave(lowerCamelCase			, dim=0   )
         __a					  =     text_mask.repeat_interleave(lowerCamelCase			, dim=0   )

         if do_classifier_free_guidance:
            __a					  =     42
            if negative_prompt is None:
               __a					  =     [''] * batch_size
            elif type(lowerCamelCase   ) is not type(lowerCamelCase   ):
               raise TypeError(
                   F"""`negative_prompt` should be the same type to `prompt`, but got {type(lowerCamelCase   )} !="""
                   F""" {type(lowerCamelCase   )}."""   )
            elif isinstance(lowerCamelCase			, lowerCamelCase   ):
               __a					  =     [negative_prompt]
            elif batch_size != len(lowerCamelCase   ):
               raise ValueError(
                   F"""`negative_prompt`: {negative_prompt} has batch size {len(lowerCamelCase   )}, 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					  =     self.tokenizer(
                lowerCamelCase			, padding='max_length'			, max_length=77			, truncation=lowerCamelCase			, return_attention_mask=lowerCamelCase			, add_special_tokens=lowerCamelCase			, return_tensors='pt'			, )
            __a					  =     uncond_input.input_ids.to(lowerCamelCase   )
            __a					  =     uncond_input.attention_mask.to(lowerCamelCase   )

            __a  ,      __a					  =     self.text_encoder(
                input_ids=lowerCamelCase			, attention_mask=lowerCamelCase   )

            # duplicate unconditional embeddings for each generation per prompt, using mps friendly method

            __a					  =     negative_prompt_embeds.shape[1]
            __a					  =     negative_prompt_embeds.repeat(1			, lowerCamelCase   )
            __a					  =     negative_prompt_embeds.view(batch_size * num_images_per_prompt			, lowerCamelCase   )

            __a					  =     uncond_text_encoder_hidden_states.shape[1]
            __a					  =     uncond_text_encoder_hidden_states.repeat(1			, lowerCamelCase			, 1   )
            __a					  =     uncond_text_encoder_hidden_states.view(
                batch_size * num_images_per_prompt			, lowerCamelCase			, -1   )
            __a					  =     uncond_text_mask.repeat_interleave(lowerCamelCase			, dim=0   )

            # done duplicates

            # 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([negative_prompt_embeds, prompt_embeds]   )
            __a					  =     torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]   )

            __a					  =     torch.cat([uncond_text_mask, text_mask]   )

         return prompt_embeds, text_encoder_hidden_states, text_mask




      def 			__UpperCamelCase				(	self			, lowerCamelCase=0   )				->Union[str, Any]:



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

         __a					  =     torch.device(F"""cuda:{gpu_id}"""   )

         __a					  =     [
             self.unet,
             self.text_encoder,
             self.movq,
         ]
         for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
               cpu_offload(lowerCamelCase			, lowerCamelCase   )




      def 			__UpperCamelCase				(	self			, lowerCamelCase=0   )				->Optional[int]:



         '''simple docstring'''
         if is_accelerate_available() and is_accelerate_version('>='			, '0.17.0.dev0'   ):
            from accelerate import cpu_offload_with_hook
         else:
            raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'   )

         __a					  =     torch.device(F"""cuda:{gpu_id}"""   )

         if self.device.type != "cpu":
            self.to('cpu'			, silence_dtype_warnings=lowerCamelCase   )
            torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

         __a					  =     None
         for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
            __a  ,      __a					  =     cpu_offload_with_hook(lowerCamelCase			, lowerCamelCase			, prev_module_hook=lowerCamelCase   )

         if self.safety_checker is not None:
            __a  ,      __a					  =     cpu_offload_with_hook(self.safety_checker			, lowerCamelCase			, prev_module_hook=lowerCamelCase   )

         # We'll offload the last model manually.
         __a					  =     hook




      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def 			__UpperCamelCase				(	self   )				->int:



         '''simple docstring'''
         if 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()
      @replace_example_docstring(lowerCamelCase   )
      def __call__(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase = None			, lowerCamelCase = 512			, lowerCamelCase = 512			, lowerCamelCase = 100			, lowerCamelCase = 4.0			, lowerCamelCase = 1			, lowerCamelCase = None			, lowerCamelCase = None			, lowerCamelCase = "pil"			, lowerCamelCase = True			, )				->int:



         '''simple docstring'''

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

         __a					  =     self._execution_device

         __a					  =     batch_size * num_images_per_prompt
         __a					  =     guidance_scale > 1.0

         __a  ,      __a  ,      __a					  =     self._encode_prompt(
             lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase   )

         if isinstance(lowerCamelCase			, lowerCamelCase   ):
            __a					  =     torch.cat(lowerCamelCase			, dim=0   )
         if isinstance(lowerCamelCase			, lowerCamelCase   ):
            __a					  =     torch.cat(lowerCamelCase			, dim=0   )

         if do_classifier_free_guidance:
            __a					  =     image_embeds.repeat_interleave(lowerCamelCase			, dim=0   )
            __a					  =     negative_image_embeds.repeat_interleave(lowerCamelCase			, dim=0   )

         __a					  =     torch.cat([negative_image_embeds, image_embeds]			, dim=0   ).to(
             dtype=prompt_embeds.dtype			, device=lowerCamelCase   )

         self.scheduler.set_timesteps(lowerCamelCase			, device=lowerCamelCase   )
         __a					  =     self.scheduler.timesteps

         __a					  =     self.unet.config.in_channels

         __a  ,      __a					  =     get_new_h_w(lowerCamelCase			, lowerCamelCase			, self.movq_scale_factor   )

         # create initial latent
         __a					  =     self.prepare_latents(
             (batch_size, num_channels_latents, height, width)			, text_encoder_hidden_states.dtype			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, self.scheduler			, )

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

            __a					  =     {'text_embeds': prompt_embeds, 'image_embeds': image_embeds}
            __a					  =     self.unet(
                sample=lowerCamelCase			, timestep=lowerCamelCase			, encoder_hidden_states=lowerCamelCase			, added_cond_kwargs=lowerCamelCase			, return_dict=lowerCamelCase			, )[0]

            if do_classifier_free_guidance:
               __a  ,      __a					  =     noise_pred.split(latents.shape[1]			, dim=1   )
               __a  ,      __a					  =     noise_pred.chunk(2   )
               __a  ,      __a					  =     variance_pred.chunk(2   )
               __a					  =     noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
               __a					  =     torch.cat([noise_pred, variance_pred_text]			, dim=1   )

            if not (
                hasattr(self.scheduler.config			, 'variance_type'   )
                and self.scheduler.config.variance_type in ["learned", "learned_range"]
            ):
               __a  ,      __a					  =     noise_pred.split(latents.shape[1]			, dim=1   )

            # compute the previous noisy sample x_t -> x_t-1
            __a					  =     self.scheduler.step(
                lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, generator=lowerCamelCase			, ).prev_sample
         # post-processing
         __a					  =     self.movq.decode(lowerCamelCase			, force_not_quantize=lowerCamelCase   )['sample']

         if output_type not in ["pt", "np", "pil"]:
            raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"""   )

         if output_type in ["np", "pil"]:
            __a					  =     image * 0.5 + 0.5
            __a					  =     image.clamp(0			, 1   )
            __a					  =     image.cpu().permute(0			, 2			, 3			, 1   ).float().numpy()

         if output_type == "pil":
            __a					  =     self.numpy_to_pil(lowerCamelCase   )

         if not return_dict:
            return (image,)

         return ImagePipelineOutput(images=lowerCamelCase   )







'''simple docstring'''



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

import datasets


__UpperCamelCase   :							List[str]         =   """\
@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\",
}
"""

__UpperCamelCase   :							Union[str, Any]         =   """\
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.
"""

__UpperCamelCase   :							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 				__SCREAMING_SNAKE_CASE							(				datasets.Metric  ):




      def 			__UpperCamelCase				(	self   )				->Union[str, Any]:



         '''simple docstring'''
         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 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase = CHRF.CHAR_ORDER			, lowerCamelCase = CHRF.WORD_ORDER			, lowerCamelCase = CHRF.BETA			, lowerCamelCase = False			, lowerCamelCase = False			, lowerCamelCase = False			, )				->Union[str, Any]:



         '''simple docstring'''
         __a					  =     len(references[0]   )
         if any(len(lowerCamelCase   ) != references_per_prediction for refs in references   ):
            raise ValueError('Sacrebleu requires the same number of references for each prediction'   )
         __a					  =     [[refs[i] for refs in references] for i in range(lowerCamelCase   )]

         __a					  =     CHRF(lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase   )
         __a					  =     sb_chrf.corpus_score(lowerCamelCase			, lowerCamelCase   )

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