
'''simple docstring'''
import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
     from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
     from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
     from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


A__   :		Optional[Any]   =DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A__   :		Tuple   ='main'
# Default branch name
A__   :		Union[str, Any]   ='f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
A__   :		str   ='aaaaaaa'
# This commit does not exist, so we should 404.

A__   :		Tuple   ='d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
A__   :		Tuple   ='4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'







@contextlib.contextmanager
def        A_     (						)				->       Dict:





  """simple docstring"""

  print("""Welcome!""" )
  yield
  print("""Bye!""" )







@contextlib.contextmanager
def        A_     (						)				->       List[Any]:





  """simple docstring"""

  print("""Bonjour!""" )
  yield
  print("""Au revoir!""" )







class  __A				( unittest.TestCase			):
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   assert transformers.__spec__ is not None
   assert importlib.util.find_spec("""transformers"""       ) is not None







class  __A				( unittest.TestCase			):
 @unittest.mock.patch("""sys.stdout"""				,   new_callable=io.StringIO       )
 def 		lowercase_(   self			:    int				,   lowerCamelCase			:    Any       ):



   """simple docstring"""





   with ContextManagers([]       ):
     print("""Transformers are awesome!"""       )
   # The print statement adds a new line at the end of the output
   self.assertEqual(mock_stdout.getvalue()				,   """Transformers are awesome!\n"""       )
 @unittest.mock.patch("""sys.stdout"""				,   new_callable=io.StringIO       )
 def 		lowercase_(   self			:    Optional[Any]				,   lowerCamelCase			:    Optional[Any]       ):



   """simple docstring"""





   with ContextManagers([context_en()]       ):
     print("""Transformers are awesome!"""       )
   # The output should be wrapped with an English welcome and goodbye
   self.assertEqual(mock_stdout.getvalue()				,   """Welcome!\nTransformers are awesome!\nBye!\n"""       )
 @unittest.mock.patch("""sys.stdout"""				,   new_callable=io.StringIO       )
 def 		lowercase_(   self			:    Dict				,   lowerCamelCase			:    Optional[Any]       ):



   """simple docstring"""





   with ContextManagers([context_fr(), context_en()]       ):
     print("""Transformers are awesome!"""       )
   # The output should be wrapped with an English and French welcome and goodbye
   self.assertEqual(mock_stdout.getvalue()				,   """Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"""       )
 @require_torch
 def 		lowercase_(   self			:    int       ):



   """simple docstring"""





   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""labels"""]       )
   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""labels""", """next_sentence_label"""]       )
   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""start_positions""", """end_positions"""]       )







   class  __A				( _SCREAMING_SNAKE_CASE			):
    pass

   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""labels"""]       )
 @require_tf
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""labels"""]       )
   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""labels""", """next_sentence_label"""]       )
   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""start_positions""", """end_positions"""]       )







   class  __A				( _SCREAMING_SNAKE_CASE			):
    pass

   self.assertEqual(find_labels(lowerCamelCase       )				,   ["""labels"""]       )






 @require_flax
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   self.assertEqual(find_labels(lowerCamelCase       )				,   []       )
   self.assertEqual(find_labels(lowerCamelCase       )				,   []       )
   self.assertEqual(find_labels(lowerCamelCase       )				,   []       )







   class  __A				( _SCREAMING_SNAKE_CASE			):
    pass

   self.assertEqual(find_labels(lowerCamelCase       )				,   []       )





'''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__   :		Dict 		=logging.get_logger(__name__)







class  __A				( _SCREAMING_SNAKE_CASE			):
 lowerCamelCase				       =['''input_values''', '''padding_mask''']
 def __init__(   self			:    Optional[int]				,   lowerCamelCase			:    int = 1				,   lowerCamelCase			:    int = 2_40_00				,   lowerCamelCase			:    float = 0.0				,   lowerCamelCase			:    float = None				,   lowerCamelCase			:    float = None				,   **lowerCamelCase			:    Dict				,   ):



   """simple docstring"""





   super().__init__(feature_size=lowerCamelCase				,   sampling_rate=lowerCamelCase				,   padding_value=lowerCamelCase				,   **lowerCamelCase       )
   __A		:     str												=		chunk_length_s
   __A		:     str												=		overlap
 @property
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   if self.chunk_length_s is None:
     return None
   else:
     return int(self.chunk_length_s * self.sampling_rate       )
 @property
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   if self.chunk_length_s is None or self.overlap is None:
     return None
   else:
     return max(1				,   int((1.0 - self.overlap) * self.chunk_length       )       )






 def __call__(   self			:    List[str]				,   lowerCamelCase			:    Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,   lowerCamelCase			:    Optional[Union[bool, str, PaddingStrategy]] = None				,   lowerCamelCase			:    Optional[bool] = False				,   lowerCamelCase			:    Optional[int] = None				,   lowerCamelCase			:    Optional[Union[str, TensorType]] = None				,   lowerCamelCase			:    Optional[int] = None				,   ):



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

   if padding and truncation:
     raise ValueError("""Both padding and truncation were set. Make sure you only set one."""       )
   elif padding is None:
     # by default let's pad the inputs
     __A		:     List[Any]												=		True

   __A		:     List[str]												=		bool(
       isinstance(lowerCamelCase				,   (list, tuple)       ) and (isinstance(raw_audio[0]				,   (np.ndarray, tuple, list)       ))       )

   if is_batched:
     __A		:     Optional[Any]												=		[np.asarray(lowerCamelCase				,   dtype=np.floataa       ).T for audio in raw_audio]
   elif not is_batched and not isinstance(lowerCamelCase				,   np.ndarray       ):
     __A		:     Union[str, Any]												=		np.asarray(lowerCamelCase				,   dtype=np.floataa       )
   elif isinstance(lowerCamelCase				,   np.ndarray       ) and raw_audio.dtype is np.dtype(np.floataa       ):
     __A		:     Optional[Any]												=		raw_audio.astype(np.floataa       )

   # always return batch
   if not is_batched:
     __A		:     Tuple												=		[np.asarray(lowerCamelCase       ).T]

   # verify inputs are valid
   for idx, example in enumerate(lowerCamelCase       ):
     if example.ndim > 2:
       raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}"       )
     if self.feature_size == 1 and example.ndim != 1:
       raise ValueError(f"Expected mono audio but example has {example.shape[-1]} channels"       )
     if self.feature_size == 2 and example.shape[-1] != 2:
       raise ValueError(f"Expected stereo audio but example has {example.shape[-1]} channels"       )

   __A		:     Optional[Any]												=		None
   __A		:     Dict												=		BatchFeature({"""input_values""": raw_audio}       )
   if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
     if truncation:
       __A		:     Optional[Any]												=		min(array.shape[0] for array in raw_audio       )
       __A		:     Dict												=		int(np.floor(max_length / self.chunk_stride       )       )
       __A		:     Union[str, Any]												=		(nb_step - 1) * self.chunk_stride + self.chunk_length
     elif padding:
       __A		:     int												=		max(array.shape[0] for array in raw_audio       )
       __A		:     Optional[Any]												=		int(np.ceil(max_length / self.chunk_stride       )       )
       __A		:     Any												=		(nb_step - 1) * self.chunk_stride + self.chunk_length
       __A		:     Optional[int]												=		"""max_length"""
     else:
       __A		:     Optional[Any]												=		input_values

        # normal padding on batch
   if padded_inputs is None:
     __A		:     Tuple												=		self.pad(
         lowerCamelCase				,   max_length=lowerCamelCase				,   truncation=lowerCamelCase				,   padding=lowerCamelCase				,   return_attention_mask=lowerCamelCase				,   )
     if padding:
       __A		:     List[Any]												=		padded_inputs.pop("""attention_mask"""       )

   __A		:     List[Any]												=		[]
   for example in padded_inputs.pop("""input_values"""       ):
     if self.feature_size == 1:
       __A		:     Optional[Any]												=		example[..., None]
     input_values.append(example.T       )

   __A		:     str												=		input_values
   if return_tensors is not None:
     __A		:     Any												=		padded_inputs.convert_to_tensors(lowerCamelCase       )

   return padded_inputs



