






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


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




class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						0



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:List[str]          =						AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""    )
            self.assertIsInstance(lowerCamelCase_			,						lowerCamelCase_    )



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






            '''simple docstring'''





            __snake_case			:Dict          =						AutoFeatureExtractor.from_pretrained(lowerCamelCase_    )
            self.assertIsInstance(lowerCamelCase_			,						lowerCamelCase_    )



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






            '''simple docstring'''





            with tempfile.TemporaryDirectory() as tmpdirname:
                 __snake_case			:int          =						WavaVecaConfig()

                 # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
                 __snake_case			:int          =						AutoFeatureExtractor.from_pretrained(lowerCamelCase_    ).to_dict()

                 config_dict.pop("""feature_extractor_type"""    )
                 __snake_case			:str          =						WavaVecaFeatureExtractor(**lowerCamelCase_    )

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

                 __snake_case			:Tuple          =						AutoFeatureExtractor.from_pretrained(lowerCamelCase_    )

                 # make sure private variable is not incorrectly saved
                 __snake_case			:Optional[int]          =						json.loads(config.to_json_string()    )
                 self.assertTrue("""_processor_class""" not in dict_as_saved    )

            self.assertIsInstance(lowerCamelCase_			,						lowerCamelCase_    )



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






            '''simple docstring'''





            __snake_case			:Tuple          =						AutoFeatureExtractor.from_pretrained(lowerCamelCase_    )
            self.assertIsInstance(lowerCamelCase_			,						lowerCamelCase_    )



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






            '''simple docstring'''





            with self.assertRaisesRegex(
                lowerCamelCase_			,						"""bert-base is not a local folder and is not a valid model identifier"""    ):
                 __snake_case			:Optional[int]          =						AutoFeatureExtractor.from_pretrained("""bert-base"""    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            with self.assertRaisesRegex(
                lowerCamelCase_			,						R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""    ):
                 __snake_case			:List[str]          =						AutoFeatureExtractor.from_pretrained(lowerCamelCase_			,						revision="""aaaaaa"""    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





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



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






            '''simple docstring'''





            with self.assertRaises(lowerCamelCase_    ):
                 __snake_case			:List[Any]          =						AutoFeatureExtractor.from_pretrained(
                     """hf-internal-testing/test_dynamic_feature_extractor"""    )
            # If remote code is disabled, we can't load this config.
            with self.assertRaises(lowerCamelCase_    ):
                 __snake_case			:List[str]          =						AutoFeatureExtractor.from_pretrained(
                     """hf-internal-testing/test_dynamic_feature_extractor"""			,						trust_remote_code=lowerCamelCase_    )

            __snake_case			:List[str]          =						AutoFeatureExtractor.from_pretrained(
                """hf-internal-testing/test_dynamic_feature_extractor"""			,						trust_remote_code=lowerCamelCase_    )
            self.assertEqual(feature_extractor.__class__.__name__			,						"""NewFeatureExtractor"""    )

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



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





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

                 # Now that the config is registered, it can be used as any other config with the auto-API
                 __snake_case			:List[Any]          =						CustomFeatureExtractor.from_pretrained(lowerCamelCase_    )
                 with tempfile.TemporaryDirectory() as tmp_dir:
                      feature_extractor.save_pretrained(lowerCamelCase_    )
                      __snake_case			:List[str]          =						AutoFeatureExtractor.from_pretrained(lowerCamelCase_    )
                      self.assertIsInstance(lowerCamelCase_			,						lowerCamelCase_    )

            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 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            class 			snake_case__   (							_UpperCAmelCase):

                   '''simple docstring'''
                   lowerCamelCase							:				List[Any] 				= True

            try:
                 AutoConfig.register("""custom"""			,						lowerCamelCase_    )
                 AutoFeatureExtractor.register(lowerCamelCase_			,						lowerCamelCase_    )
                 # If remote code is not set, the default is to use local
                 __snake_case			:int          =						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.
                 __snake_case			:int          =						AutoFeatureExtractor.from_pretrained(
                     """hf-internal-testing/test_dynamic_feature_extractor"""			,						trust_remote_code=lowerCamelCase_    )
                 self.assertEqual(feature_extractor.__class__.__name__			,						"""NewFeatureExtractor"""    )
                 self.assertTrue(feature_extractor.is_local    )

                 # If remote is enabled, we load from the Hub
                 __snake_case			:Union[str, Any]          =						AutoFeatureExtractor.from_pretrained(
                     """hf-internal-testing/test_dynamic_feature_extractor"""			,						trust_remote_code=lowerCamelCase_    )
                 self.assertEqual(feature_extractor.__class__.__name__			,						"""NewFeatureExtractor"""    )
                 self.assertTrue(not hasattr(lowerCamelCase_			,						"""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]










def   UpperCamelCase  (       snake_case__     :   str	,snake_case__     :   int  ):




     '''simple docstring'''






     __snake_case			:list[list[str]]          =						[[] for _ in range(snake_case__  )]
     __snake_case			:Union[str, Any]          =						key - 1

     if key <= 0:
          raise ValueError("""Height of grid can't be 0 or negative"""  )
     if key == 1 or len(snake_case__  ) <= key:
          return input_string

     for position, character in enumerate(snake_case__  ):
          __snake_case			:Any          =						position % (lowest * 2)  # puts it in bounds
          __snake_case			:Optional[int]          =						min(snake_case__	,lowest * 2 - num  )  # creates zigzag pattern
          temp_grid[num].append(snake_case__  )
     __snake_case			:List[Any]          =						["""""".join(snake_case__  ) for row in temp_grid]
     __snake_case			:Any          =						"""""".join(snake_case__  )

     return output_string






def   UpperCamelCase  (       snake_case__     :   str	,snake_case__     :   int  ):




     '''simple docstring'''






     __snake_case			:Union[str, Any]          =						[]
     __snake_case			:Optional[int]          =						key - 1

     if key <= 0:
          raise ValueError("""Height of grid can't be 0 or negative"""  )
     if key == 1:
          return input_string

     __snake_case			:list[list[str]]          =						[[] for _ in range(snake_case__  )]  # generates template
     for position in range(len(snake_case__  )  ):
          __snake_case			:List[str]          =						position % (lowest * 2)  # puts it in bounds
          __snake_case			:int          =						min(snake_case__	,lowest * 2 - num  )  # creates zigzag pattern
          temp_grid[num].append("""*"""  )

     __snake_case			:str          =						0
     for row in temp_grid:  # fills in the characters
          __snake_case			:str          =						input_string[counter : counter + len(snake_case__  )]
          grid.append(list(snake_case__  )  )
          counter += len(snake_case__  )

     __snake_case			:Any          =						""""""  # reads as zigzag
     for position in range(len(snake_case__  )  ):
          __snake_case			:Optional[int]          =						position % (lowest * 2)  # puts it in bounds
          __snake_case			:int          =						min(snake_case__	,lowest * 2 - num  )  # creates zigzag pattern
          output_string += grid[num][0]
          grid[num].pop(0  )
     return output_string






def   UpperCamelCase  (       snake_case__     :   str  ):




     '''simple docstring'''






     __snake_case			:Optional[Any]          =						{}
     for key_guess in range(1	,len(snake_case__  )  ):  # tries every key
          __snake_case			:Dict          =						decrypt(snake_case__	,snake_case__  )
     return results


if __name__ == "__main__":
     import doctest

     doctest.testmod()


