





import functools
import operator

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


UpperCAmelCase     :     Any							=	logging.get_logger(__name__)

UpperCAmelCase     :     List[Any]							=	{
    """facebook/wav2vec2-base-960h""": """https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json""",
    # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}







class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : int            =      """wav2vec2"""







      def __init__(   self		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__=7_6_8		,				lowerCAmelCase__=1_2		,				lowerCAmelCase__=1_2		,				lowerCAmelCase__=3_0_7_2		,				lowerCAmelCase__="gelu"		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.0		,				lowerCAmelCase__=0.0		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.02		,				lowerCAmelCase__=1E-5		,				lowerCAmelCase__="group"		,				lowerCAmelCase__="gelu"		,				lowerCAmelCase__=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2)		,				lowerCAmelCase__=(5, 2, 2, 2, 2, 2, 2)		,				lowerCAmelCase__=(1_0, 3, 3, 3, 3, 2, 2)		,				lowerCAmelCase__=False		,				lowerCAmelCase__=1_2_8		,				lowerCAmelCase__=1_6		,				lowerCAmelCase__=False		,				lowerCAmelCase__=True		,				lowerCAmelCase__=0.05		,				lowerCAmelCase__=1_0		,				lowerCAmelCase__=2		,				lowerCAmelCase__=0.0		,				lowerCAmelCase__=1_0		,				lowerCAmelCase__=0		,				lowerCAmelCase__=3_2_0		,				lowerCAmelCase__=2		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=1_0_0		,				lowerCAmelCase__=2_5_6		,				lowerCAmelCase__=2_5_6		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__="sum"		,				lowerCAmelCase__=False		,				lowerCAmelCase__=False		,				lowerCAmelCase__=2_5_6		,				lowerCAmelCase__=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0)		,				lowerCAmelCase__=(5, 3, 3, 1, 1)		,				lowerCAmelCase__=(1, 2, 3, 1, 1)		,				lowerCAmelCase__=5_1_2		,				lowerCAmelCase__=0		,				lowerCAmelCase__=1		,				lowerCAmelCase__=2		,				lowerCAmelCase__=False		,				lowerCAmelCase__=3		,				lowerCAmelCase__=2		,				lowerCAmelCase__=3		,				lowerCAmelCase__=None		,				lowerCAmelCase__=None		,				**lowerCAmelCase__		,				)       ->						str:



        '''simple docstring'''




        super().__init__(**lowerCAmelCase__		,				pad_token_id=lowerCAmelCase__		,				bos_token_id=lowerCAmelCase__		,				eos_token_id=lowerCAmelCase__							)
        a__     : int  =hidden_size
        a__     : Optional[Any]  =feat_extract_norm
        a__     : Optional[int]  =feat_extract_activation
        a__     : List[str]  =list(lowerCAmelCase__							)
        a__     : Optional[Any]  =list(lowerCAmelCase__							)
        a__     : Tuple  =list(lowerCAmelCase__							)
        a__     : List[str]  =conv_bias
        a__     : List[Any]  =num_conv_pos_embeddings
        a__     : Union[str, Any]  =num_conv_pos_embedding_groups
        a__     : List[Any]  =len(self.conv_dim							)
        a__     : str  =num_hidden_layers
        a__     : List[str]  =intermediate_size
        a__     : Optional[int]  =hidden_act
        a__     : Tuple  =num_attention_heads
        a__     : Any  =hidden_dropout
        a__     : int  =attention_dropout
        a__     : Dict  =activation_dropout
        a__     : int  =feat_proj_dropout
        a__     : List[str]  =final_dropout
        a__     : List[str]  =layerdrop
        a__     : Tuple  =layer_norm_eps
        a__     : Optional[Any]  =initializer_range
        a__     : Any  =vocab_size
        a__     : Tuple  =do_stable_layer_norm
        a__     : List[Any]  =use_weighted_layer_sum

        if (
            (len(self.conv_stride							) != self.num_feat_extract_layers)
            or (len(self.conv_kernel							) != self.num_feat_extract_layers)
            or (len(self.conv_dim							) != self.num_feat_extract_layers)
        ):
          raise ValueError(
              "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
              " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
              F''' {len(self.conv_dim							)}`, `len(config.conv_stride) = {len(self.conv_stride							)}`,'''
              F''' `len(config.conv_kernel) = {len(self.conv_kernel							)}`.'''							)

        # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
        a__     : List[str]  =apply_spec_augment
        a__     : Tuple  =mask_time_prob
        a__     : Tuple  =mask_time_length
        a__     : int  =mask_time_min_masks
        a__     : str  =mask_feature_prob
        a__     : int  =mask_feature_length
        a__     : List[Any]  =mask_feature_min_masks

        # parameters for pretraining with codevector quantized representations
        a__     : Dict  =num_codevectors_per_group
        a__     : List[Any]  =num_codevector_groups
        a__     : List[str]  =contrastive_logits_temperature
        a__     : List[str]  =feat_quantizer_dropout
        a__     : List[str]  =num_negatives
        a__     : str  =codevector_dim
        a__     : List[str]  =proj_codevector_dim
        a__     : Optional[int]  =diversity_loss_weight

        # ctc loss
        a__     : int  =ctc_loss_reduction
        a__     : Union[str, Any]  =ctc_zero_infinity

        # adapter
        a__     : List[str]  =add_adapter
        a__     : List[Any]  =adapter_kernel_size
        a__     : List[Any]  =adapter_stride
        a__     : Union[str, Any]  =num_adapter_layers
        a__     : Dict  =output_hidden_size or hidden_size
        a__     : List[str]  =adapter_attn_dim

        # SequenceClassification-specific parameter. Feel free to ignore for other classes.
        a__     : str  =classifier_proj_size

        # XVector-specific parameters. Feel free to ignore for other classes.
        a__     : List[str]  =list(lowerCAmelCase__							)
        a__     : str  =list(lowerCAmelCase__							)
        a__     : Dict  =list(lowerCAmelCase__							)
        a__     : List[str]  =xvector_output_dim







      @property
      def        _lowercase  (   self							)       ->						Tuple:



        '''simple docstring'''




        return functools.reduce(operator.mul		,				self.conv_stride		,				1							)













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	(   UpperCamelCase__):
      _lowercase    : str            =      ["""vqvae"""]







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



        '''simple docstring'''




        super().__init__()
        self.register_modules(unet=lowerCAmelCase__		,				scheduler=lowerCAmelCase__		,				mel=lowerCAmelCase__		,				vqvae=lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						int:



        '''simple docstring'''




        return 5_0 if isinstance(self.scheduler		,				lowerCAmelCase__							) else 1_0_0_0







      @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]]],
      ]:



        '''simple docstring'''




        a__     : List[Any]  =steps or self.get_default_steps()
        self.scheduler.set_timesteps(lowerCAmelCase__							)
        a__     : Tuple  =step_generator or generator
        # For backwards compatibility
        if type(self.unet.config.sample_size							) == int:
          a__     : List[str]  =(self.unet.config.sample_size, self.unet.config.sample_size)
        if noise is None:
          a__     : Optional[Any]  =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		,				)
        a__     : List[str]  =noise
        a__     : Optional[Any]  =None

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

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

          if start_step > 0:
            a__     : Optional[int]  =self.scheduler.add_noise(lowerCAmelCase__		,				lowerCAmelCase__		,				self.scheduler.timesteps[start_step - 1]							)

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

          if isinstance(self.scheduler		,				lowerCAmelCase__							):
            a__     : int  =self.scheduler.step(
                model_output=lowerCAmelCase__		,				timestep=lowerCAmelCase__		,				sample=lowerCAmelCase__		,				eta=lowerCAmelCase__		,				generator=lowerCAmelCase__		,				)["prev_sample"]
          else:
            a__     : str  =self.scheduler.step(
                model_output=lowerCAmelCase__		,				timestep=lowerCAmelCase__		,				sample=lowerCAmelCase__		,				generator=lowerCAmelCase__		,				)["prev_sample"]

          if mask is not None:
            if mask_start > 0:
              a__     : List[Any]  =mask[:, step, :, :mask_start]
            if mask_end > 0:
              a__     : Union[str, Any]  =mask[:, step, :, -mask_end:]

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

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

        a__     : str  =[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        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__ = 5_0							)       ->						np.ndarray:



        '''simple docstring'''




        assert isinstance(self.scheduler		,				lowerCAmelCase__							)
        self.scheduler.set_timesteps(lowerCAmelCase__							)
        a__     : Union[str, Any]  =np.array(
            [np.frombuffer(image.tobytes()		,				dtype="uint8"							).reshape((1, image.height, image.width)							) for image in images]							)
        a__     : Tuple  =(sample / 2_5_5) * 2 - 1
        a__     : List[Any]  =torch.Tensor(lowerCAmelCase__							).to(self.device							)

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

        return sample







      @staticmethod
      def        _lowercase  (   lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						torch.Tensor:



        '''simple docstring'''




        a__     : Any  =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__							)






