
'''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			      =      logging.get_logger(__name__)




@add_end_docstrings(a__)
class     __snake_case		(   a__):
					def __init__(     self,    **A      ):

									"""simple docstring"""


									super().__init__(**A      )

									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      ):

									"""simple docstring"""


									return super().__call__(A,    **A      )
					def     UpperCAmelCase_							(     self,    **A      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[Any]									= {}
									if "candidate_labels" in kwargs:
													lowerCamelCase					:			int									= kwargs['candidate_labels']
									if "hypothesis_template" in kwargs:
													lowerCamelCase					:			str									= kwargs['hypothesis_template']

									return preprocess_params, {}, {}
					def     UpperCAmelCase_							(     self,    A,    A=None,    A="This is a sound of {}."      ):

									"""simple docstring"""


									if isinstance(A,    A      ):
													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					:			List[Any]									= requests.get(A      ).content
													else:
																	with open(A,    'rb'      ) as f:
																					lowerCamelCase					:			Dict									= f.read()

									if isinstance(A,    A      ):
													lowerCamelCase					:			List[str]									= ffmpeg_read(A,    self.feature_extractor.sampling_rate      )

									if not isinstance(A,    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					:			List[str]									= self.feature_extractor(
									    [audio],    sampling_rate=self.feature_extractor.sampling_rate,    return_tensors='pt'      )
									lowerCamelCase					:			str									= candidate_labels
									lowerCamelCase					:			Tuple									= [hypothesis_template.format(A      ) for x in candidate_labels]
									lowerCamelCase					:			str									= self.tokenizer(A,    return_tensors=self.framework,    padding=A      )
									lowerCamelCase					:			Union[str, Any]									= [text_inputs]
									return inputs
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			List[Any]									= model_inputs.pop('candidate_labels'      )
									lowerCamelCase					:			List[str]									= model_inputs.pop('text_inputs'      )
									if isinstance(text_inputs[0],    A      ):
													lowerCamelCase					:			Optional[int]									= text_inputs[0]
									else:
													# Batching case.
													lowerCamelCase					:			Dict									= text_inputs[0][0]

									lowerCamelCase					:			Union[str, Any]									= self.model(**A,    **A      )

									lowerCamelCase					:			str									= {
									    'candidate_labels': candidate_labels,
									    'logits': outputs.logits_per_audio,
									}
									return model_outputs




					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			str									= model_outputs.pop('candidate_labels'      )
									lowerCamelCase					:			Tuple									= model_outputs['logits'][0]

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

									lowerCamelCase					:			List[str]									= [
									    {'score': score, 'label': candidate_label}
									    for score, candidate_label in sorted(zip(A,    A      ),    key=lambda A      : -x[0]      )
									]
									return result


'''simple docstring'''






import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

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


A			      =      logging.get_logger(__name__)

A			      =      {
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}




class     __snake_case		(   a__):
					_lowerCAmelCase			     =	'''segformer'''
					def __init__(     self,    A=3,    A=4,    A=[2, 2, 2, 2],    A=[8, 4, 2, 1],    A=[32, 64, 160, 256],    A=[7, 3, 3, 3],    A=[4, 2, 2, 2],    A=[1, 2, 5, 8],    A=[4, 4, 4, 4],    A="gelu",    A=0.0,    A=0.0,    A=0.1,    A=0.02,    A=0.1,    A=1e-6,    A=256,    A=255,    **A,    ):

									"""simple docstring"""


									super().__init__(**A      )

									if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
													warnings.warn(
													    'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
													    ' removed, as the behaviour will default to that of reshape_last_stage = True.',    A,    )

									lowerCamelCase					:			Tuple									= num_channels
									lowerCamelCase					:			Dict									= num_encoder_blocks
									lowerCamelCase					:			Dict									= depths
									lowerCamelCase					:			Any									= sr_ratios
									lowerCamelCase					:			List[Any]									= hidden_sizes
									lowerCamelCase					:			List[Any]									= patch_sizes
									lowerCamelCase					:			Tuple									= strides
									lowerCamelCase					:			int									= mlp_ratios
									lowerCamelCase					:			Dict									= num_attention_heads
									lowerCamelCase					:			Union[str, Any]									= hidden_act
									lowerCamelCase					:			Tuple									= hidden_dropout_prob
									lowerCamelCase					:			Optional[int]									= attention_probs_dropout_prob
									lowerCamelCase					:			List[str]									= classifier_dropout_prob
									lowerCamelCase					:			Union[str, Any]									= initializer_range
									lowerCamelCase					:			Union[str, Any]									= drop_path_rate
									lowerCamelCase					:			int									= layer_norm_eps
									lowerCamelCase					:			Any									= decoder_hidden_size
									lowerCamelCase					:			Optional[int]									= kwargs.get('reshape_last_stage',    A      )
									lowerCamelCase					:			Any									= semantic_loss_ignore_index





class     __snake_case		(   a__):
					_lowerCAmelCase			     =	version.parse('''1.11''')
					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return OrderedDict(
									    [
									        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
									    ]      )
					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return 1e-4




					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return 12
