


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


_snake_case     :		Any						=				logging.get_logger(__name__)

_snake_case     :		int						=				{
    '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''',
}

class 				a		(__UpperCAmelCase      ):




							"""simple docstring"""


							__UpperCAmelCase    :							Optional[int]       =  'transfo-xl'
							__UpperCAmelCase    :							Union[str, Any]       =  ['mems']
							__UpperCAmelCase    :							Union[str, Any]       =  {
							    'n_token': 'vocab_size',
							    'hidden_size': 'd_model',
							    'num_attention_heads': 'n_head',
							    'num_hidden_layers': 'n_layer',
							}

							def __init__(							self       :  List[str]    ,	lowerCamelCase       :  Union[str, Any]=267735    ,	lowerCamelCase       :  Any=[20000, 40000, 200000]    ,	lowerCamelCase       :  Optional[Any]=1024    ,	lowerCamelCase       :  int=1024    ,	lowerCamelCase       :  List[Any]=16    ,	lowerCamelCase       :  List[str]=64    ,	lowerCamelCase       :  Optional[int]=4096    ,	lowerCamelCase       :  int=4    ,	lowerCamelCase       :  int=False    ,	lowerCamelCase       :  Optional[Any]=18    ,	lowerCamelCase       :  Tuple=1600    ,	lowerCamelCase       :  Optional[int]=1000    ,	lowerCamelCase       :  List[str]=True    ,	lowerCamelCase       :  Optional[int]=True    ,	lowerCamelCase       :  Tuple=0    ,	lowerCamelCase       :  int=-1    ,	lowerCamelCase       :  Optional[int]=True    ,	lowerCamelCase       :  Any=0.1    ,	lowerCamelCase       :  Dict=0.0    ,	lowerCamelCase       :  Optional[Any]=True    ,	lowerCamelCase       :  Union[str, Any]="normal"    ,	lowerCamelCase       :  List[Any]=0.01    ,	lowerCamelCase       :  Any=0.01    ,	lowerCamelCase       :  Dict=0.02    ,	lowerCamelCase       :  Optional[Any]=1E-5    ,	lowerCamelCase       :  Tuple=0    ,	**lowerCamelCase       :  Union[str, Any]    ,	)	->    Any:
														__snake_case		:			int							 =   vocab_size
														__snake_case		:			int							 =   []
														self.cutoffs.extend(lowerCamelCase				)
														if proj_share_all_but_first:
																					__snake_case		:			Optional[Any]							 =   [False] + [True] * len(self.cutoffs				)
														else:
																					__snake_case		:			List[Any]							 =   [False] + [False] * len(self.cutoffs				)
														__snake_case		:			str							 =   d_model
														__snake_case		:			Optional[Any]							 =   d_embed
														__snake_case		:			List[str]							 =   d_head
														__snake_case		:			Any							 =   d_inner
														__snake_case		:			List[Any]							 =   div_val
														__snake_case		:			Tuple							 =   pre_lnorm
														__snake_case		:			List[Any]							 =   n_layer
														__snake_case		:			List[str]							 =   n_head
														__snake_case		:			List[str]							 =   mem_len
														__snake_case		:			Dict							 =   same_length
														__snake_case		:			List[Any]							 =   attn_type
														__snake_case		:			Optional[int]							 =   clamp_len
														__snake_case		:			int							 =   sample_softmax
														__snake_case		:			List[str]							 =   adaptive
														__snake_case		:			Dict							 =   dropout
														__snake_case		:			int							 =   dropatt
														__snake_case		:			Optional[int]							 =   untie_r
														__snake_case		:			List[Any]							 =   init
														__snake_case		:			int							 =   init_range
														__snake_case		:			Dict							 =   proj_init_std
														__snake_case		:			Optional[int]							 =   init_std
														__snake_case		:			List[str]							 =   layer_norm_epsilon
														super().__init__(eos_token_id=lowerCamelCase    ,	**lowerCamelCase				)

							@property
							def     __snake_case					(							self       :  Tuple				)	->    Tuple:
														# Message copied from Transformer-XL documentation
														logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.'				)
														return -1






							@max_position_embeddings.setter
							def     __snake_case					(							self       :  str    ,	lowerCamelCase       :  List[Any]				)	->    int:
														# Message copied from Transformer-XL documentation
														raise NotImplementedError(
														    F'The model {self.model_type} is one of the few models that has no sequence length limit.'				)






'''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							:Union[str, Any]				    =					logging.get_logger(__name__)







@add_end_docstrings(__UpperCAmelCase )
class 	_lowerCAmelCase							(			__UpperCAmelCase ):


	def __init__(self       ,      **lowercase							):
				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       ,      lowercase       ,      **lowercase							):
				return super().__call__(lowercase       ,      **lowercase							)


	def     _a	(self       ,      **lowercase							):
				A_	:						Tuple	=     {}
				if "candidate_labels" in kwargs:
							A_	:						Dict	=     kwargs["""candidate_labels"""]
				if "hypothesis_template" in kwargs:
							A_	:						Optional[Any]	=     kwargs["""hypothesis_template"""]

				return preprocess_params, {}, {}


	def     _a	(self       ,      lowercase       ,      lowercase=None       ,      lowercase="This is a sound of {}."							):
				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_	:						Dict	=     requests.get(lowercase							).content
							else:
										with open(lowercase       ,      """rb"""							) as f:
													A_	:						List[str]	=     f.read()

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


	def     _a	(self       ,      lowercase							):
				A_	:						Union[str, Any]	=     model_inputs.pop("""candidate_labels"""							)
				A_	:						List[Any]	=     model_inputs.pop("""text_inputs"""							)
				if isinstance(text_inputs[0]       ,      lowercase							):
							A_	:						Union[str, Any]	=     text_inputs[0]
				else:
							# Batching case.
							A_	:						Optional[int]	=     text_inputs[0][0]

				A_	:						str	=     self.model(**lowercase       ,      **lowercase							)

				A_	:						Union[str, Any]	=     {
				    """candidate_labels""": candidate_labels,
				    """logits""": outputs.logits_per_audio,
				}
				return model_outputs


	def     _a	(self       ,      lowercase							):
				A_	:						Union[str, Any]	=     model_outputs.pop("""candidate_labels"""							)
				A_	:						List[Any]	=     model_outputs["""logits"""][0]

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

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