





'''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									=   """
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline
        >>> from diffusers.utils import load_image
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior.to(\"cuda\")

        >>> prompt = \"A red cartoon frog, 4k\"
        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)

        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16
        ... )
        >>> pipe.to(\"cuda\")

        >>> init_image = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/frog.png\"
        ... )

        >>> image = pipe(
        ...     image=init_image,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ...     strength=0.2,
        ... ).images

        >>> image[0].save(\"red_frog.png\")
        ```
"""






def   __A    (				a_    :	Any   ,a_    :	Tuple   ,a_    :	Union[str, Any]=8						):
		lowerCAmelCase  :     str       						= height // scale_factor**2
		if height % scale_factor**2 != 0:
				new_height += 1
		lowerCAmelCase  :     str       						= width // scale_factor**2
		if width % scale_factor**2 != 0:
				new_width += 1
		return new_height * scale_factor, new_width * scale_factor






def   __A    (				a_    :	Tuple   ,a_    :	int=5_1_2   ,a_    :	int=5_1_2						):
		lowerCAmelCase  :     str       						= pil_image.resize((w, h)   ,resample=Image.BICUBIC   ,reducing_gap=1						)
		lowerCAmelCase  :     str       						= np.array(pil_image.convert("RGB"						)						)
		lowerCAmelCase  :     List[Any]       						= arr.astype(np.floataa						) / 1_2_7.5 - 1
		lowerCAmelCase  :     Any       						= np.transpose(a_   ,[2, 0, 1]						)
		lowerCAmelCase  :     Optional[int]       						= torch.from_numpy(a_						).unsqueeze(0						)
		return image

class 		lowerCamelCase	(   _A							):



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

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



	def 	_lowerCamelCase     ( self		,   a_		,   a_		,   a_						):
			# get the original timestep using init_timestep
			lowerCAmelCase  :     Optional[Any]       						= min(int(num_inference_steps * strength						)		,   a_						)

			lowerCAmelCase  :     str       						= max(num_inference_steps - init_timestep		,   0						)
			lowerCAmelCase  :     List[Any]       						= self.scheduler.timesteps[t_start:]

			return timesteps, num_inference_steps - t_start



	def 	_lowerCamelCase     ( self		,   a_		,   a_		,   a_		,   a_		,   a_		,   a_		,   a_=None						):
			if not isinstance(a_		,   (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(a_						)}'''						)

			lowerCAmelCase  :     int       						= image.to(device=a_		,   dtype=a_						)

			lowerCAmelCase  :     int       						= batch_size * num_images_per_prompt

			if image.shape[1] == 4:
					lowerCAmelCase  :     int       						= image

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

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

					lowerCAmelCase  :     Tuple       						= self.movq.config.scaling_factor * init_latents

			lowerCAmelCase  :     List[str]       						= torch.cat([init_latents]		,   dim=0						)

			lowerCAmelCase  :     Dict       						= init_latents.shape
			lowerCAmelCase  :     int       						= randn_tensor(a_		,   generator=a_		,   device=a_		,   dtype=a_						)

			# get latents
			lowerCAmelCase  :     Any       						= self.scheduler.add_noise(a_		,   a_		,   a_						)

			lowerCAmelCase  :     Optional[Any]       						= init_latents

			return latents



	def 	_lowerCamelCase     ( self		,   a_=0						):
			if is_accelerate_available():
					from accelerate import cpu_offload
			else:
					raise ImportError("Please install accelerate via `pip install accelerate`"						)

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

			lowerCAmelCase  :     Tuple       						= [
			    self.unet,
			    self.movq,
			]
			for cpu_offloaded_model in models:
					if cpu_offloaded_model is not None:
							cpu_offload(a_		,   a_						)



	def 	_lowerCamelCase     ( self		,   a_=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."						)

			lowerCAmelCase  :     Optional[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)

			lowerCAmelCase  :     Optional[Any]       						= None
			for cpu_offloaded_model in [self.unet, self.movq]:
					lowerCAmelCase						,		lowerCAmelCase  :     int       						= cpu_offload_with_hook(a_		,   a_		,   prev_module_hook=a_						)

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



	@property
	# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
	def 	_lowerCamelCase     ( self						):
			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		,   a_		,   a_		,   a_		,   a_ = 512		,   a_ = 512		,   a_ = 100		,   a_ = 4.0		,   a_ = 0.3		,   a_ = 1		,   a_ = None		,   a_ = "pil"		,   a_ = True		,   ):
			lowerCAmelCase  :     Optional[Any]       						= self._execution_device

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

			if isinstance(a_		,   a_						):
					lowerCAmelCase  :     Any       						= torch.cat(a_		,   dim=0						)
			lowerCAmelCase  :     List[str]       						= image_embeds.shape[0]
			if isinstance(a_		,   a_						):
					lowerCAmelCase  :     Optional[Any]       						= torch.cat(a_		,   dim=0						)

			if do_classifier_free_guidance:
					lowerCAmelCase  :     Dict       						= image_embeds.repeat_interleave(a_		,   dim=0						)
					lowerCAmelCase  :     Any       						= negative_image_embeds.repeat_interleave(a_		,   dim=0						)

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

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

			lowerCAmelCase  :     List[Any]       						= torch.cat([prepare_image(a_		,   a_		,   a_						) for i in image]		,   dim=0						)
			lowerCAmelCase  :     Union[str, Any]       						= image.to(dtype=image_embeds.dtype		,   device=a_						)

			lowerCAmelCase  :     int       						= self.movq.encode(a_						)["latents"]
			lowerCAmelCase  :     Tuple       						= latents.repeat_interleave(a_		,   dim=0						)
			self.scheduler.set_timesteps(a_		,   device=a_						)
			lowerCAmelCase						,		lowerCAmelCase  :     Dict       						= self.get_timesteps(a_		,   a_		,   a_						)
			lowerCAmelCase  :     Any       						= timesteps[:1].repeat(batch_size * num_images_per_prompt						)
			lowerCAmelCase						,		lowerCAmelCase  :     List[Any]       						= downscale_height_and_width(a_		,   a_		,   self.movq_scale_factor						)
			lowerCAmelCase  :     Optional[int]       						= self.prepare_latents(
			    a_		,   a_		,   a_		,   a_		,   image_embeds.dtype		,   a_		,   a_						)
			for i, t in enumerate(self.progress_bar(a_						)						):
					# expand the latents if we are doing classifier free guidance
					lowerCAmelCase  :     List[Any]       						= torch.cat([latents] * 2						) if do_classifier_free_guidance else latents

					lowerCAmelCase  :     List[Any]       						= {"image_embeds": image_embeds}
					lowerCAmelCase  :     List[str]       						= self.unet(
					    sample=a_		,   timestep=a_		,   encoder_hidden_states=a_		,   added_cond_kwargs=a_		,   return_dict=a_		,   )[0]

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

					# compute the previous noisy sample x_t -> x_t-1
					lowerCAmelCase  :     Tuple       						= self.scheduler.step(
					    a_		,   a_		,   a_		,   generator=a_		,   )[0]

			# post-processing
			lowerCAmelCase  :     Any       						= 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"]:
					lowerCAmelCase  :     Any       						= image * 0.5 + 0.5
					lowerCAmelCase  :     Any       						= image.clamp(0		,   1						)
					lowerCAmelCase  :     Tuple       						= image.cpu().permute(0		,   2		,   3		,   1						).float().numpy()

			if output_type == "pil":
					lowerCAmelCase  :     List[Any]       						= self.numpy_to_pil(a_						)

			if not return_dict:
					return (image,)

			return ImagePipelineOutput(images=a_						)










