



import unittest

from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM







@require_torch
class       __lowerCAmelCase   :



			def __init__(						self       :  List[Any]			,		A       :  Dict			,		A       :  Tuple=99			,		A       :  Dict=13			,		A       :  str=16			,		A       :  List[Any]=7			,		A       :  str=True			,		A       :  int=True			,		A       :  Tuple=True			,		A       :  List[Any]=False			,		A       :  Dict=True			,		A       :  int=2			,		A       :  str=32			,		A       :  Tuple=4			,		A       :  Optional[Any]=4			,		A       :  Union[str, Any]=30			,		A       :  Dict=0			,		A       :  List[str]=1			,		A       :  Union[str, Any]=2			,		A       :  Optional[int]=None			,		)       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       parent
						_UpperCAmelCase			=       batch_size
						_UpperCAmelCase			=       decoder_seq_length
						# For common tests
						_UpperCAmelCase			=       self.decoder_seq_length
						_UpperCAmelCase			=       is_training
						_UpperCAmelCase			=       use_attention_mask
						_UpperCAmelCase			=       use_labels

						_UpperCAmelCase			=       vocab_size
						_UpperCAmelCase			=       d_model
						_UpperCAmelCase			=       d_model
						_UpperCAmelCase			=       decoder_layers
						_UpperCAmelCase			=       decoder_layers
						_UpperCAmelCase			=       decoder_ffn_dim
						_UpperCAmelCase			=       decoder_attention_heads
						_UpperCAmelCase			=       decoder_attention_heads
						_UpperCAmelCase			=       eos_token_id
						_UpperCAmelCase			=       bos_token_id
						_UpperCAmelCase			=       pad_token_id
						_UpperCAmelCase			=       decoder_start_token_id
						_UpperCAmelCase			=       use_cache
						_UpperCAmelCase			=       max_position_embeddings

						_UpperCAmelCase			=       None
						_UpperCAmelCase			=       decoder_seq_length
						_UpperCAmelCase			=       2
						_UpperCAmelCase			=       1



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



						"""simple docstring"""






						_UpperCAmelCase			=       ids_tensor([self.batch_size, self.decoder_seq_length]			,		self.vocab_size)

						_UpperCAmelCase			=       None
						if self.use_attention_mask:
									_UpperCAmelCase			=       ids_tensor([self.batch_size, self.decoder_seq_length]			,		vocab_size=2)

						_UpperCAmelCase			=       None
						if self.use_labels:
									_UpperCAmelCase			=       ids_tensor([self.batch_size, self.decoder_seq_length]			,		self.vocab_size)

						_UpperCAmelCase			=       TrOCRConfig(
						    vocab_size=self.vocab_size			,		d_model=self.d_model			,		decoder_layers=self.decoder_layers			,		decoder_ffn_dim=self.decoder_ffn_dim			,		decoder_attention_heads=self.decoder_attention_heads			,		eos_token_id=self.eos_token_id			,		bos_token_id=self.bos_token_id			,		use_cache=self.use_cache			,		pad_token_id=self.pad_token_id			,		decoder_start_token_id=self.decoder_start_token_id			,		max_position_embeddings=self.max_position_embeddings			,		)

						return (config, input_ids, attention_mask, lm_labels)



			def    _lowerCamelCase	(						self       :  Optional[Any]			,		A       :  Optional[int]			,		A       :  Tuple			,		A       :  List[str]			,		A       :  str			,		)       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       True
						_UpperCAmelCase			=       TrOCRDecoder(config=A).to(A).eval()
						_UpperCAmelCase			=       input_ids[:2]

						input_ids[input_ids == 0] += 1
						# first forward pass
						_UpperCAmelCase			=       model(A			,		use_cache=A)
						_UpperCAmelCase			=       model(A)
						_UpperCAmelCase			=       model(A			,		use_cache=A)

						self.parent.assertTrue(len(A) == len(A))
						self.parent.assertTrue(len(A) == len(A) + 1)

						_UpperCAmelCase			=       outputs['past_key_values']

						# create hypothetical next token and extent to next_input_ids
						_UpperCAmelCase			=       ids_tensor((2, 1)			,		config.vocab_size - 1) + 1

						# append to next input_ids and
						_UpperCAmelCase			=       torch.cat([input_ids, next_tokens]			,		dim=-1)

						_UpperCAmelCase			=       model(A)['last_hidden_state']
						_UpperCAmelCase			=       model(A			,		past_key_values=A)['last_hidden_state']

						# select random slice
						_UpperCAmelCase			=       ids_tensor((1,)			,		output_from_past.shape[-1]).item()
						_UpperCAmelCase			=       output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
						_UpperCAmelCase			=       output_from_past[:, 0, random_slice_idx].detach()

						# test that outputs are equal for slice
						assert torch.allclose(A			,		A			,		atol=1E-3)



			def    _lowerCamelCase	(						self       :  List[Any])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       self.prepare_config_and_inputs()
						_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase			=       config_and_inputs

						_UpperCAmelCase			=       {'input_ids': input_ids, 'attention_mask': attention_mask}
						return config, inputs_dict







