


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 PaddingStrategy, TensorType, logging


a__       =     logging.get_logger(__name__)


class    _lowerCAmelCase			(		lowercase_      ):



				"""simple docstring"""



				_lowercase				:   str      =  ['''input_features''', '''attention_mask''']



				def __init__(      self    :    int			,		UpperCamelCase__    :    Dict=8_0			,		UpperCamelCase__    :    int=1_6_0_0_0			,		UpperCamelCase__    :    Optional[Any]=8_0			,		UpperCamelCase__    :    int=0.0			,		UpperCamelCase__    :    Any=True			,		UpperCamelCase__    :    Tuple=True			,		UpperCamelCase__    :    List[str]=True			,		**UpperCamelCase__    :    List[Any]			,		):






											'''simple docstring'''







											super().__init__(feature_size=UpperCamelCase__			,		sampling_rate=UpperCamelCase__			,		padding_value=UpperCamelCase__			,		**UpperCamelCase__)
											snake_case__	  =       num_mel_bins
											snake_case__	  =       do_ceptral_normalize
											snake_case__	  =       normalize_means
											snake_case__	  =       normalize_vars
											snake_case__	  =       True



				def 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    Dict			,		):






											'''simple docstring'''







											snake_case__	  =       waveform * (2**1_5)  # Kaldi compliance: 16-bit signed integers
											snake_case__	  =       torch.from_numpy(UpperCamelCase__).unsqueeze(0)
											snake_case__	  =       ta_kaldi.fbank(UpperCamelCase__			,		num_mel_bins=self.num_mel_bins			,		sample_frequency=self.sampling_rate)
											return features.numpy()



				@staticmethod
				def 					__magic_name__							(      UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    str = True			,		UpperCamelCase__    :    Dict = True			,		UpperCamelCase__    :    str = 0.0			,		):






											'''simple docstring'''







											if normalize_means:
																		snake_case__	  =       x[:input_length].mean(axis=0)
																		snake_case__	  =       np.subtract(UpperCamelCase__			,		UpperCamelCase__)
											if normalize_vars:
																		snake_case__	  =       x[:input_length].std(axis=0)
																		snake_case__	  =       np.divide(UpperCamelCase__			,		UpperCamelCase__)

											if input_length < x.shape[0]:
																		snake_case__	  =       padding_value

											# make sure array is in float32
											snake_case__	  =       x.astype(np.floataa)

											return x



				def 					__magic_name__							(      self    :    List[str]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    Tuple = None):






											'''simple docstring'''







											snake_case__	  =       attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
											return [
											    self.utterance_cmvn(UpperCamelCase__			,		UpperCamelCase__			,		self.normalize_means			,		self.normalize_vars			,		self.padding_value)
											    for x, n in zip(UpperCamelCase__			,		UpperCamelCase__)
											]



				def __call__(      self    :    int			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Dict = False			,		UpperCamelCase__    :    Dict = None			,		UpperCamelCase__    :    Any = False			,		UpperCamelCase__    :    int = None			,		UpperCamelCase__    :    int = None			,		UpperCamelCase__    :    List[Any] = None			,		UpperCamelCase__    :    Dict = None			,		**UpperCamelCase__    :    Union[str, Any]			,		):






											'''simple docstring'''







											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.""")

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

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

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

											# extract fbank features
											snake_case__	  =       [self._extract_fbank_features(UpperCamelCase__) for waveform in raw_speech]

											# convert into correct format for padding
											snake_case__	  =       BatchFeature({"""input_features""": features})

											snake_case__	  =       self.pad(
											    UpperCamelCase__			,		padding=UpperCamelCase__			,		max_length=UpperCamelCase__			,		truncation=UpperCamelCase__			,		pad_to_multiple_of=UpperCamelCase__			,		return_attention_mask=UpperCamelCase__			,		**UpperCamelCase__			,		)

											# make sure list is in array format
											snake_case__	  =       padded_inputs.get("""input_features""")
											if isinstance(input_features[0]			,		UpperCamelCase__):
																		snake_case__	  =       [np.asarray(UpperCamelCase__			,		dtype=np.floataa) for feature in input_features]

											snake_case__	  =       padded_inputs.get("""attention_mask""")
											if attention_mask is not None:
																		snake_case__	  =       [np.asarray(UpperCamelCase__			,		dtype=np.intaa) for array in attention_mask]

											# Utterance-level cepstral mean and variance normalization
											if self.do_ceptral_normalize:
																		snake_case__	  =       (
																		    np.array(UpperCamelCase__			,		dtype=np.intaa)
																		    if self._get_padding_strategies(UpperCamelCase__			,		max_length=UpperCamelCase__) is not PaddingStrategy.DO_NOT_PAD
																		    else None
																		)
																		snake_case__	  =       self.normalize(
																		    padded_inputs["""input_features"""]			,		attention_mask=UpperCamelCase__)

											if return_tensors is not None:
																		snake_case__	  =       padded_inputs.convert_to_tensors(UpperCamelCase__)

											return padded_inputs








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


a__       =     {
    """configuration_clip""": [
        """CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """CLIPConfig""",
        """CLIPOnnxConfig""",
        """CLIPTextConfig""",
        """CLIPVisionConfig""",
    ],
    """processing_clip""": ["""CLIPProcessor"""],
    """tokenization_clip""": ["""CLIPTokenizer"""],
}

try:
	if not is_tokenizers_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     ["""CLIPTokenizerFast"""]

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     ["""CLIPFeatureExtractor"""]
	a__       =     ["""CLIPImageProcessor"""]

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """CLIPModel""",
	    """CLIPPreTrainedModel""",
	    """CLIPTextModel""",
	    """CLIPTextModelWithProjection""",
	    """CLIPVisionModel""",
	    """CLIPVisionModelWithProjection""",
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """TFCLIPModel""",
	    """TFCLIPPreTrainedModel""",
	    """TFCLIPTextModel""",
	    """TFCLIPVisionModel""",
	]

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """FlaxCLIPModel""",
	    """FlaxCLIPPreTrainedModel""",
	    """FlaxCLIPTextModel""",
	    """FlaxCLIPTextPreTrainedModel""",
	    """FlaxCLIPVisionModel""",
	    """FlaxCLIPVisionPreTrainedModel""",
	]


if TYPE_CHECKING:
	from .configuration_clip import (
	    CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    CLIPConfig,
	    CLIPOnnxConfig,
	    CLIPTextConfig,
	    CLIPVisionConfig,
	)
	from .processing_clip import CLIPProcessor
	from .tokenization_clip import CLIPTokenizer

	try:
		if not is_tokenizers_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tokenization_clip_fast import CLIPTokenizerFast

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .feature_extraction_clip import CLIPFeatureExtractor
		from .image_processing_clip import CLIPImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_clip import (
		    CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    CLIPModel,
		    CLIPPreTrainedModel,
		    CLIPTextModel,
		    CLIPTextModelWithProjection,
		    CLIPVisionModel,
		    CLIPVisionModelWithProjection,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_clip import (
		    TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFCLIPModel,
		    TFCLIPPreTrainedModel,
		    TFCLIPTextModel,
		    TFCLIPVisionModel,
		)

	try:
		if not is_flax_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_flax_clip import (
		    FlaxCLIPModel,
		    FlaxCLIPPreTrainedModel,
		    FlaxCLIPTextModel,
		    FlaxCLIPTextPreTrainedModel,
		    FlaxCLIPVisionModel,
		    FlaxCLIPVisionPreTrainedModel,
		)


else:
	import sys

	a__       =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