'''simple docstring'''






import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCAmelCase									=   random.Random()






def   __A    (				a_    :	Union[str, Any]   ,a_    :	Tuple=1.0   ,a_    :	Optional[int]=None   ,a_    :	Union[str, Any]=None						):
		if rng is None:
				lowerCAmelCase  :     str       						= global_rng

		lowerCAmelCase  :     Any       						= []
		for batch_idx in range(shape[0]						):
				values.append([]						)
				for _ in range(shape[1]						):
						values[-1].append(rng.random() * scale						)

		return values
class 		lowerCamelCase	(   unittest.TestCase							):



	def __init__( self		,   a_		,   a_=7		,   a_=400		,   a_=2_000		,   a_=1		,   a_=0.0		,   a_=16_000		,   a_=True		,   a_=True		,   ):
			lowerCAmelCase  :     Dict       						= parent
			lowerCAmelCase  :     Optional[int]       						= batch_size
			lowerCAmelCase  :     Dict       						= min_seq_length
			lowerCAmelCase  :     Dict       						= max_seq_length
			lowerCAmelCase  :     Optional[Any]       						= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
			lowerCAmelCase  :     Union[str, Any]       						= feature_size
			lowerCAmelCase  :     Tuple       						= padding_value
			lowerCAmelCase  :     Dict       						= sampling_rate
			lowerCAmelCase  :     int       						= return_attention_mask
			lowerCAmelCase  :     Optional[Any]       						= do_normalize



	def 	_lowerCamelCase     ( self						):
			return {
			    "feature_size": self.feature_size,
			    "padding_value": self.padding_value,
			    "sampling_rate": self.sampling_rate,
			    "return_attention_mask": self.return_attention_mask,
			    "do_normalize": self.do_normalize,
			}





	def 	_lowerCamelCase     ( self		,   a_=False		,   a_=False						):
			def _flatten(a_						):
					return list(itertools.chain(*a_						)						)

			if equal_length:
					lowerCAmelCase  :     List[Any]       						= floats_list((self.batch_size, self.max_seq_length)						)
			else:
					# make sure that inputs increase in size
					lowerCAmelCase  :     Any       						= [
					    _flatten(floats_list((x, self.feature_size)						)						)
					    for x in range(self.min_seq_length		,   self.max_seq_length		,   self.seq_length_diff						)
					]

			if numpify:
					lowerCAmelCase  :     List[str]       						= [np.asarray(a_						) for x in speech_inputs]

			return speech_inputs






