





"""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(__SCREAMING_SNAKE_CASE   )
class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       int	,			**UpperCAmelCase_    :       Tuple)	->List[Any]:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_)

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

 def __call__(self    :       str	,			UpperCAmelCase_    :       Union[np.ndarray, bytes, str]	,			**UpperCAmelCase_    :       Any)	->str:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			**UpperCAmelCase_    :       Union[str, Any])	->int:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        ={}
   if "candidate_labels" in kwargs:
     lowerCamelCase__:				int        =kwargs["candidate_labels"]
   if "hypothesis_template" in kwargs:
     lowerCamelCase__:				Any        =kwargs["hypothesis_template"]

   return preprocess_params, {}, {}

 def 							SCREAMING_SNAKE_CASE_ (self    :       int	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       Optional[Any]=None	,			UpperCAmelCase_    :       Any="This is a sound of {}.")	->List[str]:



   '''simple docstring'''



   if isinstance(UpperCAmelCase_	,			UpperCAmelCase_):
     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
       lowerCamelCase__:				Tuple        =requests.get(UpperCAmelCase_).content
     else:
       with open(UpperCAmelCase_	,			"rb") as f:
         lowerCamelCase__:				Tuple        =f.read()

   if isinstance(UpperCAmelCase_	,			UpperCAmelCase_):
     lowerCamelCase__:				Optional[Any]        =ffmpeg_read(UpperCAmelCase_	,			self.feature_extractor.sampling_rate)

   if not isinstance(UpperCAmelCase_	,			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")

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

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       Any)	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =model_inputs.pop("candidate_labels")
   lowerCamelCase__:				str        =model_inputs.pop("text_inputs")
   if isinstance(text_inputs[0]	,			UpperCAmelCase_):
     lowerCamelCase__:				Any        =text_inputs[0]
   else:
     # Batching case.
     lowerCamelCase__:				Tuple        =text_inputs[0][0]

   lowerCamelCase__:				Tuple        =self.model(**UpperCAmelCase_	,			**UpperCAmelCase_)

   lowerCamelCase__:				Any        ={
       "candidate_labels": candidate_labels,
       "logits": outputs.logits_per_audio,
   }
   return model_outputs







 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       List[Any])	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =model_outputs.pop("candidate_labels")
   lowerCamelCase__:				str        =model_outputs["logits"][0]

   if self.framework == "pt":
     lowerCamelCase__:				Union[str, Any]        =logits.softmax(dim=0)
     lowerCamelCase__:				Union[str, Any]        =probs.tolist()
   else:
     raise ValueError("`tf` framework not supported.")

   lowerCamelCase__:				List[Any]        =[
       {"score": score, "label": candidate_label}
       for score, candidate_label in sorted(zip(UpperCAmelCase_	,			UpperCAmelCase_)	,			key=lambda UpperCAmelCase_: -x[0])
   ]
   return result








from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__A     =    logging.get_logger(__name__)

__A     =    {
    "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json",
    "distilbert-base-uncased-distilled-squad": (
        "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json",
    "distilbert-base-cased-distilled-squad": (
        "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json",
    "distilbert-base-multilingual-cased": (
        "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json"
    ),
    "distilbert-base-uncased-finetuned-sst-2-english": (
        "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json"
    ),
}



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      "distilbert"
 lowercase_		=      {
     "hidden_size": "dim",
     "num_attention_heads": "n_heads",
     "num_hidden_layers": "n_layers",
 }

 def __init__(self    :       Any	,			UpperCAmelCase_    :       str=30_522	,			UpperCAmelCase_    :       Union[str, Any]=512	,			UpperCAmelCase_    :       int=False	,			UpperCAmelCase_    :       Optional[Any]=6	,			UpperCAmelCase_    :       Optional[Any]=12	,			UpperCAmelCase_    :       Any=768	,			UpperCAmelCase_    :       List[Any]=4 * 768	,			UpperCAmelCase_    :       Tuple=0.1	,			UpperCAmelCase_    :       List[Any]=0.1	,			UpperCAmelCase_    :       Any="gelu"	,			UpperCAmelCase_    :       int=0.02	,			UpperCAmelCase_    :       Optional[Any]=0.1	,			UpperCAmelCase_    :       Optional[int]=0.2	,			UpperCAmelCase_    :       int=0	,			**UpperCAmelCase_    :       List[Any]	,			)	->Any:



   '''simple docstring'''



   lowerCamelCase__:				int        =vocab_size
   lowerCamelCase__:				Any        =max_position_embeddings
   lowerCamelCase__:				Optional[int]        =sinusoidal_pos_embds
   lowerCamelCase__:				str        =n_layers
   lowerCamelCase__:				str        =n_heads
   lowerCamelCase__:				str        =dim
   lowerCamelCase__:				Optional[Any]        =hidden_dim
   lowerCamelCase__:				Dict        =dropout
   lowerCamelCase__:				Optional[Any]        =attention_dropout
   lowerCamelCase__:				int        =activation
   lowerCamelCase__:				Dict        =initializer_range
   lowerCamelCase__:				Optional[Any]        =qa_dropout
   lowerCamelCase__:				int        =seq_classif_dropout
   super().__init__(**UpperCAmelCase_	,			pad_token_id=UpperCAmelCase_)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->Mapping[str, Mapping[int, str]]:



   '''simple docstring'''



   if self.task == "multiple-choice":
     lowerCamelCase__:				Dict        ={0: "batch", 1: "choice", 2: "sequence"}
   else:
     lowerCamelCase__:				Optional[int]        ={0: "batch", 1: "sequence"}
   return OrderedDict(
       [
           ("input_ids", dynamic_axis),
           ("attention_mask", dynamic_axis),
       ])

