
"""simple docstring"""



from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


a					:	Tuple							=		logging.get_logger(__name__)




class 		a_						( _UpperCAmelCase	):
    a      :				Tuple     =				['audio_values', 'audio_mask']







    def __init__(			self			:       Optional[Any]     ,					__UpperCamelCase			:       Optional[Any]=20_48     ,					__UpperCamelCase			:       Any=1     ,					__UpperCamelCase			:       Any=[16, 16]     ,					__UpperCamelCase			:       Optional[int]=1_28     ,					__UpperCamelCase			:       Union[str, Any]=4_41_00     ,					__UpperCamelCase			:       List[str]=86     ,					__UpperCamelCase			:       int=20_48     ,					__UpperCamelCase			:       Optional[Any]=0.0     ,					**__UpperCamelCase			:       Dict     ,					)		->Dict:






        '''simple docstring'''






        super().__init__(
            feature_size=__UpperCamelCase     ,					sampling_rate=__UpperCamelCase     ,					padding_value=__UpperCamelCase     ,					**__UpperCamelCase     ,					)

        _UpperCAmelCase          =   spectrogram_length
        _UpperCAmelCase          =   num_channels
        _UpperCAmelCase          =   patch_size
        _UpperCAmelCase          =   feature_size // self.patch_size[1]
        _UpperCAmelCase          =   n_fft
        _UpperCAmelCase          =   sampling_rate // hop_length_to_sampling_rate
        _UpperCAmelCase          =   sampling_rate
        _UpperCAmelCase          =   padding_value
        _UpperCAmelCase          =   mel_filter_bank(
            num_frequency_bins=1 + n_fft // 2     ,					num_mel_filters=__UpperCamelCase     ,					min_frequency=0.0     ,					max_frequency=2_2_0_5_0.0     ,					sampling_rate=__UpperCamelCase     ,					norm="""slaney"""     ,					mel_scale="""slaney"""     ,					).T







    def      _snake_case					(			self			:       Dict     ,					__UpperCamelCase			:       np.array     )		->np.ndarray:






        '''simple docstring'''






        _UpperCAmelCase          =   spectrogram(
            __UpperCamelCase     ,					window_function(self.n_fft     ,					"""hann"""     )     ,					frame_length=self.n_fft     ,					hop_length=self.hop_length     ,					power=2.0     ,					mel_filters=self.mel_filters.T     ,					log_mel="""dB"""     ,					db_range=8_0.0     ,					)
        _UpperCAmelCase          =   log_spec[:, :-1]
        _UpperCAmelCase          =   log_spec - 2_0.0
        _UpperCAmelCase          =   np.clip(log_spec / 4_0.0     ,					-2.0     ,					0.0     ) + 1.0
        return log_spec







    def __call__(			self			:       Optional[Any]     ,					__UpperCamelCase			:       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]     ,					__UpperCamelCase			:       Optional[Union[str, TensorType]] = None     ,					__UpperCamelCase			:       Optional[bool] = True     ,					__UpperCamelCase			:       Optional[int] = None     ,					__UpperCamelCase			:       bool = False     ,					__UpperCamelCase			:       bool = False     ,					**__UpperCamelCase			:       str     ,					)		->BatchFeature:






        '''simple docstring'''






        if sampling_rate is not None:
            if sampling_rate != self.sampling_rate:
                raise ValueError(
                    """This feature extractor is set to support sampling rate"""
                    f""" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"""
                    f""" with {self.sampling_rate} and not {sampling_rate}."""     )
        else:
            logger.warning(
                """It is strongly recommended to pass the `sampling_rate` argument to this function. """
                """Failing to do so can result in silent errors that might be hard to debug."""     )

        _UpperCAmelCase          =   isinstance(__UpperCamelCase     ,					np.ndarray     ) and len(raw_speech.shape     ) > 1
        if is_batched_numpy and len(raw_speech.shape     ) > 2:
            raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""     )
        _UpperCAmelCase          =   is_batched_numpy or (
            isinstance(__UpperCamelCase     ,					(list, tuple)     ) and (isinstance(raw_speech[0]     ,					(np.ndarray, tuple, list)     ))
        )
        if is_batched:
            _UpperCAmelCase          =   [np.asarray([speech]     ,					dtype=np.floataa     ).T for speech in raw_speech]
        elif not is_batched and not isinstance(__UpperCamelCase     ,					np.ndarray     ):
            _UpperCAmelCase          =   np.asarray(__UpperCamelCase     ,					dtype=np.floataa     )
        elif isinstance(__UpperCamelCase     ,					np.ndarray     ) and raw_speech.dtype is np.dtype(np.floataa     ):
            _UpperCAmelCase          =   raw_speech.astype(np.floataa     )
        # always return batch
        if not is_batched:
            _UpperCAmelCase          =   [np.asarray([raw_speech]     ).T]

        # Convert audio signals to log mel spectrograms, truncate by time axis
        _UpperCAmelCase          =   [
            self._np_extract_fbank_features(waveform.squeeze()     ).T[: self.spectrogram_length] for waveform in raw_speech
        ]
        if isinstance(audio_features[0]     ,					__UpperCamelCase     ):
            _UpperCAmelCase          =   [np.asarray(__UpperCamelCase     ,					dtype=np.floataa     ) for feature in audio_features]

        # Create audio attention mask
        _UpperCAmelCase          =   max(
            [ceil(feature.shape[0] / self.patch_size[0]     ) * self.freq_len for feature in audio_features]     )  # The maximum number of audio patches in a batch
        if return_attention_mask:
            _UpperCAmelCase          =   [
                (ceil(feature.shape[0] / self.patch_size[0]     ) * self.freq_len) * [1]
                + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]     ) * self.freq_len) * [0]
                for feature in audio_features
            ]
            _UpperCAmelCase          =   np.array(__UpperCamelCase     ).astype(np.floataa     )

        # convert into correct format for padding
        _UpperCAmelCase          =   max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
        _UpperCAmelCase          =   np.ones([len(__UpperCamelCase     ), 1, max_time_len, self.feature_size]     ).astype(np.floataa     )
        _UpperCAmelCase          =   padded_audio_features * self.padding_value
        for i in range(len(__UpperCamelCase     )     ):
            _UpperCAmelCase          =   audio_features[i]
            _UpperCAmelCase          =   feature

        # return as BatchFeature
        if return_attention_mask:
            _UpperCAmelCase          =   {"""audio_values""": padded_audio_features, """audio_mask""": audio_mask}
        else:
            _UpperCAmelCase          =   {"""audio_values""": padded_audio_features}

        _UpperCAmelCase          =   BatchFeature(data=__UpperCamelCase     ,					tensor_type=__UpperCamelCase     )
        return encoded_inputs

