



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


__lowerCamelCase         = logging.get_logger(__name__)


@add_end_docstrings(_a  )
class   snake_case_ (_a  ):




       """simple docstring"""






       def __init__(     self     ,**lowercase):

             """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     ,lowercase     ,**lowercase):

             """simple docstring"""





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



       def  A_   (     self     ,**lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		{}
             if "candidate_labels" in kwargs:
                   UpperCAmelCase_  :	Optional[int]				      =		kwargs["candidate_labels"]
             if "hypothesis_template" in kwargs:
                   UpperCAmelCase_  :	Tuple				      =		kwargs["hypothesis_template"]

             return preprocess_params, {}, {}



       def  A_   (     self     ,lowercase     ,lowercase=None     ,lowercase="This is a sound of {}."):

             """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_  :	Union[str, Any]				      =		f.read()

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



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		model_inputs.pop("candidate_labels")
             UpperCAmelCase_  :	Dict				      =		model_inputs.pop("text_inputs")
             if isinstance(text_inputs[0]     ,_A):
                   UpperCAmelCase_  :	Any				      =		text_inputs[0]
             else:
                   # Batching case.
                   UpperCAmelCase_  :	Dict				      =		text_inputs[0][0]

             UpperCAmelCase_  :	Optional[Any]				      =		self.model(**_A     ,**_A)

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



       def  A_   (     self     ,lowercase):

             """simple docstring"""





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

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

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





from typing import Mapping

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


__lowerCamelCase         =			logging.get_logger(__name__)

__lowerCamelCase         =			{
    '''google/umt5-small''': '''https://huggingface.co/google/umt5-small/resolve/main/config.json''',
    # See all umt5 models at https://huggingface.co/models?filter=umt5
}


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       _lowerCamelCase			    =				"""umt5"""
       _lowerCamelCase			    =				["""past_key_values"""]



       def __init__(     self     ,lowercase=250112     ,lowercase=512     ,lowercase=64     ,lowercase=1024     ,lowercase=8     ,lowercase=None     ,lowercase=6     ,lowercase=32     ,lowercase=128     ,lowercase=0.1     ,lowercase=1E-6     ,lowercase=1.0     ,lowercase="gated-gelu"     ,lowercase=True     ,lowercase=True     ,lowercase="T5Tokenizer"     ,lowercase=True     ,lowercase=0     ,lowercase=1     ,lowercase=0     ,**lowercase     ,):

             """simple docstring"""





             super().__init__(
                 is_encoder_decoder=lowercase     ,tokenizer_class=lowercase     ,tie_word_embeddings=lowercase     ,pad_token_id=lowercase     ,eos_token_id=lowercase     ,decoder_start_token_id=lowercase     ,**lowercase     ,)
             UpperCAmelCase_  :	Optional[int]				      =		vocab_size
             UpperCAmelCase_  :	Any				      =		d_model
             UpperCAmelCase_  :	Any				      =		d_kv
             UpperCAmelCase_  :	int				      =		d_ff
             UpperCAmelCase_  :	Tuple				      =		num_layers
             UpperCAmelCase_  :	int				      =		(
                 num_decoder_layers if num_decoder_layers is not None else self.num_layers
             )  # default = symmetry
             UpperCAmelCase_  :	Optional[int]				      =		num_heads
             UpperCAmelCase_  :	str				      =		relative_attention_num_buckets
             UpperCAmelCase_  :	Any				      =		relative_attention_max_distance
             UpperCAmelCase_  :	Optional[Any]				      =		dropout_rate
             UpperCAmelCase_  :	Union[str, Any]				      =		layer_norm_epsilon
             UpperCAmelCase_  :	Optional[Any]				      =		initializer_factor
             UpperCAmelCase_  :	int				      =		feed_forward_proj
             UpperCAmelCase_  :	str				      =		use_cache

             UpperCAmelCase_  :	List[str]				      =		self.feed_forward_proj.split("-")
             UpperCAmelCase_  :	Any				      =		act_info[-1]
             UpperCAmelCase_  :	Optional[int]				      =		act_info[0] == "gated"

             if len(lowercase) > 1 and act_info[0] != "gated" or len(lowercase) > 2:
                   raise ValueError(
                       F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
                       "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
                       "'gated-gelu' or 'relu'")

             if feed_forward_proj == "gated-gelu":
                   UpperCAmelCase_  :	Tuple				      =		"gelu_new"



       @property
       def  A_   (     self):

             """simple docstring"""





             return self.d_model



       @property
       def  A_   (     self):

             """simple docstring"""





             return self.num_heads



       @property
       def  A_   (     self):

             """simple docstring"""





             return self.num_layers


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       @property
       # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		{
                 "input_ids": {0: "batch", 1: "encoder_sequence"},
                 "attention_mask": {0: "batch", 1: "encoder_sequence"},
             }
             if self.use_past:
                   UpperCAmelCase_  :	Union[str, Any]				      =		"past_encoder_sequence + sequence"
                   UpperCAmelCase_  :	Optional[int]				      =		{0: "batch"}
                   UpperCAmelCase_  :	Union[str, Any]				      =		{0: "batch", 1: "past_decoder_sequence + sequence"}
             else:
                   UpperCAmelCase_  :	Optional[int]				      =		{0: "batch", 1: "decoder_sequence"}
                   UpperCAmelCase_  :	Dict				      =		{0: "batch", 1: "decoder_sequence"}

             if self.use_past:
                   self.fill_with_past_key_values_(lowercase     ,direction="inputs")

             return common_inputs



       @property
       # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
       def  A_   (     self):

             """simple docstring"""





             return 13



       @property
       def  A_   (     self):

             """simple docstring"""





             return 5E-4
