



"""simple docstring"""





import string

import numpy
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__				):
      return b if a == 0 else greatest_common_divisor(b % a     ,      lowerCAmelCase__				)
class 				lowercase__       :







       '''simple docstring'''


       UpperCamelCase						=					string.ascii_uppercase + string.digits
       # This cipher takes alphanumerics into account
       # i.e. a total of 36 characters

       # take x and return x % len(key_string)
       UpperCamelCase						=					numpy.vectorize(lambda SCREAMING_SNAKE_CASE				: x % 36				)

       UpperCamelCase						=					numpy.vectorize(SCREAMING_SNAKE_CASE				)



       def __init__(							self      :  Optional[Any]		,    _UpperCAmelCase      :  numpy.ndarray   )			->						None:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.modulus(_UpperCAmelCase   )  # mod36 calc's on the encrypt key
             self.check_determinant()  # validate the determinant of the encryption key
             UpperCAmelCase_      			=							encrypt_key.shape[0]



       def 					lowercase__    (							self      :  str		,    _UpperCAmelCase      :  str   )			->						int:


             '''simple docstring'''




             return self.key_string.index(_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  int   )			->						str:


             '''simple docstring'''




             return self.key_string[round(_UpperCAmelCase   )]



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


             '''simple docstring'''




             UpperCAmelCase_      			=							round(numpy.linalg.det(self.encrypt_key   )   )

             if det < 0:
                   UpperCAmelCase_      			=							det % len(self.key_string   )

             UpperCAmelCase_      			=							len(self.key_string   )
             if greatest_common_divisor(_UpperCAmelCase		,    len(self.key_string   )   ) != 1:
                   UpperCAmelCase_      			=							(
                       F"""determinant modular {req_l} of encryption key({det}) """
                       F"""is not co prime w.r.t {req_l}.\nTry another key."""
                   )
                   raise ValueError(_UpperCAmelCase   )



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


             '''simple docstring'''




             UpperCAmelCase_      			=							[char for char in text.upper() if char in self.key_string]

             UpperCAmelCase_      			=							chars[-1]
             while len(_UpperCAmelCase   ) % self.break_key != 0:
                   chars.append(_UpperCAmelCase   )

             return "".join(_UpperCAmelCase   )



       def 					lowercase__    (							self      :  List[str]		,    _UpperCAmelCase      :  str   )			->						str:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.process_text(text.upper()   )
             UpperCAmelCase_      			=							""

             for i in range(0		,    len(_UpperCAmelCase   ) - self.break_key + 1		,    self.break_key   ):
                   UpperCAmelCase_      			=							text[i : i + self.break_key]
                   UpperCAmelCase_      			=							[self.replace_letters(_UpperCAmelCase   ) for char in batch]
                   UpperCAmelCase_      			=							numpy.array([vec]   ).T
                   UpperCAmelCase_      			=							self.modulus(self.encrypt_key.dot(_UpperCAmelCase   )   ).T.tolist()[
                       0
                   ]
                   UpperCAmelCase_      			=							"".join(
                       self.replace_digits(_UpperCAmelCase   ) for num in batch_encrypted   )
                   encrypted += encrypted_batch

             return encrypted



       def 					lowercase__    (							self      :  Dict   )			->						numpy.ndarray:


             '''simple docstring'''




             UpperCAmelCase_      			=							round(numpy.linalg.det(self.encrypt_key   )   )

             if det < 0:
                   UpperCAmelCase_      			=							det % len(self.key_string   )
             UpperCAmelCase_      			=							None
             for i in range(len(self.key_string   )   ):
                   if (det * i) % len(self.key_string   ) == 1:
                         UpperCAmelCase_      			=							i
                         break

             UpperCAmelCase_      			=							(
                 det_inv
                 * numpy.linalg.det(self.encrypt_key   )
                 * numpy.linalg.inv(self.encrypt_key   )
             )

             return self.to_int(self.modulus(_UpperCAmelCase   )   )







       def 					lowercase__    (							self      :  List[str]		,    _UpperCAmelCase      :  str   )			->						str:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.make_decrypt_key()
             UpperCAmelCase_      			=							self.process_text(text.upper()   )
             UpperCAmelCase_      			=							""

             for i in range(0		,    len(_UpperCAmelCase   ) - self.break_key + 1		,    self.break_key   ):
                   UpperCAmelCase_      			=							text[i : i + self.break_key]
                   UpperCAmelCase_      			=							[self.replace_letters(_UpperCAmelCase   ) for char in batch]
                   UpperCAmelCase_      			=							numpy.array([vec]   ).T
                   UpperCAmelCase_      			=							self.modulus(decrypt_key.dot(_UpperCAmelCase   )   ).T.tolist()[0]
                   UpperCAmelCase_      			=							"".join(
                       self.replace_digits(_UpperCAmelCase   ) for num in batch_decrypted   )
                   decrypted += decrypted_batch

             return decrypted



