





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


__lowerCAmelCase				:      Any						      =logging.get_logger(__name__)






@add_end_docstrings(UpperCamelCase__							)
class   UpperCAmelCase      (			UpperCamelCase__							):
 def __init__(							self :List[Any]		,			**lowercase_ :Tuple				)->				str:
     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 :Optional[Any]		,			lowercase_ :Union[np.ndarray, bytes, str]		,			**lowercase_ :Optional[Any]				)->				Union[str, Any]:
     return super().__call__(lowercase_		,			**lowercase_				)
 def 	UpperCAmelCase_				(							self :int		,			**lowercase_ :str				)->				str:
     A__							=     {}
     if "candidate_labels" in kwargs:
         A__							=     kwargs["candidate_labels"]
     if "hypothesis_template" in kwargs:
         A__							=     kwargs["hypothesis_template"]

     return preprocess_params, {}, {}
 def 	UpperCAmelCase_				(							self :Optional[int]		,			lowercase_ :Any		,			lowercase_ :Any=None		,			lowercase_ :str="This is a sound of {}."				)->				Any:
     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
             A__							=     requests.get(lowercase_				).content
         else:
             with open(lowercase_		,			"rb"				) as f:
                 A__							=     f.read()

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

     A__							=     self.feature_extractor(
         [audio]		,			sampling_rate=self.feature_extractor.sampling_rate		,			return_tensors="pt"				)
     A__							=     candidate_labels
     A__							=     [hypothesis_template.format(lowercase_				) for x in candidate_labels]
     A__							=     self.tokenizer(lowercase_		,			return_tensors=self.framework		,			padding=lowercase_				)
     A__							=     [text_inputs]
     return inputs
 def 	UpperCAmelCase_				(							self :Dict		,			lowercase_ :List[str]				)->				List[str]:
     A__							=     model_inputs.pop("candidate_labels"				)
     A__							=     model_inputs.pop("text_inputs"				)
     if isinstance(text_inputs[0]		,			lowercase_				):
         A__							=     text_inputs[0]
     else:
         # Batching case.
         A__							=     text_inputs[0][0]

     A__							=     self.model(**lowercase_		,			**lowercase_				)

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



 def 	UpperCAmelCase_				(							self :Union[str, Any]		,			lowercase_ :Dict				)->				List[str]:
     A__							=     model_outputs.pop("candidate_labels"				)
     A__							=     model_outputs["logits"][0]

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

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










'''simple docstring'''

# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__lowerCAmelCase				:      Union[str, Any]						      ={"configuration_mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"]}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __lowerCAmelCase				:      int						      =[
      "MRA_PRETRAINED_MODEL_ARCHIVE_LIST",
      "MraForMaskedLM",
      "MraForMultipleChoice",
      "MraForQuestionAnswering",
      "MraForSequenceClassification",
      "MraForTokenClassification",
      "MraLayer",
      "MraModel",
      "MraPreTrainedModel",
  ]


if TYPE_CHECKING:
  from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_mra import (
        MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
        MraForMaskedLM,
        MraForMultipleChoice,
        MraForQuestionAnswering,
        MraForSequenceClassification,
        MraForTokenClassification,
        MraLayer,
        MraModel,
        MraPreTrainedModel,
    )
else:
  import sys

  __lowerCAmelCase				:      Dict						      =_LazyModule(__name__, globals()["__file__"], _import_structure)



