


'''simple docstring'''

import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


lowerCAmelCase				:Optional[Any]        =      '''\
@inproceedings{snover-etal-2006-study,
    title = "A Study of Translation Edit Rate with Targeted Human Annotation",
    author = "Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John",
    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",
    month = aug # " 8-12",
    year = "2006",
    address = "Cambridge, Massachusetts, USA",
    publisher = "Association for Machine Translation in the Americas",
    url = "https://aclanthology.org/2006.amta-papers.25",
    pages = "223--231",
}
@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				:str        =      '''\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

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#ter for more information.
'''

lowerCAmelCase				:List[Any]        =      '''
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)
    \'num_edits\' (int): The cumulative number of edits
    \'ref_length\' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?",
        ...                     "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}

    Example 2:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}

    Example 3:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}

    Example 4:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}

    Example 5:
        >>> predictions = ["does this sentence match??",
        ...                    "what about this sentence?",
        ...                    "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,					_KWARGS_DESCRIPTION							)
class _lowerCamelCase	(						datasets.Metric							):



		'''simple docstring'''







		def        __lowerCAmelCase		( self		:						int      )  ->			Optional[int]:
			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='http://www.cs.umd.edu/~snover/tercom/'  ,					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#ter']  ,					reference_urls=[
			        'https://github.com/jhclark/tercom',
			    ]  ,					)







		def        __lowerCAmelCase		( self		:						Dict  ,					_A		:						int  ,					_A		:						Tuple  ,					_A		:						bool = False  ,					_A		:						bool = False  ,					_A		:						bool = False  ,					_A		:						bool = False  ,					)  ->			List[Any]:
			__magic_name__	:   Optional[int]					     =					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'      )
			__magic_name__	:   Dict					     =					[[refs[i] for refs in references] for i in range(_A      )]

			__magic_name__	:   Dict					     =					TER(
			    normalized=_A  ,					no_punct=_A  ,					asian_support=_A  ,					case_sensitive=_A  ,					)
			__magic_name__	:   List[str]					     =					sb_ter.corpus_score(_A  ,					_A      )

			return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}









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


