






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




@add_end_docstrings(lowercase_)
class 			snake_case__   (							lowercase_):

       '''simple docstring'''



       def __init__(							self			,						**a__    ) ->      str:






            '''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__    ) ->      Tuple:






            '''simple docstring'''





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



       def 					__lowercase						(							self			,						**a__    ) ->      str:






            '''simple docstring'''





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

            return preprocess_params, {}, {}



       def 					__lowercase						(							self			,						a__			,						a__=None			,						a__="This is a sound of {}."    ) ->      int:






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

            if isinstance(a__			,						a__    ):
                 __snake_case			:Tuple          =						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"""    )

            __snake_case			:str          =						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(a__    ) for x in candidate_labels]
            __snake_case			:Optional[Any]          =						self.tokenizer(a__			,						return_tensors=self.framework			,						padding=a__    )
            __snake_case			:int          =						[text_inputs]
            return inputs



       def 					__lowercase						(							self			,						a__    ) ->      str:






            '''simple docstring'''





            __snake_case			:Tuple          =						model_inputs.pop("""candidate_labels"""    )
            __snake_case			:List[Any]          =						model_inputs.pop("""text_inputs"""    )
            if isinstance(text_inputs[0]			,						a__    ):
                 __snake_case			:List[Any]          =						text_inputs[0]
            else:
                 # Batching case.
                 __snake_case			:Optional[int]          =						text_inputs[0][0]

            __snake_case			:Union[str, Any]          =						self.model(**a__			,						**a__    )

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



       def 					__lowercase						(							self			,						a__    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						model_outputs.pop("""candidate_labels"""    )
            __snake_case			:int          =						model_outputs["""logits"""][0]

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

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










import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowerCamelCase__							=     get_tests_dir("""fixtures/dummy-config.json""")




class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						0



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            self.assertIsNotNone(transformers.models.auto.__spec__    )
            self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto"""    )    )



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						AutoConfig.from_pretrained("""bert-base-uncased"""    )
            self.assertIsInstance(a__			,						a__    )



       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            __snake_case			:List[str]          =						AutoConfig.from_pretrained(a__    )
            self.assertIsInstance(a__			,						a__    )



       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Tuple          =						AutoConfig.from_pretrained(a__    )
            self.assertIsInstance(a__			,						a__    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						AutoConfig.for_model("""roberta"""    )
            self.assertIsInstance(a__			,						a__    )



       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            with tempfile.TemporaryDirectory() as tmp_dir:
                 # This model name contains bert and roberta, but roberta ends up being picked.
                 __snake_case			:List[Any]          =						os.path.join(a__			,						"""fake-roberta"""    )
                 os.makedirs(a__			,						exist_ok=a__    )
                 with open(os.path.join(a__			,						"""config.json"""    )			,						"""w"""    ) as f:
                      f.write(json.dumps({}    )    )
                 __snake_case			:Optional[Any]          =						AutoConfig.from_pretrained(a__    )
                 self.assertEqual(type(a__    )			,						a__    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            try:
                 AutoConfig.register("""custom"""			,						a__    )
                 # Wrong model type will raise an error
                 with self.assertRaises(a__    ):
                      AutoConfig.register("""model"""			,						a__    )
                 # Trying to register something existing in the Transformers library will raise an error
                 with self.assertRaises(a__    ):
                      AutoConfig.register("""bert"""			,						a__    )

                 # Now that the config is registered, it can be used as any other config with the auto-API
                 __snake_case			:Optional[int]          =						CustomConfig()
                 with tempfile.TemporaryDirectory() as tmp_dir:
                      config.save_pretrained(a__    )
                      __snake_case			:Tuple          =						AutoConfig.from_pretrained(a__    )
                      self.assertIsInstance(a__			,						a__    )

            finally:
                 if "custom" in CONFIG_MAPPING._extra_content:
                      del CONFIG_MAPPING._extra_content["custom"]



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            with self.assertRaisesRegex(
                a__			,						"""bert-base is not a local folder and is not a valid model identifier"""    ):
                 __snake_case			:str          =						AutoConfig.from_pretrained("""bert-base"""    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            with self.assertRaisesRegex(
                a__			,						R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""    ):
                 __snake_case			:Dict          =						AutoConfig.from_pretrained(a__			,						revision="""aaaaaa"""    )



       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            with self.assertRaisesRegex(
                a__			,						"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."""			,						):
                 __snake_case			:Optional[int]          =						AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo"""    )



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            with self.assertRaises(a__    ):
                 __snake_case			:Dict          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""    )
            # If remote code is disabled, we can't load this config.
            with self.assertRaises(a__    ):
                 __snake_case			:int          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )

            __snake_case			:Tuple          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )
            self.assertEqual(config.__class__.__name__			,						"""NewModelConfig"""    )

            # Test config can be reloaded.
            with tempfile.TemporaryDirectory() as tmp_dir:
                 config.save_pretrained(a__    )
                 __snake_case			:Union[str, Any]          =						AutoConfig.from_pretrained(a__			,						trust_remote_code=a__    )
            self.assertEqual(reloaded_config.__class__.__name__			,						"""NewModelConfig"""    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            class 			snake_case__   (							lowercase_):

                   '''simple docstring'''
                   lowerCamelCase							:				Optional[Any] 				= "new-model"

            try:
                 AutoConfig.register("""new-model"""			,						a__    )
                 # If remote code is not set, the default is to use local
                 __snake_case			:List[Any]          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""    )
                 self.assertEqual(config.__class__.__name__			,						"""NewModelConfigLocal"""    )

                 # If remote code is disabled, we load the local one.
                 __snake_case			:Tuple          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )
                 self.assertEqual(config.__class__.__name__			,						"""NewModelConfigLocal"""    )

                 # If remote is enabled, we load from the Hub
                 __snake_case			:List[Any]          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )
                 self.assertEqual(config.__class__.__name__			,						"""NewModelConfig"""    )

            finally:
                 if "new-model" in CONFIG_MAPPING._extra_content:
                      del CONFIG_MAPPING._extra_content["new-model"]


