



"""simple docstring"""
import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
A:  int      				=						'src/transformers'
A:  int      				=						'docs/source/en'
A:  List[Any]      				=						'.'

def  _snake_case		(		UpperCamelCase		:						Dict     ,						UpperCamelCase		:						List[str]     ,						UpperCamelCase		:						Dict		):
 with open(UpperCAmelCase_     ,						"""r"""     ,						encoding="""utf-8"""     ,						newline="""\n"""		) as f:
  UpperCAmelCase      :   Any      =      f.readlines()
 # Find the start prompt.
 UpperCAmelCase      :   str      =      0
 while not lines[start_index].startswith(UpperCAmelCase_		):
  start_index += 1
 start_index += 1

 UpperCAmelCase      :   Optional[int]      =      start_index
 while not lines[end_index].startswith(UpperCAmelCase_		):
  end_index += 1
 end_index -= 1

 while len(lines[start_index]		) <= 1:
  start_index += 1
 while len(lines[end_index]		) <= 1:
  end_index -= 1
 end_index += 1
 return "".join(lines[start_index:end_index]		), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
A:  List[str]      				=						'Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
A:  List[str]      				=						re.compile(R"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
A:  Optional[Any]      				=						re.compile(R"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
A:  str      				=						re.compile(R"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")


# This is to make sure the transformers module imported is the one in the repo.
A:  List[Any]      				=						direct_transformers_import(TRANSFORMERS_PATH)

def  _snake_case		(		UpperCamelCase		:						Optional[Any]		):
 UpperCAmelCase      :   Any      =      re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)"""     ,						UpperCAmelCase_		)
 return [m.group(0		) for m in matches]

def  _snake_case		(		UpperCamelCase		:						int     ,						UpperCamelCase		:						Dict		):
 UpperCAmelCase      :   Any      =      2 if text == '✅' or text == '❌' else len(UpperCAmelCase_		)
 UpperCAmelCase      :   Tuple      =      (width - text_length) // 2
 UpperCAmelCase      :   Tuple      =      width - text_length - left_indent
 return " " * left_indent + text + " " * right_indent

def  _snake_case		(		):
 UpperCAmelCase      :   List[Any]      =      transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
 UpperCAmelCase      :   List[str]      =      {
     name: config_maping_names[code]
     for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
     if code in config_maping_names
 }
 UpperCAmelCase      :   List[str]      =      {name: config.replace("""Config"""     ,						""""""		) for name, config in model_name_to_config.items()}

 # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
 UpperCAmelCase      :   Optional[int]      =      collections.defaultdict(UpperCAmelCase_		)
 UpperCAmelCase      :   int      =      collections.defaultdict(UpperCAmelCase_		)
 UpperCAmelCase      :   Optional[int]      =      collections.defaultdict(UpperCAmelCase_		)
 UpperCAmelCase      :   Union[str, Any]      =      collections.defaultdict(UpperCAmelCase_		)
 UpperCAmelCase      :   Union[str, Any]      =      collections.defaultdict(UpperCAmelCase_		)

 # Let's lookup through all transformers object (once).
 for attr_name in dir(UpperCAmelCase_		):
  UpperCAmelCase      :   str      =      None
  if attr_name.endswith("""Tokenizer"""		):
   UpperCAmelCase      :   Tuple      =      slow_tokenizers
   UpperCAmelCase      :   Optional[int]      =      attr_name[:-9]
  elif attr_name.endswith("""TokenizerFast"""		):
   UpperCAmelCase      :   Any      =      fast_tokenizers
   UpperCAmelCase      :   Tuple      =      attr_name[:-13]
  elif _re_tf_models.match(UpperCAmelCase_		) is not None:
   UpperCAmelCase      :   str      =      tf_models
   UpperCAmelCase      :   Dict      =      _re_tf_models.match(UpperCAmelCase_		).groups()[0]
  elif _re_flax_models.match(UpperCAmelCase_		) is not None:
   UpperCAmelCase      :   str      =      flax_models
   UpperCAmelCase      :   Optional[Any]      =      _re_flax_models.match(UpperCAmelCase_		).groups()[0]
  elif _re_pt_models.match(UpperCAmelCase_		) is not None:
   UpperCAmelCase      :   List[str]      =      pt_models
   UpperCAmelCase      :   List[str]      =      _re_pt_models.match(UpperCAmelCase_		).groups()[0]

  if lookup_dict is not None:
   while len(UpperCAmelCase_		) > 0:
    if attr_name in model_name_to_prefix.values():
     UpperCAmelCase      :   Tuple      =      True
     break
    # Try again after removing the last word in the name
    UpperCAmelCase      :   Optional[Any]      =      ''.join(camel_case_split(UpperCAmelCase_		)[:-1]		)

    # Let's build that table!
 UpperCAmelCase      :   Optional[Any]      =      list(model_name_to_config.keys()		)
 model_names.sort(key=str.lower		)
 UpperCAmelCase      :   Any      =      ['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support']
 # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
 UpperCAmelCase      :   List[str]      =      [len(UpperCAmelCase_		) + 2 for c in columns]
 UpperCAmelCase      :   Optional[Any]      =      max([len(UpperCAmelCase_		) for name in model_names]		) + 2

 # Build the table per se
 UpperCAmelCase      :   List[Any]      =      '|' + '|'.join([_center_text(UpperCAmelCase_     ,						UpperCAmelCase_		) for c, w in zip(UpperCAmelCase_     ,						UpperCAmelCase_		)]		) + '|\n'
 # Use ":-----:" format to center-aligned table cell texts
 table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths]		) + "|\n"

 UpperCAmelCase      :   int      =      {True: '✅', False: '❌'}
 for name in model_names:
  UpperCAmelCase      :   Union[str, Any]      =      model_name_to_prefix[name]
  UpperCAmelCase      :   str      =      [
      name,
      check[slow_tokenizers[prefix]],
      check[fast_tokenizers[prefix]],
      check[pt_models[prefix]],
      check[tf_models[prefix]],
      check[flax_models[prefix]],
  ]
  table += "|" + "|".join([_center_text(UpperCAmelCase_     ,						UpperCAmelCase_		) for l, w in zip(UpperCAmelCase_     ,						UpperCAmelCase_		)]		) + "|\n"
 return table

def  _snake_case		(		UpperCamelCase		:						Optional[Any]=False		):
 UpperCAmelCase      :   Any      =      _find_text_in_file(
     filename=os.path.join(UpperCAmelCase_     ,						"""index.md"""		)     ,						start_prompt="""<!--This table is updated automatically from the auto modules"""     ,						end_prompt="""<!-- End table-->"""     ,						)
 UpperCAmelCase      :   str      =      get_model_table_from_auto_modules()

 if current_table != new_table:
  if overwrite:
   with open(os.path.join(UpperCAmelCase_     ,						"""index.md"""		)     ,						"""w"""     ,						encoding="""utf-8"""     ,						newline="""\n"""		) as f:
    f.writelines(lines[:start_index] + [new_table] + lines[end_index:]		)
  else:
   raise ValueError(
       """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this."""		)


if __name__ == "__main__":
      A:  int      				=						argparse.ArgumentParser()
      parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
      A:  Union[str, Any]      				=						parser.parse_args()

      check_model_table(args.fix_and_overwrite)





'''simple docstring'''
from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


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






@add_end_docstrings(lowercase  )
class 				lowercase__      (				lowercase  ):





	def __init__(					self   :							Tuple					,**lowerCamelCase__   :							Union[str, Any]					):







							'''simple docstring'''
							super().__init__(**lowerCamelCase__					)

							if self.framework != "pt":
													raise ValueError(F'The {self.__class__} is only available in PyTorch.'					)
							# No specific FOR_XXX available yet





	def __call__(					self   :							Dict					,lowerCamelCase__   :							Union[np.ndarray, bytes, str]					,**lowerCamelCase__   :							Any					):







							'''simple docstring'''
							return super().__call__(lowerCamelCase__					,**lowerCamelCase__					)





	def       UpperCamelCase_    (					self   :							int					,**lowerCamelCase__   :							Optional[int]					):







							'''simple docstring'''
							_UpperCamelCase   :						List[Any]												=  {}
							if "candidate_labels" in kwargs:
													_UpperCamelCase   :						Any												=  kwargs['candidate_labels']
							if "hypothesis_template" in kwargs:
													_UpperCamelCase   :						Any												=  kwargs['hypothesis_template']

							return preprocess_params, {}, {}





	def       UpperCamelCase_    (					self   :							Any					,lowerCamelCase__   :							List[str]					,lowerCamelCase__   :							str=None					,lowerCamelCase__   :							List[Any]="This is a sound of {}."					):







							'''simple docstring'''
							if isinstance(lowerCamelCase__					,lowerCamelCase__					):
													if audio.startswith('http://'					) or audio.startswith('https://'					):
																			# We need to actually check for a real protocol, otherwise it's impossible to use a local file
																			# like http_huggingface_co.png
																			_UpperCamelCase   :						Optional[Any]												=  requests.get(lowerCamelCase__					).content
													else:
																			with open(lowerCamelCase__					,'rb'					) as f:
																									_UpperCamelCase   :						List[str]												=  f.read()

							if isinstance(lowerCamelCase__					,lowerCamelCase__					):
													_UpperCamelCase   :						int												=  ffmpeg_read(lowerCamelCase__					,self.feature_extractor.sampling_rate					)

							if not isinstance(lowerCamelCase__					,np.ndarray					):
													raise ValueError('We expect a numpy ndarray as input'					)
							if len(audio.shape					) != 1:
													raise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline'					)

							_UpperCamelCase   :						Dict												=  self.feature_extractor(
							    [audio]					,sampling_rate=self.feature_extractor.sampling_rate					,return_tensors='pt'					)
							_UpperCamelCase   :						List[Any]												=  candidate_labels
							_UpperCamelCase   :						Tuple												=  [hypothesis_template.format(lowerCamelCase__					) for x in candidate_labels]
							_UpperCamelCase   :						Dict												=  self.tokenizer(lowerCamelCase__					,return_tensors=self.framework					,padding=lowerCamelCase__					)
							_UpperCamelCase   :						Optional[Any]												=  [text_inputs]
							return inputs





	def       UpperCamelCase_    (					self   :							str					,lowerCamelCase__   :							Tuple					):







							'''simple docstring'''
							_UpperCamelCase   :						Any												=  model_inputs.pop('candidate_labels'					)
							_UpperCamelCase   :						str												=  model_inputs.pop('text_inputs'					)
							if isinstance(text_inputs[0]					,lowerCamelCase__					):
													_UpperCamelCase   :						Union[str, Any]												=  text_inputs[0]
							else:
													# Batching case.
													_UpperCamelCase   :						int												=  text_inputs[0][0]

							_UpperCamelCase   :						List[str]												=  self.model(**lowerCamelCase__					,**lowerCamelCase__					)

							_UpperCamelCase   :						Optional[Any]												=  {
							    'candidate_labels': candidate_labels,
							    'logits': outputs.logits_per_audio,
							}
							return model_outputs





	def       UpperCamelCase_    (					self   :							int					,lowerCamelCase__   :							Optional[Any]					):







							'''simple docstring'''
							_UpperCamelCase   :						Optional[Any]												=  model_outputs.pop('candidate_labels'					)
							_UpperCamelCase   :						int												=  model_outputs['logits'][0]

							if self.framework == "pt":
													_UpperCamelCase   :						Tuple												=  logits.softmax(dim=0					)
													_UpperCamelCase   :						str												=  probs.tolist()
							else:
													raise ValueError('`tf` framework not supported.'					)

							_UpperCamelCase   :						Union[str, Any]												=  [
							    {'score': score, 'label': candidate_label}
							    for score, candidate_label in sorted(zip(lowerCamelCase__					,lowerCamelCase__					)					,key=lambda lowerCamelCase__					: -x[0]					)
							]
							return result


