






'''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


a_					=	logging.get_logger(__name__)






@add_end_docstrings(lowerCamelCase			)
class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def __init__( self		:							Optional[int]   , **__lowercase		:							Optional[Any] )		->  Union[str, Any]:
       super().__init__(**__lowercase )

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




 def __call__( self		:							List[Any]   , __lowercase		:							Union[np.ndarray, bytes, str]   , **__lowercase		:							Dict )		->  int:
       return super().__call__(__lowercase   , **__lowercase )




 def        __magic_name__		( self		:							Optional[Any]   , **__lowercase		:							Union[str, Any] )		->  List[Any]:
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													={}
       if "candidate_labels" in kwargs:
             SCREAMING_SNAKE_CASE__       :			Dict													=kwargs['''candidate_labels''']
       if "hypothesis_template" in kwargs:
             SCREAMING_SNAKE_CASE__       :			Optional[Any]													=kwargs['''hypothesis_template''']

       return preprocess_params, {}, {}




 def        __magic_name__		( self		:							Tuple   , __lowercase		:							Optional[Any]   , __lowercase		:							Dict=None   , __lowercase		:							Any="This is a sound of {}." )		->  List[str]:
       if isinstance(__lowercase   , __lowercase ):
             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
                   SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=requests.get(__lowercase ).content
             else:
                   with open(__lowercase   , '''rb''' ) as f:
                         SCREAMING_SNAKE_CASE__       :			List[str]													=f.read()

       if isinstance(__lowercase   , __lowercase ):
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=ffmpeg_read(__lowercase   , self.feature_extractor.sampling_rate )

       if not isinstance(__lowercase   , 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''' )

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




 def        __magic_name__		( self		:							Optional[Any]   , __lowercase		:							Optional[int] )		->  Tuple:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=model_inputs.pop('''candidate_labels''' )
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=model_inputs.pop('''text_inputs''' )
       if isinstance(text_inputs[0]   , __lowercase ):
             SCREAMING_SNAKE_CASE__       :			int													=text_inputs[0]
       else:
             # Batching case.
             SCREAMING_SNAKE_CASE__       :			str													=text_inputs[0][0]

       SCREAMING_SNAKE_CASE__       :			Dict													=self.model(**__lowercase   , **__lowercase )

       SCREAMING_SNAKE_CASE__       :			Tuple													={
           '''candidate_labels''': candidate_labels,
           '''logits''': outputs.logits_per_audio,
       }
       return model_outputs




 def        __magic_name__		( self		:							List[str]   , __lowercase		:							Optional[Any] )		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__       :			List[Any]													=model_outputs.pop('''candidate_labels''' )
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=model_outputs['''logits'''][0]

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

       SCREAMING_SNAKE_CASE__       :			int													=[
           {'''score''': score, '''label''': candidate_label}
           for score, candidate_label in sorted(zip(__lowercase   , __lowercase )   , key=lambda __lowercase : -x[0] )
       ]
       return result







'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


a_					=	{
    'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  a_					=	[
      'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST',
      'MegatronBertForCausalLM',
      'MegatronBertForMaskedLM',
      'MegatronBertForMultipleChoice',
      'MegatronBertForNextSentencePrediction',
      'MegatronBertForPreTraining',
      'MegatronBertForQuestionAnswering',
      'MegatronBertForSequenceClassification',
      'MegatronBertForTokenClassification',
      'MegatronBertModel',
      'MegatronBertPreTrainedModel',
  ]

if TYPE_CHECKING:
  from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_megatron_bert import (
        MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
        MegatronBertForCausalLM,
        MegatronBertForMaskedLM,
        MegatronBertForMultipleChoice,
        MegatronBertForNextSentencePrediction,
        MegatronBertForPreTraining,
        MegatronBertForQuestionAnswering,
        MegatronBertForSequenceClassification,
        MegatronBertForTokenClassification,
        MegatronBertModel,
        MegatronBertPreTrainedModel,
    )

else:
  import sys

  a_					=	_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)