






import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


A_		:		int		     =			threading.Lock()
A_		:		Optional[logging.Handler]		     =			None

A_		:		Tuple		     =			{
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

A_		:		int		     =			logging.WARNING

A_		:		List[str]		     =			True

def   snake_case ()	->    Union[str, Any]:
  UpperCamelCase_: List[Any]   				=    os.getenv('TRANSFORMERS_VERBOSITY'     ,   UpperCAmelCase__  )
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          F'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, '''
          F'''has to be one of: { ', '.join(log_levels.keys()  ) }'''  )
  return _default_log_level

def   snake_case ()	->    str:
  return __name__.split('.'  )[0]

def   snake_case ()	->    logging.Logger:
  return logging.getLogger(_get_library_name()  )

def   snake_case ()	->    None:
  global _default_handler

  with _lock:
    if _default_handler:
      # This library has already configured the library root logger.
      return
    UpperCamelCase_: Optional[Any]   				=    logging.StreamHandler()  # Set sys.stderr as stream.
    UpperCamelCase_: List[str]   				=    sys.stderr.flush

    # Apply our default configuration to the library root logger.
    UpperCamelCase_: str   				=    _get_library_root_logger()
    library_root_logger.addHandler(_default_handler  )
    library_root_logger.setLevel(_get_default_logging_level()  )
    UpperCamelCase_: Union[str, Any]   				=    False

def   snake_case ()	->    None:
  global _default_handler

  with _lock:
    if not _default_handler:
      return

    UpperCamelCase_: Tuple   				=    _get_library_root_logger()
    library_root_logger.removeHandler(_default_handler  )
    library_root_logger.setLevel(logging.NOTSET  )
    UpperCamelCase_: Union[str, Any]   				=    None

def   snake_case ()	->    str:
  return log_levels

def   snake_case (UpperCAmelCase__ = None  )	->    logging.Logger:

  if name is None:
    UpperCamelCase_: int   				=    _get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(UpperCAmelCase__  )

def   snake_case ()	->    int:
  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()

def   snake_case (UpperCAmelCase__  )	->    None:
  _configure_library_root_logger()
  _get_library_root_logger().setLevel(UpperCAmelCase__  )

def   snake_case ()	->    str:
  return set_verbosity(UpperCAmelCase__  )

def   snake_case ()	->    int:
  return set_verbosity(UpperCAmelCase__  )

def   snake_case ()	->    Optional[Any]:
  return set_verbosity(UpperCAmelCase__  )

def   snake_case ()	->    str:
  return set_verbosity(UpperCAmelCase__  )

def   snake_case ()	->    None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler  )

def   snake_case ()	->    None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler  )

def   snake_case (UpperCAmelCase__  )	->    None:
  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(UpperCAmelCase__  )

def   snake_case (UpperCAmelCase__  )	->    None:
  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(UpperCAmelCase__  )

def   snake_case ()	->    None:
  _configure_library_root_logger()
  UpperCamelCase_: Optional[int]   				=    False

def   snake_case ()	->    None:
  _configure_library_root_logger()
  UpperCamelCase_: List[str]   				=    True

def   snake_case ()	->    None:
  UpperCamelCase_: List[Any]   				=    _get_library_root_logger().handlers

  for handler in handlers:
    UpperCamelCase_: Any   				=    logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'  )
    handler.setFormatter(UpperCAmelCase__  )

def   snake_case ()	->    None:
  UpperCamelCase_: List[Any]   				=    _get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(UpperCAmelCase__  )

def   snake_case (self     ,   *UpperCAmelCase__     ,   **UpperCAmelCase__  )	->    str:
  UpperCamelCase_: Dict   				=    os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS'     ,   UpperCAmelCase__  )
  if no_advisory_warnings:
    return
  self.warning(*UpperCAmelCase__     ,   **UpperCAmelCase__  )


A_		:		Dict		     =			warning_advice

@functools.lru_cache(UpperCAmelCase__  )
def   snake_case (self     ,   *UpperCAmelCase__     ,   **UpperCAmelCase__  )	->    Optional[Any]:
  self.warning(*UpperCAmelCase__     ,   **UpperCAmelCase__  )


A_		:		str		     =			warning_once




