




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


lowercase__				:      Optional[Any]	   = logging.get_logger(__name__)




@add_end_docstrings(_lowerCAmelCase				)
class       a__	( _lowerCAmelCase				):







     def __init__(     self  ,		**A			)  ->   str:



          '''simple docstring'''



          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  ,		A  ,		**A			)  ->   Optional[int]:



          '''simple docstring'''



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







     def       lowerCAmelCase_    (     self  ,		**A			)  ->   Union[str, Any]:



          '''simple docstring'''



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

          return preprocess_params, {}, {}







     def       lowerCAmelCase_    (     self  ,		A  ,		A=None  ,		A="This is a sound of {}."			)  ->   Optional[int]:



          '''simple docstring'''



          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       lowerCAmelCase_    (     self  ,		A			)  ->   List[str]:



          '''simple docstring'''



          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       lowerCAmelCase_    (     self  ,		A			)  ->   Union[str, Any]:



          '''simple docstring'''



          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 A			: -x[0]			)
          ]
          return result







import functools
import operator

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


lowercase__				:      Any	   = logging.get_logger(__name__)

lowercase__				:      int	   = {
    "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}




class       a__	( UpperCamelCase__				):
     a		:      Optional[Any]		 =     """sew-d"""







     def __init__(     self  ,		A=32  ,		A=768  ,		A=12  ,		A=12  ,		A=3072  ,		A=2  ,		A=512  ,		A=256  ,		A=True  ,		A=True  ,		A=("p2c", "c2p")  ,		A="layer_norm"  ,		A="gelu_python"  ,		A=0.1  ,		A=0.1  ,		A=0.1  ,		A=0.0  ,		A=0.1  ,		A=0.0_2  ,		A=1e-7  ,		A=1e-5  ,		A="group"  ,		A="gelu"  ,		A=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)  ,		A=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)  ,		A=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)  ,		A=False  ,		A=128  ,		A=16  ,		A=True  ,		A=0.0_5  ,		A=10  ,		A=2  ,		A=0.0  ,		A=10  ,		A=0  ,		A="mean"  ,		A=False  ,		A=False  ,		A=256  ,		A=0  ,		A=1  ,		A=2  ,		**A  ,		)  ->   Dict:



          '''simple docstring'''



          super().__init__(**A  ,		pad_token_id=A  ,		bos_token_id=A  ,		eos_token_id=A			)
          a     =				hidden_size
          a     =				feat_extract_norm
          a     =				feat_extract_activation
          a     =				list(A			)
          a     =				list(A			)
          a     =				list(A			)
          a     =				conv_bias
          a     =				num_conv_pos_embeddings
          a     =				num_conv_pos_embedding_groups
          a     =				len(self.conv_dim			)
          a     =				num_hidden_layers
          a     =				intermediate_size
          a     =				squeeze_factor
          a     =				max_position_embeddings
          a     =				position_buckets
          a     =				share_att_key
          a     =				relative_attention
          a     =				norm_rel_ebd
          a     =				list(A			)
          a     =				hidden_act
          a     =				num_attention_heads
          a     =				hidden_dropout
          a     =				attention_dropout
          a     =				activation_dropout
          a     =				feat_proj_dropout
          a     =				final_dropout
          a     =				layer_norm_eps
          a     =				feature_layer_norm_eps
          a     =				initializer_range
          a     =				vocab_size

          if (
              (len(self.conv_stride			) != self.num_feat_extract_layers)
              or (len(self.conv_kernel			) != self.num_feat_extract_layers)
              or (len(self.conv_dim			) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   "Configuration for convolutional layers is incorrect."
                   "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"
                   F'''but is `len(config.conv_dim) = {len(self.conv_dim			)}`, `len(config.conv_stride)'''
                   F'''= {len(self.conv_stride			)}`, `len(config.conv_kernel) = {len(self.conv_kernel			)}`.'''			)

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          a     =				apply_spec_augment
          a     =				mask_time_prob
          a     =				mask_time_length
          a     =				mask_time_min_masks
          a     =				mask_feature_prob
          a     =				mask_feature_length
          a     =				mask_feature_min_masks

          # ctc loss
          a     =				ctc_loss_reduction
          a     =				ctc_zero_infinity

          # sequence classification
          a     =				use_weighted_layer_sum
          a     =				classifier_proj_size







     @property
     def       lowerCAmelCase_    (     self			)  ->   List[str]:



          '''simple docstring'''



          return functools.reduce(operator.mul  ,		self.conv_stride  ,		1			)

