

'''simple docstring'''




import string

import numpy


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : int							, SCREAMING_SNAKE_CASE   : int    ):
  return b if a == 0 else greatest_common_divisor(b % a							, SCREAMING_SNAKE_CASE    )



class 							lowercase_						:

  '''simple docstring'''





  __lowerCAmelCase       :			int     	= 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)
  __lowerCAmelCase       :			Optional[Any]     	= numpy.vectorize(lambda a			: x % 36			)

  __lowerCAmelCase       :			List[Any]     	= numpy.vectorize(a			)
  def __init__(  self ,			a_  )				->					None:


    """simple docstring"""
    UpperCAmelCase    				=						self.modulus(a_  )  # mod36 calc's on the encrypt key
    self.check_determinant()  # validate the determinant of the encryption key
    UpperCAmelCase    				=						encrypt_key.shape[0]
  def     snake_case_      (  self ,			a_  )				->					int:


    """simple docstring"""
    return self.key_string.index(a_  )
  def     snake_case_      (  self ,			a_  )				->					str:


    """simple docstring"""
    return self.key_string[round(a_  )]
  def     snake_case_      (  self  )				->					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(a_ ,			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(a_  )
  def     snake_case_      (  self ,			a_  )				->					str:


    """simple docstring"""
    UpperCAmelCase    				=						[char for char in text.upper() if char in self.key_string]

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

    return "".join(a_  )
  def     snake_case_      (  self ,			a_  )				->					str:


    """simple docstring"""
    UpperCAmelCase    				=						self.process_text(text.upper()  )
    UpperCAmelCase    				=						''

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

    return encrypted
  def     snake_case_      (  self  )				->					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(a_  )  )





  def     snake_case_      (  self ,			a_  )				->					str:


    """simple docstring"""
    UpperCAmelCase    				=						self.make_decrypt_key()
    UpperCAmelCase    				=						self.process_text(text.upper()  )
    UpperCAmelCase    				=						''

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

    return decrypted




def    lowerCamelCase__		(    ):
  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(SCREAMING_SNAKE_CASE    ):
    UpperCAmelCase    				=						[int(SCREAMING_SNAKE_CASE    ) for x in input().split()]
    hill_matrix.append(SCREAMING_SNAKE_CASE    )

  UpperCAmelCase    				=						HillCipher(numpy.array(SCREAMING_SNAKE_CASE    )    )

  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(SCREAMING_SNAKE_CASE    )    )
  elif option == "2":
    UpperCAmelCase    				=						input('What text would you like to decrypt?: '    )
    print('Your decrypted text is:'    )
    print(hc.decrypt(SCREAMING_SNAKE_CASE    )    )


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  main()





'''simple docstring'''




import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch



class 							lowercase_						(		a			):

  '''simple docstring'''





  @require_torch
  def     snake_case_      (  self  )				->					Optional[Any]:


    """simple docstring"""
    # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
    # `transformers` is loaded, and it's too late for inside pytest - so we are changing it
    # while running an external program

    # python one-liner segments

    # this must be loaded before socket.socket is monkey-patched
    UpperCAmelCase    				=						'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n        '

    # Force fetching the files so that we can use the cache
    UpperCAmelCase    				=						'hf-internal-testing/tiny-random-bert'
    BertConfig.from_pretrained(a_  )
    BertModel.from_pretrained(a_  )
    BertTokenizer.from_pretrained(a_  )
    pipeline(task='fill-mask' ,			model=a_  )

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run, mock]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )
  @require_torch
  def     snake_case_      (  self  )				->					Union[str, Any]:


    """simple docstring"""
    # python one-liner segments
    # this must be loaded before socket.socket is monkey-patched
    UpperCAmelCase    				=						'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n        '

    # Force fetching the files so that we can use the cache
    UpperCAmelCase    				=						'hf-internal-testing/tiny-random-bert'
    BertConfig.from_pretrained(a_  )
    BertModel.from_pretrained(a_  )
    BertTokenizer.from_pretrained(a_  )
    pipeline(task='fill-mask' ,			model=a_  )

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run, mock]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )
  @require_torch
  def     snake_case_      (  self  )				->					List[str]:


    """simple docstring"""
    # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
    # `transformers` is loaded, and it's too late for inside pytest - so we are changing it
    # while running an external program

    # python one-liner segments

    # this must be loaded before socket.socket is monkey-patched
    UpperCAmelCase    				=						'\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        '

    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n        '

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )

    # next emulate no network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, mock, run]  )]

    # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
    # env["TRANSFORMERS_OFFLINE"] = "0"
    # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
    # self.assertEqual(result.returncode, 1, result.stderr)

    # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )
  @require_torch
  def     snake_case_      (  self  )				->					Optional[Any]:


    """simple docstring"""
    UpperCAmelCase    				=						'\nfrom transformers import pipeline\n        '
    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n        '
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, mock, run]  )]
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			1 ,			result.stderr  )
    self.assertIn(
        'You cannot infer task automatically within `pipeline` when using offline mode' ,			result.stderr.decode().replace('\n' ,			''  ) ,			)





  @require_torch
  def     snake_case_      (  self  )				->					str:


    """simple docstring"""
    UpperCAmelCase    				=						'\nfrom transformers import AutoModel\n        '
    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n        '

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )

    # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )


