
"""simple docstring"""


from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

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,
)


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

_lowercase							   =				'''\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to("cuda")\n\n        >>> prompt = "A red cartoon frog, 4k"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to("cuda")\n\n        >>> init_image = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/frog.png"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save("red_frog.png")\n        ```\n'''






def       _snake_case				(		snake_case__   :     Any	,      snake_case__   :     int	,      snake_case__   :     Any=8     ):
	A						   =   height // scale_factor**2
	if height % scale_factor**2 != 0:
		new_height += 1
	A						   =   width // scale_factor**2
	if width % scale_factor**2 != 0:
		new_width += 1
	return new_height * scale_factor, new_width * scale_factor






def       _snake_case				(		snake_case__   :     Union[str, Any]	,      snake_case__   :     Optional[int]=512	,      snake_case__   :     int=512     ):
	A						   =   pil_image.resize((w, h)	,      resample=Image.BICUBIC	,      reducing_gap=1     )
	A						   =   np.array(pil_image.convert('RGB'     )     )
	A						   =   arr.astype(np.floataa     ) / 127.5 - 1
	A						   =   np.transpose(__lowerCAmelCase	,      [2, 0, 1]     )
	A						   =   torch.from_numpy(__lowerCAmelCase     ).unsqueeze(0     )
	return image







class 				lowerCAmelCase_				(      UpperCAmelCase__    ):



						'''simple docstring'''


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

							self.register_modules(
							    unet=lowerCamelCase__  ,scheduler=lowerCamelCase__  ,movq=lowerCamelCase__  ,)
							A						   =   2 ** (len(self.movq.config.block_out_channels      ) - 1)


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]  ,A_     :      int  ,A_     :      Tuple  ,A_     :      Union[str, Any]      )     ->   Union[str, Any]:
							A						   =   min(int(num_inference_steps * strength      )  ,lowerCamelCase__      )

							A						   =   max(num_inference_steps - init_timestep  ,0      )
							A						   =   self.scheduler.timesteps[t_start:]

							return timesteps, num_inference_steps - t_start


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]  ,A_     :      Tuple  ,A_     :      Dict  ,A_     :      Optional[Any]  ,A_     :      Dict  ,A_     :      Union[str, Any]  ,A_     :      List[str]  ,A_     :      Dict=None      )     ->   Any:







							if not isinstance(lowerCamelCase__  ,(torch.Tensor, PIL.Image.Image, list)      ):
								raise ValueError(
								    F'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCamelCase__      )}'      )

							A						   =   image.to(device=lowerCamelCase__  ,dtype=lowerCamelCase__      )

							A						   =   batch_size * num_images_per_prompt

							if image.shape[1] == 4:
								A						   =   image

							else:
								if isinstance(lowerCamelCase__  ,lowerCamelCase__      ) and len(lowerCamelCase__      ) != batch_size:
									raise ValueError(
									    F'You have passed a list of generators of length {len(lowerCamelCase__      )}, but requested an effective batch'
									    F' size of {batch_size}. Make sure the batch size matches the length of the generators.'      )

								elif isinstance(lowerCamelCase__  ,lowerCamelCase__      ):
									A						   =   [
									    self.movq.encode(image[i : i + 1]      ).latent_dist.sample(generator[i]      ) for i in range(lowerCamelCase__      )
									]
									A						   =   torch.cat(lowerCamelCase__  ,dim=0      )
								else:
									A						   =   self.movq.encode(lowerCamelCase__      ).latent_dist.sample(lowerCamelCase__      )

								A						   =   self.movq.config.scaling_factor * init_latents

							A						   =   torch.cat([init_latents]  ,dim=0      )

							A						   =   init_latents.shape
							A						   =   randn_tensor(lowerCamelCase__  ,generator=lowerCamelCase__  ,device=lowerCamelCase__  ,dtype=lowerCamelCase__      )

							# get latents
							A						   =   self.scheduler.add_noise(lowerCamelCase__  ,lowerCamelCase__  ,lowerCamelCase__      )

							A						   =   init_latents

							return latents


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any  ,A_     :      List[Any]=0      )     ->   str:







							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.movq,
							]
							for cpu_offloaded_model in models:
								if cpu_offloaded_model is not None:
									cpu_offload(lowerCamelCase__  ,lowerCamelCase__      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any  ,A_     :      Tuple=0      )     ->   List[Any]:







							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.unet, self.movq]:
								A						   =   cpu_offload_with_hook(lowerCamelCase__  ,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 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   Optional[Any]:







							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     :      str  ,A_     :      Union[torch.FloatTensor, List[torch.FloatTensor]]  ,A_     :      Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]  ,A_     :      Union[torch.FloatTensor, List[torch.FloatTensor]]  ,A_     :      int = 512  ,A_     :      int = 512  ,A_     :      int = 100  ,A_     :      float = 4.0  ,A_     :      float = 0.3  ,A_     :      int = 1  ,A_     :      Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,A_     :      Optional[str] = "pil"  ,A_     :      bool = True  ,)     ->   str:
							A						   =   self._execution_device

							A						   =   guidance_scale > 1.0

							if isinstance(lowerCamelCase__  ,lowerCamelCase__      ):
								A						   =   torch.cat(lowerCamelCase__  ,dim=0      )
							A						   =   image_embeds.shape[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=self.unet.dtype  ,device=lowerCamelCase__      )

							if not isinstance(lowerCamelCase__  ,lowerCamelCase__      ):
								A						   =   [image]
							if not all(isinstance(lowerCamelCase__  ,(PIL.Image.Image, torch.Tensor)      ) for i in image      ):
								raise ValueError(
								    F'Input is in incorrect format: {[type(lowerCamelCase__      ) for i in image]}. Currently, we only support  PIL image and pytorch tensor'      )

							A						   =   torch.cat([prepare_image(lowerCamelCase__  ,lowerCamelCase__  ,lowerCamelCase__      ) for i in image]  ,dim=0      )
							A						   =   image.to(dtype=image_embeds.dtype  ,device=lowerCamelCase__      )

							A						   =   self.movq.encode(lowerCamelCase__      )["latents"]
							A						   =   latents.repeat_interleave(lowerCamelCase__  ,dim=0      )
							self.scheduler.set_timesteps(lowerCamelCase__  ,device=lowerCamelCase__      )
							A						   =   self.get_timesteps(lowerCamelCase__  ,lowerCamelCase__  ,lowerCamelCase__      )
							A						   =   timesteps[:1].repeat(batch_size * num_images_per_prompt      )
							A						   =   downscale_height_and_width(lowerCamelCase__  ,lowerCamelCase__  ,self.movq_scale_factor      )
							A						   =   self.prepare_latents(
							    lowerCamelCase__  ,lowerCamelCase__  ,lowerCamelCase__  ,lowerCamelCase__  ,image_embeds.dtype  ,lowerCamelCase__  ,lowerCamelCase__      )
							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						   =   {"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						   =   noise_pred.split(latents.shape[1]  ,dim=1      )
									A						   =   noise_pred.chunk(2      )
									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						   =   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__  ,)[0]

							# 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 json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List

