






'''simple docstring'''







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_A     :      Union[str, Any]   					=logging.get_logger(__name__)

_A     :      List[str]   					={
    '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''',
    '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''',
    '''junnyu/roformer_chinese_char_small''': (
        '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json'''
    ),
    '''junnyu/roformer_chinese_char_base''': (
        '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json'''
    ),
    '''junnyu/roformer_small_discriminator''': (
        '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json'''
    ),
    '''junnyu/roformer_small_generator''': (
        '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json'''
    ),
    # See all RoFormer models at https://huggingface.co/models?filter=roformer
}

class _lowercase     (    _lowercase		):
							a    				=	"""roformer"""




							def __init__(							self:    Tuple      ,							UpperCamelCase__:    Optional[Any]=50_000      ,							UpperCamelCase__:    List[str]=None      ,							UpperCamelCase__:    List[Any]=768      ,							UpperCamelCase__:    Optional[int]=12      ,							UpperCamelCase__:    Optional[int]=12      ,							UpperCamelCase__:    List[str]=3_072      ,							UpperCamelCase__:    Dict="gelu"      ,							UpperCamelCase__:    int=0.1      ,							UpperCamelCase__:    List[Any]=0.1      ,							UpperCamelCase__:    Optional[int]=1_536      ,							UpperCamelCase__:    int=2      ,							UpperCamelCase__:    Tuple=0.02      ,							UpperCamelCase__:    List[Any]=1e-12      ,							UpperCamelCase__:    Optional[Any]=0      ,							UpperCamelCase__:    List[Any]=False      ,							UpperCamelCase__:    Dict=True      ,							**UpperCamelCase__:    List[Any]      ,							):
														super().__init__(pad_token_id=UpperCamelCase__      ,							**UpperCamelCase__					)

														lowerCamelCase__ :     int	  =	vocab_size
														lowerCamelCase__ :     Dict	  =	hidden_size if embedding_size is None else embedding_size
														lowerCamelCase__ :     List[Any]	  =	hidden_size
														lowerCamelCase__ :     Any	  =	num_hidden_layers
														lowerCamelCase__ :     List[Any]	  =	num_attention_heads
														lowerCamelCase__ :     Optional[int]	  =	hidden_act
														lowerCamelCase__ :     int	  =	intermediate_size
														lowerCamelCase__ :     Dict	  =	hidden_dropout_prob
														lowerCamelCase__ :     Any	  =	attention_probs_dropout_prob
														lowerCamelCase__ :     Optional[int]	  =	max_position_embeddings
														lowerCamelCase__ :     Optional[Any]	  =	type_vocab_size
														lowerCamelCase__ :     Union[str, Any]	  =	initializer_range
														lowerCamelCase__ :     Optional[int]	  =	layer_norm_eps
														lowerCamelCase__ :     Tuple	  =	rotary_value
														lowerCamelCase__ :     List[str]	  =	use_cache



class _lowercase     (    _lowercase		):




							@property
							def 		lowerCamelCase_    (							self:    int					):
														if self.task == "multiple-choice":
																					lowerCamelCase__ :     List[Any]	  =	{0: """batch""", 1: """choice""", 2: """sequence"""}
														else:
																					lowerCamelCase__ :     Dict	  =	{0: """batch""", 1: """sequence"""}
														lowerCamelCase__ :     Union[str, Any]	  =	{0: """batch""", 1: """sequence"""}
														return OrderedDict(
														    [
														        ("""input_ids""", dynamic_axis),
														        ("""attention_mask""", dynamic_axis),
														        ("""token_type_ids""", dynamic_axis),
														    ]					)









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

@add_end_docstrings(_lowercase		)
class _lowercase     (    _lowercase		):




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




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							**UpperCamelCase__:    int					):
														lowerCamelCase__ :     Optional[Any]	  =	{}
														if "candidate_labels" in kwargs:
																					lowerCamelCase__ :     str	  =	kwargs["""candidate_labels"""]
														if "hypothesis_template" in kwargs:
																					lowerCamelCase__ :     int	  =	kwargs["""hypothesis_template"""]

														return preprocess_params, {}, {}




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    List[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
																												lowerCamelCase__ :     int	  =	requests.get(UpperCamelCase__					).content
																					else:
																												with open(UpperCamelCase__      ,							"""rb"""					) as f:
																																			lowerCamelCase__ :     Dict	  =	f.read()

														if isinstance(UpperCamelCase__      ,							UpperCamelCase__					):
																					lowerCamelCase__ :     str	  =	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"""					)

														lowerCamelCase__ :     Optional[Any]	  =	self.feature_extractor(
														    [audio]      ,							sampling_rate=self.feature_extractor.sampling_rate      ,							return_tensors="""pt"""					)
														lowerCamelCase__ :     Any	  =	candidate_labels
														lowerCamelCase__ :     Any	  =	[hypothesis_template.format(UpperCamelCase__					) for x in candidate_labels]
														lowerCamelCase__ :     int	  =	self.tokenizer(UpperCamelCase__      ,							return_tensors=self.framework      ,							padding=UpperCamelCase__					)
														lowerCamelCase__ :     Tuple	  =	[text_inputs]
														return inputs




							def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    Union[str, Any]					):
														lowerCamelCase__ :     Any	  =	model_inputs.pop("""candidate_labels"""					)
														lowerCamelCase__ :     Union[str, Any]	  =	model_inputs.pop("""text_inputs"""					)
														if isinstance(text_inputs[0]      ,							UpperCamelCase__					):
																					lowerCamelCase__ :     Optional[int]	  =	text_inputs[0]
														else:
																					# Batching case.
																					lowerCamelCase__ :     Tuple	  =	text_inputs[0][0]

														lowerCamelCase__ :     Tuple	  =	self.model(**UpperCamelCase__      ,							**UpperCamelCase__					)

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




							def 		lowerCamelCase_    (							self:    List[str]      ,							UpperCamelCase__:    Union[str, Any]					):
														lowerCamelCase__ :     List[str]	  =	model_outputs.pop("""candidate_labels"""					)
														lowerCamelCase__ :     int	  =	model_outputs["""logits"""][0]

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

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

