





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


@add_end_docstrings(_UpperCamelCase      )
class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	def __init__(						self:						List[str],					**lowerCamelCase_:						Dict			):
			super().__init__(**lowerCamelCase_			)

			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[int],					lowerCamelCase_:						Union[np.ndarray, bytes, str],					**lowerCamelCase_:						Dict			):
			return super().__call__(lowerCamelCase_,					**lowerCamelCase_			)

	def    snake_case__(						self:						Optional[Any],					**lowerCamelCase_:						List[str]			):
			lowercase__					:      Optional[Any]      =		{}
			if "candidate_labels" in kwargs:
					lowercase__					:      List[Any]      =		kwargs['candidate_labels']
			if "hypothesis_template" in kwargs:
					lowercase__					:      Optional[int]      =		kwargs['hypothesis_template']

			return preprocess_params, {}, {}

	def    snake_case__(						self:						Union[str, Any],					lowerCamelCase_:						Tuple,					lowerCamelCase_:						str=None,					lowerCamelCase_:						int="This is a sound of {}."			):
			if isinstance(lowerCamelCase_,					lowerCamelCase_			):
					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
							lowercase__					:      Union[str, Any]      =		requests.get(lowerCamelCase_			).content
					else:
							with open(lowerCamelCase_,					'rb'			) as f:
									lowercase__					:      int      =		f.read()

			if isinstance(lowerCamelCase_,					lowerCamelCase_			):
					lowercase__					:      Optional[Any]      =		ffmpeg_read(lowerCamelCase_,					self.feature_extractor.sampling_rate			)

			if not isinstance(lowerCamelCase_,					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'			)

			lowercase__					:      str      =		self.feature_extractor(
			    [audio],					sampling_rate=self.feature_extractor.sampling_rate,					return_tensors='pt'			)
			lowercase__					:      Optional[Any]      =		candidate_labels
			lowercase__					:      List[Any]      =		[hypothesis_template.format(lowerCamelCase_			) for x in candidate_labels]
			lowercase__					:      Tuple      =		self.tokenizer(lowerCamelCase_,					return_tensors=self.framework,					padding=lowerCamelCase_			)
			lowercase__					:      Tuple      =		[text_inputs]
			return inputs

	def    snake_case__(						self:						List[str],					lowerCamelCase_:						Union[str, Any]			):
			lowercase__					:      str      =		model_inputs.pop('candidate_labels'			)
			lowercase__					:      Any      =		model_inputs.pop('text_inputs'			)
			if isinstance(text_inputs[0],					lowerCamelCase_			):
					lowercase__					:      Tuple      =		text_inputs[0]
			else:
					# Batching case.
					lowercase__					:      int      =		text_inputs[0][0]

			lowercase__					:      Dict      =		self.model(**lowerCamelCase_,					**lowerCamelCase_			)

			lowercase__					:      Tuple      =		{
			    'candidate_labels': candidate_labels,
			    'logits': outputs.logits_per_audio,
			}
			return model_outputs





	def    snake_case__(						self:						Tuple,					lowerCamelCase_:						int			):
			lowercase__					:      Any      =		model_outputs.pop('candidate_labels'			)
			lowercase__					:      List[Any]      =		model_outputs['logits'][0]

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

			lowercase__					:      Any      =		[
			    {'score': score, 'label': candidate_label}
			    for score, candidate_label in sorted(zip(lowerCamelCase_,					lowerCamelCase_			),					key=lambda lowerCamelCase_			: -x[0]			)
			]
			return result









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


__UpperCamelCase:	List[Any] = logging.get_logger(__name__)

__UpperCamelCase:	Dict = {
    """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""",
    """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""",
}


class       __lowerCAmelCase					(       _UpperCamelCase      ):


	'''simple docstring'''





	_A													=				"luke"

	def __init__(						self:						Union[str, Any],					lowerCamelCase_:						str=50267,					lowerCamelCase_:						Dict=500000,					lowerCamelCase_:						Union[str, Any]=768,					lowerCamelCase_:						Dict=256,					lowerCamelCase_:						int=12,					lowerCamelCase_:						Union[str, Any]=12,					lowerCamelCase_:						str=3072,					lowerCamelCase_:						List[Any]="gelu",					lowerCamelCase_:						int=0.1,					lowerCamelCase_:						Optional[Any]=0.1,					lowerCamelCase_:						Any=512,					lowerCamelCase_:						List[str]=2,					lowerCamelCase_:						str=0.0_2,					lowerCamelCase_:						Union[str, Any]=1E-12,					lowerCamelCase_:						List[Any]=True,					lowerCamelCase_:						List[Any]=None,					lowerCamelCase_:						Optional[Any]=1,					lowerCamelCase_:						Dict=0,					lowerCamelCase_:						List[Any]=2,					**lowerCamelCase_:						Optional[Any],					):
			super().__init__(pad_token_id=lowerCamelCase_,					bos_token_id=lowerCamelCase_,					eos_token_id=lowerCamelCase_,					**lowerCamelCase_			)

			lowercase__					:      Tuple      =		vocab_size
			lowercase__					:      Any      =		entity_vocab_size
			lowercase__					:      Tuple      =		hidden_size
			lowercase__					:      List[str]      =		entity_emb_size
			lowercase__					:      Tuple      =		num_hidden_layers
			lowercase__					:      Optional[Any]      =		num_attention_heads
			lowercase__					:      Dict      =		hidden_act
			lowercase__					:      Optional[int]      =		intermediate_size
			lowercase__					:      List[str]      =		hidden_dropout_prob
			lowercase__					:      Dict      =		attention_probs_dropout_prob
			lowercase__					:      Union[str, Any]      =		max_position_embeddings
			lowercase__					:      int      =		type_vocab_size
			lowercase__					:      Optional[Any]      =		initializer_range
			lowercase__					:      Dict      =		layer_norm_eps
			lowercase__					:      List[Any]      =		use_entity_aware_attention
			lowercase__					:      Optional[Any]      =		classifier_dropout


