





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

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
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
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowercase_					     =	get_tests_dir("""fixtures""")
lowercase_					     =	get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
lowercase_					     =	get_tests_dir("""fixtures/dummy-config.json""")
class        SCREAMING_SNAKE_CASE     (unittest.TestCase   ):


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     str:





     """simple docstring"""







     lowercase__			    =						0


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     List[Any]:





     """simple docstring"""







     lowercase__			    =						AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h' )
     self.assertIsInstance(a    ,  a )


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





     """simple docstring"""







     lowercase__			    =						AutoFeatureExtractor.from_pretrained(a )
     self.assertIsInstance(a    ,  a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Tuple:





     """simple docstring"""







     with tempfile.TemporaryDirectory() as tmpdirname:
       lowercase__			    =						WavaVecaConfig()

       # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(a ).to_dict()

       config_dict.pop('feature_extractor_type' )
       lowercase__			    =						WavaVecaFeatureExtractor(**a )

       # save in new folder
       model_config.save_pretrained(a )
       config.save_pretrained(a )

       lowercase__			    =						AutoFeatureExtractor.from_pretrained(a )

       # make sure private variable is not incorrectly saved
       lowercase__			    =						json.loads(config.to_json_string() )
       self.assertTrue('_processor_class' not in dict_as_saved )

     self.assertIsInstance(a    ,  a )


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





     """simple docstring"""







     lowercase__			    =						AutoFeatureExtractor.from_pretrained(a )
     self.assertIsInstance(a    ,  a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     Tuple:





     """simple docstring"""







     with self.assertRaisesRegex(
         a    ,  'bert-base is not a local folder and is not a valid model identifier' ):
       lowercase__			    =						AutoFeatureExtractor.from_pretrained('bert-base' )


   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     Dict:





     """simple docstring"""







     with self.assertRaisesRegex(
         a    ,  R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ):
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(a    ,  revision='aaaaaa' )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int] )->     Any:





     """simple docstring"""







     with self.assertRaisesRegex(
         a    ,  'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'    ,  ):
       lowercase__			    =						AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model' )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int] )->     List[str]:





     """simple docstring"""







     with self.assertRaises(a ):
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(
           'hf-internal-testing/test_dynamic_feature_extractor' )
     # If remote code is disabled, we can't load this config.
     with self.assertRaises(a ):
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(
           'hf-internal-testing/test_dynamic_feature_extractor'    ,  trust_remote_code=a )

     lowercase__			    =						AutoFeatureExtractor.from_pretrained(
         'hf-internal-testing/test_dynamic_feature_extractor'    ,  trust_remote_code=a )
     self.assertEqual(feature_extractor.__class__.__name__    ,  'NewFeatureExtractor' )

     # Test feature extractor can be reloaded.
     with tempfile.TemporaryDirectory() as tmp_dir:
       feature_extractor.save_pretrained(a )
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(a    ,  trust_remote_code=a )
     self.assertEqual(reloaded_feature_extractor.__class__.__name__    ,  'NewFeatureExtractor' )


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Dict:





     """simple docstring"""







     try:
       AutoConfig.register('custom'    ,  a )
       AutoFeatureExtractor.register(a    ,  a )
       # Trying to register something existing in the Transformers library will raise an error
       with self.assertRaises(a ):
         AutoFeatureExtractor.register(a    ,  a )

       # Now that the config is registered, it can be used as any other config with the auto-API
       lowercase__			    =						CustomFeatureExtractor.from_pretrained(a )
       with tempfile.TemporaryDirectory() as tmp_dir:
         feature_extractor.save_pretrained(a )
         lowercase__			    =						AutoFeatureExtractor.from_pretrained(a )
         self.assertIsInstance(a    ,  a )

     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]


   def  SCREAMING_SNAKE_CASE_							(					self    :       Any )->     Any:





     """simple docstring"""







     class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):
        _UpperCamelCase					:	Dict				      = True

     try:
       AutoConfig.register('custom'    ,  a )
       AutoFeatureExtractor.register(a    ,  a )
       # If remote code is not set, the default is to use local
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(
           'hf-internal-testing/test_dynamic_feature_extractor' )
       self.assertEqual(feature_extractor.__class__.__name__    ,  'NewFeatureExtractor' )
       self.assertTrue(feature_extractor.is_local )

       # If remote code is disabled, we load the local one.
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(
           'hf-internal-testing/test_dynamic_feature_extractor'    ,  trust_remote_code=a )
       self.assertEqual(feature_extractor.__class__.__name__    ,  'NewFeatureExtractor' )
       self.assertTrue(feature_extractor.is_local )

       # If remote is enabled, we load from the Hub
       lowercase__			    =						AutoFeatureExtractor.from_pretrained(
           'hf-internal-testing/test_dynamic_feature_extractor'    ,  trust_remote_code=a )
       self.assertEqual(feature_extractor.__class__.__name__    ,  'NewFeatureExtractor' )
       self.assertTrue(not hasattr(a    ,  'is_local' ) )

     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]









import os
import zipfile

import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=7	)       ->     List[Any]:
  lowercase__			    =						None
  if token is not None:
    lowercase__			    =						{'Accept': 'application/vnd.github+json', 'Authorization': F"""Bearer {token}"""}

  # The id of a workflow (not of a workflow run)
  lowercase__			    =						'636036'

  lowercase__			    =						F"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
  # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
  url += F"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""

  lowercase__			    =						requests.get(_SCREAMING_SNAKE_CASE	,		headers=_SCREAMING_SNAKE_CASE	).json()

  return result["workflow_runs"]




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Union[str, Any]:
  lowercase__			    =						get_daily_ci_runs(_SCREAMING_SNAKE_CASE	)
  lowercase__			    =						None
  for workflow_run in workflow_runs:
    if workflow_run["status"] == "completed":
      lowercase__			    =						workflow_run['id']
      break

  return workflow_run_id




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Tuple:
  lowercase__			    =						get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE	)
  if workflow_run_id is not None:
    lowercase__			    =						get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE	,		token=_SCREAMING_SNAKE_CASE	)
    for artifact_name in artifact_names:
      if artifact_name in artifacts_links:
        lowercase__			    =						artifacts_links[artifact_name]
        download_artifact(
            artifact_name=_SCREAMING_SNAKE_CASE	,		artifact_url=_SCREAMING_SNAKE_CASE	,		output_dir=_SCREAMING_SNAKE_CASE	,		token=_SCREAMING_SNAKE_CASE	)




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Dict:
  get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)

  lowercase__			    =						{}
  for artifact_name in artifact_names:
    lowercase__			    =						os.path.join(_SCREAMING_SNAKE_CASE	,		F"""{artifact_name}.zip"""	)
    if os.path.isfile(_SCREAMING_SNAKE_CASE	):
      lowercase__			    =						{}
      with zipfile.ZipFile(_SCREAMING_SNAKE_CASE	) as z:
        for filename in z.namelist():
          if not os.path.isdir(_SCREAMING_SNAKE_CASE	):
            # read the file
            with z.open(_SCREAMING_SNAKE_CASE	) as f:
              lowercase__			    =						f.read().decode('UTF-8'	)

  return results