class     _lowerCAmelCase:





       """simple docstring"""







       def __init__( self  ,      *_lowerCamelCase  ,      **_lowerCamelCase							):  # pylint: disable=unused-argument
         UpperCamelCase_: Optional[Any]   				=    args[0] if args else None





       def __iter__( self							):
         return iter(self._iterator							)





       def __getattr__( self  ,      _lowerCamelCase							):

         def empty_fn(*_lowerCamelCase  ,      **_lowerCamelCase							):  # pylint: disable=unused-argument
           return

         return empty_fn





       def __enter__( self							):
         return self





       def __exit__( self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase							):
         return







class     _lowerCAmelCase:





       """simple docstring"""







       def __call__( self  ,      *_lowerCamelCase  ,      **_lowerCamelCase							):
         if _tqdm_active:
           return tqdm_lib.tqdm(*_lowerCamelCase  ,      **_lowerCamelCase							)
         else:
           return EmptyTqdm(*_lowerCamelCase  ,      **_lowerCamelCase							)





       def       _a   ( self  ,      *_lowerCamelCase  ,      **_lowerCamelCase							):
         UpperCamelCase_: Optional[int]   				=    None
         if _tqdm_active:
           return tqdm_lib.tqdm.set_lock(*_lowerCamelCase  ,      **_lowerCamelCase							)





       def       _a   ( self							):
         if _tqdm_active:
           return tqdm_lib.tqdm.get_lock()







A_		:		int		     =			_tqdm_cls()

def   snake_case ()	->    bool:
  global _tqdm_active
  return bool(_tqdm_active  )

def   snake_case ()	->    Any:
  global _tqdm_active
  UpperCamelCase_: Optional[Any]   				=    True
  hf_hub_utils.enable_progress_bars()

def   snake_case ()	->    int:
  global _tqdm_active
  UpperCamelCase_: Tuple   				=    False
  hf_hub_utils.disable_progress_bars()







import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union