"""simple docstring"""



import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()




class 		a_						( unittest.TestCase	):







    @property
    def      _snake_case					(			self			:       Dict     )		->int:






        '''simple docstring'''






        torch.manual_seed(0     )
        _UpperCAmelCase          =   UNetaDModel(
            block_out_channels=(32, 64)     ,					layers_per_block=2     ,					sample_size=32     ,					in_channels=3     ,					out_channels=3     ,					down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")     ,					up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")     ,					)
        return model







    @property
    def      _snake_case					(			self			:       Optional[Any]     )		->str:






        '''simple docstring'''






        torch.manual_seed(0     )
        _UpperCAmelCase          =   VQModel(
            block_out_channels=[32, 64]     ,					in_channels=3     ,					out_channels=3     ,					down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]     ,					up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]     ,					latent_channels=3     ,					)
        return model







    @property
    def      _snake_case					(			self			:       List[Any]     )		->Optional[int]:






        '''simple docstring'''






        torch.manual_seed(0     )
        _UpperCAmelCase          =   CLIPTextConfig(
            bos_token_id=0     ,					eos_token_id=2     ,					hidden_size=32     ,					intermediate_size=37     ,					layer_norm_eps=1e-05     ,					num_attention_heads=4     ,					num_hidden_layers=5     ,					pad_token_id=1     ,					vocab_size=10_00     ,					)
        return CLIPTextModel(__UpperCamelCase     )







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






        '''simple docstring'''






        _UpperCAmelCase          =   self.dummy_uncond_unet
        _UpperCAmelCase          =   DDIMScheduler()
        _UpperCAmelCase          =   self.dummy_vq_model

        _UpperCAmelCase          =   LDMPipeline(unet=__UpperCamelCase     ,					vqvae=__UpperCamelCase     ,					scheduler=__UpperCamelCase     )
        ldm.to(__UpperCamelCase     )
        ldm.set_progress_bar_config(disable=__UpperCamelCase     )

        _UpperCAmelCase          =   torch.manual_seed(0     )
        _UpperCAmelCase          =   ldm(generator=__UpperCamelCase     ,					num_inference_steps=2     ,					output_type="""numpy"""     ).images

        _UpperCAmelCase          =   torch.manual_seed(0     )
        _UpperCAmelCase          =   ldm(generator=__UpperCamelCase     ,					num_inference_steps=2     ,					output_type="""numpy"""     ,					return_dict=__UpperCamelCase     )[0]

        _UpperCAmelCase          =   image[0, -3:, -3:, -1]
        _UpperCAmelCase          =   image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        _UpperCAmelCase          =   np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2]     )
        _UpperCAmelCase          =   1e-2 if torch_device != """mps""" else 3e-2

        assert np.abs(image_slice.flatten() - expected_slice     ).max() < tolerance
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < tolerance







@slow
@require_torch
class 		a_						( unittest.TestCase	):







    def      _snake_case					(			self			:       List[Any]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   LDMPipeline.from_pretrained("""CompVis/ldm-celebahq-256"""     )
        ldm.to(__UpperCamelCase     )
        ldm.set_progress_bar_config(disable=__UpperCamelCase     )

        _UpperCAmelCase          =   torch.manual_seed(0     )
        _UpperCAmelCase          =   ldm(generator=__UpperCamelCase     ,					num_inference_steps=5     ,					output_type="""numpy"""     ).images

        _UpperCAmelCase          =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 2_56, 2_56, 3)
        _UpperCAmelCase          =   np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7]     )
        _UpperCAmelCase          =   1e-2 if torch_device != """mps""" else 3e-2

        assert np.abs(image_slice.flatten() - expected_slice     ).max() < tolerance