lowerCAmelCase				:str        =      logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase				:int        =      '''
    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 lowerCamelCase      (      lowerCAmelCase    :     Optional[int]		,		lowerCAmelCase    :     Union[str, Any]		,		lowerCAmelCase    :     List[Any]=8		):





	"""simple docstring"""







	__magic_name__	:   List[str]					     =					h // scale_factor**2
	if h % scale_factor**2 != 0:
		new_h += 1
	__magic_name__	:   str					     =					w // scale_factor**2
	if w % scale_factor**2 != 0:
		new_w += 1
	return new_h * scale_factor, new_w * scale_factor





class _lowerCamelCase	(						lowercase__							):



		'''simple docstring'''







		def __init__( self		:						Union[str, Any]  ,					_A		:						MultilingualCLIP  ,					_A		:						XLMRobertaTokenizer  ,					_A		:						UNetaDConditionModel  ,					_A		:						Union[DDIMScheduler, DDPMScheduler]  ,					_A		:						VQModel  ,					)  ->			int:
			super().__init__()

			self.register_modules(
			    text_encoder=_A  ,					tokenizer=_A  ,					unet=_A  ,					scheduler=_A  ,					movq=_A  ,					)
			__magic_name__	:   List[Any]					     =					2 ** (len(self.movq.config.block_out_channels      ) - 1)







		def        __lowerCAmelCase		( self		:						List[Any]  ,					_A		:						Tuple  ,					_A		:						Optional[Any]  ,					_A		:						Optional[int]  ,					_A		:						Dict  ,					_A		:						str  ,					_A		:						List[str]      )  ->			str:
			if latents is None:
				__magic_name__	:   Any					     =					randn_tensor(_A  ,					generator=_A  ,					device=_A  ,					dtype=_A      )
			else:
				if latents.shape != shape:
					raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}'      )
				__magic_name__	:   int					     =					latents.to(_A      )

			__magic_name__	:   Union[str, Any]					     =					latents * scheduler.init_noise_sigma
			return latents







		def        __lowerCAmelCase		( self		:						List[Any]  ,					_A		:						List[str]  ,					_A		:						List[str]  ,					_A		:						List[str]  ,					_A		:						List[Any]  ,					_A		:						str=None  ,					)  ->			Dict:
			__magic_name__	:   Optional[Any]					     =					len(_A      ) if isinstance(_A  ,					_A      ) else 1
			# get prompt text embeddings
			__magic_name__	:   str					     =					self.tokenizer(
			    _A  ,					padding='max_length'  ,					truncation=_A  ,					max_length=77  ,					return_attention_mask=_A  ,					add_special_tokens=_A  ,					return_tensors='pt'  ,					)

			__magic_name__	:   Optional[Any]					     =					text_inputs.input_ids
			__magic_name__	:   Optional[Any]					     =					self.tokenizer(_A  ,					padding='longest'  ,					return_tensors='pt'      ).input_ids

			if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(_A  ,					_A      ):
				__magic_name__	:   str					     =					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}'      )

			__magic_name__	:   Union[str, Any]					     =					text_input_ids.to(_A      )
			__magic_name__	:   Dict					     =					text_inputs.attention_mask.to(_A      )

			__magic_name__     ,    __magic_name__	:   str					     =					self.text_encoder(
			    input_ids=_A  ,					attention_mask=_A      )

			__magic_name__	:   Tuple					     =					prompt_embeds.repeat_interleave(_A  ,					dim=0      )
			__magic_name__	:   int					     =					text_encoder_hidden_states.repeat_interleave(_A  ,					dim=0      )
			__magic_name__	:   Union[str, Any]					     =					text_mask.repeat_interleave(_A  ,					dim=0      )

			if do_classifier_free_guidance:
				__magic_name__	:   List[str]
				if negative_prompt is None:
					__magic_name__	:   Optional[Any]					     =					[''] * 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      ):
					__magic_name__	:   int					     =					[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:
					__magic_name__	:   Dict					     =					negative_prompt

				__magic_name__	:   List[str]					     =					self.tokenizer(
				    _A  ,					padding='max_length'  ,					max_length=77  ,					truncation=_A  ,					return_attention_mask=_A  ,					add_special_tokens=_A  ,					return_tensors='pt'  ,					)
				__magic_name__	:   Optional[int]					     =					uncond_input.input_ids.to(_A      )
				__magic_name__	:   Optional[Any]					     =					uncond_input.attention_mask.to(_A      )

				__magic_name__     ,    __magic_name__	:   int					     =					self.text_encoder(
				    input_ids=_A  ,					attention_mask=_A      )

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

				__magic_name__	:   List[str]					     =					negative_prompt_embeds.shape[1]
				__magic_name__	:   str					     =					negative_prompt_embeds.repeat(1  ,					_A      )
				__magic_name__	:   Dict					     =					negative_prompt_embeds.view(batch_size * num_images_per_prompt  ,					_A      )

				__magic_name__	:   Any					     =					uncond_text_encoder_hidden_states.shape[1]
				__magic_name__	:   Optional[int]					     =					uncond_text_encoder_hidden_states.repeat(1  ,					_A  ,					1      )
				__magic_name__	:   Tuple					     =					uncond_text_encoder_hidden_states.view(
				    batch_size * num_images_per_prompt  ,					_A  ,					-1      )
				__magic_name__	:   List[Any]					     =					uncond_text_mask.repeat_interleave(_A  ,					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
				__magic_name__	:   Tuple					     =					torch.cat([negative_prompt_embeds, prompt_embeds]      )
				__magic_name__	:   str					     =					torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]      )

				__magic_name__	:   str					     =					torch.cat([uncond_text_mask, text_mask]      )

			return prompt_embeds, text_encoder_hidden_states, text_mask







		def        __lowerCAmelCase		( self		:						Dict  ,					_A		:						List[Any]=0      )  ->			Tuple:
			if is_accelerate_available():
				from accelerate import cpu_offload
			else:
				raise ImportError('Please install accelerate via `pip install accelerate`'      )

			__magic_name__	:   List[Any]					     =					torch.device(F'cuda:{gpu_id}'      )

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







		def        __lowerCAmelCase		( self		:						List[Any]  ,					_A		:						List[str]=0      )  ->			str:
			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.'      )

			__magic_name__	:   int					     =					torch.device(F'cuda:{gpu_id}'      )

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

			__magic_name__	:   Optional[int]					     =					None
			for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
				__magic_name__     ,    __magic_name__	:   Union[str, Any]					     =					cpu_offload_with_hook(_A  ,					_A  ,					prev_module_hook=_A      )

			if self.safety_checker is not None:
				__magic_name__     ,    __magic_name__	:   List[str]					     =					cpu_offload_with_hook(self.safety_checker  ,					_A  ,					prev_module_hook=_A      )

			# We'll offload the last model manually.
			__magic_name__	:   Any					     =					hook







		@property
		# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
		def        __lowerCAmelCase		( self		:						int      )  ->			List[str]:
			if not hasattr(self.unet  ,					'_hf_hook'      ):
				return self.device
			for module in self.unet.modules():
				if (
				    hasattr(_A  ,					'_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(_A      )
		def __call__( self		:						int  ,					_A		:						Union[str, List[str]]  ,					_A		:						Union[torch.FloatTensor, List[torch.FloatTensor]]  ,					_A		:						Union[torch.FloatTensor, List[torch.FloatTensor]]  ,					_A		:						Optional[Union[str, List[str]]] = None  ,					_A		:						int = 512  ,					_A		:						int = 512  ,					_A		:						int = 100  ,					_A		:						float = 4.0  ,					_A		:						int = 1  ,					_A		:						Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,					_A		:						Optional[torch.FloatTensor] = None  ,					_A		:						Optional[str] = "pil"  ,					_A		:						bool = True  ,					)  ->			Optional[int]:

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

			__magic_name__	:   Tuple					     =					self._execution_device

			__magic_name__	:   Any					     =					batch_size * num_images_per_prompt
			__magic_name__	:   int					     =					guidance_scale > 1.0

			__magic_name__     ,    __magic_name__     ,    __magic_name__	:   Optional[int]					     =					self._encode_prompt(
			    _A  ,					_A  ,					_A  ,					_A  ,					_A      )

			if isinstance(_A  ,					_A      ):
				__magic_name__	:   Union[str, Any]					     =					torch.cat(_A  ,					dim=0      )
			if isinstance(_A  ,					_A      ):
				__magic_name__	:   Dict					     =					torch.cat(_A  ,					dim=0      )

			if do_classifier_free_guidance:
				__magic_name__	:   Dict					     =					image_embeds.repeat_interleave(_A  ,					dim=0      )
				__magic_name__	:   Optional[int]					     =					negative_image_embeds.repeat_interleave(_A  ,					dim=0      )

			__magic_name__	:   Optional[int]					     =					torch.cat([negative_image_embeds, image_embeds]  ,					dim=0      ).to(
			    dtype=prompt_embeds.dtype  ,					device=_A      )

			self.scheduler.set_timesteps(_A  ,					device=_A      )
			__magic_name__	:   Tuple					     =					self.scheduler.timesteps

			__magic_name__	:   Optional[int]					     =					self.unet.config.in_channels

			__magic_name__     ,    __magic_name__	:   Dict					     =					get_new_h_w(_A  ,					_A  ,					self.movq_scale_factor      )

			# create initial latent
			__magic_name__	:   Union[str, Any]					     =					self.prepare_latents(
			    (batch_size, num_channels_latents, height, width)  ,					text_encoder_hidden_states.dtype  ,					_A  ,					_A  ,					_A  ,					self.scheduler  ,					)

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

				__magic_name__	:   Tuple					     =					{'text_embeds': prompt_embeds, 'image_embeds': image_embeds}
				__magic_name__	:   Union[str, Any]					     =					self.unet(
				    sample=_A  ,					timestep=_A  ,					encoder_hidden_states=_A  ,					added_cond_kwargs=_A  ,					return_dict=_A  ,					)[0]

				if do_classifier_free_guidance:
					__magic_name__     ,    __magic_name__	:   Optional[Any]					     =					noise_pred.split(latents.shape[1]  ,					dim=1      )
					__magic_name__     ,    __magic_name__	:   Dict					     =					noise_pred.chunk(2      )
					__magic_name__     ,    __magic_name__	:   List[str]					     =					variance_pred.chunk(2      )
					__magic_name__	:   List[Any]					     =					noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
					__magic_name__	:   Any					     =					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"]
				):
					__magic_name__     ,    __magic_name__	:   Optional[Any]					     =					noise_pred.split(latents.shape[1]  ,					dim=1      )

				# compute the previous noisy sample x_t -> x_t-1
				__magic_name__	:   List[Any]					     =					self.scheduler.step(
				    _A  ,					_A  ,					_A  ,					generator=_A  ,					).prev_sample
			# post-processing
			__magic_name__	:   int					     =					self.movq.decode(_A  ,					force_not_quantize=_A      )['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"]:
				__magic_name__	:   Dict					     =					image * 0.5 + 0.5
				__magic_name__	:   str					     =					image.clamp(0  ,					1      )
				__magic_name__	:   List[Any]					     =					image.cpu().permute(0  ,					2  ,					3  ,					1      ).float().numpy()

			if output_type == "pil":
				__magic_name__	:   str					     =					self.numpy_to_pil(_A      )

			if not return_dict:
				return (image,)

			return ImagePipelineOutput(images=_A      )