



from typing import List, Optional, Union

import torch

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


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

A        =			'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n        >>> pipe_prior.to("cuda")\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> zero_image_emb = out.negative_image_embeds\n        >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n        >>> pipe.to("cuda")\n        >>> image = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=50,\n        ... ).images\n        >>> image[0].save("cat.png")\n        ```\n'



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]    ,    lowerCAmelCase__				:		Dict    ,    lowerCAmelCase__				:		str=8      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   height // scale_factor**2
				if height % scale_factor**2 != 0:
								new_height += 1
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   width // scale_factor**2
				if width % scale_factor**2 != 0:
								new_width += 1
				return new_height * scale_factor, new_width * scale_factor


class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    ):
						super().__init__()

						self.register_modules(
						    unet=UpperCAmelCase__ ,    scheduler=UpperCAmelCase__ ,    movq=UpperCAmelCase__ ,    )
						SCREAMING_SNAKE_CASE_   :	int													=   2 ** (len(self.movq.config.block_out_channels       ) - 1)


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       ):
						if latents is None:
										SCREAMING_SNAKE_CASE_   :	str													=   randn_tensor(UpperCAmelCase__ ,    generator=UpperCAmelCase__ ,    device=UpperCAmelCase__ ,    dtype=UpperCAmelCase__       )
						else:
										if latents.shape != shape:
														raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''       )
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   latents.to(UpperCAmelCase__       )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   latents * scheduler.init_noise_sigma
						return latents


		def   __snake_case			(						self ,    UpperCamelCase__=0       ):
						if is_accelerate_available():
										from accelerate import cpu_offload
						else:
										raise ImportError('Please install accelerate via `pip install accelerate`'       )

						SCREAMING_SNAKE_CASE_   :	Tuple													=   torch.device(F'''cuda:{gpu_id}'''       )

						SCREAMING_SNAKE_CASE_   :	Any													=   [
						    self.unet,
						    self.movq,
						]
						for cpu_offloaded_model in models:
										if cpu_offloaded_model is not None:
														cpu_offload(UpperCAmelCase__ ,    UpperCAmelCase__       )


		def   __snake_case			(						self ,    UpperCamelCase__=0       ):
						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.'       )

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

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

						SCREAMING_SNAKE_CASE_   :	Tuple													=   None
						for cpu_offloaded_model in [self.unet, self.movq]:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   cpu_offload_with_hook(UpperCAmelCase__ ,    UpperCAmelCase__ ,    prev_module_hook=UpperCAmelCase__       )

						# We'll offload the last model manually.
						SCREAMING_SNAKE_CASE_   :	Dict													=   hook


		@property
		# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
		def   __snake_case			(						self       ):
						if not hasattr(self.unet ,    '_hf_hook'       ):
										return self.device
						for module in self.unet.modules():
										if (
										    hasattr(UpperCAmelCase__ ,    '_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(UpperCAmelCase__       )
		def __call__(						self ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ = 512 ,    UpperCamelCase__ = 512 ,    UpperCamelCase__ = 100 ,    UpperCamelCase__ = 4.0 ,    UpperCamelCase__ = 1 ,    UpperCamelCase__ = None ,    UpperCamelCase__ = None ,    UpperCamelCase__ = "pil" ,    UpperCamelCase__ = True ,    ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   self._execution_device

						SCREAMING_SNAKE_CASE_   :	int													=   guidance_scale > 1.0

						if isinstance(UpperCAmelCase__ ,    UpperCAmelCase__       ):
										SCREAMING_SNAKE_CASE_   :	Tuple													=   torch.cat(UpperCAmelCase__ ,    dim=0       )
						SCREAMING_SNAKE_CASE_   :	List[str]													=   image_embeds.shape[0] * num_images_per_prompt
						if isinstance(UpperCAmelCase__ ,    UpperCAmelCase__       ):
										SCREAMING_SNAKE_CASE_   :	str													=   torch.cat(UpperCAmelCase__ ,    dim=0       )

						if do_classifier_free_guidance:
										SCREAMING_SNAKE_CASE_   :	str													=   image_embeds.repeat_interleave(UpperCAmelCase__ ,    dim=0       )
										SCREAMING_SNAKE_CASE_   :	str													=   negative_image_embeds.repeat_interleave(UpperCAmelCase__ ,    dim=0       )

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   torch.cat([negative_image_embeds, image_embeds] ,    dim=0       ).to(dtype=self.unet.dtype ,    device=UpperCAmelCase__       )

						self.scheduler.set_timesteps(UpperCAmelCase__ ,    device=UpperCAmelCase__       )
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.scheduler.timesteps

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

						SCREAMING_SNAKE_CASE_   :	Dict													=   downscale_height_and_width(UpperCAmelCase__ ,    UpperCAmelCase__ ,    self.movq_scale_factor       )

						# create initial latent
						SCREAMING_SNAKE_CASE_   :	str													=   self.prepare_latents(
						    (batch_size, num_channels_latents, height, width) ,    image_embeds.dtype ,    UpperCAmelCase__ ,    UpperCAmelCase__ ,    UpperCAmelCase__ ,    self.scheduler ,    )

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

										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   {'''image_embeds''': image_embeds}
										SCREAMING_SNAKE_CASE_   :	Any													=   self.unet(
										    sample=UpperCAmelCase__ ,    timestep=UpperCAmelCase__ ,    encoder_hidden_states=UpperCAmelCase__ ,    added_cond_kwargs=UpperCAmelCase__ ,    return_dict=UpperCAmelCase__ ,    )[0]

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

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

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

						if not return_dict:
										return (image,)

						return ImagePipelineOutput(images=UpperCAmelCase__       )







import os

from bleurt import score  # From: git+https://github.com/google-research/bleurt.git

import datasets


A        =			datasets.logging.get_logger(__name__)


A        =			'\\n@inproceedings{bleurt,\n  title={BLEURT: Learning Robust Metrics for Text Generation},\n  author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n  booktitle={ACL},\n  year={2020},\n  url={https://arxiv.org/abs/2004.04696}\n}\n'

A        =			'\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project\'s README at https://github.com/google-research/bleurt#readme for more information.\n'

A        =			'\nBLEURT score.\n\nArgs:\n    `predictions` (list of str): prediction/candidate sentences\n    `references` (list of str): reference sentences\n    `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n    \'scores\': List of scores.\nExamples:\n\n    >>> predictions = ["hello there", "general kenobi"]\n    >>> references = ["hello there", "general kenobi"]\n    >>> bleurt = datasets.load_metric("bleurt")\n    >>> results = bleurt.compute(predictions=predictions, references=references)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [1.03, 1.04]\n'

A        =			{
    'bleurt-tiny-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip',
    'bleurt-tiny-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip',
    'bleurt-base-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip',
    'bleurt-base-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip',
    'bleurt-large-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip',
    'bleurt-large-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip',
    'BLEURT-20-D3': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip',
    'BLEURT-20-D6': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip',
    'BLEURT-20-D12': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip',
    'BLEURT-20': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip',
}


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





		'''simple docstring'''



		def   __snake_case			(						self       ):
						return datasets.MetricInfo(
						    description=_DESCRIPTION ,    citation=_CITATION ,    homepage='https://github.com/google-research/bleurt' ,    inputs_description=_KWARGS_DESCRIPTION ,    features=datasets.Features(
						        {
						            'predictions': datasets.Value('string' ,    id='sequence'       ),
						            'references': datasets.Value('string' ,    id='sequence'       ),
						        }       ) ,    codebase_urls=['https://github.com/google-research/bleurt'] ,    reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] ,    )


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						# check that config name specifies a valid BLEURT model
						if self.config_name == "default":
										logger.warning(
										    'Using default BLEURT-Base checkpoint for sequence maximum length 128. '
										    'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').'       )
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   'bleurt-base-128'

						if self.config_name.lower() in CHECKPOINT_URLS:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   self.config_name.lower()

						elif self.config_name.upper() in CHECKPOINT_URLS:
										SCREAMING_SNAKE_CASE_   :	Any													=   self.config_name.upper()

						else:
										raise KeyError(
										    F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}'''       )

						# download the model checkpoint specified by self.config_name and set up the scorer
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name]       )
						SCREAMING_SNAKE_CASE_   :	int													=   score.BleurtScorer(os.path.join(UpperCamelCase__ ,    UpperCamelCase__       )       )






		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   self.scorer.score(references=UpperCamelCase__ ,    candidates=UpperCamelCase__       )
						return {"scores": scores}