



"""simple docstring"""
import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


_UpperCAmelCase   =	get_tests_dir("""fixtures""")
_UpperCAmelCase   =	get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
_UpperCAmelCase   =	get_tests_dir("""fixtures/dummy-config.json""")
class     a		(     unittest.TestCase				):



  def 		lowerCamelCase__				(  self       :    Any						)   ->    str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Any   	=0



  def 		lowerCamelCase__				(  self       :    Dict						)   ->    List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       str   	=AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""						)
     self.assertIsInstance(lowerCAmelCase				,						lowerCAmelCase						)



  def 		lowerCamelCase__				(  self       :    int						)   ->    List[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Tuple   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase						)
     self.assertIsInstance(lowerCAmelCase				,						lowerCAmelCase						)



  def 		lowerCamelCase__				(  self       :    Any						)   ->    Tuple:


     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
        SCREAMING_SNAKE_CASE_:       str   	=WavaVecaConfig()

        # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
        SCREAMING_SNAKE_CASE_:       Optional[int]   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase						).to_dict()

        config_dict.pop("""feature_extractor_type"""						)
        SCREAMING_SNAKE_CASE_:       Any   	=WavaVecaFeatureExtractor(**lowerCAmelCase						)

        # save in new folder
        model_config.save_pretrained(lowerCAmelCase						)
        config.save_pretrained(lowerCAmelCase						)

        SCREAMING_SNAKE_CASE_:       int   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase						)

        # make sure private variable is not incorrectly saved
        SCREAMING_SNAKE_CASE_:       Dict   	=json.loads(config.to_json_string()						)
        self.assertTrue("""_processor_class""" not in dict_as_saved						)

     self.assertIsInstance(lowerCAmelCase				,						lowerCAmelCase						)



  def 		lowerCamelCase__				(  self       :    Optional[int]						)   ->    Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Dict   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase						)
     self.assertIsInstance(lowerCAmelCase				,						lowerCAmelCase						)



  def 		lowerCamelCase__				(  self       :    str						)   ->    Union[str, Any]:


     '''simple docstring'''




     with self.assertRaisesRegex(
         lowerCAmelCase				,						"""bert-base is not a local folder and is not a valid model identifier"""						):
        SCREAMING_SNAKE_CASE_:       Optional[int]   	=AutoFeatureExtractor.from_pretrained("""bert-base"""						)



  def 		lowerCamelCase__				(  self       :    Optional[Any]						)   ->    Tuple:


     '''simple docstring'''




     with self.assertRaisesRegex(
         lowerCAmelCase				,						R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""						):
        SCREAMING_SNAKE_CASE_:       int   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase				,						revision="""aaaaaa"""						)



  def 		lowerCamelCase__				(  self       :    Tuple						)   ->    Dict:


     '''simple docstring'''




     with self.assertRaisesRegex(
         lowerCAmelCase				,						"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""				,						):
        SCREAMING_SNAKE_CASE_:       List[str]   	=AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""						)



  def 		lowerCamelCase__				(  self       :    List[str]						)   ->    Union[str, Any]:


     '''simple docstring'''




     with self.assertRaises(lowerCAmelCase						):
        SCREAMING_SNAKE_CASE_:       Optional[int]   	=AutoFeatureExtractor.from_pretrained(
            """hf-internal-testing/test_dynamic_feature_extractor"""						)
     # If remote code is disabled, we can't load this config.
     with self.assertRaises(lowerCAmelCase						):
        SCREAMING_SNAKE_CASE_:       Any   	=AutoFeatureExtractor.from_pretrained(
            """hf-internal-testing/test_dynamic_feature_extractor"""				,						trust_remote_code=lowerCAmelCase						)

     SCREAMING_SNAKE_CASE_:       List[str]   	=AutoFeatureExtractor.from_pretrained(
         """hf-internal-testing/test_dynamic_feature_extractor"""				,						trust_remote_code=lowerCAmelCase						)
     self.assertEqual(feature_extractor.__class__.__name__				,						"""NewFeatureExtractor"""						)

     # Test feature extractor can be reloaded.
     with tempfile.TemporaryDirectory() as tmp_dir:
        feature_extractor.save_pretrained(lowerCAmelCase						)
        SCREAMING_SNAKE_CASE_:       Dict   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase				,						trust_remote_code=lowerCAmelCase						)
     self.assertEqual(reloaded_feature_extractor.__class__.__name__				,						"""NewFeatureExtractor"""						)



  def 		lowerCamelCase__				(  self       :    List[Any]						)   ->    Union[str, Any]:


     '''simple docstring'''




     try:
        AutoConfig.register("""custom"""				,						lowerCAmelCase						)
        AutoFeatureExtractor.register(lowerCAmelCase				,						lowerCAmelCase						)
        # Trying to register something existing in the Transformers library will raise an error
        with self.assertRaises(lowerCAmelCase						):
           AutoFeatureExtractor.register(lowerCAmelCase				,						lowerCAmelCase						)

        # Now that the config is registered, it can be used as any other config with the auto-API
        SCREAMING_SNAKE_CASE_:       int   	=CustomFeatureExtractor.from_pretrained(lowerCAmelCase						)
        with tempfile.TemporaryDirectory() as tmp_dir:
           feature_extractor.save_pretrained(lowerCAmelCase						)
           SCREAMING_SNAKE_CASE_:       Optional[Any]   	=AutoFeatureExtractor.from_pretrained(lowerCAmelCase						)
           self.assertIsInstance(lowerCAmelCase				,						lowerCAmelCase						)

     finally:
        if "custom" in CONFIG_MAPPING._extra_content:
           del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
           del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]





  def 		lowerCamelCase__				(  self       :    str						)   ->    Optional[Any]:


     '''simple docstring'''




     class     a		(     __a				):
       UpperCamelCase		: Optional[Any]     =    True

     try:
        AutoConfig.register("""custom"""				,						lowerCAmelCase						)
        AutoFeatureExtractor.register(lowerCAmelCase				,						lowerCAmelCase						)
        # If remote code is not set, the default is to use local
        SCREAMING_SNAKE_CASE_:       List[Any]   	=AutoFeatureExtractor.from_pretrained(
            """hf-internal-testing/test_dynamic_feature_extractor"""						)
        self.assertEqual(feature_extractor.__class__.__name__				,						"""NewFeatureExtractor"""						)
        self.assertTrue(feature_extractor.is_local						)

        # If remote code is disabled, we load the local one.
        SCREAMING_SNAKE_CASE_:       Dict   	=AutoFeatureExtractor.from_pretrained(
            """hf-internal-testing/test_dynamic_feature_extractor"""				,						trust_remote_code=lowerCAmelCase						)
        self.assertEqual(feature_extractor.__class__.__name__				,						"""NewFeatureExtractor"""						)
        self.assertTrue(feature_extractor.is_local						)

        # If remote is enabled, we load from the Hub
        SCREAMING_SNAKE_CASE_:       Any   	=AutoFeatureExtractor.from_pretrained(
            """hf-internal-testing/test_dynamic_feature_extractor"""				,						trust_remote_code=lowerCAmelCase						)
        self.assertEqual(feature_extractor.__class__.__name__				,						"""NewFeatureExtractor"""						)
        self.assertTrue(not hasattr(lowerCAmelCase				,						"""is_local"""						)						)

     finally:
        if "custom" in CONFIG_MAPPING._extra_content:
           del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
           del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]









