


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


__UpperCamelCase    		=       logging.get_logger(__name__)







@add_end_docstrings(UpperCAmelCase      )
class        lowerCamelCase__	(							UpperCAmelCase      ):






   """simple docstring"""






   def __init__(							self      ,						**snake_case     ):

      '''simple docstring'''


      super().__init__(**snake_case     )

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




   def __call__(							self      ,						snake_case      ,						**snake_case     ):

      '''simple docstring'''


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




   def 				snake_case__				(							self      ,						**snake_case     ):

      '''simple docstring'''


      UpperCamelCase__					=       {}
      if "candidate_labels" in kwargs:
         UpperCamelCase__					=       kwargs["candidate_labels"]
      if "hypothesis_template" in kwargs:
         UpperCamelCase__					=       kwargs["hypothesis_template"]

      return preprocess_params, {}, {}




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

      '''simple docstring'''


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

      if isinstance(snake_case      ,						snake_case     ):
         UpperCamelCase__					=       ffmpeg_read(snake_case      ,						self.feature_extractor.sampling_rate     )

      if not isinstance(snake_case      ,						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__					=       self.feature_extractor(
          [audio]      ,						sampling_rate=self.feature_extractor.sampling_rate      ,						return_tensors="pt"     )
      UpperCamelCase__					=       candidate_labels
      UpperCamelCase__					=       [hypothesis_template.format(snake_case     ) for x in candidate_labels]
      UpperCamelCase__					=       self.tokenizer(snake_case      ,						return_tensors=self.framework      ,						padding=snake_case     )
      UpperCamelCase__					=       [text_inputs]
      return inputs




   def 				snake_case__				(							self      ,						snake_case     ):

      '''simple docstring'''


      UpperCamelCase__					=       model_inputs.pop("candidate_labels"     )
      UpperCamelCase__					=       model_inputs.pop("text_inputs"     )
      if isinstance(text_inputs[0]      ,						snake_case     ):
         UpperCamelCase__					=       text_inputs[0]
      else:
         # Batching case.
         UpperCamelCase__					=       text_inputs[0][0]

      UpperCamelCase__					=       self.model(**snake_case      ,						**snake_case     )

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







   def 				snake_case__				(							self      ,						snake_case     ):

      '''simple docstring'''


      UpperCamelCase__					=       model_outputs.pop("candidate_labels"     )
      UpperCamelCase__					=       model_outputs["logits"][0]

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

      UpperCamelCase__					=       [
          {"score": score, "label": candidate_label}
          for score, candidate_label in sorted(zip(snake_case      ,						snake_case     )      ,						key=lambda snake_case     : -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


__UpperCamelCase    		=       logging.get_logger(__name__)

__UpperCamelCase    		=       {
    'kssteven/ibert-roberta-base': 'https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json',
    'kssteven/ibert-roberta-large': 'https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json',
    'kssteven/ibert-roberta-large-mnli': (
        'https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json'
    ),
}







class        lowerCamelCase__	(							UpperCAmelCase      ):






			"""simple docstring"""






			_UpperCamelCase		:					Any    =		'ibert'




			def __init__(							self      ,						snake_case=30522      ,						snake_case=768      ,						snake_case=12      ,						snake_case=12      ,						snake_case=3072      ,						snake_case="gelu"      ,						snake_case=0.1      ,						snake_case=0.1      ,						snake_case=512      ,						snake_case=2      ,						snake_case=0.02      ,						snake_case=1E-1_2      ,						snake_case=1      ,						snake_case=0      ,						snake_case=2      ,						snake_case="absolute"      ,						snake_case=False      ,						snake_case="none"      ,						**snake_case      ,						):

						'''simple docstring'''


						super().__init__(pad_token_id=snake_case      ,						bos_token_id=snake_case      ,						eos_token_id=snake_case      ,						**snake_case     )

						UpperCamelCase__					=       vocab_size
						UpperCamelCase__					=       hidden_size
						UpperCamelCase__					=       num_hidden_layers
						UpperCamelCase__					=       num_attention_heads
						UpperCamelCase__					=       hidden_act
						UpperCamelCase__					=       intermediate_size
						UpperCamelCase__					=       hidden_dropout_prob
						UpperCamelCase__					=       attention_probs_dropout_prob
						UpperCamelCase__					=       max_position_embeddings
						UpperCamelCase__					=       type_vocab_size
						UpperCamelCase__					=       initializer_range
						UpperCamelCase__					=       layer_norm_eps
						UpperCamelCase__					=       position_embedding_type
						UpperCamelCase__					=       quant_mode
						UpperCamelCase__					=       force_dequant







class        lowerCamelCase__	(							UpperCAmelCase      ):






			"""simple docstring"""






			@property
			def 				snake_case__				(							self     ):

						'''simple docstring'''


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