from ..utils import logging
from . import BaseTransformersCLICommand


try:
		from cookiecutter.main import cookiecutter

		_lowercase							   =				True
except ImportError:
		_lowercase							   =				False

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






def       _snake_case				(		snake_case__   :     Namespace     ):
	return AddNewModelCommand(args.testing	,      args.testing_file	,      path=args.path     )







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						@staticmethod
						def 						_SCREAMING_SNAKE_CASE      ( A_     :      ArgumentParser      )     ->   Any:
							A						   =   parser.add_parser('add-new-model'      )
							add_new_model_parser.add_argument('--testing'  ,action='store_true'  ,help='If in testing mode.'      )
							add_new_model_parser.add_argument('--testing_file'  ,type=A_  ,help='Configuration file on which to run.'      )
							add_new_model_parser.add_argument(
							    '--path'  ,type=A_  ,help='Path to cookiecutter. Should only be used for testing purposes.'      )
							add_new_model_parser.set_defaults(func=A_      )


						def __init__( self     :      Tuple  ,A_     :      bool  ,A_     :      str  ,A_     :      Tuple=None  ,*A_     :      List[str]      )     ->   Union[str, Any]:
							A						   =   testing
							A						   =   testing_file
							A						   =   path




						def 						_SCREAMING_SNAKE_CASE      ( self     :      int      )     ->   int:
							warnings.warn(
							    'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. '
							    'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality '
							    'checks, you should use `transformers-cli add-new-model-like` instead.'      )
							if not _has_cookiecutter:
								raise ImportError(
								    'Model creation dependencies are required to use the `add_new_model` command. Install them by running '
								    'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n'      )
							# Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
							A						   =   [directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]]
							if len(A_      ) > 0:
								raise ValueError(
								    'Several directories starting with `cookiecutter-template-` in current working directory. '
								    'Please clean your directory by removing all folders starting with `cookiecutter-template-` or '
								    'change your working directory.'      )

							A						   =   (
							    Path(A_      ).parent.parent.parent.parent if self._path is None else Path(self._path      ).parent.parent
							)
							A						   =   path_to_transformer_root / 'templates' / 'adding_a_new_model'

							# Execute cookiecutter
							if not self._testing:
								cookiecutter(str(A_      )      )
							else:
								with open(self._testing_file  ,'r'      ) as configuration_file:
									A						   =   json.load(A_      )

								cookiecutter(
								    str(path_to_cookiecutter if self._path is None else self._path      )  ,no_input=A_  ,extra_context=A_  ,)

							A						   =   [directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0]

							# Retrieve configuration
							with open(directory + '/configuration.json'  ,'r'      ) as configuration_file:
								A						   =   json.load(A_      )

							A						   =   configuration['lowercase_modelname']
							A						   =   configuration['generate_tensorflow_pytorch_and_flax']
							os.remove(F'{directory}/configuration.json'      )

							A						   =   'PyTorch' in generate_tensorflow_pytorch_and_flax
							A						   =   'TensorFlow' in generate_tensorflow_pytorch_and_flax
							A						   =   'Flax' in generate_tensorflow_pytorch_and_flax

							A						   =   F'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}'
							os.makedirs(A_  ,exist_ok=A_      )
							os.makedirs(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}'  ,exist_ok=A_      )

							# Tests require submodules as they have parent imports
							with open(F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py'  ,'w'      ):
								pass

							shutil.move(
							    F'{directory}/__init__.py'  ,F'{model_dir}/__init__.py'  ,)
							shutil.move(
							    F'{directory}/configuration_{lowercase_model_name}.py'  ,F'{model_dir}/configuration_{lowercase_model_name}.py'  ,)

							def remove_copy_lines(A_     :      int      ):
								with open(A_  ,'r'      ) as f:
									A						   =   f.readlines()
								with open(A_  ,'w'      ) as f:
									for line in lines:
										if "# Copied from transformers." not in line:
											f.write(A_      )

							if output_pytorch:
								if not self._testing:
									remove_copy_lines(F'{directory}/modeling_{lowercase_model_name}.py'      )

								shutil.move(
								    F'{directory}/modeling_{lowercase_model_name}.py'  ,F'{model_dir}/modeling_{lowercase_model_name}.py'  ,)

								shutil.move(
								    F'{directory}/test_modeling_{lowercase_model_name}.py'  ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py'  ,)
							else:
								os.remove(F'{directory}/modeling_{lowercase_model_name}.py'      )
								os.remove(F'{directory}/test_modeling_{lowercase_model_name}.py'      )

							if output_tensorflow:
								if not self._testing:
									remove_copy_lines(F'{directory}/modeling_tf_{lowercase_model_name}.py'      )

								shutil.move(
								    F'{directory}/modeling_tf_{lowercase_model_name}.py'  ,F'{model_dir}/modeling_tf_{lowercase_model_name}.py'  ,)

								shutil.move(
								    F'{directory}/test_modeling_tf_{lowercase_model_name}.py'  ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py'  ,)
							else:
								os.remove(F'{directory}/modeling_tf_{lowercase_model_name}.py'      )
								os.remove(F'{directory}/test_modeling_tf_{lowercase_model_name}.py'      )

							if output_flax:
								if not self._testing:
									remove_copy_lines(F'{directory}/modeling_flax_{lowercase_model_name}.py'      )

								shutil.move(
								    F'{directory}/modeling_flax_{lowercase_model_name}.py'  ,F'{model_dir}/modeling_flax_{lowercase_model_name}.py'  ,)

								shutil.move(
								    F'{directory}/test_modeling_flax_{lowercase_model_name}.py'  ,F'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py'  ,)
							else:
								os.remove(F'{directory}/modeling_flax_{lowercase_model_name}.py'      )
								os.remove(F'{directory}/test_modeling_flax_{lowercase_model_name}.py'      )

							shutil.move(
							    F'{directory}/{lowercase_model_name}.md'  ,F'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md'  ,)

							shutil.move(
							    F'{directory}/tokenization_{lowercase_model_name}.py'  ,F'{model_dir}/tokenization_{lowercase_model_name}.py'  ,)

							shutil.move(
							    F'{directory}/tokenization_fast_{lowercase_model_name}.py'  ,F'{model_dir}/tokenization_{lowercase_model_name}_fast.py'  ,)

							from os import fdopen, remove
							from shutil import copymode, move
							from tempfile import mkstemp

							def replace(A_     :      str  ,A_     :      str  ,A_     :      List[str]      ):
								# Create temp file
								A   ,      A						   =   mkstemp()
								A						   =   False
								with fdopen(A_  ,'w'      ) as new_file:
									with open(A_      ) as old_file:
										for line in old_file:
											new_file.write(A_      )
											if line_to_copy_below in line:
												A						   =   True
												for line_to_copy in lines_to_copy:
													new_file.write(A_      )

								if not line_found:
									raise ValueError(F'Line {line_to_copy_below} was not found in file.'      )

								# Copy the file permissions from the old file to the new file
								copymode(A_  ,A_      )
								# Remove original file
								remove(A_      )
								# Move new file
								move(A_  ,A_      )

							def skip_units(A_     :      Dict      ):
								return (
								    ("generating PyTorch" in line and not output_pytorch)
								    or ("generating TensorFlow" in line and not output_tensorflow)
								    or ("generating Flax" in line and not output_flax)
								)

							def replace_in_files(A_     :      Tuple      ):
								with open(A_      ) as datafile:
									A						   =   []
									A						   =   False
									A						   =   False
									for line in datafile:
										if "# To replace in: " in line and "##" not in line:
											A						   =   line.split('"'      )[1]
											A						   =   skip_units(A_      )
										elif "# Below: " in line and "##" not in line:
											A						   =   line.split('"'      )[1]
											A						   =   skip_units(A_      )
										elif "# End." in line and "##" not in line:
											if not skip_file and not skip_snippet:
												replace(A_  ,A_  ,A_      )

											A						   =   []
										elif "# Replace with" in line and "##" not in line:
											A						   =   []
										elif "##" not in line:
											lines_to_copy.append(A_      )

								remove(A_      )

							replace_in_files(F'{directory}/to_replace_{lowercase_model_name}.py'      )
							os.rmdir(A_      )