


"""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


__snake_case         =					logging.get_logger(__name__)







@add_end_docstrings(snake_case_			)
class _lowerCAmelCase       (   snake_case_			):







   def __init__(			self		,			**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		,			UpperCamelCase__		,			**UpperCamelCase__		)			->	Any:

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			**UpperCamelCase__		)			->	List[Any]:

       '''simple docstring'''




       snake_case					:   List[Any]         =					{}
       if "candidate_labels" in kwargs:
           snake_case					:   List[Any]         =					kwargs["candidate_labels"]
       if "hypothesis_template" in kwargs:
           snake_case					:   Union[str, Any]         =					kwargs["hypothesis_template"]

       return preprocess_params, {}, {}







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__=None		,			UpperCamelCase__="This is a sound of {}."		)			->	List[Any]:

       '''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					:   Union[str, Any]         =					requests.get(UpperCamelCase__		).content
           else:
               with open(UpperCamelCase__		,			"rb"		) as f:
                   snake_case					:   List[str]         =					f.read()

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

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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Optional[Any]:

       '''simple docstring'''




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

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

       snake_case					:   Optional[int]         =					{
           "candidate_labels": candidate_labels,
           "logits": outputs.logits_per_audio,
       }
       return model_outputs







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Optional[int]:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					model_outputs.pop("candidate_labels"		)
       snake_case					:   List[Any]         =					model_outputs["logits"][0]

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

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









"""simple docstring"""



import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__snake_case         =					"""src/diffusers"""

# Matches is_xxx_available()
__snake_case         =					re.compile(R"""is\_([a-z_]*)_available\(\)""")
# Matches from xxx import bla
__snake_case         =					re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")


__snake_case         =					"""
{0} = None
"""

__snake_case         =					"""
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, {1})

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, {1})
"""


__snake_case         =					"""
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""







def 						__lowerCAmelCase		(		lowercase						:						Tuple				)			->		str:


    """simple docstring"""





    snake_case					:   Optional[Any]         =					_re_backend.findall(lowercase				)
    if len(lowercase				) == 0:
        return None

    return "_and_".join(lowercase				)







def 						__lowerCAmelCase		(		)			->		Tuple:


    """simple docstring"""





    with open(os.path.join(lowercase		,							"__init__.py"				)		,							"r"		,							encoding="utf-8"		,							newline="\n"				) as f:
        snake_case					:   Tuple         =					f.readlines()

    # Get to the point we do the actual imports for type checking
    snake_case					:   Tuple         =					0
    snake_case					:   Optional[Any]         =					{}
    # Go through the end of the file
    while line_index < len(lowercase				):
        # If the line contains is_backend_available, we grab all objects associated with the `else` block
        snake_case					:   List[Any]         =					find_backend(lines[line_index]				)
        if backend is not None:
            while not lines[line_index].startswith("else:"				):
                line_index += 1
            line_index += 1
            snake_case					:   str         =					[]
            # Until we unindent, add backend objects to the list
            while line_index < len(lowercase				) and len(lines[line_index]				) > 1:
                snake_case					:   List[str]         =					lines[line_index]
                snake_case					:   Any         =					_re_single_line_import.search(lowercase				)
                if single_line_import_search is not None:
                    objects.extend(single_line_import_search.groups()[0].split(", "				)				)
                elif line.startswith(" " * 8				):
                    objects.append(line[8:-2]				)
                line_index += 1

            if len(lowercase				) > 0:
                snake_case					:   Any         =					objects
        else:
            line_index += 1

    return backend_specific_objects







def 						__lowerCAmelCase		(		lowercase						:						Union[str, Any]		,							lowercase						:						Tuple				)			->		int:


    """simple docstring"""





    if name.isupper():
        return DUMMY_CONSTANT.format(lowercase				)
    elif name.islower():
        return DUMMY_FUNCTION.format(lowercase		,							lowercase				)
    else:
        return DUMMY_CLASS.format(lowercase		,							lowercase				)







def 						__lowerCAmelCase		(		lowercase						:						Union[str, Any]=None				)			->		Optional[int]:


    """simple docstring"""





    if backend_specific_objects is None:
        snake_case					:   List[str]         =					read_init()
    # For special correspondence backend to module name as used in the function requires_modulename
    snake_case					:   Dict         =					{}

    for backend, objects in backend_specific_objects.items():
        snake_case					:   Union[str, Any]         =					"[" + ", ".join(F'"{b}"' for b in backend.split("_and_"				)				) + "]"
        snake_case					:   Union[str, Any]         =					"# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
        dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
        dummy_file += "\n".join([create_dummy_object(lowercase		,							lowercase				) for o in objects]				)
        snake_case					:   Optional[Any]         =					dummy_file

    return dummy_files







def 						__lowerCAmelCase		(		lowercase						:						Optional[Any]=False				)			->		Any:


    """simple docstring"""





    snake_case					:   str         =					create_dummy_files()
    # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
    snake_case					:   Dict         =					{"torch": "pt"}

    # Locate actual dummy modules and read their content.
    snake_case					:   Optional[Any]         =					os.path.join(lowercase		,							"utils"				)
    snake_case					:   Union[str, Any]         =					{
        backend: os.path.join(lowercase		,							F'dummy_{short_names.get(lowercase		,							lowercase				)}_objects.py'				)
        for backend in dummy_files.keys()
    }

    snake_case					:   Optional[Any]         =					{}
    for backend, file_path in dummy_file_paths.items():
        if os.path.isfile(lowercase				):
            with open(lowercase		,							"r"		,							encoding="utf-8"		,							newline="\n"				) as f:
                snake_case					:   int         =					f.read()
        else:
            snake_case					:   Optional[Any]         =					""

    for backend in dummy_files.keys():
        if dummy_files[backend] != actual_dummies[backend]:
            if overwrite:
                print(
                    F'Updating diffusers.utils.dummy_{short_names.get(lowercase		,							lowercase				)}_objects.py as the main '
                    "__init__ has new objects."				)
                with open(dummy_file_paths[backend]		,							"w"		,							encoding="utf-8"		,							newline="\n"				) as f:
                    f.write(dummy_files[backend]				)
            else:
                raise ValueError(
                    "The main __init__ has objects that are not present in "
                    F'diffusers.utils.dummy_{short_names.get(lowercase		,							lowercase				)}_objects.py. Run `make fix-copies` '
                    "to fix this."				)


if __name__ == "__main__":
  __snake_case         =					argparse.ArgumentParser()
  parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
  __snake_case         =					parser.parse_args()

  check_dummies(args.fix_and_overwrite)