def        a__     (				):
      UpperCAmelCase_      			=							int(input("Enter the order of the encryption key: "				)				)
      UpperCAmelCase_      			=							[]

      print("Enter each row of the encryption key with space separated integers"				)
      for _ in range(lowerCAmelCase__				):
            UpperCAmelCase_      			=							[int(lowerCAmelCase__				) for x in input().split()]
            hill_matrix.append(lowerCAmelCase__				)

      UpperCAmelCase_      			=							HillCipher(numpy.array(lowerCAmelCase__				)				)

      print("Would you like to encrypt or decrypt some text? (1 or 2)"				)
      UpperCAmelCase_      			=							input("\n1. Encrypt\n2. Decrypt\n"				)
      if option == "1":
            UpperCAmelCase_      			=							input("What text would you like to encrypt?: "				)
            print("Your encrypted text is:"				)
            print(hc.encrypt(lowerCAmelCase__				)				)
      elif option == "2":
            UpperCAmelCase_      			=							input("What text would you like to decrypt?: "				)
            print("Your decrypted text is:"				)
            print(hc.decrypt(lowerCAmelCase__				)				)


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  main()









"""simple docstring"""





# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


lowerCamelCase       	=						Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

lowerCamelCase       	=						{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

lowerCamelCase       	=						"""zero2"""
lowerCamelCase       	=						"""zero3"""
lowerCamelCase       	=						[ZEROa, ZEROa]
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # customize the test name generator function as we want both params to appear in the sub-test
      # name, as by default it shows only the first param
      UpperCAmelCase_      			=							parameterized.to_safe_name("_".join(str(lowerCAmelCase__				) for x in param.args				)				)
      return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
lowerCamelCase       	=						list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Dict		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Any   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  str   )			->						Any:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Union[str, Any]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  int		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Optional[int]   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							models[model]

             UpperCAmelCase_      			=							self.run_trainer(
                 stage=_UpperCAmelCase		,    model_name=_UpperCAmelCase		,    eval_steps=_UpperCAmelCase		,    num_train_epochs=1		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )

             self.do_checks(_UpperCAmelCase   )

             return output_dir



       def 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  int = 1		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_auto_remove_tmp_dir("./xxx"		,    after=_UpperCAmelCase   )
             UpperCAmelCase_      			=							F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(_UpperCAmelCase   )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

             if fpaa:
                   args.extend(["--fp16"]   )

             # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
             # hence the separate config files
             UpperCAmelCase_      			=							F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
             UpperCAmelCase_      			=							[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
             UpperCAmelCase_      			=							self.get_launcher(_UpperCAmelCase   )

             UpperCAmelCase_      			=							launcher + script + args + ds_args
             # keep for quick debug
             # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
             execute_subprocess_async(_UpperCAmelCase		,    env=self.get_env()   )

             return output_dir







       def 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  int=False   )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							min(2		,    get_gpu_count()   ) if distributed else 1
             return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()




