
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 			_lowerCAmelCase      (			__a ):
				_lowercase    	=['''vqvae''']




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




				def   __a		(      self  )       ->   int:
							return 50 if isinstance(self.scheduler       ,       _UpperCamelCase  ) else 1_000




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

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

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

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

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

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

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

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

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

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

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

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




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

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

							return sample




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





import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
			from test_module.custom_tokenization_fast import CustomTokenizerFast





class 			_lowerCAmelCase      (			unittest.TestCase ):




				def   __a		(      self  )       ->   str:
							# A mock response for an HTTP head request to emulate server down
							lowerCAmelCase_      			=			mock.Mock()
							lowerCAmelCase_      			=			500
							lowerCAmelCase_      			=			{}
							lowerCAmelCase_      			=			HTTPError
							lowerCAmelCase_      			=			{}

							# Download this model to make sure it's in the cache.
							lowerCAmelCase_      			=			BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"  )

							# Under the mock environment we get a 500 error when trying to reach the tokenizer.
							with mock.patch("requests.Session.request"       ,       return_value=_UpperCamelCase  ) as mock_head:
										lowerCAmelCase_      			=			BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"  )
										# This check we did call the fake head request
										mock_head.assert_called()




				@require_tokenizers
				def   __a		(      self  )       ->   int:
							# A mock response for an HTTP head request to emulate server down
							lowerCAmelCase_      			=			mock.Mock()
							lowerCAmelCase_      			=			500
							lowerCAmelCase_      			=			{}
							lowerCAmelCase_      			=			HTTPError
							lowerCAmelCase_      			=			{}

							# Download this model to make sure it's in the cache.
							lowerCAmelCase_      			=			GPTaTokenizerFast.from_pretrained("gpt2"  )

							# Under the mock environment we get a 500 error when trying to reach the tokenizer.
							with mock.patch("requests.Session.request"       ,       return_value=_UpperCamelCase  ) as mock_head:
										lowerCAmelCase_      			=			GPTaTokenizerFast.from_pretrained("gpt2"  )
										# This check we did call the fake head request
										mock_head.assert_called()




				def   __a		(      self  )       ->   List[Any]:
							# This test is for deprecated behavior and can be removed in v5
							try:
										lowerCAmelCase_      			=			tempfile.mktemp()
										with open(_UpperCamelCase       ,       "wb"  ) as f:
													http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"       ,       _UpperCamelCase  )

										lowerCAmelCase_      			=			AlbertTokenizer.from_pretrained(_UpperCamelCase  )
							finally:
										os.remove(_UpperCamelCase  )

							# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
							# the current folder and have the right name.
							if os.path.isfile("tokenizer.json"  ):
										# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
										return
							try:
										with open("tokenizer.json"       ,       "wb"  ) as f:
													http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json"       ,       _UpperCamelCase  )
										lowerCAmelCase_      			=			AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2"  )
										# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
										self.assertEqual(tokenizer.vocab_size       ,       1_000  )
										# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

							finally:
										os.remove("tokenizer.json"  )




				def   __a		(      self  )       ->   Union[str, Any]:
							# This test is for deprecated behavior and can be removed in v5
							lowerCAmelCase_      			=			AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"  )