'''simple docstring'''







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 			_a  (	__a ):
       __a				:     str   				=					["""vqvae"""]
       def __init__(	self						:	str   ,				lowercase						:	AutoencoderKL   ,				lowercase						:	UNetaDConditionModel   ,				lowercase						:	Mel   ,				lowercase						:	Union[DDIMScheduler, DDPMScheduler]   ,				):



           '''simple docstring'''

           super().__init__()
           self.register_modules(unet=lowercase   ,				scheduler=lowercase   ,				mel=lowercase   ,				vqvae=lowercase				)
       def     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

           return 50 if isinstance(self.scheduler   ,				lowercase				) else 1_000
       @torch.no_grad()
       def __call__(	self						:	Optional[Any]   ,				lowercase						:	int = 1   ,				lowercase						:	str = None   ,				lowercase						:	np.ndarray = None   ,				lowercase						:	int = 0   ,				lowercase						:	int = 0   ,				lowercase						:	int = None   ,				lowercase						:	torch.Generator = None   ,				lowercase						:	float = 0   ,				lowercase						:	float = 0   ,				lowercase						:	torch.Generator = None   ,				lowercase						:	float = 0   ,				lowercase						:	torch.Tensor = None   ,				lowercase						:	torch.Tensor = None   ,				lowercase						:	Tuple=True   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		steps or self.get_default_steps()
           self.scheduler.set_timesteps(lowercase				)
           UpperCAmelCase			       =		step_generator or generator
           # For backwards compatibility
           if type(self.unet.config.sample_size				) == int:
               UpperCAmelCase			       =		(self.unet.config.sample_size, self.unet.config.sample_size)
           if noise is None:
               UpperCAmelCase			       =		randn_tensor(
                   (
                       batch_size,
                       self.unet.config.in_channels,
                       self.unet.config.sample_size[0],
                       self.unet.config.sample_size[1],
                   )   ,				generator=lowercase   ,				device=self.device   ,				)
           UpperCAmelCase			       =		noise
           UpperCAmelCase			       =		None

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

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

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

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

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

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

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

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

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

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

           return BaseOutput(**AudioPipelineOutput(np.array(lowercase				)[:, np.newaxis, :]				)   ,				**ImagePipelineOutput(lowercase				)				)
       @torch.no_grad()
       def     A      (	self						:	Dict   ,				lowercase						:	List[Image.Image]   ,				lowercase						:	int = 50				):



           '''simple docstring'''

           assert isinstance(self.scheduler   ,				lowercase				)
           self.scheduler.set_timesteps(lowercase				)
           UpperCAmelCase			       =		np.array(
               [np.frombuffer(image.tobytes()   ,				dtype='''uint8'''				).reshape((1, image.height, image.width)				) for image in images]				)
           UpperCAmelCase			       =		(sample / 255) * 2 - 1
           UpperCAmelCase			       =		torch.Tensor(lowercase				).to(self.device				)

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

           return sample







       @staticmethod
       def     A      (	lowercase						:	torch.Tensor   ,				lowercase						:	torch.Tensor   ,				lowercase						:	float				):



           '''simple docstring'''

           UpperCAmelCase			       =		acos(torch.dot(torch.flatten(lowercase				)   ,				torch.flatten(lowercase				)				) / torch.norm(lowercase				) / torch.norm(lowercase				)				)
           return sin((1 - alpha) * theta				) * xa / sin(lowercase				) + sin(alpha * theta				) * xa / sin(lowercase				)




