
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


lowercase  :					Optional[Any]						    =							get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
lowercase  :					Optional[Any]						    =							get_tests_dir("""fixtures/vocab.json""")
lowercase  :					int						    =							get_tests_dir("""fixtures""")

class __snake_case		(      unittest.TestCase     ):
    _a		:						Union[str, Any]=				["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      0
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h"""      )
           self.assertIsInstance(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           with tempfile.TemporaryDirectory() as tmpdirname:
                  lowercase							:     Optional[int]       	=      WavaVecaConfig()
                  lowercase							:     Any       	=      AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h"""      )

                  # save in new folder
                  model_config.save_pretrained(snake_case      )
                  processor.save_pretrained(snake_case      )

                  lowercase							:     Optional[Any]       	=      AutoProcessor.from_pretrained(snake_case      )

           self.assertIsInstance(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           with tempfile.TemporaryDirectory() as tmpdirname:
                  # copy relevant files
                  copyfile(snake_case		,os.path.join(snake_case		,snake_case      )      )
                  copyfile(snake_case		,os.path.join(snake_case		,"""vocab.json"""      )      )

                  lowercase							:     str       	=      AutoProcessor.from_pretrained(snake_case      )

           self.assertIsInstance(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           with tempfile.TemporaryDirectory() as tmpdirname:
                  lowercase							:     Optional[int]       	=      WavaVecaFeatureExtractor()
                  lowercase							:     Optional[int]       	=      AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h"""      )

                  lowercase							:     List[str]       	=      WavaVecaProcessor(snake_case		,snake_case      )

                  # save in new folder
                  processor.save_pretrained(snake_case      )

                  # drop `processor_class` in tokenizer
                  with open(os.path.join(snake_case		,snake_case      )		,"""r"""      ) as f:
                         lowercase							:     Optional[int]       	=      json.load(snake_case      )
                         config_dict.pop("""processor_class"""      )

                  with open(os.path.join(snake_case		,snake_case      )		,"""w"""      ) as f:
                         f.write(json.dumps(snake_case      )      )

                  lowercase							:     str       	=      AutoProcessor.from_pretrained(snake_case      )

           self.assertIsInstance(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           with tempfile.TemporaryDirectory() as tmpdirname:
                  lowercase							:     List[str]       	=      WavaVecaFeatureExtractor()
                  lowercase							:     List[Any]       	=      AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h"""      )

                  lowercase							:     List[str]       	=      WavaVecaProcessor(snake_case		,snake_case      )

                  # save in new folder
                  processor.save_pretrained(snake_case      )

                  # drop `processor_class` in feature extractor
                  with open(os.path.join(snake_case		,snake_case      )		,"""r"""      ) as f:
                         lowercase							:     str       	=      json.load(snake_case      )
                         config_dict.pop("""processor_class"""      )

                  with open(os.path.join(snake_case		,snake_case      )		,"""w"""      ) as f:
                         f.write(json.dumps(snake_case      )      )

                  lowercase							:     Tuple       	=      AutoProcessor.from_pretrained(snake_case      )

           self.assertIsInstance(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           with tempfile.TemporaryDirectory() as tmpdirname:
                  lowercase							:     Tuple       	=      WavaVecaConfig(processor_class="""Wav2Vec2Processor"""      )
                  model_config.save_pretrained(snake_case      )
                  # copy relevant files
                  copyfile(snake_case		,os.path.join(snake_case		,"""vocab.json"""      )      )
                  # create emtpy sample processor
                  with open(os.path.join(snake_case		,snake_case      )		,"""w"""      ) as f:
                         f.write("""{}"""      )

                  lowercase							:     str       	=      AutoProcessor.from_pretrained(snake_case      )

           self.assertIsInstance(snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           with self.assertRaises(snake_case      ):
                  lowercase							:     Optional[int]       	=      AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor"""      )
           # If remote code is disabled, we can't load this config.
           with self.assertRaises(snake_case      ):
                  lowercase							:     Tuple       	=      AutoProcessor.from_pretrained(
                      """hf-internal-testing/test_dynamic_processor"""		,trust_remote_code=snake_case      )

           lowercase							:     Dict       	=      AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor"""		,trust_remote_code=snake_case      )
           self.assertTrue(processor.special_attribute_present      )
           self.assertEqual(processor.__class__.__name__		,"""NewProcessor"""      )

           lowercase							:     Optional[Any]       	=      processor.feature_extractor
           self.assertTrue(feature_extractor.special_attribute_present      )
           self.assertEqual(feature_extractor.__class__.__name__		,"""NewFeatureExtractor"""      )

           lowercase							:     Optional[Any]       	=      processor.tokenizer
           self.assertTrue(tokenizer.special_attribute_present      )
           if is_tokenizers_available():
                  self.assertEqual(tokenizer.__class__.__name__		,"""NewTokenizerFast"""      )

                  # Test we can also load the slow version
                  lowercase							:     Optional[Any]       	=      AutoProcessor.from_pretrained(
                      """hf-internal-testing/test_dynamic_processor"""		,trust_remote_code=snake_case		,use_fast=snake_case      )
                  lowercase							:     List[Any]       	=      new_processor.tokenizer
                  self.assertTrue(new_tokenizer.special_attribute_present      )
                  self.assertEqual(new_tokenizer.__class__.__name__		,"""NewTokenizer"""      )
           else:
                  self.assertEqual(tokenizer.__class__.__name__		,"""NewTokenizer"""      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           try:
                  AutoConfig.register("""custom"""		,snake_case      )
                  AutoFeatureExtractor.register(snake_case		,snake_case      )
                  AutoTokenizer.register(snake_case		,slow_tokenizer_class=snake_case      )
                  AutoProcessor.register(snake_case		,snake_case      )
                  # Trying to register something existing in the Transformers library will raise an error
                  with self.assertRaises(snake_case      ):
                         AutoProcessor.register(snake_case		,snake_case      )

                  # Now that the config is registered, it can be used as any other config with the auto-API
                  lowercase							:     Tuple       	=      CustomFeatureExtractor.from_pretrained(snake_case      )

                  with tempfile.TemporaryDirectory() as tmp_dir:
                         lowercase							:     List[str]       	=      os.path.join(snake_case		,"""vocab.txt"""      )
                         with open(snake_case		,"""w"""		,encoding="""utf-8"""      ) as vocab_writer:
                                vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]      )      )
                         lowercase							:     int       	=      CustomTokenizer(snake_case      )

                  lowercase							:     Union[str, Any]       	=      CustomProcessor(snake_case		,snake_case      )

                  with tempfile.TemporaryDirectory() as tmp_dir:
                         processor.save_pretrained(snake_case      )
                         lowercase							:     str       	=      AutoProcessor.from_pretrained(snake_case      )
                         self.assertIsInstance(snake_case		,snake_case      )

           finally:
                  if "custom" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["custom"]
                  if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                         del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
                  if CustomConfig in TOKENIZER_MAPPING._extra_content:
                         del TOKENIZER_MAPPING._extra_content[CustomConfig]
                  if CustomConfig in PROCESSOR_MAPPING._extra_content:
                         del PROCESSOR_MAPPING._extra_content[CustomConfig]
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           class __snake_case		(      lowerCAmelCase     ):
               _a		:						List[Any]=				False






           class __snake_case		(      lowerCAmelCase     ):
               _a		:						Optional[int]=				False






           class __snake_case		(      lowerCAmelCase     ):
               _a		:						List[Any]=				"AutoFeatureExtractor"
               _a		:						Union[str, Any]=				"AutoTokenizer"
               _a		:						str=				False

           try:
                  AutoConfig.register("""custom"""		,snake_case      )
                  AutoFeatureExtractor.register(snake_case		,snake_case      )
                  AutoTokenizer.register(snake_case		,slow_tokenizer_class=snake_case      )
                  AutoProcessor.register(snake_case		,snake_case      )
                  # If remote code is not set, the default is to use local classes.
                  lowercase							:     Optional[Any]       	=      AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor"""      )
                  self.assertEqual(processor.__class__.__name__		,"""NewProcessor"""      )
                  self.assertFalse(processor.special_attribute_present      )
                  self.assertFalse(processor.feature_extractor.special_attribute_present      )
                  self.assertFalse(processor.tokenizer.special_attribute_present      )

                  # If remote code is disabled, we load the local ones.
                  lowercase							:     Dict       	=      AutoProcessor.from_pretrained(
                      """hf-internal-testing/test_dynamic_processor"""		,trust_remote_code=snake_case      )
                  self.assertEqual(processor.__class__.__name__		,"""NewProcessor"""      )
                  self.assertFalse(processor.special_attribute_present      )
                  self.assertFalse(processor.feature_extractor.special_attribute_present      )
                  self.assertFalse(processor.tokenizer.special_attribute_present      )

                  # If remote is enabled, we load from the Hub.
                  lowercase							:     Union[str, Any]       	=      AutoProcessor.from_pretrained(
                      """hf-internal-testing/test_dynamic_processor"""		,trust_remote_code=snake_case      )
                  self.assertEqual(processor.__class__.__name__		,"""NewProcessor"""      )
                  self.assertTrue(processor.special_attribute_present      )
                  self.assertTrue(processor.feature_extractor.special_attribute_present      )
                  self.assertTrue(processor.tokenizer.special_attribute_present      )

           finally:
                  if "custom" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["custom"]
                  if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                         del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
                  if CustomConfig in TOKENIZER_MAPPING._extra_content:
                         del TOKENIZER_MAPPING._extra_content[CustomConfig]
                  if CustomConfig in PROCESSOR_MAPPING._extra_content:
                         del PROCESSOR_MAPPING._extra_content[CustomConfig]
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-bert"""      )
           self.assertEqual(processor.__class__.__name__		,"""BertTokenizerFast"""      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-convnext"""      )
           self.assertEqual(processor.__class__.__name__		,"""ConvNextImageProcessor"""      )






@is_staging_test
class __snake_case		(      unittest.TestCase     ):
    _a		:						Dict=				["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
    @classmethod
    def       _SCREAMING_SNAKE_CASE       (  cls      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      TOKEN
           HfFolder.save_token(snake_case      )
    @classmethod
    def       _SCREAMING_SNAKE_CASE       (  cls      ):



           '''simple docstring'''







           try:
                  delete_repo(token=cls._token		,repo_id="""test-processor"""      )
           except HTTPError:
                  pass

           try:
                  delete_repo(token=cls._token		,repo_id="""valid_org/test-processor-org"""      )
           except HTTPError:
                  pass

           try:
                  delete_repo(token=cls._token		,repo_id="""test-dynamic-processor"""      )
           except HTTPError:
                  pass
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      WavaVecaProcessor.from_pretrained(snake_case      )
           with tempfile.TemporaryDirectory() as tmp_dir:
                  processor.save_pretrained(
                      os.path.join(snake_case		,"""test-processor"""      )		,push_to_hub=snake_case		,use_auth_token=self._token      )

                  lowercase							:     List[str]       	=      WavaVecaProcessor.from_pretrained(f"{USER}/test-processor"      )
                  for k, v in processor.feature_extractor.__dict__.items():
                         self.assertEqual(snake_case		,getattr(new_processor.feature_extractor		,snake_case      )      )
                  self.assertDictEqual(new_processor.tokenizer.get_vocab()		,processor.tokenizer.get_vocab()      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      WavaVecaProcessor.from_pretrained(snake_case      )

           with tempfile.TemporaryDirectory() as tmp_dir:
                  processor.save_pretrained(
                      os.path.join(snake_case		,"""test-processor-org"""      )		,push_to_hub=snake_case		,use_auth_token=self._token		,organization="""valid_org"""		,)

                  lowercase							:     Optional[int]       	=      WavaVecaProcessor.from_pretrained("""valid_org/test-processor-org"""      )
                  for k, v in processor.feature_extractor.__dict__.items():
                         self.assertEqual(snake_case		,getattr(new_processor.feature_extractor		,snake_case      )      )
                  self.assertDictEqual(new_processor.tokenizer.get_vocab()		,processor.tokenizer.get_vocab()      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           CustomFeatureExtractor.register_for_auto_class()
           CustomTokenizer.register_for_auto_class()
           CustomProcessor.register_for_auto_class()

           lowercase							:     Dict       	=      CustomFeatureExtractor.from_pretrained(snake_case      )

           with tempfile.TemporaryDirectory() as tmp_dir:
                  lowercase							:     List[Any]       	=      os.path.join(snake_case		,"""vocab.txt"""      )
                  with open(snake_case		,"""w"""		,encoding="""utf-8"""      ) as vocab_writer:
                         vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]      )      )
                  lowercase							:     List[Any]       	=      CustomTokenizer(snake_case      )

           lowercase							:     Optional[Any]       	=      CustomProcessor(snake_case		,snake_case      )

           with tempfile.TemporaryDirectory() as tmp_dir:
                  create_repo(f"{USER}/test-dynamic-processor"		,token=self._token      )
                  lowercase							:     Dict       	=      Repository(snake_case		,clone_from=f"{USER}/test-dynamic-processor"		,token=self._token      )
                  processor.save_pretrained(snake_case      )

                  # This has added the proper auto_map field to the feature extractor config
                  self.assertDictEqual(
                      processor.feature_extractor.auto_map		,{
                          """AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor""",
                          """AutoProcessor""": """custom_processing.CustomProcessor""",
                      }		,)

                  # This has added the proper auto_map field to the tokenizer config
                  with open(os.path.join(snake_case		,"""tokenizer_config.json"""      )      ) as f:
                         lowercase							:     Dict       	=      json.load(snake_case      )
                  self.assertDictEqual(
                      tokenizer_config["""auto_map"""]		,{
                          """AutoTokenizer""": ["""custom_tokenization.CustomTokenizer""", None],
                          """AutoProcessor""": """custom_processing.CustomProcessor""",
                      }		,)

                  # The code has been copied from fixtures
                  self.assertTrue(os.path.isfile(os.path.join(snake_case		,"""custom_feature_extraction.py"""      )      )      )
                  self.assertTrue(os.path.isfile(os.path.join(snake_case		,"""custom_tokenization.py"""      )      )      )
                  self.assertTrue(os.path.isfile(os.path.join(snake_case		,"""custom_processing.py"""      )      )      )

                  repo.push_to_hub()

           lowercase							:     Any       	=      AutoProcessor.from_pretrained(f"{USER}/test-dynamic-processor"		,trust_remote_code=snake_case      )
           # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
           self.assertEqual(new_processor.__class__.__name__		,"""CustomProcessor"""      )


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


lowercase  :					Optional[Any]						    =							logging.get_logger(__name__)

@add_end_docstrings(lowerCAmelCase     )
class __snake_case		(      lowerCAmelCase     ):
    def __init__(  self		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )

           if self.framework != "pt":
                  raise ValueError(f"The {self.__class__} is only available in PyTorch."      )
           # No specific FOR_XXX available yet
    def __call__(  self		,snake_case		,**snake_case      ):



           '''simple docstring'''







           return super().__call__(snake_case		,**snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,**snake_case      ):



           '''simple docstring'''







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

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



           '''simple docstring'''







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

           if isinstance(snake_case		,snake_case      ):
                  lowercase							:     int       	=      ffmpeg_read(snake_case		,self.feature_extractor.sampling_rate      )

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

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



           '''simple docstring'''







           lowercase							:     List[str]       	=      model_inputs.pop("""candidate_labels"""      )
           lowercase							:     Dict       	=      model_inputs.pop("""text_inputs"""      )
           if isinstance(text_inputs[0]		,snake_case      ):
                  lowercase							:     List[Any]       	=      text_inputs[0]
           else:
                  # Batching case.
                  lowercase							:     Dict       	=      text_inputs[0][0]

           lowercase							:     Optional[Any]       	=      self.model(**snake_case		,**snake_case      )

           lowercase							:     Any       	=      {
               """candidate_labels""": candidate_labels,
               """logits""": outputs.logits_per_audio,
           }
           return model_outputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      model_outputs.pop("""candidate_labels"""      )
           lowercase							:     Any       	=      model_outputs["""logits"""][0]

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

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