






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


SCREAMING_SNAKE_CASE 							=						logging.get_logger(__name__)
@add_end_docstrings(__lowercase			)
class 							A_    (						__lowercase			):






 '''simple docstring'''




 def __init__(	self							,  **_A) ->		int:

     """simple docstring"""



     super().__init__(**_A)

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


 def __call__(	self							,  _A							,  **_A) ->		List[str]:

     """simple docstring"""



     return super().__call__(_A							,  **_A)


 def  snake_case__				(	self							,  **_A) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				{}
     if "candidate_labels" in kwargs:
         _UpperCAmelCase				:      Union[str, Any]			  =				kwargs['''candidate_labels''']
     if "hypothesis_template" in kwargs:
         _UpperCAmelCase				:      Dict			  =				kwargs['''hypothesis_template''']

     return preprocess_params, {}, {}


 def  snake_case__				(	self							,  _A							,  _A=None							,  _A="This is a sound of {}.") ->		Tuple:

     """simple docstring"""



     if isinstance(_A							,  _A):
         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				:      List[Any]			  =				requests.get(_A).content
         else:
             with open(_A							,  '''rb''') as f:
                 _UpperCAmelCase				:      List[str]			  =				f.read()

     if isinstance(_A							,  _A):
         _UpperCAmelCase				:      List[Any]			  =				ffmpeg_read(_A							,  self.feature_extractor.sampling_rate)

     if not isinstance(_A							,  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				:      Optional[Any]			  =				self.feature_extractor(
         [audio]							,  sampling_rate=self.feature_extractor.sampling_rate							,  return_tensors='''pt''')
     _UpperCAmelCase				:      Dict			  =				candidate_labels
     _UpperCAmelCase				:      List[str]			  =				[hypothesis_template.format(_A) for x in candidate_labels]
     _UpperCAmelCase				:      Optional[Any]			  =				self.tokenizer(_A							,  return_tensors=self.framework							,  padding=_A)
     _UpperCAmelCase				:      str			  =				[text_inputs]
     return inputs


 def  snake_case__				(	self							,  _A) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				model_inputs.pop('''candidate_labels''')
     _UpperCAmelCase				:      Union[str, Any]			  =				model_inputs.pop('''text_inputs''')
     if isinstance(text_inputs[0]							,  _A):
         _UpperCAmelCase				:      int			  =				text_inputs[0]
     else:
         # Batching case.
         _UpperCAmelCase				:      Dict			  =				text_inputs[0][0]

     _UpperCAmelCase				:      str			  =				self.model(**_A							,  **_A)

     _UpperCAmelCase				:      str			  =				{
         '''candidate_labels''': candidate_labels,
         '''logits''': outputs.logits_per_audio,
     }
     return model_outputs


 def  snake_case__				(	self							,  _A) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				model_outputs.pop('''candidate_labels''')
     _UpperCAmelCase				:      str			  =				model_outputs['''logits'''][0]

     if self.framework == "pt":
         _UpperCAmelCase				:      int			  =				logits.softmax(dim=0)
         _UpperCAmelCase				:      Optional[Any]			  =				probs.tolist()
     else:
         raise ValueError('''`tf` framework not supported.''')

     _UpperCAmelCase				:      List[str]			  =				[
         {'''score''': score, '''label''': candidate_label}
         for score, candidate_label in sorted(zip(_A							,  _A)							,  key=lambda _A: -x[0])
     ]
     return result












import argparse
import os
import re


SCREAMING_SNAKE_CASE 							=						'src/transformers/models/auto'


# re pattern that matches mapping introductions:
#    SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
SCREAMING_SNAKE_CASE 							=						re.compile(R'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict')
# re pattern that matches identifiers in mappings
SCREAMING_SNAKE_CASE 							=						re.compile(R'\s*\(\s*"(\S[^"]+)"')

def      _lowerCamelCase	(						__A    :							Optional[int]		,		__A    :							bool = False )      ->					int:
    with open(__A		,		'''r'''		,		encoding='''utf-8''' ) as f:
        _UpperCAmelCase				:      Union[str, Any]			  =				f.read()

    _UpperCAmelCase				:      Any			  =				content.split('''\n''' )
    _UpperCAmelCase				:      Any			  =				[]
    _UpperCAmelCase				:      Tuple			  =				0
    while line_idx < len(__A ):
        if _re_intro_mapping.search(lines[line_idx] ) is not None:
            _UpperCAmelCase				:      Union[str, Any]			  =				len(re.search(r'''^(\s*)\S'''		,		lines[line_idx] ).groups()[0] ) + 8
            # Start of a new mapping!
            while not lines[line_idx].startswith(''' ''' * indent + '''(''' ):
                new_lines.append(lines[line_idx] )
                line_idx += 1

            _UpperCAmelCase				:      str			  =				[]
            while lines[line_idx].strip() != "]":
                # Blocks either fit in one line or not
                if lines[line_idx].strip() == "(":
                    _UpperCAmelCase				:      List[str]			  =				line_idx
                    while not lines[line_idx].startswith(''' ''' * indent + ''')''' ):
                        line_idx += 1
                    blocks.append('''\n'''.join(lines[start_idx : line_idx + 1] ) )
                else:
                    blocks.append(lines[line_idx] )
                line_idx += 1

            # Sort blocks by their identifiers
            _UpperCAmelCase				:      Tuple			  =				sorted(__A		,		key=lambda __A : _re_identifier.search(__A ).groups()[0] )
            new_lines += blocks
        else:
            new_lines.append(lines[line_idx] )
            line_idx += 1

    if overwrite:
        with open(__A		,		'''w'''		,		encoding='''utf-8''' ) as f:
            f.write('''\n'''.join(__A ) )
    elif "\n".join(__A ) != content:
        return True

def      _lowerCamelCase	(						__A    :							bool = False )      ->					List[str]:
    _UpperCAmelCase				:      List[str]			  =				[os.path.join(__A		,		__A ) for f in os.listdir(__A ) if f.endswith('''.py''' )]
    _UpperCAmelCase				:      List[Any]			  =				[sort_auto_mapping(__A		,		overwrite=__A ) for fname in fnames]

    if not overwrite and any(__A ):
        _UpperCAmelCase				:      Optional[int]			  =				[f for f, d in zip(__A		,		__A ) if d]
        raise ValueError(
            f'''The following files have auto mappings that need sorting: {', '.join(__A )}. Run `make style` to fix'''
            ''' this.''' )


if __name__ == "__main__":
  SCREAMING_SNAKE_CASE 							=						argparse.ArgumentParser()
  parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.')
  SCREAMING_SNAKE_CASE 							=						parser.parse_args()

  sort_all_auto_mappings(not args.check_only)




