





'''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_   :       str       =     logging.get_logger(__name__)
@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class 							__SCREAMING_SNAKE_CASE    (SCREAMING_SNAKE_CASE__ ):






				"""simple docstring"""







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




				def     UpperCamelCase__  (    self	:   List[Any]   ,							**__a	:   Any   ):
								_a				      =					{}
								if "candidate_labels" in kwargs:
												_a				      =					kwargs["candidate_labels"]
								if "hypothesis_template" in kwargs:
												_a				      =					kwargs["hypothesis_template"]

								return preprocess_params, {}, {}




				def     UpperCamelCase__  (    self	:   List[Any]   ,							__a	:   List[Any]   ,							__a	:   List[Any]=None   ,							__a	:   List[Any]="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				      =					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     UpperCamelCase__  (    self	:   Any   ,							__a	:   Optional[int]   ):
								_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     UpperCamelCase__  (    self	:   Optional[int]   ,							__a	:   Union[str, Any]   ):
								_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





"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


A		=						{'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']}

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						['ViTFeatureExtractor']
			A		=						['ViTImageProcessor']

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'VIT_PRETRAINED_MODEL_ARCHIVE_LIST',
			    'ViTForImageClassification',
			    'ViTForMaskedImageModeling',
			    'ViTModel',
			    'ViTPreTrainedModel',
			]

try:
			if not is_tf_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'TFViTForImageClassification',
			    'TFViTModel',
			    'TFViTPreTrainedModel',
			]

try:
			if not is_flax_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'FlaxViTForImageClassification',
			    'FlaxViTModel',
			    'FlaxViTPreTrainedModel',
			]

if TYPE_CHECKING:
			from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .feature_extraction_vit import ViTFeatureExtractor
						from .image_processing_vit import ViTImageProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_vit import (
						    VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    ViTForImageClassification,
						    ViTForMaskedImageModeling,
						    ViTModel,
						    ViTPreTrainedModel,
						)

			try:
						if not is_tf_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel

			try:
						if not is_flax_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel


else:
			import sys

			A		=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



