


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(lowercase_      )
class    _lowerCAmelCase			(		lowercase_      ):



				"""simple docstring"""



				def __init__(      self    :    int			,		**UpperCamelCase__    :    Any):






											'''simple docstring'''







											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[int]			,		UpperCamelCase__    :    Union[np.ndarray, bytes, str]			,		**UpperCamelCase__    :    Any):






											'''simple docstring'''







											return super().__call__(UpperCamelCase__			,		**UpperCamelCase__)



				def 					__magic_name__							(      self    :    int			,		**UpperCamelCase__    :    List[Any]):






											'''simple docstring'''







											snake_case__	  =       {}
											if "candidate_labels" in kwargs:
																		snake_case__	  =       kwargs["""candidate_labels"""]
											if "hypothesis_template" in kwargs:
																		snake_case__	  =       kwargs["""hypothesis_template"""]

											return preprocess_params, {}, {}



				def 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    Any			,		UpperCamelCase__    :    Dict=None			,		UpperCamelCase__    :    List[str]="This is a sound of {}."):






											'''simple docstring'''







											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
																									snake_case__	  =       requests.get(UpperCamelCase__).content
																		else:
																									with open(UpperCamelCase__			,		"""rb""") as f:
																																snake_case__	  =       f.read()

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

											snake_case__	  =       self.feature_extractor(
											    [audio]			,		sampling_rate=self.feature_extractor.sampling_rate			,		return_tensors="""pt""")
											snake_case__	  =       candidate_labels
											snake_case__	  =       [hypothesis_template.format(UpperCamelCase__) for x in candidate_labels]
											snake_case__	  =       self.tokenizer(UpperCamelCase__			,		return_tensors=self.framework			,		padding=UpperCamelCase__)
											snake_case__	  =       [text_inputs]
											return inputs



				def 					__magic_name__							(      self    :    int			,		UpperCamelCase__    :    Optional[int]):






											'''simple docstring'''







											snake_case__	  =       model_inputs.pop("""candidate_labels""")
											snake_case__	  =       model_inputs.pop("""text_inputs""")
											if isinstance(text_inputs[0]			,		UpperCamelCase__):
																		snake_case__	  =       text_inputs[0]
											else:
																		# Batching case.
																		snake_case__	  =       text_inputs[0][0]

											snake_case__	  =       self.model(**UpperCamelCase__			,		**UpperCamelCase__)

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



				def 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    List[str]):






											'''simple docstring'''







											snake_case__	  =       model_outputs.pop("""candidate_labels""")
											snake_case__	  =       model_outputs["""logits"""][0]

											if self.framework == "pt":
																		snake_case__	  =       logits.softmax(dim=0)
																		snake_case__	  =       probs.tolist()
											else:
																		raise ValueError("""`tf` framework not supported.""")

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








from typing import TYPE_CHECKING

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


a__       =     {
    """configuration_clip""": [
        """CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """CLIPConfig""",
        """CLIPOnnxConfig""",
        """CLIPTextConfig""",
        """CLIPVisionConfig""",
    ],
    """processing_clip""": ["""CLIPProcessor"""],
    """tokenization_clip""": ["""CLIPTokenizer"""],
}

try:
	if not is_tokenizers_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     ["""CLIPTokenizerFast"""]

try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     ["""CLIPFeatureExtractor"""]
	a__       =     ["""CLIPImageProcessor"""]

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """CLIPModel""",
	    """CLIPPreTrainedModel""",
	    """CLIPTextModel""",
	    """CLIPTextModelWithProjection""",
	    """CLIPVisionModel""",
	    """CLIPVisionModelWithProjection""",
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """TFCLIPModel""",
	    """TFCLIPPreTrainedModel""",
	    """TFCLIPTextModel""",
	    """TFCLIPVisionModel""",
	]

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """FlaxCLIPModel""",
	    """FlaxCLIPPreTrainedModel""",
	    """FlaxCLIPTextModel""",
	    """FlaxCLIPTextPreTrainedModel""",
	    """FlaxCLIPVisionModel""",
	    """FlaxCLIPVisionPreTrainedModel""",
	]


if TYPE_CHECKING:
	from .configuration_clip import (
	    CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    CLIPConfig,
	    CLIPOnnxConfig,
	    CLIPTextConfig,
	    CLIPVisionConfig,
	)
	from .processing_clip import CLIPProcessor
	from .tokenization_clip import CLIPTokenizer

	try:
		if not is_tokenizers_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tokenization_clip_fast import CLIPTokenizerFast

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .feature_extraction_clip import CLIPFeatureExtractor
		from .image_processing_clip import CLIPImageProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_clip import (
		    CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    CLIPModel,
		    CLIPPreTrainedModel,
		    CLIPTextModel,
		    CLIPTextModelWithProjection,
		    CLIPVisionModel,
		    CLIPVisionModelWithProjection,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_clip import (
		    TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFCLIPModel,
		    TFCLIPPreTrainedModel,
		    TFCLIPTextModel,
		    TFCLIPVisionModel,
		)

	try:
		if not is_flax_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_flax_clip import (
		    FlaxCLIPModel,
		    FlaxCLIPPreTrainedModel,
		    FlaxCLIPTextModel,
		    FlaxCLIPTextPreTrainedModel,
		    FlaxCLIPVisionModel,
		    FlaxCLIPVisionPreTrainedModel,
		)


else:
	import sys

	a__       =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
