



'''simple docstring'''






from typing import List, Optional, Union

import numpy as np

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


A_				:					List[Any]							=      logging.get_logger(__name__)



class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    ["""input_values""", """attention_mask"""]







 def __init__(				self    ,a_=1    ,a_=16_000    ,a_=0.0    ,a_=False    ,a_=True    ,**a_    ,)						->  Dict:
        super().__init__(feature_size=a_    ,sampling_rate=a_    ,padding_value=a_    ,**a_				)
        _UpperCAmelCase    :		str     	=					return_attention_mask
        _UpperCAmelCase    :		Union[str, Any]     	=					do_normalize







 @staticmethod
 def _snake_case					(				a_    ,a_    ,a_ = 0.0				)						->  List[np.ndarray]:
        if attention_mask is not None:
               _UpperCAmelCase    :		Dict     	=					np.array(a_    ,np.intaa				)
               _UpperCAmelCase    :		Optional[int]     	=					[]

               for vector, length in zip(a_    ,attention_mask.sum(-1				)				):
                      _UpperCAmelCase    :		Dict     	=					(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7				)
                      if length < normed_slice.shape[0]:
                             _UpperCAmelCase    :		Union[str, Any]     	=					padding_value

                      normed_input_values.append(a_				)
        else:
               _UpperCAmelCase    :		int     	=					[(x - x.mean()) / np.sqrt(x.var() + 1E-7				) for x in input_values]

        return normed_input_values







 def __call__(				self    ,a_    ,a_ = False    ,a_ = None    ,a_ = False    ,a_ = None    ,a_ = None    ,a_ = None    ,a_ = None    ,**a_    ,)						->  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."""				)

        _UpperCAmelCase    :		Union[str, Any]     	=					isinstance(a_    ,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    :		Optional[int]     	=					is_batched_numpy or (
            isinstance(a_    ,(list, tuple)				) and (isinstance(raw_speech[0]    ,(np.ndarray, tuple, list)				))
        )

        # always return batch
        if not is_batched:
               _UpperCAmelCase    :		List[Any]     	=					[raw_speech]

        # convert into correct format for padding
        _UpperCAmelCase    :		Union[str, Any]     	=					BatchFeature({"""input_values""": raw_speech}				)

        _UpperCAmelCase    :		str     	=					self.pad(
            a_    ,padding=a_    ,max_length=a_    ,truncation=a_    ,pad_to_multiple_of=a_    ,return_attention_mask=a_    ,)

        # convert input values to correct format
        _UpperCAmelCase    :		Any     	=					padded_inputs["""input_values"""]
        if not isinstance(input_values[0]    ,np.ndarray				):
               _UpperCAmelCase    :		str     	=					[np.asarray(a_    ,dtype=np.floataa				) for array in input_values]
        elif (
            not isinstance(a_    ,np.ndarray				)
            and isinstance(input_values[0]    ,np.ndarray				)
            and input_values[0].dtype is np.dtype(np.floataa				)
        ):
               _UpperCAmelCase    :		int     	=					[array.astype(np.floataa				) for array in input_values]
        elif isinstance(a_    ,np.ndarray				) and input_values.dtype is np.dtype(np.floataa				):
               _UpperCAmelCase    :		List[str]     	=					input_values.astype(np.floataa				)

        # convert attention_mask to correct format
        _UpperCAmelCase    :		Any     	=					padded_inputs.get("""attention_mask"""				)
        if attention_mask is not None:
               _UpperCAmelCase    :		Dict     	=					[np.asarray(a_    ,dtype=np.intaa				) for array in attention_mask]

        # zero-mean and unit-variance normalization
        if self.do_normalize:
               _UpperCAmelCase    :		List[Any]     	=					(
                   attention_mask
                   if self._get_padding_strategies(a_    ,max_length=a_				) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               _UpperCAmelCase    :		Dict     	=					self.zero_mean_unit_var_norm(
                   padded_inputs["""input_values"""]    ,attention_mask=a_    ,padding_value=self.padding_value				)

        if return_tensors is not None:
               _UpperCAmelCase    :		Union[str, Any]     	=					padded_inputs.convert_to_tensors(a_				)

        return padded_inputs





"""simple docstring"""






import copy

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


UpperCamelCase_						   =   logging.get_logger(__name__)





class 							snake_case       (     SCREAMING_SNAKE_CASE_		):
   a_					:		Tuple     					=     """hybrid-clip"""
   a_					:		Optional[Any]     					=     True







   def __init__( self       ,							__UpperCAmelCase=5_12       ,							**__UpperCAmelCase)   ->Dict:
      super().__init__(**__UpperCAmelCase)

      if "text_config" not in kwargs:
         raise ValueError("`text_config` can not be `None`.")

      if "vision_config" not in kwargs:
         raise ValueError("`vision_config` can not be `None`.")

      a_						   =     kwargs.pop("text_config")
      a_						   =     kwargs.pop("vision_config")

      a_						   =     text_config.pop("model_type")
      a_						   =     vision_config.pop("model_type")

      from transformers import AutoConfig

      a_						   =     AutoConfig.for_model(__UpperCAmelCase       ,							**__UpperCAmelCase)

      if vision_model_type == "clip":
         a_						   =     AutoConfig.for_model(__UpperCAmelCase       ,							**__UpperCAmelCase).vision_config
      elif vision_model_type == "clip_vision_model":
         from transformers import CLIPVisionConfig

         a_						   =     CLIPVisionConfig(**__UpperCAmelCase)
      else:
         a_						   =     AutoConfig.for_model(__UpperCAmelCase       ,							**__UpperCAmelCase)

      a_						   =     projection_dim
      a_						   =     1.0







   @classmethod
   def    UpperCAmelCase__	( cls       ,							__UpperCAmelCase       ,							__UpperCAmelCase       ,							**__UpperCAmelCase)   ->Optional[int]:
      return cls(text_config=text_config.to_dict()       ,							vision_config=vision_config.to_dict()       ,							**__UpperCAmelCase)







   def    UpperCAmelCase__	( self)   ->str:
      a_						   =     copy.deepcopy(self.__dict__)
      a_						   =     self.text_config.to_dict()
      a_						   =     self.vision_config.to_dict()
      a_						   =     self.__class__.model_type
      return output