


'''simple docstring'''






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


lowercase				=get_tests_dir('fixtures')






class    __magic_name__				(						unittest.TestCase							):






       def      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          # A mock response for an HTTP head request to emulate server down
          _UpperCAmelCase  :  int				       =mock.Mock()
          _UpperCAmelCase  :  Union[str, Any]				       =5_0_0
          _UpperCAmelCase  :  List[Any]				       ={}
          _UpperCAmelCase  :  int				       =HTTPError
          _UpperCAmelCase  :  Any				       ={}

          # Download this model to make sure it's in the cache.
          _UpperCAmelCase  :  int				       =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=snake_case) as mock_head:
             _UpperCAmelCase  :  str				       =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)		->    int:




          '''simple docstring'''
          # This test is for deprecated behavior and can be removed in v5
          _UpperCAmelCase  :  int				       =WavaVecaFeatureExtractor.from_pretrained(
              'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json')






@is_staging_test
class    __magic_name__				(						unittest.TestCase							):






       @classmethod
       def      lowerCAmelCase						(     cls)		->    Union[str, Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[Any]				       =TOKEN
          HfFolder.save_token(snake_case)






       @classmethod
       def      lowerCAmelCase						(     cls)		->    Optional[Any]:




          '''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)		->    List[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  Union[str, Any]				       =WavaVecaFeatureExtractor.from_pretrained(snake_case)
          feature_extractor.push_to_hub('test-feature-extractor'    ,				use_auth_token=self._token)

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

          # 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(
                 snake_case    ,				repo_id='test-feature-extractor'    ,				push_to_hub=snake_case    ,				use_auth_token=self._token)

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






       def      lowerCAmelCase						(     self)		->    Tuple:




          '''simple docstring'''
          _UpperCAmelCase  :  Dict				       =WavaVecaFeatureExtractor.from_pretrained(snake_case)
          feature_extractor.push_to_hub('valid_org/test-feature-extractor'    ,				use_auth_token=self._token)

          _UpperCAmelCase  :  int				       =WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor')
          for k, v in feature_extractor.__dict__.items():
             self.assertEqual(snake_case    ,				getattr(snake_case    ,				snake_case))

          # 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(
                 snake_case    ,				repo_id='valid_org/test-feature-extractor-org'    ,				push_to_hub=snake_case    ,				use_auth_token=self._token)

          _UpperCAmelCase  :  List[str]				       =WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org')
          for k, v in feature_extractor.__dict__.items():
             self.assertEqual(snake_case    ,				getattr(snake_case    ,				snake_case))






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




          '''simple docstring'''
          CustomFeatureExtractor.register_for_auto_class()
          _UpperCAmelCase  :  str				       =CustomFeatureExtractor.from_pretrained(snake_case)

          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'}    ,				)

          _UpperCAmelCase  :  int				       =AutoFeatureExtractor.from_pretrained(
              f"{USER}/test-dynamic-feature-extractor"    ,				trust_remote_code=snake_case)
          # 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')





'''simple docstring'''






def lowerCamelCase__     (		__lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  Dict				       =''
   for ch in key:
      if ch == " " or ch not in key_no_dups and ch.isalpha():
         key_no_dups += ch
   return key_no_dups





def lowerCamelCase__     (		__lowerCamelCase			:				str				):







   '''simple docstring'''




   _UpperCAmelCase  :  List[str]				       =[chr(i + 6_5				) for i in range(2_6				)]
   # Remove duplicate characters from key
   _UpperCAmelCase  :  Any				       =remove_duplicates(key.upper()				)
   _UpperCAmelCase  :  Optional[Any]				       =len(__lowerCamelCase				)
   # First fill cipher with key characters
   _UpperCAmelCase  :  List[Any]				       ={alphabet[i]: char for i, char in enumerate(__lowerCamelCase				)}
   # Then map remaining characters in alphabet to
   # the alphabet from the beginning
   for i in range(len(__lowerCamelCase				)			,       2_6				):
      _UpperCAmelCase  :  Union[str, Any]				       =alphabet[i - offset]
      # Ensure we are not mapping letters to letters previously mapped
      while char in key:
         offset -= 1
         _UpperCAmelCase  :  str				       =alphabet[i - offset]
      _UpperCAmelCase  :  Any				       =char
   return cipher_alphabet





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				dict[str, str]				):







   '''simple docstring'''




   return "".join(cipher_map.get(__lowerCamelCase			,       __lowerCamelCase				) for ch in message.upper()				)





def lowerCamelCase__     (		__lowerCamelCase			:				str			,       __lowerCamelCase			:				dict[str, str]				):







   '''simple docstring'''




   _UpperCAmelCase  :  List[str]				       ={v: k for k, v in cipher_map.items()}
   return "".join(rev_cipher_map.get(__lowerCamelCase			,       __lowerCamelCase				) for ch in message.upper()				)





def lowerCamelCase__     (		):







   '''simple docstring'''




   _UpperCAmelCase  :  Union[str, Any]				       =input('Enter message to encode or decode: '				).strip()
   _UpperCAmelCase  :  int				       =input('Enter keyword: '				).strip()
   _UpperCAmelCase  :  int				       =input('Encipher or decipher? E/D:'				).strip()[0].lower()
   try:
      _UpperCAmelCase  :  Tuple				       ={'e': encipher, 'd': decipher}[option]
   except KeyError:
      raise KeyError('invalid input option'				)
   _UpperCAmelCase  :  List[str]				       =create_cipher_map(__lowerCamelCase				)
   print(func(__lowerCamelCase			,       __lowerCamelCase				)				)


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 main()