class 		lowerCamelCase	(   _A   , unittest.TestCase							):
	snake_case_   = WavaVecaFeatureExtractor



	def 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     Tuple       						= WavaVecaFeatureExtractionTester(self						)



	def 	_lowerCamelCase     ( self		,   a_						):
			self.assertTrue(np.all(np.mean(a_		,   axis=0						) < 1e-3						)						)
			self.assertTrue(np.all(np.abs(np.var(a_		,   axis=0						) - 1						) < 1e-3						)						)



	def 	_lowerCamelCase     ( self						):
			# Tests that all call wrap to encode_plus and batch_encode_plus
			lowerCAmelCase  :     int       						= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
			# create three inputs of length 800, 1000, and 1200
			lowerCAmelCase  :     str       						= [floats_list((1, x)						)[0] for x in range(800		,   1_400		,   200						)]
			lowerCAmelCase  :     Dict       						= [np.asarray(a_						) for speech_input in speech_inputs]

			# Test not batched input
			lowerCAmelCase  :     Optional[int]       						= feat_extract(speech_inputs[0]		,   return_tensors="np"						).input_values
			lowerCAmelCase  :     Any       						= feat_extract(np_speech_inputs[0]		,   return_tensors="np"						).input_values
			self.assertTrue(np.allclose(a_		,   a_		,   atol=1e-3						)						)

			# Test batched
			lowerCAmelCase  :     Any       						= feat_extract(a_		,   return_tensors="np"						).input_values
			lowerCAmelCase  :     int       						= feat_extract(a_		,   return_tensors="np"						).input_values
			for enc_seq_a, enc_seq_a in zip(a_		,   a_						):
					self.assertTrue(np.allclose(a_		,   a_		,   atol=1e-3						)						)

			# Test 2-D numpy arrays are batched.
			lowerCAmelCase  :     Dict       						= [floats_list((1, x)						)[0] for x in (800, 800, 800)]
			lowerCAmelCase  :     Tuple       						= np.asarray(a_						)
			lowerCAmelCase  :     int       						= feat_extract(a_		,   return_tensors="np"						).input_values
			lowerCAmelCase  :     Union[str, Any]       						= feat_extract(a_		,   return_tensors="np"						).input_values
			for enc_seq_a, enc_seq_a in zip(a_		,   a_						):
					self.assertTrue(np.allclose(a_		,   a_		,   atol=1e-3						)						)



	def 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     int       						= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
			lowerCAmelCase  :     Any       						= [floats_list((1, x)						)[0] for x in range(800		,   1_400		,   200						)]

			lowerCAmelCase  :     Union[str, Any]       						= ["longest", "max_length", "do_not_pad"]
			lowerCAmelCase  :     Optional[int]       						= [None, 1_600, None]
			for max_length, padding in zip(a_		,   a_						):
					lowerCAmelCase  :     List[Any]       						= feat_extract(a_		,   padding=a_		,   max_length=a_		,   return_tensors="np"						)
					lowerCAmelCase  :     Any       						= processed.input_values

					self._check_zero_mean_unit_variance(input_values[0][:800]						)
					self.assertTrue(input_values[0][800:].sum() < 1e-6						)
					self._check_zero_mean_unit_variance(input_values[1][:1_000]						)
					self.assertTrue(input_values[0][1_000:].sum() < 1e-6						)
					self._check_zero_mean_unit_variance(input_values[2][:1_200]						)



	def 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     List[Any]       						= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
			lowerCAmelCase  :     Optional[int]       						= range(800		,   1_400		,   200						)
			lowerCAmelCase  :     Tuple       						= [floats_list((1, x)						)[0] for x in lengths]

			lowerCAmelCase  :     str       						= ["longest", "max_length", "do_not_pad"]
			lowerCAmelCase  :     Any       						= [None, 1_600, None]

			for max_length, padding in zip(a_		,   a_						):
					lowerCAmelCase  :     Dict       						= feat_extract(a_		,   max_length=a_		,   padding=a_						)
					lowerCAmelCase  :     int       						= processed.input_values

					self._check_zero_mean_unit_variance(input_values[0][:800]						)
					self._check_zero_mean_unit_variance(input_values[1][:1_000]						)
					self._check_zero_mean_unit_variance(input_values[2][:1_200]						)



	def 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     List[Any]       						= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
			lowerCAmelCase  :     Tuple       						= [floats_list((1, x)						)[0] for x in range(800		,   1_400		,   200						)]
			lowerCAmelCase  :     Dict       						= feat_extract(
			    a_		,   truncation=a_		,   max_length=1_000		,   padding="max_length"		,   return_tensors="np"						)
			lowerCAmelCase  :     Union[str, Any]       						= processed.input_values

			self._check_zero_mean_unit_variance(input_values[0, :800]						)
			self._check_zero_mean_unit_variance(input_values[1]						)
			self._check_zero_mean_unit_variance(input_values[2]						)



	def 	_lowerCamelCase     ( self						):
			lowerCAmelCase  :     Optional[int]       						= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
			lowerCAmelCase  :     Tuple       						= [floats_list((1, x)						)[0] for x in range(800		,   1_400		,   200						)]
			lowerCAmelCase  :     Union[str, Any]       						= feat_extract(
			    a_		,   truncation=a_		,   max_length=1_000		,   padding="longest"		,   return_tensors="np"						)
			lowerCAmelCase  :     Dict       						= processed.input_values

			self._check_zero_mean_unit_variance(input_values[0, :800]						)
			self._check_zero_mean_unit_variance(input_values[1, :1_000]						)
			self._check_zero_mean_unit_variance(input_values[2]						)

			# make sure that if max_length < longest -> then pad to max_length
			self.assertTrue(input_values.shape == (3, 1_000)						)

			lowerCAmelCase  :     List[str]       						= [floats_list((1, x)						)[0] for x in range(800		,   1_400		,   200						)]
			lowerCAmelCase  :     Union[str, Any]       						= feat_extract(
			    a_		,   truncation=a_		,   max_length=2_000		,   padding="longest"		,   return_tensors="np"						)
			lowerCAmelCase  :     Optional[Any]       						= processed.input_values

			self._check_zero_mean_unit_variance(input_values[0, :800]						)
			self._check_zero_mean_unit_variance(input_values[1, :1_000]						)
			self._check_zero_mean_unit_variance(input_values[2]						)

			# make sure that if max_length > longest -> then pad to longest
			self.assertTrue(input_values.shape == (3, 1_200)						)



	@require_torch
	def 	_lowerCamelCase     ( self						):
			import torch

			lowerCAmelCase  :     Optional[int]       						= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
			lowerCAmelCase  :     List[Any]       						= np.random.rand(100						).astype(np.floataa						)
			lowerCAmelCase  :     List[Any]       						= np_speech_inputs.tolist()

			for inputs in [py_speech_inputs, np_speech_inputs]:
					lowerCAmelCase  :     Union[str, Any]       						= feature_extractor.pad([{"input_values": inputs}]		,   return_tensors="np"						)
					self.assertTrue(np_processed.input_values.dtype == np.floataa						)
					lowerCAmelCase  :     Tuple       						= feature_extractor.pad([{"input_values": inputs}]		,   return_tensors="pt"						)
					self.assertTrue(pt_processed.input_values.dtype == torch.floataa						)





	@slow
	@require_torch
	def 	_lowerCamelCase     ( self						):
			# this test makes sure that models that are using
			# group norm don't have their feature extractor return the
			# attention_mask
			for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
					lowerCAmelCase  :     Any       						= WavaVecaConfig.from_pretrained(a_						)
					lowerCAmelCase  :     List[str]       						= WavaVecaFeatureExtractor.from_pretrained(a_						)

					# only "layer" feature extraction norm should make use of
					# attention_mask
					self.assertEqual(feat_extract.return_attention_mask		,   config.feat_extract_norm == "layer"						)



