

"""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(lowercase       )
class  _lowerCAmelCase  (     lowercase       ):







 """simple docstring"""







 def __init__(      self							:      List[Any], **UpperCAmelCase__							:      Dict     ):
    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							:      List[str], UpperCAmelCase__							:      Union[np.ndarray, bytes, str], **UpperCAmelCase__							:      List[Any]     ):
    return super().__call__(UpperCAmelCase__, **UpperCAmelCase__     )


 def  _lowercase			(      self							:      List[Any], **UpperCAmelCase__							:      Optional[int]     ):
    __lowercase								=						{}
    if "candidate_labels" in kwargs:
       __lowercase								=						kwargs["candidate_labels"]
    if "hypothesis_template" in kwargs:
       __lowercase								=						kwargs["hypothesis_template"]

    return preprocess_params, {}, {}


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

    if isinstance(UpperCAmelCase__, UpperCAmelCase__     ):
       __lowercase								=						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"     )

    __lowercase								=						self.feature_extractor(
        [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"     )
    __lowercase								=						candidate_labels
    __lowercase								=						[hypothesis_template.format(UpperCAmelCase__     ) for x in candidate_labels]
    __lowercase								=						self.tokenizer(UpperCAmelCase__, return_tensors=self.framework, padding=UpperCAmelCase__     )
    __lowercase								=						[text_inputs]
    return inputs


 def  _lowercase			(      self							:      List[Any], UpperCAmelCase__							:      Optional[Any]     ):
    __lowercase								=						model_inputs.pop("candidate_labels"     )
    __lowercase								=						model_inputs.pop("text_inputs"     )
    if isinstance(text_inputs[0], UpperCAmelCase__     ):
       __lowercase								=						text_inputs[0]
    else:
       # Batching case.
       __lowercase								=						text_inputs[0][0]

    __lowercase								=						self.model(**UpperCAmelCase__, **UpperCAmelCase__     )

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



 def  _lowercase			(      self							:      Dict, UpperCAmelCase__							:      Tuple     ):
    __lowercase								=						model_outputs.pop("candidate_labels"     )
    __lowercase								=						model_outputs["logits"][0]

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

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







"""simple docstring"""





from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a							=							logging.get_logger(__name__)

_a							=							{
    'MIT/ast-finetuned-audioset-10-10-0.4593': (
        'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json'
    ),
}




class  _lowerCAmelCase  (     lowercase       ):







 """simple docstring"""







 __UpperCAmelCase     : Any       		=     "audio-spectrogram-transformer"


 def __init__(      self							:      Optional[Any], UpperCAmelCase__							:      Dict=7_6_8, UpperCAmelCase__							:      Optional[Any]=1_2, UpperCAmelCase__							:      Optional[int]=1_2, UpperCAmelCase__							:      List[str]=3_0_7_2, UpperCAmelCase__							:      List[str]="gelu", UpperCAmelCase__							:      Dict=0.0, UpperCAmelCase__							:      str=0.0, UpperCAmelCase__							:      Any=0.02, UpperCAmelCase__							:      Any=1E-12, UpperCAmelCase__							:      Dict=1_6, UpperCAmelCase__							:      Optional[int]=True, UpperCAmelCase__							:      Union[str, Any]=1_0, UpperCAmelCase__							:      List[Any]=1_0, UpperCAmelCase__							:      Optional[int]=1_0_2_4, UpperCAmelCase__							:      List[str]=1_2_8, **UpperCAmelCase__							:      List[Any], ):
    super().__init__(**UpperCAmelCase__     )

    __lowercase								=						hidden_size
    __lowercase								=						num_hidden_layers
    __lowercase								=						num_attention_heads
    __lowercase								=						intermediate_size
    __lowercase								=						hidden_act
    __lowercase								=						hidden_dropout_prob
    __lowercase								=						attention_probs_dropout_prob
    __lowercase								=						initializer_range
    __lowercase								=						layer_norm_eps
    __lowercase								=						patch_size
    __lowercase								=						qkv_bias
    __lowercase								=						frequency_stride
    __lowercase								=						time_stride
    __lowercase								=						max_length
    __lowercase								=						num_mel_bins




