





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


__lowerCamelCase :  Dict										=  logging.get_logger(__name__)



class       A__     ( __snake_case    ):
      _UpperCAmelCase			:Tuple							=     ['audio_values', 'audio_mask']





      def __init__(				self ,							A_=2048 ,							A_=1 ,							A_=[16, 16] ,							A_=128 ,							A_=4_4100 ,							A_=86 ,							A_=2048 ,							A_=0.0 ,							**A_ ,							):
       '''simple docstring'''




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

       UpperCamelCase			:      Optional[int] 			=     spectrogram_length
       UpperCamelCase			:      Dict 			=     num_channels
       UpperCamelCase			:      Optional[Any] 			=     patch_size
       UpperCamelCase			:      str 			=     feature_size // self.patch_size[1]
       UpperCamelCase			:      List[str] 			=     n_fft
       UpperCamelCase			:      int 			=     sampling_rate // hop_length_to_sampling_rate
       UpperCamelCase			:      Optional[int] 			=     sampling_rate
       UpperCamelCase			:      int 			=     padding_value
       UpperCamelCase			:      str 			=     mel_filter_bank(
           num_frequency_bins=1 + n_fft // 2 ,							num_mel_filters=A_ ,							min_frequency=0.0 ,							max_frequency=2_2050.0 ,							sampling_rate=A_ ,							norm="slaney" ,							mel_scale="slaney" ,							).T





      def  __UpperCamelCase(				self ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     spectrogram(
           A_ ,							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=80.0 ,							)
       UpperCamelCase			:      List[Any] 			=     log_spec[:, :-1]
       UpperCamelCase			:      Optional[int] 			=     log_spec - 20.0
       UpperCamelCase			:      str 			=     np.clip(log_spec / 40.0 ,							-2.0 ,							0.0     ) + 1.0
       return log_spec





      def __call__(				self ,							A_ ,							A_ = None ,							A_ = True ,							A_ = None ,							A_ = False ,							A_ = False ,							**A_ ,							):
       '''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			:      Optional[int] 			=     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			:      Union[str, Any] 			=     is_batched_numpy or (
           isinstance(A_ ,							(list, tuple)     ) and (isinstance(raw_speech[0] ,							(np.ndarray, tuple, list)     ))
       )
       if is_batched:
        UpperCamelCase			:      int 			=     [np.asarray([speech] ,							dtype=np.floataa     ).T for speech in raw_speech]
       elif not is_batched and not isinstance(A_ ,							np.ndarray     ):
        UpperCamelCase			:      str 			=     np.asarray(A_ ,							dtype=np.floataa     )
       elif isinstance(A_ ,							np.ndarray     ) and raw_speech.dtype is np.dtype(np.floataa     ):
        UpperCamelCase			:      List[Any] 			=     raw_speech.astype(np.floataa     )
       # always return batch
       if not is_batched:
        UpperCamelCase			:      Tuple 			=     [np.asarray([raw_speech]     ).T]

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

       # Create audio attention mask
       UpperCamelCase			:      List[str] 			=     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			:      str 			=     [
            (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			:      Tuple 			=     np.array(A_     ).astype(np.floataa     )

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

       # return as BatchFeature
       if return_attention_mask:
        UpperCamelCase			:      Optional[Any] 			=     {"audio_values": padded_audio_features, "audio_mask": audio_mask}
       else:
        UpperCamelCase			:      int 			=     {"audio_values": padded_audio_features}

       UpperCamelCase			:      Any 			=     BatchFeature(data=A_ ,							tensor_type=A_     )
       return encoded_inputs







import logging
import os
import threading
import time


try:
    import warnings
except ImportError:
    __lowerCamelCase :  str										=  None

try:
    import msvcrt
except ImportError:
    __lowerCamelCase :  str										=  None

try:
    import fcntl
except ImportError:
    __lowerCamelCase :  List[Any]										=  None


# Backward compatibility
# ------------------------------------------------
try:
    TimeoutError
except NameError:
    __lowerCamelCase :  Union[str, Any]										=  OSError


# Data
# ------------------------------------------------
__lowerCamelCase :  str										=  [
    """Timeout""",
    """BaseFileLock""",
    """WindowsFileLock""",
    """UnixFileLock""",
    """SoftFileLock""",
    """FileLock""",
]

__lowerCamelCase :  Union[str, Any]										=  """3.0.12"""


__lowerCamelCase :  Any										=  None



def 	A_       (  )		->				List[Any]:
 global _logger
 UpperCamelCase			:      Any 			=     _logger or logging.getLogger(__name__  )
 return _logger



class       A__     ( __snake_case    ):





      def __init__(				self ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     lock_file
       return None





      def __str__(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     F"""The file lock '{self.lock_file}' could not be acquired."""
       return temp



class       A__     :





      def __init__(				self ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     lock
       return None





      def __enter__(				self     ):
       '''simple docstring'''




       return self.lock





      def __exit__(				self ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       self.lock.release()
       return None



class       A__     :





      def __init__(				self ,							A_ ,							A_=-1 ,							A_=None     ):
       '''simple docstring'''




       UpperCamelCase			:      List[Any] 			=     max_filename_length if max_filename_length is not None else 255
       # Hash the filename if it's too long
       UpperCamelCase			:      Dict 			=     self.hash_filename_if_too_long(A_ ,							A_     )
       # The path to the lock file.
       UpperCamelCase			:      List[Any] 			=     lock_file

       # The file descriptor for the *_lock_file* as it is returned by the
       # os.open() function.
       # This file lock is only NOT None, if the object currently holds the
       # lock.
       UpperCamelCase			:      Tuple 			=     None

       # The default timeout value.
       UpperCamelCase			:      Optional[Any] 			=     timeout

       # We use this lock primarily for the lock counter.
       UpperCamelCase			:      Union[str, Any] 			=     threading.Lock()

       # The lock counter is used for implementing the nested locking
       # mechanism. Whenever the lock is acquired, the counter is increased and
       # the lock is only released, when this value is 0 again.
       UpperCamelCase			:      Dict 			=     0
       return None





      @property
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return self._lock_file





      @property
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return self._timeout





      @timeout.setter
      def  __UpperCamelCase(				self ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     float(A_     )
       return None





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       raise NotImplementedError()





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       raise NotImplementedError()





      @property
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return self._lock_file_fd is not None





      def  __UpperCamelCase(				self ,							A_=None ,							A_=0.05     ):
       '''simple docstring'''




       if timeout is None:
        UpperCamelCase			:      Optional[Any] 			=     self.timeout

       # Increment the number right at the beginning.
       # We can still undo it, if something fails.
       with self._thread_lock:
        self._lock_counter += 1

       UpperCamelCase			:      Dict 			=     id(self     )
       UpperCamelCase			:      List[str] 			=     self._lock_file
       UpperCamelCase			:      int 			=     time.time()
       try:
        while True:
         with self._thread_lock:
          if not self.is_locked:
           logger().debug(F"""Attempting to acquire lock {lock_id} on {lock_filename}"""     )
           self._acquire()

         if self.is_locked:
          logger().debug(F"""Lock {lock_id} acquired on {lock_filename}"""     )
          break
         elif timeout >= 0 and time.time() - start_time > timeout:
          logger().debug(F"""Timeout on acquiring lock {lock_id} on {lock_filename}"""     )
          raise Timeout(self._lock_file     )
         else:
          logger().debug(
              F"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..."""     )
          time.sleep(A_     )
       except:  # noqa
        # Something did go wrong, so decrement the counter.
        with self._thread_lock:
         UpperCamelCase			:      List[Any] 			=     max(0 ,							self._lock_counter - 1     )

        raise
       return _Acquire_ReturnProxy(lock=self     )





      def  __UpperCamelCase(				self ,							A_=False     ):
       '''simple docstring'''




       with self._thread_lock:
        if self.is_locked:
         self._lock_counter -= 1

         if self._lock_counter == 0 or force:
          UpperCamelCase			:      List[Any] 			=     id(self     )
          UpperCamelCase			:      Dict 			=     self._lock_file

          logger().debug(F"""Attempting to release lock {lock_id} on {lock_filename}"""     )
          self._release()
          UpperCamelCase			:      Dict 			=     0
          logger().debug(F"""Lock {lock_id} released on {lock_filename}"""     )

       return None





      def __enter__(				self     ):
       '''simple docstring'''




       self.acquire()
       return self





      def __exit__(				self ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       self.release()
       return None





      def __del__(				self     ):
       '''simple docstring'''




       self.release(force=A_     )
       return None





      def  __UpperCamelCase(				self ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     os.path.basename(A_     )
       if len(A_     ) > max_length and max_length > 0:
        UpperCamelCase			:      Optional[int] 			=     os.path.dirname(A_     )
        UpperCamelCase			:      int 			=     str(hash(A_     )     )
        UpperCamelCase			:      Any 			=     filename[: max_length - len(A_     ) - 8] + "..." + hashed_filename + ".lock"
        return os.path.join(A_ ,							A_     )
       else:
        return path



class       A__     ( __snake_case    ):





      def __init__(				self ,							A_ ,							A_=-1 ,							A_=None     ):
       '''simple docstring'''




       from .file_utils import relative_to_absolute_path

       super().__init__(A_ ,							timeout=A_ ,							max_filename_length=A_     )
       UpperCamelCase			:      List[Any] 			=     "\\\\?\\" + relative_to_absolute_path(self.lock_file     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     os.O_RDWR | os.O_CREAT | os.O_TRUNC

       try:
        UpperCamelCase			:      str 			=     os.open(self._lock_file ,							A_     )
       except OSError:
        pass
       else:
        try:
         msvcrt.locking(A_ ,							msvcrt.LK_NBLCK ,							1     )
        except OSError:
         os.close(A_     )
        else:
         UpperCamelCase			:      Optional[Any] 			=     fd
       return None





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[Any] 			=     self._lock_file_fd
       UpperCamelCase			:      str 			=     None
       msvcrt.locking(A_ ,							msvcrt.LK_UNLCK ,							1     )
       os.close(A_     )

       try:
        os.remove(self._lock_file     )
       # Probably another instance of the application
       # that acquired the file lock.
       except OSError:
        pass
       return None



class       A__     ( __snake_case    ):





      def __init__(				self ,							A_ ,							A_=-1 ,							A_=None     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     os.statvfs(os.path.dirname(A_     )     ).f_namemax
       super().__init__(A_ ,							timeout=A_ ,							max_filename_length=A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     os.O_RDWR | os.O_CREAT | os.O_TRUNC
       UpperCamelCase			:      int 			=     os.open(self._lock_file ,							A_     )

       try:
        fcntl.flock(A_ ,							fcntl.LOCK_EX | fcntl.LOCK_NB     )
       except OSError:
        os.close(A_     )
       else:
        UpperCamelCase			:      List[str] 			=     fd
       return None





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     self._lock_file_fd
       UpperCamelCase			:      List[Any] 			=     None
       fcntl.flock(A_ ,							fcntl.LOCK_UN     )
       os.close(A_     )
       return None



class       A__     ( __snake_case    ):





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
       try:
        UpperCamelCase			:      Optional[int] 			=     os.open(self._lock_file ,							A_     )
       except OSError:
        pass
       else:
        UpperCamelCase			:      Tuple 			=     fd
       return None





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       os.close(self._lock_file_fd     )
       UpperCamelCase			:      str 			=     None

       try:
        os.remove(self._lock_file     )
       # The file is already deleted and that's what we want.
       except OSError:
        pass
       return None


__lowerCamelCase :  Dict										=  None

if msvcrt:
    __lowerCamelCase :  Any										=  WindowsFileLock
elif fcntl:
    __lowerCamelCase :  Any										=  UnixFileLock
else:
    __lowerCamelCase :  int										=  SoftFileLock

    if warnings is not None:
        warnings.warn("""only soft file lock is available""")
