


import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

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

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


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

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


A   :					str	=      get_tests_dir("fixtures")







class     _lowercase				(							unittest.TestCase):


       """simple docstring"""




       def 		lowerCAmelCase  (     self							:    Optional[Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						mock.Mock()
             lowerCamelCase__	:       Optional[Any]					=						500
             lowerCamelCase__	:       Optional[Any]					=						{}
             lowerCamelCase__	:       List[str]					=						HTTPError
             lowerCamelCase__	:       Tuple					=						{}

             # Download this model to make sure it's in the cache.
             lowerCamelCase__	:       Dict					=						WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" )
             # Under the mock environment we get a 500 error when trying to reach the model.
             with mock.patch("requests.Session.request"      ,   return_value=__lowerCamelCase ) as mock_head:
                   lowerCamelCase__	:       List[Any]					=						WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2" )
                   # This check we did call the fake head request
                   mock_head.assert_called()





       def 		lowerCAmelCase  (     self							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						WavaVecaFeatureExtractor.from_pretrained(
                 "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json" )







@is_staging_test
class     _lowercase				(							unittest.TestCase):


       """simple docstring"""




       @classmethod
       def 		lowerCAmelCase  (     cls							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						TOKEN
             HfFolder.save_token(__lowerCamelCase )





       @classmethod
       def 		lowerCAmelCase  (     cls							:    List[str] ):


             '''simple docstring'''



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

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

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





       def 		lowerCAmelCase  (     self							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       List[Any]					=						WavaVecaFeatureExtractor.from_pretrained(__lowerCamelCase )
             feature_extractor.push_to_hub("test-feature-extractor"      ,   use_auth_token=self._token )

             lowerCamelCase__	:       str					=						WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor" )
             for k, v in feature_extractor.__dict__.items():
                   self.assertEqual(__lowerCamelCase      ,   getattr(__lowerCamelCase      ,   __lowerCamelCase ) )

             # Reset repo
             delete_repo(token=self._token      ,   repo_id="test-feature-extractor" )

             # Push to hub via save_pretrained
             with tempfile.TemporaryDirectory() as tmp_dir:
                   feature_extractor.save_pretrained(
                       __lowerCamelCase      ,   repo_id="test-feature-extractor"      ,   push_to_hub=__lowerCamelCase      ,   use_auth_token=self._token )

             lowerCamelCase__	:       List[Any]					=						WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor" )
             for k, v in feature_extractor.__dict__.items():
                   self.assertEqual(__lowerCamelCase      ,   getattr(__lowerCamelCase      ,   __lowerCamelCase ) )





       def 		lowerCAmelCase  (     self							:    Optional[int] ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						WavaVecaFeatureExtractor.from_pretrained(__lowerCamelCase )
             feature_extractor.push_to_hub("valid_org/test-feature-extractor"      ,   use_auth_token=self._token )

             lowerCamelCase__	:       List[Any]					=						WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor" )
             for k, v in feature_extractor.__dict__.items():
                   self.assertEqual(__lowerCamelCase      ,   getattr(__lowerCamelCase      ,   __lowerCamelCase ) )

             # Reset repo
             delete_repo(token=self._token      ,   repo_id="valid_org/test-feature-extractor" )

             # Push to hub via save_pretrained
             with tempfile.TemporaryDirectory() as tmp_dir:
                   feature_extractor.save_pretrained(
                       __lowerCamelCase      ,   repo_id="valid_org/test-feature-extractor-org"      ,   push_to_hub=__lowerCamelCase      ,   use_auth_token=self._token )

             lowerCamelCase__	:       int					=						WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org" )
             for k, v in feature_extractor.__dict__.items():
                   self.assertEqual(__lowerCamelCase      ,   getattr(__lowerCamelCase      ,   __lowerCamelCase ) )





       def 		lowerCAmelCase  (     self							:    List[Any] ):


             '''simple docstring'''



             CustomFeatureExtractor.register_for_auto_class()
             lowerCamelCase__	:       Optional[Any]					=						CustomFeatureExtractor.from_pretrained(__lowerCamelCase )

             feature_extractor.push_to_hub("test-dynamic-feature-extractor"      ,   use_auth_token=self._token )

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

             lowerCamelCase__	:       Any					=						AutoFeatureExtractor.from_pretrained(
                 f"{USER}/test-dynamic-feature-extractor"      ,   trust_remote_code=__lowerCamelCase )
             # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
             self.assertEqual(new_feature_extractor.__class__.__name__      ,   "CustomFeatureExtractor" )






from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A   :					Dict	=      logging.get_logger(__name__)

A   :					Union[str, Any]	=      {
    "roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json",
    "roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json",
    "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json",
    "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json",
    "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json",
    "roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json",
}







class     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    "roberta"





       def __init__(     self							:    int      ,   __lowerCamelCase							:    Dict=50265      ,   __lowerCamelCase							:    Optional[int]=768      ,   __lowerCamelCase							:    Optional[Any]=12      ,   __lowerCamelCase							:    Optional[int]=12      ,   __lowerCamelCase							:    int=3072      ,   __lowerCamelCase							:    Dict="gelu"      ,   __lowerCamelCase							:    Union[str, Any]=0.1      ,   __lowerCamelCase							:    int=0.1      ,   __lowerCamelCase							:    Tuple=512      ,   __lowerCamelCase							:    List[str]=2      ,   __lowerCamelCase							:    Any=0.0_2      ,   __lowerCamelCase							:    Optional[int]=1E-1_2      ,   __lowerCamelCase							:    List[Any]=1      ,   __lowerCamelCase							:    int=0      ,   __lowerCamelCase							:    Any=2      ,   __lowerCamelCase							:    Tuple="absolute"      ,   __lowerCamelCase							:    Tuple=True      ,   __lowerCamelCase							:    str=None      ,   **__lowerCamelCase							:    Optional[Any]      ,   ):


             '''simple docstring'''



             super().__init__(pad_token_id=__lowerCamelCase      ,   bos_token_id=__lowerCamelCase      ,   eos_token_id=__lowerCamelCase      ,   **__lowerCamelCase )

             lowerCamelCase__	:       List[Any]					=						vocab_size
             lowerCamelCase__	:       str					=						hidden_size
             lowerCamelCase__	:       int					=						num_hidden_layers
             lowerCamelCase__	:       Optional[Any]					=						num_attention_heads
             lowerCamelCase__	:       Optional[Any]					=						hidden_act
             lowerCamelCase__	:       Any					=						intermediate_size
             lowerCamelCase__	:       Tuple					=						hidden_dropout_prob
             lowerCamelCase__	:       Any					=						attention_probs_dropout_prob
             lowerCamelCase__	:       Tuple					=						max_position_embeddings
             lowerCamelCase__	:       int					=						type_vocab_size
             lowerCamelCase__	:       Any					=						initializer_range
             lowerCamelCase__	:       Dict					=						layer_norm_eps
             lowerCamelCase__	:       int					=						position_embedding_type
             lowerCamelCase__	:       Any					=						use_cache
             lowerCamelCase__	:       int					=						classifier_dropout







class     _lowercase				(							lowercase__):


       """simple docstring"""




       @property
       def 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



             if self.task == "multiple-choice":
                   lowerCamelCase__	:       int					=						{0: "batch", 1: "choice", 2: "sequence"}
             else:
                   lowerCamelCase__	:       Optional[Any]					=						{0: "batch", 1: "sequence"}
             return OrderedDict(
                 [
                     ("input_ids", dynamic_axis),
                     ("attention_mask", dynamic_axis),
                 ] )


