





from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel
class 			UpperCamelCase_		(  _lowerCamelCase					):
					lowerCAmelCase_							=	['''vqvae''']




					def __init__(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_				,						)		->							Any:
										super().__init__()
										self.register_modules(unet=lowerCAmelCase_				,						scheduler=lowerCAmelCase_				,						mel=lowerCAmelCase_				,						vqvae=lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							int:
										return 50 if isinstance(self.scheduler				,						lowerCAmelCase_  ) else 1000




					@torch.no_grad()
					def __call__(		self				,						lowerCAmelCase_ = 1				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = 0				,						lowerCAmelCase_ = 0				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = 0				,						lowerCAmelCase_ = 0				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = 0				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_=True				,						)		->							Union[
					    Union[AudioPipelineOutput, ImagePipelineOutput],
					    Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]],
					]:
										_snake_case									=				steps or self.get_default_steps()
										self.scheduler.set_timesteps(lowerCAmelCase_  )
										_snake_case									=				step_generator or generator
										# For backwards compatibility
										if type(self.unet.config.sample_size  ) == int:
															_snake_case									=				(self.unet.config.sample_size, self.unet.config.sample_size)
										if noise is None:
															_snake_case									=				randn_tensor(
															    (
															        batch_size,
															        self.unet.config.in_channels,
															        self.unet.config.sample_size[0],
															        self.unet.config.sample_size[1],
															    )				,						generator=lowerCAmelCase_				,						device=self.device				,						)
										_snake_case									=				noise
										_snake_case									=				None

										if audio_file is not None or raw_audio is not None:
															self.mel.load_audio(lowerCAmelCase_				,						lowerCAmelCase_  )
															_snake_case									=				self.mel.audio_slice_to_image(lowerCAmelCase_  )
															_snake_case									=				np.frombuffer(input_image.tobytes()				,						dtype='uint8'  ).reshape(
															    (input_image.height, input_image.width)  )
															_snake_case									=				(input_image / 255) * 2 - 1
															_snake_case									=				torch.tensor(input_image[np.newaxis, :, :]				,						dtype=torch.float  ).to(self.device  )

															if self.vqvae is not None:
																				_snake_case									=				self.vqvae.encode(torch.unsqueeze(lowerCAmelCase_				,						0  )  ).latent_dist.sample(
																				    generator=lowerCAmelCase_  )[0]
																				_snake_case									=				self.vqvae.config.scaling_factor * input_images

															if start_step > 0:
																				_snake_case									=				self.scheduler.add_noise(lowerCAmelCase_				,						lowerCAmelCase_				,						self.scheduler.timesteps[start_step - 1]  )

															_snake_case									=				(
															    self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
															)
															_snake_case									=				int(mask_start_secs * pixels_per_second  )
															_snake_case									=				int(mask_end_secs * pixels_per_second  )
															_snake_case									=				self.scheduler.add_noise(lowerCAmelCase_				,						lowerCAmelCase_				,						torch.tensor(self.scheduler.timesteps[start_step:]  )  )

										for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]  )  ):
															if isinstance(self.unet				,						lowerCAmelCase_  ):
																				_snake_case									=				self.unet(lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )['sample']
															else:
																				_snake_case									=				self.unet(lowerCAmelCase_				,						lowerCAmelCase_  )['sample']

															if isinstance(self.scheduler				,						lowerCAmelCase_  ):
																				_snake_case									=				self.scheduler.step(
																				    model_output=lowerCAmelCase_				,						timestep=lowerCAmelCase_				,						sample=lowerCAmelCase_				,						eta=lowerCAmelCase_				,						generator=lowerCAmelCase_				,						)['prev_sample']
															else:
																				_snake_case									=				self.scheduler.step(
																				    model_output=lowerCAmelCase_				,						timestep=lowerCAmelCase_				,						sample=lowerCAmelCase_				,						generator=lowerCAmelCase_				,						)['prev_sample']

															if mask is not None:
																				if mask_start > 0:
																									_snake_case									=				mask[:, step, :, :mask_start]
																				if mask_end > 0:
																									_snake_case									=				mask[:, step, :, -mask_end:]

										if self.vqvae is not None:
															# 0.18215 was scaling factor used in training to ensure unit variance
															_snake_case									=				1 / self.vqvae.config.scaling_factor * images
															_snake_case									=				self.vqvae.decode(lowerCAmelCase_  )['sample']

										_snake_case									=				(images / 2 + 0.5).clamp(0				,						1  )
										_snake_case									=				images.cpu().permute(0				,						2				,						3				,						1  ).numpy()
										_snake_case									=				(images * 255).round().astype('uint8'  )
										_snake_case									=				list(
										    (Image.fromarray(_[:, :, 0]  ) for _ in images)
										    if images.shape[3] == 1
										    else (Image.fromarray(lowerCAmelCase_				,						mode='RGB'  ).convert('L'  ) for _ in images)  )

										_snake_case									=				[self.mel.image_to_audio(lowerCAmelCase_  ) for _ in images]
										if not return_dict:
															return images, (self.mel.get_sample_rate(), audios)

										return BaseOutput(**AudioPipelineOutput(np.array(lowerCAmelCase_  )[:, np.newaxis, :]  )				,						**ImagePipelineOutput(lowerCAmelCase_  )  )




					@torch.no_grad()
					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = 50  )		->							np.ndarray:
										assert isinstance(self.scheduler				,						lowerCAmelCase_  )
										self.scheduler.set_timesteps(lowerCAmelCase_  )
										_snake_case									=				np.array(
										    [np.frombuffer(image.tobytes()				,						dtype='uint8'  ).reshape((1, image.height, image.width)  ) for image in images]  )
										_snake_case									=				(sample / 255) * 2 - 1
										_snake_case									=				torch.Tensor(lowerCAmelCase_  ).to(self.device  )

										for t in self.progress_bar(torch.flip(self.scheduler.timesteps				,						(0,)  )  ):
															_snake_case									=				t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
															_snake_case									=				self.scheduler.alphas_cumprod[t]
															_snake_case									=				(
															    self.scheduler.alphas_cumprod[prev_timestep]
															    if prev_timestep >= 0
															    else self.scheduler.final_alpha_cumprod
															)
															_snake_case									=				1 - alpha_prod_t
															_snake_case									=				self.unet(lowerCAmelCase_				,						lowerCAmelCase_  )['sample']
															_snake_case									=				(1 - alpha_prod_t_prev) ** 0.5 * model_output
															_snake_case									=				(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
															_snake_case									=				sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

										return sample






					@staticmethod
					def 	lowerCAmelCase			(		lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )		->							torch.Tensor:
										_snake_case									=				acos(torch.dot(torch.flatten(lowerCAmelCase_  )				,						torch.flatten(lowerCAmelCase_  )  ) / torch.norm(lowerCAmelCase_  ) / torch.norm(lowerCAmelCase_  )  )
										return sin((1 - alpha) * theta  ) * xa / sin(lowerCAmelCase_  ) + sin(alpha * theta  ) * xa / sin(lowerCAmelCase_  )










import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
class 			UpperCamelCase_		(  unittest.TestCase					):




					@parameterized.expand([(None,), ('foo.json',)]  )
					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_  )		->							str:
										_snake_case									=				GenerationConfig(
										    do_sample=lowerCAmelCase_				,						temperature=0.7				,						length_penalty=1.0				,						bad_words_ids=[[1, 2, 3], [4, 5]]				,						)
										with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(lowerCAmelCase_				,						config_name=lowerCAmelCase_  )
															_snake_case									=				GenerationConfig.from_pretrained(lowerCAmelCase_				,						config_name=lowerCAmelCase_  )

										# Checks parameters that were specified
										self.assertEqual(loaded_config.do_sample				,						lowerCAmelCase_  )
										self.assertEqual(loaded_config.temperature				,						0.7  )
										self.assertEqual(loaded_config.length_penalty				,						1.0  )
										self.assertEqual(loaded_config.bad_words_ids				,						[[1, 2, 3], [4, 5]]  )

										# Checks parameters that were not specified (defaults)
										self.assertEqual(loaded_config.top_k				,						50  )
										self.assertEqual(loaded_config.max_length				,						20  )
										self.assertEqual(loaded_config.max_time				,						lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							Optional[int]:
										_snake_case									=				AutoConfig.from_pretrained('gpt2'  )
										_snake_case									=				GenerationConfig.from_model_config(lowerCAmelCase_  )
										_snake_case									=				GenerationConfig()

										# The generation config has loaded a few non-default parameters from the model config
										self.assertNotEqual(lowerCAmelCase_				,						lowerCAmelCase_  )

										# One of those parameters is eos_token_id -- check if it matches
										self.assertNotEqual(generation_config_from_model.eos_token_id				,						default_generation_config.eos_token_id  )
										self.assertEqual(generation_config_from_model.eos_token_id				,						model_config.eos_token_id  )




					def 	lowerCAmelCase			(		self  )		->							Tuple:
										_snake_case									=				GenerationConfig()
										_snake_case									=				{
										    'max_new_tokens': 1024,
										    'foo': 'bar',
										}
										_snake_case									=				copy.deepcopy(lowerCAmelCase_  )
										_snake_case									=				generation_config.update(**lowerCAmelCase_  )

										# update_kwargs was not modified (no side effects)
										self.assertEqual(lowerCAmelCase_				,						lowerCAmelCase_  )

										# update_kwargs was used to update the config on valid attributes
										self.assertEqual(generation_config.max_new_tokens				,						1024  )

										# `.update()` returns a dictionary of unused kwargs
										self.assertEqual(lowerCAmelCase_				,						{'foo': 'bar'}  )




					def 	lowerCAmelCase			(		self  )		->							Optional[int]:
										_snake_case									=				GenerationConfig()
										_snake_case									=				'bar'

										with tempfile.TemporaryDirectory('test-generation-config'  ) as tmp_dir:
															generation_config.save_pretrained(lowerCAmelCase_  )

															_snake_case									=				GenerationConfig.from_pretrained(lowerCAmelCase_  )
										# update_kwargs was used to update the config on valid attributes
										self.assertEqual(new_config.foo				,						'bar'  )

										_snake_case									=				GenerationConfig.from_model_config(lowerCAmelCase_  )
										assert not hasattr(lowerCAmelCase_				,						'foo'  )  # no new kwargs should be initialized if from config






					def 	lowerCAmelCase			(		self  )		->							List[Any]:
										_snake_case									=				GenerationConfig()
										self.assertEqual(default_config.temperature				,						1.0  )
										self.assertEqual(default_config.do_sample				,						lowerCAmelCase_  )
										self.assertEqual(default_config.num_beams				,						1  )

										_snake_case									=				GenerationConfig(
										    do_sample=lowerCAmelCase_				,						temperature=0.7				,						length_penalty=1.0				,						bad_words_ids=[[1, 2, 3], [4, 5]]				,						)
										self.assertEqual(config.temperature				,						0.7  )
										self.assertEqual(config.do_sample				,						lowerCAmelCase_  )
										self.assertEqual(config.num_beams				,						1  )

										with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(lowerCAmelCase_  )
															_snake_case									=				GenerationConfig.from_pretrained(lowerCAmelCase_				,						temperature=1.0  )

										self.assertEqual(loaded_config.temperature				,						1.0  )
										self.assertEqual(loaded_config.do_sample				,						lowerCAmelCase_  )
										self.assertEqual(loaded_config.num_beams				,						1  )  # default value





@is_staging_test
class 			UpperCamelCase_		(  unittest.TestCase					):




					@classmethod
					def 	lowerCAmelCase			(		cls  )		->							List[str]:
										_snake_case									=				TOKEN
										HfFolder.save_token(lowerCAmelCase_  )




					@classmethod
					def 	lowerCAmelCase			(		cls  )		->							Union[str, Any]:
										try:
															delete_repo(token=cls._token				,						repo_id='test-generation-config'  )
										except HTTPError:
															pass

										try:
															delete_repo(token=cls._token				,						repo_id='valid_org/test-generation-config-org'  )
										except HTTPError:
															pass




					def 	lowerCAmelCase			(		self  )		->							int:
										_snake_case									=				GenerationConfig(
										    do_sample=lowerCAmelCase_				,						temperature=0.7				,						length_penalty=1.0				,						)
										config.push_to_hub('test-generation-config'				,						use_auth_token=self._token  )

										_snake_case									=				GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''  )
										for k, v in config.to_dict().items():
															if k != "transformers_version":
																				self.assertEqual(lowerCAmelCase_				,						getattr(lowerCAmelCase_				,						lowerCAmelCase_  )  )

        # Reset repo
										delete_repo(token=self._token				,						repo_id='test-generation-config'  )

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(
															    lowerCAmelCase_				,						repo_id='test-generation-config'				,						push_to_hub=lowerCAmelCase_				,						use_auth_token=self._token  )

										_snake_case									=				GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''  )
										for k, v in config.to_dict().items():
															if k != "transformers_version":
																				self.assertEqual(lowerCAmelCase_				,						getattr(lowerCAmelCase_				,						lowerCAmelCase_  )  )






					def 	lowerCAmelCase			(		self  )		->							List[str]:
										_snake_case									=				GenerationConfig(
										    do_sample=lowerCAmelCase_				,						temperature=0.7				,						length_penalty=1.0				,						)
										config.push_to_hub('valid_org/test-generation-config-org'				,						use_auth_token=self._token  )

										_snake_case									=				GenerationConfig.from_pretrained('valid_org/test-generation-config-org'  )
										for k, v in config.to_dict().items():
															if k != "transformers_version":
																				self.assertEqual(lowerCAmelCase_				,						getattr(lowerCAmelCase_				,						lowerCAmelCase_  )  )

        # Reset repo
										delete_repo(token=self._token				,						repo_id='valid_org/test-generation-config-org'  )

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(
															    lowerCAmelCase_				,						repo_id='valid_org/test-generation-config-org'				,						push_to_hub=lowerCAmelCase_				,						use_auth_token=self._token  )

										_snake_case									=				GenerationConfig.from_pretrained('valid_org/test-generation-config-org'  )
										for k, v in config.to_dict().items():
															if k != "transformers_version":
																				self.assertEqual(lowerCAmelCase_				,						getattr(lowerCAmelCase_				,						lowerCAmelCase_  )  )