import numpy as np

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__  )	->    np.array:
  UpperCamelCase_: Dict   				=    F'''{sampling_rate}'''
  UpperCamelCase_: Any   				=    '1'
  UpperCamelCase_: Any   				=    'f32le'
  UpperCamelCase_: Union[str, Any]   				=    [
      'ffmpeg',
      '-i',
      'pipe:0',
      '-ac',
      ac,
      '-ar',
      ar,
      '-f',
      format_for_conversion,
      '-hide_banner',
      '-loglevel',
      'quiet',
      'pipe:1',
  ]

  try:
    with subprocess.Popen(UpperCAmelCase__     ,   stdin=subprocess.PIPE     ,   stdout=subprocess.PIPE  ) as ffmpeg_process:
      UpperCamelCase_: Optional[Any]   				=    ffmpeg_process.communicate(UpperCAmelCase__  )
  except FileNotFoundError as error:
    raise ValueError('ffmpeg was not found but is required to load audio files from filename'  ) from error
  UpperCamelCase_: Union[str, Any]   				=    output_stream[0]
  UpperCamelCase_: List[str]   				=    np.frombuffer(UpperCAmelCase__     ,   np.floataa  )
  if audio.shape[0] == 0:
    raise ValueError('Malformed soundfile'  )
  return audio

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__ = "f32le"     ,   )	->    Tuple:
  UpperCamelCase_: Any   				=    F'''{sampling_rate}'''
  UpperCamelCase_: Union[str, Any]   				=    '1'
  if format_for_conversion == "s16le":
    UpperCamelCase_: Optional[Any]   				=    2
  elif format_for_conversion == "f32le":
    UpperCamelCase_: Any   				=    4
  else:
    raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`'''  )

  UpperCamelCase_: int   				=    platform.system()
  if system == "Linux":
    UpperCamelCase_: Tuple   				=    'alsa'
    UpperCamelCase_: List[str]   				=    'default'
  elif system == "Darwin":
    UpperCamelCase_: int   				=    'avfoundation'
    UpperCamelCase_: Union[str, Any]   				=    ':0'
  elif system == "Windows":
    UpperCamelCase_: Tuple   				=    'dshow'
    UpperCamelCase_: Dict   				=    'default'

  UpperCamelCase_: Any   				=    [
      'ffmpeg',
      '-f',
      format_,
      '-i',
      input_,
      '-ac',
      ac,
      '-ar',
      ar,
      '-f',
      format_for_conversion,
      '-fflags',
      'nobuffer',
      '-hide_banner',
      '-loglevel',
      'quiet',
      'pipe:1',
  ]
  UpperCamelCase_: Tuple   				=    int(round(sampling_rate * chunk_length_s  )  ) * size_of_sample
  UpperCamelCase_: Optional[int]   				=    _ffmpeg_stream(UpperCAmelCase__     ,   UpperCAmelCase__  )
  for item in iterator:
    yield item

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__ = None     ,   UpperCAmelCase__ = None     ,   UpperCAmelCase__ = "f32le"     ,   )	->    Any:
  if stream_chunk_s is not None:
    UpperCamelCase_: List[Any]   				=    stream_chunk_s
  else:
    UpperCamelCase_: Dict   				=    chunk_length_s

  UpperCamelCase_: List[str]   				=    ffmpeg_microphone(UpperCAmelCase__     ,   UpperCAmelCase__     ,   format_for_conversion=UpperCAmelCase__  )
  if format_for_conversion == "s16le":
    UpperCamelCase_: Union[str, Any]   				=    np.intaa
    UpperCamelCase_: List[Any]   				=    2
  elif format_for_conversion == "f32le":
    UpperCamelCase_: str   				=    np.floataa
    UpperCamelCase_: Tuple   				=    4
  else:
    raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`'''  )

  if stride_length_s is None:
    UpperCamelCase_: int   				=    chunk_length_s / 6
  UpperCamelCase_: Tuple   				=    int(round(sampling_rate * chunk_length_s  )  ) * size_of_sample
  if isinstance(UpperCAmelCase__     ,   (int, float)  ):
    UpperCamelCase_: Union[str, Any]   				=    [stride_length_s, stride_length_s]

  UpperCamelCase_: Any   				=    int(round(sampling_rate * stride_length_s[0]  )  ) * size_of_sample
  UpperCamelCase_: Dict   				=    int(round(sampling_rate * stride_length_s[1]  )  ) * size_of_sample
  UpperCamelCase_: Optional[int]   				=    datetime.datetime.now()
  UpperCamelCase_: Optional[int]   				=    datetime.timedelta(seconds=UpperCAmelCase__  )
  for item in chunk_bytes_iter(UpperCAmelCase__     ,   UpperCAmelCase__     ,   stride=(stride_left, stride_right)     ,   stream=UpperCAmelCase__  ):
    # Put everything back in numpy scale
    UpperCamelCase_: Tuple   				=    np.frombuffer(item['raw']     ,   dtype=UpperCAmelCase__  )
    UpperCamelCase_: Optional[int]   				=    (
        item['stride'][0] // size_of_sample,
        item['stride'][1] // size_of_sample,
    )
    UpperCamelCase_: int   				=    sampling_rate
    audio_time += delta
    if datetime.datetime.now() > audio_time + 1_0 * delta:
      # We're late !! SKIP
      continue
    yield item

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__     ,   UpperCAmelCase__ = False  )	->    int:
  UpperCamelCase_: str   				=    b''
  UpperCamelCase_				,UpperCamelCase_: Union[str, Any]   				=    stride
  if stride_left + stride_right >= chunk_len:
    raise ValueError(
        F'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}'''  )
  UpperCamelCase_: List[str]   				=    0
  for raw in iterator:
    acc += raw
    if stream and len(UpperCAmelCase__  ) < chunk_len:
      UpperCamelCase_: Optional[Any]   				=    (_stride_left, 0)
      yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
    else:
      while len(UpperCAmelCase__  ) >= chunk_len:
        # We are flushing the accumulator
        UpperCamelCase_: int   				=    (_stride_left, stride_right)
        UpperCamelCase_: Optional[Any]   				=    {'raw': acc[:chunk_len], 'stride': stride}
        if stream:
          UpperCamelCase_: Any   				=    False
        yield item
        UpperCamelCase_: Optional[int]   				=    stride_left
        UpperCamelCase_: Optional[Any]   				=    acc[chunk_len - stride_left - stride_right :]
    # Last chunk
  if len(UpperCAmelCase__  ) > stride_left:
    UpperCamelCase_: int   				=    {'raw': acc, 'stride': (_stride_left, 0)}
    if stream:
      UpperCamelCase_: Optional[Any]   				=    False
    yield item

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__  )	->    int:
  UpperCamelCase_: Any   				=    2**2_4  # 16Mo
  try:
    with subprocess.Popen(UpperCAmelCase__     ,   stdout=subprocess.PIPE     ,   bufsize=UpperCAmelCase__  ) as ffmpeg_process:
      while True:
        UpperCamelCase_: Any   				=    ffmpeg_process.stdout.read(UpperCAmelCase__  )
        if raw == b"":
          break
        yield raw
  except FileNotFoundError as error:
    raise ValueError('ffmpeg was not found but is required to stream audio files from filename'  ) from error