@is_staging_test
class 			_lowerCAmelCase      (			unittest.TestCase ):
				_lowercase    	=['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']




				@classmethod
				def   __a		(      cls  )       ->   Tuple:
							lowerCAmelCase_      			=			TOKEN
							HfFolder.save_token(_UpperCamelCase  )




				@classmethod
				def   __a		(      cls  )       ->   Tuple:
							try:
										delete_repo(token=cls._token       ,       repo_id="test-tokenizer"  )
							except HTTPError:
										pass

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

							try:
										delete_repo(token=cls._token       ,       repo_id="test-dynamic-tokenizer"  )
							except HTTPError:
										pass




				def   __a		(      self  )       ->   int:
							with tempfile.TemporaryDirectory() as tmp_dir:
										lowerCAmelCase_      			=			os.path.join(_UpperCamelCase       ,       "vocab.txt"  )
										with open(_UpperCamelCase       ,       "w"       ,       encoding="utf-8"  ) as vocab_writer:
													vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]  )  )
										lowerCAmelCase_      			=			BertTokenizer(_UpperCamelCase  )

							tokenizer.push_to_hub("test-tokenizer"       ,       use_auth_token=self._token  )
							lowerCAmelCase_      			=			BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer"""  )
							self.assertDictEqual(new_tokenizer.vocab       ,       tokenizer.vocab  )

							# Reset repo
							delete_repo(token=self._token       ,       repo_id="test-tokenizer"  )

							# Push to hub via save_pretrained
							with tempfile.TemporaryDirectory() as tmp_dir:
										tokenizer.save_pretrained(_UpperCamelCase       ,       repo_id="test-tokenizer"       ,       push_to_hub=_UpperCamelCase       ,       use_auth_token=self._token  )

							lowerCAmelCase_      			=			BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer"""  )
							self.assertDictEqual(new_tokenizer.vocab       ,       tokenizer.vocab  )




				def   __a		(      self  )       ->   Optional[int]:
							with tempfile.TemporaryDirectory() as tmp_dir:
										lowerCAmelCase_      			=			os.path.join(_UpperCamelCase       ,       "vocab.txt"  )
										with open(_UpperCamelCase       ,       "w"       ,       encoding="utf-8"  ) as vocab_writer:
													vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]  )  )
										lowerCAmelCase_      			=			BertTokenizer(_UpperCamelCase  )

							tokenizer.push_to_hub("valid_org/test-tokenizer-org"       ,       use_auth_token=self._token  )
							lowerCAmelCase_      			=			BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"  )
							self.assertDictEqual(new_tokenizer.vocab       ,       tokenizer.vocab  )

							# Reset repo
							delete_repo(token=self._token       ,       repo_id="valid_org/test-tokenizer-org"  )

							# Push to hub via save_pretrained
							with tempfile.TemporaryDirectory() as tmp_dir:
										tokenizer.save_pretrained(
										    _UpperCamelCase       ,       repo_id="valid_org/test-tokenizer-org"       ,       push_to_hub=_UpperCamelCase       ,       use_auth_token=self._token  )

							lowerCAmelCase_      			=			BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"  )
							self.assertDictEqual(new_tokenizer.vocab       ,       tokenizer.vocab  )




				@require_tokenizers
				def   __a		(      self  )       ->   Optional[Any]:
							CustomTokenizer.register_for_auto_class()
							with tempfile.TemporaryDirectory() as tmp_dir:
										lowerCAmelCase_      			=			os.path.join(_UpperCamelCase       ,       "vocab.txt"  )
										with open(_UpperCamelCase       ,       "w"       ,       encoding="utf-8"  ) as vocab_writer:
													vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]  )  )
										lowerCAmelCase_      			=			CustomTokenizer(_UpperCamelCase  )

							# No fast custom tokenizer
							tokenizer.push_to_hub("test-dynamic-tokenizer"       ,       use_auth_token=self._token  )

							lowerCAmelCase_      			=			AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer"""       ,       trust_remote_code=_UpperCamelCase  )
							# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
							self.assertEqual(tokenizer.__class__.__name__       ,       "CustomTokenizer"  )

							# Fast and slow custom tokenizer
							CustomTokenizerFast.register_for_auto_class()
							with tempfile.TemporaryDirectory() as tmp_dir:
										lowerCAmelCase_      			=			os.path.join(_UpperCamelCase       ,       "vocab.txt"  )
										with open(_UpperCamelCase       ,       "w"       ,       encoding="utf-8"  ) as vocab_writer:
													vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]  )  )

										lowerCAmelCase_      			=			BertTokenizerFast.from_pretrained(_UpperCamelCase  )
										bert_tokenizer.save_pretrained(_UpperCamelCase  )
										lowerCAmelCase_      			=			CustomTokenizerFast.from_pretrained(_UpperCamelCase  )

							tokenizer.push_to_hub("test-dynamic-tokenizer"       ,       use_auth_token=self._token  )

							lowerCAmelCase_      			=			AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer"""       ,       trust_remote_code=_UpperCamelCase  )
							# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
							self.assertEqual(tokenizer.__class__.__name__       ,       "CustomTokenizerFast"  )
							lowerCAmelCase_      			=			AutoTokenizer.from_pretrained(
							    f"""{USER}/test-dynamic-tokenizer"""       ,       use_fast=_UpperCamelCase       ,       trust_remote_code=_UpperCamelCase  )
							# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
							self.assertEqual(tokenizer.__class__.__name__       ,       "CustomTokenizer"  )





class 			_lowerCAmelCase      (			unittest.TestCase ):




				def   __a		(      self  )       ->   Any:
							lowerCAmelCase_      			=			Trie()
							trie.add("Hello 友達"  )
							self.assertEqual(trie.data       ,       {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}  )
							trie.add("Hello"  )
							trie.data
							self.assertEqual(trie.data       ,       {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}  )




				def   __a		(      self  )       ->   Optional[int]:
							lowerCAmelCase_      			=			Trie()
							self.assertEqual(trie.split("[CLS] This is a extra_id_100"  )       ,       ["[CLS] This is a extra_id_100"]  )
							trie.add("[CLS]"  )
							trie.add("extra_id_1"  )
							trie.add("extra_id_100"  )
							self.assertEqual(trie.split("[CLS] This is a extra_id_100"  )       ,       ["[CLS]", " This is a ", "extra_id_100"]  )




				def   __a		(      self  )       ->   str:
							lowerCAmelCase_      			=			Trie()
							trie.add("A"  )
							self.assertEqual(trie.split("ABC"  )       ,       ["A", "BC"]  )
							self.assertEqual(trie.split("BCA"  )       ,       ["BC", "A"]  )




				def   __a		(      self  )       ->   int:
							lowerCAmelCase_      			=			Trie()
							trie.add("TOKEN]"  )
							trie.add("[SPECIAL_TOKEN]"  )
							self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"  )       ,       ["This is something ", "[SPECIAL_TOKEN]"]  )




				def   __a		(      self  )       ->   int:
							lowerCAmelCase_      			=			Trie()
							trie.add("A"  )
							trie.add("P"  )
							trie.add("[SPECIAL_TOKEN]"  )
							self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"  )       ,       ["This is something ", "[SPECIAL_TOKEN]"]  )




				def   __a		(      self  )       ->   str:
							lowerCAmelCase_      			=			Trie()
							trie.add("AB"  )
							trie.add("B"  )
							trie.add("C"  )
							self.assertEqual(trie.split("ABC"  )       ,       ["AB", "C"]  )




				def   __a		(      self  )       ->   List[Any]:
							lowerCAmelCase_      			=			Trie()
							trie.add("ABC"  )
							trie.add("B"  )
							trie.add("CD"  )
							self.assertEqual(trie.split("ABCD"  )       ,       ["ABC", "D"]  )




				def   __a		(      self  )       ->   List[Any]:
							# Even if the offsets are wrong, we necessarily output correct string
							# parts.
							lowerCAmelCase_      			=			Trie()
							lowerCAmelCase_      			=			trie.cut_text("ABC"       ,       [0, 0, 2, 1, 2, 3]  )
							self.assertEqual(_UpperCamelCase       ,       ["AB", "C"]  )



