




"""simple docstring"""







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

__A   :  List[Any]					=      '\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)["depth"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline("depth-estimation")\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to("cuda")\n\n        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to("cuda")\n\n\n        >>> img = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/cat.png"\n        ... ).resize((768, 768))\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n        >>> prompt = "A robot, 4k photo"\n        >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n        >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n        >>> image_emb, zero_image_emb = pipe_prior(\n        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n        ... ).to_tuple()\n\n        >>> images = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save("robot_cat.png")\n        ```\n'

def 						snake_case__       (					_lowerCamelCase,  _lowerCamelCase,  _lowerCamelCase=8				)			->str:






		"""simple docstring"""


		__lowercase				:		Optional[Any]												=				height // scale_factor**2
		if height % scale_factor**2 != 0:
				new_height += 1
		__lowercase				:		Union[str, Any]												=				width // scale_factor**2
		if width % scale_factor**2 != 0:
				new_width += 1
		return new_height * scale_factor, new_width * scale_factor





class       lowerCAmelCase__       (			lowerCAmelCase_    ):


				"""simple docstring"""





				def __init__(     self					:	Any    ,   lowercase__					:	UNetaDConditionModel    ,   lowercase__					:	DDPMScheduler    ,   lowercase__					:	VQModel    ,   ):
						super().__init__()

						self.register_modules(
						    unet=lowercase__    ,   scheduler=lowercase__    ,   movq=lowercase__    ,   )
						__lowercase				:		List[str]												=				2 ** (len(self.movq.config.block_out_channels						) - 1)



				def       snake_case    (     self					:	Any    ,   lowercase__					:	List[str]    ,   lowercase__					:	Union[str, Any]    ,   lowercase__					:	Union[str, Any]    ,   lowercase__					:	int    ,   lowercase__					:	Union[str, Any]    ,   lowercase__					:	Union[str, Any]						):
						if latents is None:
								__lowercase				:		Optional[int]												=				randn_tensor(lowercase__    ,   generator=lowercase__    ,   device=lowercase__    ,   dtype=lowercase__						)
						else:
								if latents.shape != shape:
										raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'						)
								__lowercase				:		Any												=				latents.to(lowercase__						)

						__lowercase				:		Dict												=				latents * scheduler.init_noise_sigma
						return latents



				def       snake_case    (     self					:	Any    ,   lowercase__					:	List[str]=0						):
						if is_accelerate_available():
								from accelerate import cpu_offload
						else:
								raise ImportError("Please install accelerate via `pip install accelerate`"						)

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

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



				def       snake_case    (     self					:	Optional[int]    ,   lowercase__					:	Any=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."						)

						__lowercase				:		Optional[int]												=				torch.device(f'cuda:{gpu_id}'						)

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

						__lowercase				:		Union[str, Any]												=				None
						for cpu_offloaded_model in [self.unet, self.movq]:
								__lowercase						,__lowercase				:		Union[str, Any]												=				cpu_offload_with_hook(lowercase__    ,   lowercase__    ,   prev_module_hook=lowercase__						)

						# We'll offload the last model manually.
						__lowercase				:		List[str]												=				hook



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

						__lowercase				:		Union[str, Any]												=				guidance_scale > 1.0

						if isinstance(lowercase__    ,   lowercase__						):
								__lowercase				:		Tuple												=				torch.cat(lowercase__    ,   dim=0						)
						if isinstance(lowercase__    ,   lowercase__						):
								__lowercase				:		Dict												=				torch.cat(lowercase__    ,   dim=0						)
						if isinstance(lowercase__    ,   lowercase__						):
								__lowercase				:		List[str]												=				torch.cat(lowercase__    ,   dim=0						)

						__lowercase				:		Tuple												=				image_embeds.shape[0] * num_images_per_prompt

						if do_classifier_free_guidance:
								__lowercase				:		Optional[Any]												=				image_embeds.repeat_interleave(lowercase__    ,   dim=0						)
								__lowercase				:		Union[str, Any]												=				negative_image_embeds.repeat_interleave(lowercase__    ,   dim=0						)
								__lowercase				:		Any												=				hint.repeat_interleave(lowercase__    ,   dim=0						)

						__lowercase				:		Tuple												=				torch.cat([negative_image_embeds, image_embeds]    ,   dim=0						).to(dtype=self.unet.dtype    ,   device=lowercase__						)
						__lowercase				:		str												=				torch.cat([hint, hint]    ,   dim=0						).to(dtype=self.unet.dtype    ,   device=lowercase__						)
						self.scheduler.set_timesteps(lowercase__    ,   device=lowercase__						)
						__lowercase				:		Union[str, Any]												=				self.scheduler.timesteps

						__lowercase				:		Dict												=				self.movq.config.latent_channels

						__lowercase						,__lowercase				:		Optional[int]												=				downscale_height_and_width(lowercase__    ,   lowercase__    ,   self.movq_scale_factor						)

						# create initial latent
						__lowercase				:		List[Any]												=				self.prepare_latents(
						    (batch_size, num_channels_latents, height, width)    ,   image_embeds.dtype    ,   lowercase__    ,   lowercase__    ,   lowercase__    ,   self.scheduler    ,   )

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

								__lowercase				:		int												=				{"image_embeds": image_embeds, "hint": hint}
								__lowercase				:		List[str]												=				self.unet(
								    sample=lowercase__    ,   timestep=lowercase__    ,   encoder_hidden_states=lowercase__    ,   added_cond_kwargs=lowercase__    ,   return_dict=lowercase__    ,   )[0]

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

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

						if output_type == "pil":
								__lowercase				:		List[Any]												=				self.numpy_to_pil(lowercase__						)

						if not return_dict:
								return (image,)

						return ImagePipelineOutput(images=lowercase__						)






"""simple docstring"""







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


__A   :  Optional[int]					=      {
    'Acehnese Arabic': 'ace_Arab',
    'Acehnese Latin': 'ace_Latn',
    'Mesopotamian Arabic': 'acm_Arab',
    'Ta\'izzi-Adeni Arabic': 'acq_Arab',
    'Tunisian Arabic': 'aeb_Arab',
    'Afrikaans': 'afr_Latn',
    'South Levantine Arabic': 'ajp_Arab',
    'Akan': 'aka_Latn',
    'Amharic': 'amh_Ethi',
    'North Levantine Arabic': 'apc_Arab',
    'Modern Standard Arabic': 'arb_Arab',
    'Modern Standard Arabic Romanized': 'arb_Latn',
    'Najdi Arabic': 'ars_Arab',
    'Moroccan Arabic': 'ary_Arab',
    'Egyptian Arabic': 'arz_Arab',
    'Assamese': 'asm_Beng',
    'Asturian': 'ast_Latn',
    'Awadhi': 'awa_Deva',
    'Central Aymara': 'ayr_Latn',
    'South Azerbaijani': 'azb_Arab',
    'North Azerbaijani': 'azj_Latn',
    'Bashkir': 'bak_Cyrl',
    'Bambara': 'bam_Latn',
    'Balinese': 'ban_Latn',
    'Belarusian': 'bel_Cyrl',
    'Bemba': 'bem_Latn',
    'Bengali': 'ben_Beng',
    'Bhojpuri': 'bho_Deva',
    'Banjar Arabic': 'bjn_Arab',
    'Banjar Latin': 'bjn_Latn',
    'Standard Tibetan': 'bod_Tibt',
    'Bosnian': 'bos_Latn',
    'Buginese': 'bug_Latn',
    'Bulgarian': 'bul_Cyrl',
    'Catalan': 'cat_Latn',
    'Cebuano': 'ceb_Latn',
    'Czech': 'ces_Latn',
    'Chokwe': 'cjk_Latn',
    'Central Kurdish': 'ckb_Arab',
    'Crimean Tatar': 'crh_Latn',
    'Welsh': 'cym_Latn',
    'Danish': 'dan_Latn',
    'German': 'deu_Latn',
    'Southwestern Dinka': 'dik_Latn',
    'Dyula': 'dyu_Latn',
    'Dzongkha': 'dzo_Tibt',
    'Greek': 'ell_Grek',
    'English': 'eng_Latn',
    'Esperanto': 'epo_Latn',
    'Estonian': 'est_Latn',
    'Basque': 'eus_Latn',
    'Ewe': 'ewe_Latn',
    'Faroese': 'fao_Latn',
    'Fijian': 'fij_Latn',
    'Finnish': 'fin_Latn',
    'Fon': 'fon_Latn',
    'French': 'fra_Latn',
    'Friulian': 'fur_Latn',
    'Nigerian Fulfulde': 'fuv_Latn',
    'Scottish Gaelic': 'gla_Latn',
    'Irish': 'gle_Latn',
    'Galician': 'glg_Latn',
    'Guarani': 'grn_Latn',
    'Gujarati': 'guj_Gujr',
    'Haitian Creole': 'hat_Latn',
    'Hausa': 'hau_Latn',
    'Hebrew': 'heb_Hebr',
    'Hindi': 'hin_Deva',
    'Chhattisgarhi': 'hne_Deva',
    'Croatian': 'hrv_Latn',
    'Hungarian': 'hun_Latn',
    'Armenian': 'hye_Armn',
    'Igbo': 'ibo_Latn',
    'Ilocano': 'ilo_Latn',
    'Indonesian': 'ind_Latn',
    'Icelandic': 'isl_Latn',
    'Italian': 'ita_Latn',
    'Javanese': 'jav_Latn',
    'Japanese': 'jpn_Jpan',
    'Kabyle': 'kab_Latn',
    'Jingpho': 'kac_Latn',
    'Kamba': 'kam_Latn',
    'Kannada': 'kan_Knda',
    'Kashmiri Arabic': 'kas_Arab',
    'Kashmiri Devanagari': 'kas_Deva',
    'Georgian': 'kat_Geor',
    'Central Kanuri Arabic': 'knc_Arab',
    'Central Kanuri Latin': 'knc_Latn',
    'Kazakh': 'kaz_Cyrl',
    'Kabiyè': 'kbp_Latn',
    'Kabuverdianu': 'kea_Latn',
    'Khmer': 'khm_Khmr',
    'Kikuyu': 'kik_Latn',
    'Kinyarwanda': 'kin_Latn',
    'Kyrgyz': 'kir_Cyrl',
    'Kimbundu': 'kmb_Latn',
    'Northern Kurdish': 'kmr_Latn',
    'Kikongo': 'kon_Latn',
    'Korean': 'kor_Hang',
    'Lao': 'lao_Laoo',
    'Ligurian': 'lij_Latn',
    'Limburgish': 'lim_Latn',
    'Lingala': 'lin_Latn',
    'Lithuanian': 'lit_Latn',
    'Lombard': 'lmo_Latn',
    'Latgalian': 'ltg_Latn',
    'Luxembourgish': 'ltz_Latn',
    'Luba-Kasai': 'lua_Latn',
    'Ganda': 'lug_Latn',
    'Luo': 'luo_Latn',
    'Mizo': 'lus_Latn',
    'Standard Latvian': 'lvs_Latn',
    'Magahi': 'mag_Deva',
    'Maithili': 'mai_Deva',
    'Malayalam': 'mal_Mlym',
    'Marathi': 'mar_Deva',
    'Minangkabau Arabic ': 'min_Arab',
    'Minangkabau Latin': 'min_Latn',
    'Macedonian': 'mkd_Cyrl',
    'Plateau Malagasy': 'plt_Latn',
    'Maltese': 'mlt_Latn',
    'Meitei Bengali': 'mni_Beng',
    'Halh Mongolian': 'khk_Cyrl',
    'Mossi': 'mos_Latn',
    'Maori': 'mri_Latn',
    'Burmese': 'mya_Mymr',
    'Dutch': 'nld_Latn',
    'Norwegian Nynorsk': 'nno_Latn',
    'Norwegian Bokmål': 'nob_Latn',
    'Nepali': 'npi_Deva',
    'Northern Sotho': 'nso_Latn',
    'Nuer': 'nus_Latn',
    'Nyanja': 'nya_Latn',
    'Occitan': 'oci_Latn',
    'West Central Oromo': 'gaz_Latn',
    'Odia': 'ory_Orya',
    'Pangasinan': 'pag_Latn',
    'Eastern Panjabi': 'pan_Guru',
    'Papiamento': 'pap_Latn',
    'Western Persian': 'pes_Arab',
    'Polish': 'pol_Latn',
    'Portuguese': 'por_Latn',
    'Dari': 'prs_Arab',
    'Southern Pashto': 'pbt_Arab',
    'Ayacucho Quechua': 'quy_Latn',
    'Romanian': 'ron_Latn',
    'Rundi': 'run_Latn',
    'Russian': 'rus_Cyrl',
    'Sango': 'sag_Latn',
    'Sanskrit': 'san_Deva',
    'Santali': 'sat_Olck',
    'Sicilian': 'scn_Latn',
    'Shan': 'shn_Mymr',
    'Sinhala': 'sin_Sinh',
    'Slovak': 'slk_Latn',
    'Slovenian': 'slv_Latn',
    'Samoan': 'smo_Latn',
    'Shona': 'sna_Latn',
    'Sindhi': 'snd_Arab',
    'Somali': 'som_Latn',
    'Southern Sotho': 'sot_Latn',
    'Spanish': 'spa_Latn',
    'Tosk Albanian': 'als_Latn',
    'Sardinian': 'srd_Latn',
    'Serbian': 'srp_Cyrl',
    'Swati': 'ssw_Latn',
    'Sundanese': 'sun_Latn',
    'Swedish': 'swe_Latn',
    'Swahili': 'swh_Latn',
    'Silesian': 'szl_Latn',
    'Tamil': 'tam_Taml',
    'Tatar': 'tat_Cyrl',
    'Telugu': 'tel_Telu',
    'Tajik': 'tgk_Cyrl',
    'Tagalog': 'tgl_Latn',
    'Thai': 'tha_Thai',
    'Tigrinya': 'tir_Ethi',
    'Tamasheq Latin': 'taq_Latn',
    'Tamasheq Tifinagh': 'taq_Tfng',
    'Tok Pisin': 'tpi_Latn',
    'Tswana': 'tsn_Latn',
    'Tsonga': 'tso_Latn',
    'Turkmen': 'tuk_Latn',
    'Tumbuka': 'tum_Latn',
    'Turkish': 'tur_Latn',
    'Twi': 'twi_Latn',
    'Central Atlas Tamazight': 'tzm_Tfng',
    'Uyghur': 'uig_Arab',
    'Ukrainian': 'ukr_Cyrl',
    'Umbundu': 'umb_Latn',
    'Urdu': 'urd_Arab',
    'Northern Uzbek': 'uzn_Latn',
    'Venetian': 'vec_Latn',
    'Vietnamese': 'vie_Latn',
    'Waray': 'war_Latn',
    'Wolof': 'wol_Latn',
    'Xhosa': 'xho_Latn',
    'Eastern Yiddish': 'ydd_Hebr',
    'Yoruba': 'yor_Latn',
    'Yue Chinese': 'yue_Hant',
    'Chinese Simplified': 'zho_Hans',
    'Chinese Traditional': 'zho_Hant',
    'Standard Malay': 'zsm_Latn',
    'Zulu': 'zul_Latn',
}




class       lowerCAmelCase__       (			lowerCAmelCase_    ):


				"""simple docstring"""





				__UpperCAmelCase :     str       =      "facebook/nllb-200-distilled-600M"
				__UpperCAmelCase :     Tuple       =      (
				    "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should "
				    "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, "
				    "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in "
				    "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`."
				)
				__UpperCAmelCase :     str       =      "translator"
				__UpperCAmelCase :     Optional[int]       =      AutoTokenizer
				__UpperCAmelCase :     Dict       =      AutoModelForSeqaSeqLM
				__UpperCAmelCase :     Tuple       =      LANGUAGE_CODES

				__UpperCAmelCase :     int       =      ["text", "text", "text"]
				__UpperCAmelCase :     int       =      ["text"]



				def       snake_case    (     self					:	Dict    ,   lowercase__					:	List[Any]    ,   lowercase__					:	Optional[Any]    ,   lowercase__					:	Any						):
						if src_lang not in self.lang_to_code:
								raise ValueError(f'{src_lang} is not a supported language.'						)
						if tgt_lang not in self.lang_to_code:
								raise ValueError(f'{tgt_lang} is not a supported language.'						)
						__lowercase				:		List[str]												=				self.lang_to_code[src_lang]
						__lowercase				:		List[str]												=				self.lang_to_code[tgt_lang]
						return self.pre_processor._build_translation_inputs(
						    lowercase__    ,   return_tensors="pt"    ,   src_lang=lowercase__    ,   tgt_lang=lowercase__						)



				def       snake_case    (     self					:	str    ,   lowercase__					:	Tuple						):
						return self.model.generate(**lowercase__						)



				def       snake_case    (     self					:	Union[str, Any]    ,   lowercase__					:	List[Any]						):
						return self.post_processor.decode(outputs[0].tolist()    ,   skip_special_tokens=lowercase__						)
