






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


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

__lowerCAmelCase				="\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 				a						( _UpperCAmelCase       ,	_UpperCAmelCase       ,	_UpperCAmelCase=8			)					->					List[Any]:






					"""simple docstring"""







					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 				a						( _UpperCAmelCase       ,	_UpperCAmelCase=5_1_2       ,	_UpperCAmelCase=5_1_2			)					->					str:






					"""simple docstring"""







					a_						= pil_image.resize((w, h)       ,	resample=Image.BICUBIC       ,	reducing_gap=1			)
					a_						= np.array(pil_image.convert('RGB'			)			)
					a_						= arr.astype(np.floataa			) / 1_2_7.5 - 1
					a_						= np.transpose(__lowerCamelCase       ,	[2, 0, 1]			)
					a_						= torch.from_numpy(__lowerCamelCase			).unsqueeze(0			)
					return image





class  _snake_case (					snake_case       ):

					"""simple docstring"""





					def __init__(  self ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			)   ->						Dict:
										super().__init__()

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




					def 			__SCREAMING_SNAKE_CASE			(  self ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__  )   ->						Tuple:
										a_						= min(int(num_inference_steps * strength  ) ,			UpperCAmelCase__  )

										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 ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__=None  )   ->						Dict:
										if not isinstance(UpperCAmelCase__ ,			(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(UpperCAmelCase__  )}'''  )

										a_						= image.to(device=UpperCAmelCase__ ,			dtype=UpperCAmelCase__  )

										a_						= batch_size * num_images_per_prompt

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

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

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

															a_						= self.movq.config.scaling_factor * init_latents

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

										a_						= init_latents.shape
										a_						= randn_tensor(UpperCAmelCase__ ,			generator=UpperCAmelCase__ ,			device=UpperCAmelCase__ ,			dtype=UpperCAmelCase__  )

										# get latents
										a_						= self.scheduler.add_noise(UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__  )

										a_						= init_latents

										return latents




					def 			__SCREAMING_SNAKE_CASE			(  self ,			UpperCAmelCase__=0  )   ->						Tuple:
										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(UpperCAmelCase__ ,			UpperCAmelCase__  )




					def 			__SCREAMING_SNAKE_CASE			(  self ,			UpperCAmelCase__=0  )   ->						Optional[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=UpperCAmelCase__  )
															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(UpperCAmelCase__ ,			UpperCAmelCase__ ,			prev_module_hook=UpperCAmelCase__  )

										# 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  )   ->						Tuple:
										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__ ,			UpperCAmelCase__ = 512 ,			UpperCAmelCase__ = 512 ,			UpperCAmelCase__ = 100 ,			UpperCAmelCase__ = 4.0 ,			UpperCAmelCase__ = 0.3 ,			UpperCAmelCase__ = 1 ,			UpperCAmelCase__ = None ,			UpperCAmelCase__ = "pil" ,			UpperCAmelCase__ = True ,			)   ->						Any:
										a_						= self._execution_device

										a_						= guidance_scale > 1.0

										if isinstance(UpperCAmelCase__ ,			UpperCAmelCase__  ):
															a_						= torch.cat(UpperCAmelCase__ ,			dim=0  )
										a_						= image_embeds.shape[0]
										if isinstance(UpperCAmelCase__ ,			UpperCAmelCase__  ):
															a_						= torch.cat(UpperCAmelCase__ ,			dim=0  )

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

										a_						= torch.cat([negative_image_embeds, image_embeds] ,			dim=0  ).to(dtype=self.unet.dtype ,			device=UpperCAmelCase__  )

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

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

										a_						= self.movq.encode(UpperCAmelCase__  )['latents']
										a_						= latents.repeat_interleave(UpperCAmelCase__ ,			dim=0  )
										self.scheduler.set_timesteps(UpperCAmelCase__ ,			device=UpperCAmelCase__  )
										a_						= self.get_timesteps(UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__  )
										a_						= timesteps[:1].repeat(batch_size * num_images_per_prompt  )
										a_						= downscale_height_and_width(UpperCAmelCase__ ,			UpperCAmelCase__ ,			self.movq_scale_factor  )
										a_						= self.prepare_latents(
										    UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			image_embeds.dtype ,			UpperCAmelCase__ ,			UpperCAmelCase__  )
										for i, t in enumerate(self.progress_bar(UpperCAmelCase__  )  ):
															# 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=UpperCAmelCase__ ,			timestep=UpperCAmelCase__ ,			encoder_hidden_states=UpperCAmelCase__ ,			added_cond_kwargs=UpperCAmelCase__ ,			return_dict=UpperCAmelCase__ ,			)[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(
															    UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			generator=UpperCAmelCase__ ,			)[0]

										# post-processing
										a_						= 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"]:
															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(UpperCAmelCase__  )

										if not return_dict:
															return (image,)

										return ImagePipelineOutput(images=UpperCAmelCase__  )





'''simple docstring'''






from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


lowercase				=logging.get_logger(__name__)






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 =["audio_values", "audio_mask"]






       def __init__(     self    ,				snake_case=2_0_4_8    ,				snake_case=1    ,				snake_case=[1_6, 1_6]    ,				snake_case=1_2_8    ,				snake_case=4_4_1_0_0    ,				snake_case=8_6    ,				snake_case=2_0_4_8    ,				snake_case=0.0    ,				**snake_case    ,				)		->    Optional[int]:




          '''simple docstring'''
          super().__init__(
              feature_size=snake_case    ,				sampling_rate=snake_case    ,				padding_value=snake_case    ,				**snake_case    ,				)

          _UpperCAmelCase  :  Dict				       =spectrogram_length
          _UpperCAmelCase  :  Any				       =num_channels
          _UpperCAmelCase  :  Optional[int]				       =patch_size
          _UpperCAmelCase  :  List[str]				       =feature_size // self.patch_size[1]
          _UpperCAmelCase  :  Optional[int]				       =n_fft
          _UpperCAmelCase  :  int				       =sampling_rate // hop_length_to_sampling_rate
          _UpperCAmelCase  :  int				       =sampling_rate
          _UpperCAmelCase  :  List[Any]				       =padding_value
          _UpperCAmelCase  :  Optional[int]				       =mel_filter_bank(
              num_frequency_bins=1 + n_fft // 2    ,				num_mel_filters=snake_case    ,				min_frequency=0.0    ,				max_frequency=2_20_50.0    ,				sampling_rate=snake_case    ,				norm='slaney'    ,				mel_scale='slaney'    ,				).T






       def      lowerCAmelCase						(     self    ,				snake_case)		->    np.ndarray:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       =spectrogram(
              snake_case    ,				window_function(self.n_fft    ,				'hann')    ,				frame_length=self.n_fft    ,				hop_length=self.hop_length    ,				power=2.0    ,				mel_filters=self.mel_filters.T    ,				log_mel='dB'    ,				db_range=80.0    ,				)
          _UpperCAmelCase  :  Any				       =log_spec[:, :-1]
          _UpperCAmelCase  :  List[str]				       =log_spec - 20.0
          _UpperCAmelCase  :  Union[str, Any]				       =np.clip(log_spec / 40.0    ,				-2.0    ,				0.0) + 1.0
          return log_spec






       def __call__(     self    ,				snake_case    ,				snake_case = None    ,				snake_case = True    ,				snake_case = None    ,				snake_case = False    ,				snake_case = False    ,				**snake_case    ,				)		->    BatchFeature:




          '''simple docstring'''

          if sampling_rate is not None:
             if sampling_rate != self.sampling_rate:
                raise ValueError(
                    'This feature extractor is set to support sampling rate'
                    f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
                    f" with {self.sampling_rate} and not {sampling_rate}.")
          else:
             logger.warning(
                 'It is strongly recommended to pass the `sampling_rate` argument to this function. '
                 'Failing to do so can result in silent errors that might be hard to debug.')

          _UpperCAmelCase  :  Tuple				       =isinstance(snake_case    ,				np.ndarray) and len(raw_speech.shape) > 1
          if is_batched_numpy and len(raw_speech.shape) > 2:
             raise ValueError(f"Only mono-channel audio is supported for input to {self}")
          _UpperCAmelCase  :  str				       =is_batched_numpy or (
              isinstance(snake_case    ,				(list, tuple)) and (isinstance(raw_speech[0]    ,				(np.ndarray, tuple, list)))
          )
          if is_batched:
             _UpperCAmelCase  :  List[str]				       =[np.asarray([speech]    ,				dtype=np.floataa).T for speech in raw_speech]
          elif not is_batched and not isinstance(snake_case    ,				np.ndarray):
             _UpperCAmelCase  :  List[Any]				       =np.asarray(snake_case    ,				dtype=np.floataa)
          elif isinstance(snake_case    ,				np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
             _UpperCAmelCase  :  List[Any]				       =raw_speech.astype(np.floataa)
          # always return batch
          if not is_batched:
             _UpperCAmelCase  :  Dict				       =[np.asarray([raw_speech]).T]

          # Convert audio signals to log mel spectrograms, truncate by time axis
          _UpperCAmelCase  :  List[Any]				       =[
              self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
          ]
          if isinstance(audio_features[0]    ,				snake_case):
             _UpperCAmelCase  :  Dict				       =[np.asarray(snake_case    ,				dtype=np.floataa) for feature in audio_features]

          # Create audio attention mask
          _UpperCAmelCase  :  Tuple				       =max(
              [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features])  # The maximum number of audio patches in a batch
          if return_attention_mask:
             _UpperCAmelCase  :  Any				       =[
                 (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
                 + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
                 for feature in audio_features
             ]
             _UpperCAmelCase  :  int				       =np.array(snake_case).astype(np.floataa)

          # convert into correct format for padding
          _UpperCAmelCase  :  List[Any]				       =max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
          _UpperCAmelCase  :  List[str]				       =np.ones([len(snake_case), 1, max_time_len, self.feature_size]).astype(np.floataa)
          _UpperCAmelCase  :  Any				       =padded_audio_features * self.padding_value
          for i in range(len(snake_case)):
             _UpperCAmelCase  :  List[str]				       =audio_features[i]
             _UpperCAmelCase  :  Dict				       =feature

          # return as BatchFeature
          if return_attention_mask:
             _UpperCAmelCase  :  List[str]				       ={'audio_values': padded_audio_features, 'audio_mask': audio_mask}
          else:
             _UpperCAmelCase  :  Optional[int]				       ={'audio_values': padded_audio_features}

          _UpperCAmelCase  :  Any				       =BatchFeature(data=snake_case    ,				tensor_type=snake_case)
          return encoded_inputs

