



import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput





def     __lowerCamelCase							(   __magic_name__						:	str  ,			__magic_name__						:	List[str]=0.999  ,			__magic_name__						:	str="cosine"  ,			):
							if alpha_transform_type == "cosine":

														def alpha_bar_fn(__magic_name__						:	Optional[Any]    ):
																					return math.cos((t + 0.008) / 1.008 * math.pi / 2    ) ** 2

							elif alpha_transform_type == "exp":

														def alpha_bar_fn(__magic_name__						:	Dict    ):
																					return math.exp(t * -12.0    )

							else:
														raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}"    )

							a__:							str									=[]
							for i in range(__magic_name__    ):
														a__:							List[Any]									=i / num_diffusion_timesteps
														a__:							Union[str, Any]									=(i + 1) / num_diffusion_timesteps
														betas.append(min(1 - alpha_bar_fn(__magic_name__    ) / alpha_bar_fn(__magic_name__    )  ,			__magic_name__    )    )
							return torch.tensor(__magic_name__  ,			dtype=torch.floataa    )







class 						lowerCamelCase__			(		_a					,       _a ):
						_lowerCAmelCase             =			[e.name for e in KarrasDiffusionSchedulers]
						_lowerCAmelCase             =			2


						@register_to_config
						def __init__(			self    :	Optional[int]   ,							_a    :	int = 1_0_0_0   ,							_a    :	float = 0.0_0_0_8_5   ,							_a    :	float = 0.0_1_2   ,							_a    :	str = "linear"   ,							_a    :	Optional[Union[np.ndarray, List[float]]] = None   ,							_a    :	str = "epsilon"   ,							_a    :	str = "linspace"   ,							_a    :	int = 0   ,							):
													if trained_betas is not None:
																				a__:							List[Any]									=torch.tensor(_a   ,							dtype=torch.floataa      )
													elif beta_schedule == "linear":
																				a__:							Any									=torch.linspace(_a   ,							_a   ,							_a   ,							dtype=torch.floataa      )
													elif beta_schedule == "scaled_linear":
																				# this schedule is very specific to the latent diffusion model.
																				a__:							Any									=(
																				    torch.linspace(beta_start**0.5   ,							beta_end**0.5   ,							_a   ,							dtype=torch.floataa      ) ** 2
																				)
													elif beta_schedule == "squaredcos_cap_v2":
																				# Glide cosine schedule
																				a__:							Tuple									=betas_for_alpha_bar(_a      )
													else:
																				raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}"      )

													a__:							int									=1.0 - self.betas
													a__:							Union[str, Any]									=torch.cumprod(self.alphas   ,							dim=0      )

													#  set all values
													self.set_timesteps(_a   ,							_a   ,							_a      )


						def 	_lowerCamelCase      (			self    :	str   ,							_a    :	str   ,							_a    :	List[Any]=None      ):
													if schedule_timesteps is None:
																				a__:							Optional[int]									=self.timesteps

													a__:							Tuple									=(schedule_timesteps == timestep).nonzero()

													# The sigma index that is taken for the **very** first `step`
													# is always the second index (or the last index if there is only 1)
													# This way we can ensure we don't accidentally skip a sigma in
													# case we start in the middle of the denoising schedule (e.g. for image-to-image)
													if len(self._index_counter      ) == 0:
																				a__:							Any									=1 if len(_a      ) > 1 else 0
													else:
																				a__:							Any									=timestep.cpu().item() if torch.is_tensor(_a      ) else timestep
																				a__:							int									=self._index_counter[timestep_int]

													return indices[pos].item()


						@property
						def 	_lowerCamelCase      (			self    :	Optional[int]      ):
													# standard deviation of the initial noise distribution
													if self.config.timestep_spacing in ["linspace", "trailing"]:
																				return self.sigmas.max()

													return (self.sigmas.max() ** 2 + 1) ** 0.5


						def 	_lowerCamelCase      (			self    :	Optional[int]   ,							_a    :	torch.FloatTensor   ,							_a    :	Union[float, torch.FloatTensor]   ,							):
													a__:							List[str]									=self.index_for_timestep(_a      )

													if self.state_in_first_order:
																				a__:							str									=self.sigmas[step_index]
													else:
																				a__:							List[str]									=self.sigmas_interpol[step_index - 1]

													a__:							Dict									=sample / ((sigma**2 + 1) ** 0.5)
													return sample


						def 	_lowerCamelCase      (			self    :	Dict   ,							_a    :	int   ,							_a    :	Union[str, torch.device] = None   ,							_a    :	Optional[int] = None   ,							):
													a__:							Tuple									=num_inference_steps

													a__:							Any									=num_train_timesteps or self.config.num_train_timesteps

													# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
													if self.config.timestep_spacing == "linspace":
																				a__:							int									=np.linspace(0   ,							num_train_timesteps - 1   ,							_a   ,							dtype=_a      )[::-1].copy()
													elif self.config.timestep_spacing == "leading":
																				a__:							Optional[Any]									=num_train_timesteps // self.num_inference_steps
																				# creates integer timesteps by multiplying by ratio
																				# casting to int to avoid issues when num_inference_step is power of 3
																				a__:							Tuple									=(np.arange(0   ,							_a      ) * step_ratio).round()[::-1].copy().astype(_a      )
																				timesteps += self.config.steps_offset
													elif self.config.timestep_spacing == "trailing":
																				a__:							Tuple									=num_train_timesteps / self.num_inference_steps
																				# creates integer timesteps by multiplying by ratio
																				# casting to int to avoid issues when num_inference_step is power of 3
																				a__:							List[Any]									=(np.arange(_a   ,							0   ,							-step_ratio      )).round().copy().astype(_a      )
																				timesteps -= 1
													else:
																				raise ValueError(
																				    F"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."      )

													a__:							List[str]									=np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5      )
													a__:							Tuple									=torch.from_numpy(np.log(_a      )      ).to(_a      )

													a__:							Any									=np.interp(_a   ,							np.arange(0   ,							len(_a      )      )   ,							_a      )
													a__:							Dict									=np.concatenate([sigmas, [0.0]]      ).astype(np.floataa      )
													a__:							int									=torch.from_numpy(_a      ).to(device=_a      )

													# compute up and down sigmas
													a__:							int									=sigmas.roll(-1      )
													a__:							Optional[int]									=0.0
													a__:							Optional[int]									=(sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
													a__:							Any									=(sigmas_next**2 - sigmas_up**2) ** 0.5
													a__:							List[str]									=0.0

													# compute interpolated sigmas
													a__:							List[Any]									=sigmas.log().lerp(sigmas_down.log()   ,							0.5      ).exp()
													a__:							List[Any]									=0.0

													# set sigmas
													a__:							Optional[int]									=torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2      ), sigmas[-1:]]      )
													a__:							List[Any]									=torch.cat(
													    [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2      ), sigmas_interpol[-1:]]      )
													a__:							List[Any]									=torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2      ), sigmas_up[-1:]]      )
													a__:							Optional[int]									=torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2      ), sigmas_down[-1:]]      )

													if str(_a      ).startswith("mps"      ):
																				# mps does not support float64
																				a__:							List[str]									=torch.from_numpy(_a      ).to(_a   ,							dtype=torch.floataa      )
													else:
																				a__:							Optional[Any]									=torch.from_numpy(_a      ).to(_a      )

													a__:							Optional[int]									=self.sigma_to_t(_a      ).to(_a   ,							dtype=timesteps.dtype      )
													a__:							Optional[Any]									=torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])   ,							dim=-1      ).flatten()

													a__:							Union[str, Any]									=torch.cat([timesteps[:1], interleaved_timesteps]      )

													a__:							Any									=None

													# for exp beta schedules, such as the one for `pipeline_shap_e.py`
													# we need an index counter
													a__:							Optional[int]									=defaultdict(_a      )


						def 	_lowerCamelCase      (			self    :	List[str]   ,							_a    :	Tuple      ):
													# get log sigma
													a__:							Optional[Any]									=sigma.log()

													# get distribution
													a__:							str									=log_sigma - self.log_sigmas[:, None]

													# get sigmas range
													a__:							Optional[int]									=dists.ge(0      ).cumsum(dim=0      ).argmax(dim=0      ).clamp(max=self.log_sigmas.shape[0] - 2      )
													a__:							Any									=low_idx + 1

													a__:							Union[str, Any]									=self.log_sigmas[low_idx]
													a__:							Tuple									=self.log_sigmas[high_idx]

													# interpolate sigmas
													a__:							Tuple									=(low - log_sigma) / (low - high)
													a__:							Dict									=w.clamp(0   ,							1      )

													# transform interpolation to time range
													a__:							Any									=(1 - w) * low_idx + w * high_idx
													a__:							List[Any]									=t.view(sigma.shape      )
													return t


						@property
						def 	_lowerCamelCase      (			self    :	Union[str, Any]      ):
													return self.sample is None


						def 	_lowerCamelCase      (			self    :	int   ,							_a    :	Union[torch.FloatTensor, np.ndarray]   ,							_a    :	Union[float, torch.FloatTensor]   ,							_a    :	Union[torch.FloatTensor, np.ndarray]   ,							_a    :	Optional[torch.Generator] = None   ,							_a    :	bool = True   ,							):
													a__:							Dict									=self.index_for_timestep(_a      )

													# advance index counter by 1
													a__:							Optional[Any]									=timestep.cpu().item() if torch.is_tensor(_a      ) else timestep
													self._index_counter[timestep_int] += 1

													if self.state_in_first_order:
																				a__:							Optional[Any]									=self.sigmas[step_index]
																				a__:							List[str]									=self.sigmas_interpol[step_index]
																				a__:							Union[str, Any]									=self.sigmas_up[step_index]
																				a__:							Tuple									=self.sigmas_down[step_index - 1]
													else:
																				# 2nd order / KPDM2's method
																				a__:							Dict									=self.sigmas[step_index - 1]
																				a__:							int									=self.sigmas_interpol[step_index - 1]
																				a__:							Any									=self.sigmas_up[step_index - 1]
																				a__:							List[str]									=self.sigmas_down[step_index - 1]

													# currently only gamma=0 is supported. This usually works best anyways.
													# We can support gamma in the future but then need to scale the timestep before
													# passing it to the model which requires a change in API
													a__:							Any									=0
													a__:							List[Any]									=sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

													a__:							Dict									=model_output.device
													a__:							Union[str, Any]									=randn_tensor(model_output.shape   ,							dtype=model_output.dtype   ,							device=_a   ,							generator=_a      )

													# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
													if self.config.prediction_type == "epsilon":
																				a__:							Any									=sigma_hat if self.state_in_first_order else sigma_interpol
																				a__:							int									=sample - sigma_input * model_output
													elif self.config.prediction_type == "v_prediction":
																				a__:							List[Any]									=sigma_hat if self.state_in_first_order else sigma_interpol
																				a__:							Tuple									=model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
																				    sample / (sigma_input**2 + 1)
																				)
													elif self.config.prediction_type == "sample":
																				raise NotImplementedError("prediction_type not implemented yet: sample"      )
													else:
																				raise ValueError(
																				    F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"      )

													if self.state_in_first_order:
																				# 2. Convert to an ODE derivative for 1st order
																				a__:							int									=(sample - pred_original_sample) / sigma_hat
																				# 3. delta timestep
																				a__:							Optional[Any]									=sigma_interpol - sigma_hat

																				# store for 2nd order step
																				a__:							int									=sample
																				a__:							int									=dt
																				a__:							Union[str, Any]									=sample + derivative * dt
													else:
																				# DPM-Solver-2
																				# 2. Convert to an ODE derivative for 2nd order
																				a__:							Union[str, Any]									=(sample - pred_original_sample) / sigma_interpol
																				# 3. delta timestep
																				a__:							int									=sigma_down - sigma_hat

																				a__:							Union[str, Any]									=self.sample
																				a__:							Dict									=None

																				a__:							List[str]									=sample + derivative * dt
																				a__:							Any									=prev_sample + noise * sigma_up

													if not return_dict:
																				return (prev_sample,)

													return SchedulerOutput(prev_sample=_a      )


						def 	_lowerCamelCase      (			self    :	Any   ,							_a    :	torch.FloatTensor   ,							_a    :	torch.FloatTensor   ,							_a    :	torch.FloatTensor   ,							):
													# Make sure sigmas and timesteps have the same device and dtype as original_samples
													a__:							Optional[Any]									=self.sigmas.to(device=original_samples.device   ,							dtype=original_samples.dtype      )
													if original_samples.device.type == "mps" and torch.is_floating_point(_a      ):
																				# mps does not support float64
																				a__:							Optional[int]									=self.timesteps.to(original_samples.device   ,							dtype=torch.floataa      )
																				a__:							List[str]									=timesteps.to(original_samples.device   ,							dtype=torch.floataa      )
													else:
																				a__:							List[str]									=self.timesteps.to(original_samples.device      )
																				a__:							Any									=timesteps.to(original_samples.device      )

													a__:							Dict									=[self.index_for_timestep(_a   ,							_a      ) for t in timesteps]

													a__:							Optional[int]									=sigmas[step_indices].flatten()
													while len(sigma.shape      ) < len(original_samples.shape      ):
																				a__:							int									=sigma.unsqueeze(-1      )

													a__:							List[str]									=original_samples + noise * sigma
													return noisy_samples







						def __len__(			self    :	Optional[Any]      ):
													return self.config.num_train_timesteps










import shutil
import tempfile
import unittest

import pytest

from transformers import WhisperTokenizer, is_speech_available
from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio

from .test_feature_extraction_whisper import floats_list


if is_speech_available():
		from transformers import WhisperFeatureExtractor, WhisperProcessor


__UpperCAmelCase    	=  5_03_58
__UpperCAmelCase    	=  5_03_62


@require_torch
@require_torchaudio
@require_sentencepiece
class 						lowerCamelCase__			(		unittest.TestCase ):


						def 	_lowerCamelCase      (			self    :	List[Any]      ):
													a__:							str									="openai/whisper-small.en"
													a__:							Union[str, Any]									=tempfile.mkdtemp()


						def 	_lowerCamelCase      (			self    :	Optional[Any]   ,							**_a    :	Optional[int]      ):
													return WhisperTokenizer.from_pretrained(self.checkpoint   ,							**_a      )


						def 	_lowerCamelCase      (			self    :	str   ,							**_a    :	Tuple      ):
													return WhisperFeatureExtractor.from_pretrained(self.checkpoint   ,							**_a      )


						def 	_lowerCamelCase      (			self    :	Union[str, Any]      ):
													shutil.rmtree(self.tmpdirname      )


						def 	_lowerCamelCase      (			self    :	int      ):
													a__:							str									=self.get_tokenizer()
													a__:							Union[str, Any]									=self.get_feature_extractor()

													a__:							int									=WhisperProcessor(tokenizer=_a   ,							feature_extractor=_a      )

													processor.save_pretrained(self.tmpdirname      )
													a__:							List[Any]									=WhisperProcessor.from_pretrained(self.tmpdirname      )

													self.assertEqual(processor.tokenizer.get_vocab()   ,							tokenizer.get_vocab()      )
													self.assertIsInstance(processor.tokenizer   ,							_a      )

													self.assertEqual(processor.feature_extractor.to_json_string()   ,							feature_extractor.to_json_string()      )
													self.assertIsInstance(processor.feature_extractor   ,							_a      )


						def 	_lowerCamelCase      (			self    :	Dict      ):
													a__:							str									=WhisperProcessor(tokenizer=self.get_tokenizer()   ,							feature_extractor=self.get_feature_extractor()      )
													processor.save_pretrained(self.tmpdirname      )

													a__:							Tuple									=self.get_tokenizer(bos_token="(BOS)"   ,							eos_token="(EOS)"      )
													a__:							Optional[int]									=self.get_feature_extractor(do_normalize=_a   ,							padding_value=1.0      )

													a__:							Any									=WhisperProcessor.from_pretrained(
													    self.tmpdirname   ,							bos_token="(BOS)"   ,							eos_token="(EOS)"   ,							do_normalize=_a   ,							padding_value=1.0      )

													self.assertEqual(processor.tokenizer.get_vocab()   ,							tokenizer_add_kwargs.get_vocab()      )
													self.assertIsInstance(processor.tokenizer   ,							_a      )

													self.assertEqual(processor.feature_extractor.to_json_string()   ,							feature_extractor_add_kwargs.to_json_string()      )
													self.assertIsInstance(processor.feature_extractor   ,							_a      )


						def 	_lowerCamelCase      (			self    :	Tuple      ):
													a__:							Optional[int]									=self.get_feature_extractor()
													a__:							str									=self.get_tokenizer()

													a__:							int									=WhisperProcessor(tokenizer=_a   ,							feature_extractor=_a      )

													a__:							List[str]									=floats_list((3, 1_0_0_0)      )

													a__:							Optional[int]									=feature_extractor(_a   ,							return_tensors="np"      )
													a__:							Optional[int]									=processor(_a   ,							return_tensors="np"      )

													for key in input_feat_extract.keys():
																				self.assertAlmostEqual(input_feat_extract[key].sum()   ,							input_processor[key].sum()   ,							delta=1e-2      )


						def 	_lowerCamelCase      (			self    :	Optional[Any]      ):
													a__:							Dict									=self.get_feature_extractor()
													a__:							int									=self.get_tokenizer()

													a__:							List[Any]									=WhisperProcessor(tokenizer=_a   ,							feature_extractor=_a      )

													a__:							List[Any]									="This is a test string"

													a__:							Tuple									=processor(text=_a      )

													a__:							int									=tokenizer(_a      )

													for key in encoded_tok.keys():
																				self.assertListEqual(encoded_tok[key]   ,							encoded_processor[key]      )


						def 	_lowerCamelCase      (			self    :	Any      ):
													a__:							int									=self.get_feature_extractor()
													a__:							List[str]									=self.get_tokenizer()

													a__:							List[str]									=WhisperProcessor(tokenizer=_a   ,							feature_extractor=_a      )

													a__:							List[Any]									=[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

													a__:							List[Any]									=processor.batch_decode(_a      )
													a__:							int									=tokenizer.batch_decode(_a      )

													self.assertListEqual(_a   ,							_a      )


						def 	_lowerCamelCase      (			self    :	List[str]      ):
													a__:							List[Any]									=self.get_feature_extractor()
													a__:							Any									=self.get_tokenizer()

													a__:							Optional[int]									=WhisperProcessor(tokenizer=_a   ,							feature_extractor=_a      )

													self.assertListEqual(
													    processor.model_input_names   ,							feature_extractor.model_input_names   ,							msg="`processor` and `feature_extractor` model input names do not match"   ,							)


						def 	_lowerCamelCase      (			self    :	List[Any]      ):
													a__:							Any									=self.get_feature_extractor()
													a__:							str									=self.get_tokenizer()

													a__:							Dict									=WhisperProcessor(tokenizer=_a   ,							feature_extractor=_a      )
													a__:							List[Any]									=processor.get_decoder_prompt_ids(task="transcribe"   ,							no_timestamps=_a      )

													self.assertIsInstance(_a   ,							_a      )
													for ids in forced_decoder_ids:
																				self.assertIsInstance(_a   ,							(list, tuple)      )

													a__:							Any									=[TRANSCRIBE, NOTIMESTAMPS]
													self.assertListEqual([ids[-1] for ids in forced_decoder_ids]   ,							_a      )


						def 	_lowerCamelCase      (			self    :	str      ):
													a__:							Tuple									=WhisperProcessor(tokenizer=self.get_tokenizer()   ,							feature_extractor=self.get_feature_extractor()      )
													a__:							List[Any]									=processor.get_prompt_ids("Mr. Quilter"      )
													a__:							Optional[Any]									=processor.tokenizer.decode(_a      )

													self.assertListEqual(prompt_ids.tolist()   ,							[5_0_3_6_0, 1_7_7_0, 1_3, 2_2_6_4, 3_4_6, 3_5_3]      )
													self.assertEqual(_a   ,							"<|startofprev|> Mr. Quilter"      )


						def 	_lowerCamelCase      (			self    :	List[str]      ):
													a__:							int									=WhisperProcessor(tokenizer=self.get_tokenizer()   ,							feature_extractor=self.get_feature_extractor()      )
													a__:							List[str]									=processor.get_prompt_ids(""      )
													a__:							Any									=processor.tokenizer.decode(_a      )

													self.assertListEqual(prompt_ids.tolist()   ,							[5_0_3_6_0, 2_2_0]      )
													self.assertEqual(_a   ,							"<|startofprev|> "      )







						def 	_lowerCamelCase      (			self    :	Any      ):
													a__:							Tuple									=WhisperProcessor(tokenizer=self.get_tokenizer()   ,							feature_extractor=self.get_feature_extractor()      )

													def _test_prompt_error_raised_helper(_a    :	Union[str, Any]   ,							_a    :	List[str]      ):
																				with pytest.raises(_a      ) as excinfo:
																											processor.get_prompt_ids(_a      )
																				a__:							List[Any]									=F"Encountered text in the prompt corresponding to disallowed special token: {special_token}."
																				self.assertEqual(_a   ,							str(excinfo.value      )      )

													_test_prompt_error_raised_helper("<|startofprev|> test"   ,							"<|startofprev|>"      )
													_test_prompt_error_raised_helper("test <|notimestamps|>"   ,							"<|notimestamps|>"      )
													_test_prompt_error_raised_helper("test <|zh|> test <|transcribe|>"   ,							"<|zh|>"      )