@require_torch
class       __lowerCAmelCase   (      A    ,						A    ,						A    ,						unittest.TestCase						):
			UpperCamelCase        =					(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
			UpperCamelCase        =					(TrOCRForCausalLM,) if is_torch_available() else ()
			UpperCamelCase        =					{'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
			UpperCamelCase        =					True
			UpperCamelCase        =					False



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



						"""simple docstring"""






						_UpperCAmelCase			=       TrOCRStandaloneDecoderModelTester(self			,		is_training=A)
						_UpperCAmelCase			=       ConfigTester(self			,		config_class=A)



			def    _lowerCamelCase	(						self       :  Any)       ->   List[str]:



						"""simple docstring"""






						pass



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



						"""simple docstring"""






						pass



			def    _lowerCamelCase	(						self       :  List[Any])       ->   int:



						"""simple docstring"""






						pass



			def    _lowerCamelCase	(						self       :  Any)       ->   str:



						"""simple docstring"""






						self.config_tester.run_common_tests()



			def    _lowerCamelCase	(						self       :  Dict)       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past(*A)



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Optional[Any]:



						"""simple docstring"""






						return



			@unittest.skip('The model doesn\'t support left padding')  # and it's not used enough to be worth fixing :)
			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   List[str]:



						"""simple docstring"""






						pass





import string

import numpy





def 							A     (					_UpperCAmelCase    :       int							,       _UpperCAmelCase    :       int   )    ->			int:







			'''simple docstring'''
			return b if a == 0 else greatest_common_divisor(b % a							,       _UpperCAmelCase   )







class       __lowerCAmelCase   :
			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 A						: x % 3_6						)

			UpperCamelCase        =					numpy.vectorize(A						)



			def __init__(						self       :  Tuple			,		A       :  numpy.ndarray)       ->   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    _lowerCamelCase	(						self       :  str			,		A       :  str)       ->   int:



						"""simple docstring"""






						return self.key_string.index(A)



			def    _lowerCamelCase	(						self       :  Any			,		A       :  int)       ->   str:



						"""simple docstring"""






						return self.key_string[round(A)]



			def    _lowerCamelCase	(						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(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    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  str)       ->   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    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  str)       ->   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    _lowerCamelCase	(						self       :  Optional[Any])       ->   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    _lowerCamelCase	(						self       :  Tuple			,		A       :  str)       ->   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 							A     (					)    ->			None:







			'''simple docstring'''
			_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(_UpperCAmelCase   ):
						_UpperCAmelCase			=       [int(_UpperCAmelCase   ) for x in input().split()]
						hill_matrix.append(_UpperCAmelCase   )

			_UpperCAmelCase			=       HillCipher(numpy.array(_UpperCAmelCase   )   )

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


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							main()
