






'''simple docstring'''
from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__lowerCAmelCase							=logging.get_logger(__name__)


class    _snake_case   (				snake_case					):

					"""simple docstring"""





					_UpperCamelCase		 =      ["input_values", "attention_mask"]




					def __init__(     self   , UpperCAmelCase__=1   , UpperCAmelCase__=1_6000   , UpperCAmelCase__=128   , UpperCAmelCase__=1024   , UpperCAmelCase__=0.0   , UpperCAmelCase__=True   , UpperCAmelCase__=-4.2_6_7_7_3_9_3   , UpperCAmelCase__=4.5_6_8_9_9_7_4   , UpperCAmelCase__=False   , **UpperCAmelCase__   , )      ->	List[Any]:
										super().__init__(feature_size=UpperCAmelCase__   , sampling_rate=UpperCAmelCase__   , padding_value=UpperCAmelCase__   , **UpperCAmelCase__     )
										a_									=   num_mel_bins
										a_									=   max_length
										a_									=   do_normalize
										a_									=   mean
										a_									=   std
										a_									=   return_attention_mask




					def  __SCREAMING_SNAKE_CASE (     self   , UpperCAmelCase__   , UpperCAmelCase__   , )      ->	np.ndarray:
										a_									=   torch.from_numpy(UpperCAmelCase__     ).unsqueeze(0     )
										a_									=   ta_kaldi.fbank(
										    UpperCAmelCase__   , htk_compat=UpperCAmelCase__   , sample_frequency=self.sampling_rate   , use_energy=UpperCAmelCase__   , window_type='hanning'   , num_mel_bins=self.num_mel_bins   , dither=0.0   , frame_shift=10   , )

										a_									=   fbank.shape[0]
										a_									=   max_length - n_frames

										# pad or truncate, depending on difference
										if difference > 0:
															a_									=   torch.nn.ZeroPadad((0, 0, 0, difference)     )
															a_									=   pad_module(UpperCAmelCase__     )
										elif difference < 0:
															a_									=   fbank[0:max_length, :]

										a_									=   fbank.numpy()

										return fbank




					def  __SCREAMING_SNAKE_CASE (     self   , UpperCAmelCase__     )      ->	np.ndarray:
										return (input_values - (self.mean)) / (self.std * 2)




					def __call__(     self   , UpperCAmelCase__   , UpperCAmelCase__ = None   , UpperCAmelCase__ = None   , **UpperCAmelCase__   , )      ->	BatchFeature:

										if sampling_rate is not None:
															if sampling_rate != self.sampling_rate:
																				raise ValueError(
																				    F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
																				    F''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
																				    F''' {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.'     )

										a_									=   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}'''     )
										a_									=   is_batched_numpy or (
										    isinstance(UpperCAmelCase__   , (list, tuple)     ) and (isinstance(raw_speech[0]   , (np.ndarray, tuple, list)     ))
										)

										if is_batched:
															a_									=   [np.asarray(UpperCAmelCase__   , dtype=np.floataa     ) for speech in raw_speech]
										elif not is_batched and not isinstance(UpperCAmelCase__   , np.ndarray     ):
															a_									=   np.asarray(UpperCAmelCase__   , dtype=np.floataa     )
										elif isinstance(UpperCAmelCase__   , np.ndarray     ) and raw_speech.dtype is np.dtype(np.floataa     ):
															a_									=   raw_speech.astype(np.floataa     )

										# always return batch
										if not is_batched:
															a_									=   [raw_speech]

										# extract fbank features and pad/truncate to max_length
										a_									=   [self._extract_fbank_features(UpperCAmelCase__   , max_length=self.max_length     ) for waveform in raw_speech]

										# convert into BatchFeature
										a_									=   BatchFeature({'input_values': features}     )

										# make sure list is in array format
										a_									=   padded_inputs.get('input_values'     )
										if isinstance(input_values[0]   , UpperCAmelCase__     ):
															a_									=   [np.asarray(UpperCAmelCase__   , dtype=np.floataa     ) for feature in input_values]

										# normalization
										if self.do_normalize:
															a_									=   [self.normalize(UpperCAmelCase__     ) for feature in input_values]

										if return_tensors is not None:
															a_									=   padded_inputs.convert_to_tensors(UpperCAmelCase__     )

										return padded_inputs









'''simple docstring'''
from typing import List, Optional, Tuple, Union

import torch

from ...models import UNetaDModel
from ...schedulers import PNDMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


class    _snake_case   (				snake_case					):

					"""simple docstring"""





					_UpperCamelCase		 =      42
					_UpperCamelCase		 =      42




					def __init__(     self   , UpperCAmelCase__   , UpperCAmelCase__     )      ->	int:
										super().__init__()

										a_									=   PNDMScheduler.from_config(scheduler.config     )

										self.register_modules(unet=UpperCAmelCase__   , scheduler=UpperCAmelCase__     )




					@torch.no_grad()
					def __call__(     self   , UpperCAmelCase__ = 1   , UpperCAmelCase__ = 50   , UpperCAmelCase__ = None   , UpperCAmelCase__ = "pil"   , UpperCAmelCase__ = True   , **UpperCAmelCase__   , )      ->	Union[ImagePipelineOutput, Tuple]:
										a_									=   randn_tensor(
										    (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size)   , generator=UpperCAmelCase__   , device=self.device   , )

										self.scheduler.set_timesteps(UpperCAmelCase__     )
										for t in self.progress_bar(self.scheduler.timesteps     ):
															a_									=   self.unet(UpperCAmelCase__   , UpperCAmelCase__     ).sample

															a_									=   self.scheduler.step(UpperCAmelCase__   , UpperCAmelCase__   , UpperCAmelCase__     ).prev_sample

										a_									=   (image / 2 + 0.5).clamp(0   , 1     )
										a_									=   image.cpu().permute(0   , 2   , 3   , 1     ).numpy()
										if output_type == "pil":
															a_									=   self.numpy_to_pil(UpperCAmelCase__     )

										if not return_dict:
															return (image,)

										return ImagePipelineOutput(images=UpperCAmelCase__     )

