
from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_					:   int 							=						logging.get_logger(__name__)

UpperCAmelCase_					:   int 							=						{
    """facebook/s2t-small-librispeech-asr""": (
        """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json"""
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text
}





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """speech_to_text"""
  __UpperCamelCase	     =  ["""past_key_values"""]
  __UpperCamelCase	     =  {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}







  def __init__(	self    ,						_lowercase=10_000    ,						_lowercase=12    ,						_lowercase=2_048    ,						_lowercase=4    ,						_lowercase=6    ,						_lowercase=2_048    ,						_lowercase=4    ,						_lowercase=0.0    ,						_lowercase=0.0    ,						_lowercase=True    ,						_lowercase=True    ,						_lowercase="relu"    ,						_lowercase=256    ,						_lowercase=0.1    ,						_lowercase=0.0    ,						_lowercase=0.0    ,						_lowercase=0.02    ,						_lowercase=2    ,						_lowercase=True    ,						_lowercase=1    ,						_lowercase=0    ,						_lowercase=2    ,						_lowercase=6_000    ,						_lowercase=1_024    ,						_lowercase=2    ,						_lowercase=(5, 5)    ,						_lowercase=1_024    ,						_lowercase=80    ,						_lowercase=1    ,						**_lowercase    ,						):
       lowerCAmelCase_					:       Any    =		vocab_size
       lowerCAmelCase_					:       str    =		d_model
       lowerCAmelCase_					:       Dict    =		encoder_ffn_dim
       lowerCAmelCase_					:       Optional[int]    =		encoder_layers
       lowerCAmelCase_					:       Optional[Any]    =		encoder_attention_heads
       lowerCAmelCase_					:       Optional[Any]    =		decoder_ffn_dim
       lowerCAmelCase_					:       Tuple    =		decoder_layers
       lowerCAmelCase_					:       Dict    =		decoder_attention_heads
       lowerCAmelCase_					:       Optional[Any]    =		dropout
       lowerCAmelCase_					:       Union[str, Any]    =		attention_dropout
       lowerCAmelCase_					:       Dict    =		activation_dropout
       lowerCAmelCase_					:       Tuple    =		activation_function
       lowerCAmelCase_					:       List[Any]    =		init_std
       lowerCAmelCase_					:       Any    =		encoder_layerdrop
       lowerCAmelCase_					:       List[Any]    =		decoder_layerdrop
       lowerCAmelCase_					:       Union[str, Any]    =		use_cache
       lowerCAmelCase_					:       str    =		encoder_layers
       lowerCAmelCase_					:       Optional[Any]    =		scale_embedding  # scale factor will be sqrt(d_model) if True
       lowerCAmelCase_					:       Dict    =		max_source_positions
       lowerCAmelCase_					:       List[Any]    =		max_target_positions
       lowerCAmelCase_					:       Union[str, Any]    =		num_conv_layers
       lowerCAmelCase_					:       Optional[Any]    =		list(_lowercase						)
       lowerCAmelCase_					:       int    =		conv_channels
       lowerCAmelCase_					:       Dict    =		input_feat_per_channel
       lowerCAmelCase_					:       List[str]    =		input_channels

       if len(self.conv_kernel_sizes						) != self.num_conv_layers:
            raise ValueError(
                """Configuration for convolutional module is incorrect. """
                """It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` """
                F'but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes						)}`, '
                F'`config.num_conv_layers = {self.num_conv_layers}`.'						)

       super().__init__(
           pad_token_id=_lowercase    ,						bos_token_id=_lowercase    ,						eos_token_id=_lowercase    ,						is_encoder_decoder=_lowercase    ,						decoder_start_token_id=_lowercase    ,						**_lowercase    ,						)







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      lowercase__    (							__A  ):
  __UpperCamelCase	     =  ["""vqvae"""]







  def __init__(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						):
       super().__init__()
       self.register_modules(unet=_lowercase    ,						scheduler=_lowercase    ,						mel=_lowercase    ,						vqvae=_lowercase						)







  def 	UpperCAmelCase__		(	self						):
       return 50 if isinstance(self.scheduler    ,						_lowercase						) else 1_000







  @torch.no_grad()
  def __call__(	self    ,						_lowercase = 1    ,						_lowercase = None    ,						_lowercase = None    ,						_lowercase = 0    ,						_lowercase = 0    ,						_lowercase = None    ,						_lowercase = None    ,						_lowercase = 0    ,						_lowercase = 0    ,						_lowercase = None    ,						_lowercase = 0    ,						_lowercase = None    ,						_lowercase = None    ,						_lowercase=True    ,						):
       lowerCAmelCase_					:       Tuple    =		steps or self.get_default_steps()
       self.scheduler.set_timesteps(_lowercase						)
       lowerCAmelCase_					:       Union[str, Any]    =		step_generator or generator
       # For backwards compatibility
       if type(self.unet.config.sample_size						) == int:
            lowerCAmelCase_					:       Optional[Any]    =		(self.unet.config.sample_size, self.unet.config.sample_size)
       if noise is None:
            lowerCAmelCase_					:       Tuple    =		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    ,						)
       lowerCAmelCase_					:       List[str]    =		noise
       lowerCAmelCase_					:       List[str]    =		None

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

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

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

            lowerCAmelCase_					:       Dict    =		(
                self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
            )
            lowerCAmelCase_					:       Union[str, Any]    =		int(mask_start_secs * pixels_per_second						)
            lowerCAmelCase_					:       str    =		int(mask_end_secs * pixels_per_second						)
            lowerCAmelCase_					:       List[Any]    =		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						):
                 lowerCAmelCase_					:       List[Any]    =		self.unet(_lowercase    ,						_lowercase    ,						_lowercase						)["""sample"""]
            else:
                 lowerCAmelCase_					:       Any    =		self.unet(_lowercase    ,						_lowercase						)["""sample"""]

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

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

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

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

       lowerCAmelCase_					:       str    =		[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 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase = 50						):
       assert isinstance(self.scheduler    ,						_lowercase						)
       self.scheduler.set_timesteps(_lowercase						)
       lowerCAmelCase_					:       List[Any]    =		np.array(
           [np.frombuffer(image.tobytes()    ,						dtype="""uint8"""						).reshape((1, image.height, image.width)						) for image in images]						)
       lowerCAmelCase_					:       List[str]    =		(sample / 255) * 2 - 1
       lowerCAmelCase_					:       Optional[Any]    =		torch.Tensor(_lowercase						).to(self.device						)

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

       return sample







  @staticmethod
  def 	UpperCAmelCase__		(	_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Optional[int]    =		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						)
