


import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TextaTextGenerationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available

from .test_pipelines_common import ANY


if is_torch_available():
							import torch

@is_pipeline_test
class 						A__							(		unittest.TestCase  ):
						UpperCAmelCase             =						MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						UpperCAmelCase             =						TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING




						def 							__UpperCamelCase				(       self					:      Optional[Any]				,    _a					:      Tuple				,    _a					:      Optional[int]				,    _a					:      Any  )							->     Tuple:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =TextaTextGenerationPipeline(model=_a				,    tokenizer=_a  )
										return generator, ["Something to write", "Something else"]




						def 							__UpperCamelCase				(       self					:      Tuple				,    _a					:      Optional[Any]				,    _a					:      Dict  )							->     Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =generator('''Something there'''  )
										self.assertEqual(_a				,    [{'''generated_text''': ANY(_a  )}]  )
										# These are encoder decoder, they don't just append to incoming string
										self.assertFalse(outputs[0]['''generated_text'''].startswith('''Something there'''  )  )

										_SCREAMING_SNAKE_CASE			  =generator(['''This is great !''', '''Something else''']				,    num_return_sequences=2				,    do_sample=_a  )
										self.assertEqual(
										    _a				,    [
										        [{'''generated_text''': ANY(_a  )}, {'''generated_text''': ANY(_a  )}],
										        [{'''generated_text''': ANY(_a  )}, {'''generated_text''': ANY(_a  )}],
										    ]				,    )

										_SCREAMING_SNAKE_CASE			  =generator(
										    ['''This is great !''', '''Something else''']				,    num_return_sequences=2				,    batch_size=2				,    do_sample=_a  )
										self.assertEqual(
										    _a				,    [
										        [{'''generated_text''': ANY(_a  )}, {'''generated_text''': ANY(_a  )}],
										        [{'''generated_text''': ANY(_a  )}, {'''generated_text''': ANY(_a  )}],
										    ]				,    )

										with self.assertRaises(_a  ):
														generator(4  )




						@require_torch
						def 							__UpperCamelCase				(       self					:      Dict  )							->     Any:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =pipeline('''text2text-generation'''				,    model='''patrickvonplaten/t5-tiny-random'''				,    framework='''pt'''  )
										# do_sample=False necessary for reproducibility
										_SCREAMING_SNAKE_CASE			  =generator('''Something there'''				,    do_sample=_a  )
										self.assertEqual(_a				,    [{'''generated_text''': ''''''}]  )

										_SCREAMING_SNAKE_CASE			  =3
										_SCREAMING_SNAKE_CASE			  =generator(
										    '''Something there'''				,    num_return_sequences=_a				,    num_beams=_a				,    )
										_SCREAMING_SNAKE_CASE			  =[
										    {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide Beide'''},
										    {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide'''},
										    {'''generated_text''': ''''''},
										]
										self.assertEqual(_a				,    _a  )

										_SCREAMING_SNAKE_CASE			  =generator('''This is a test'''				,    do_sample=_a				,    num_return_sequences=2				,    return_tensors=_a  )
										self.assertEqual(
										    _a				,    [
										        {'''generated_token_ids''': ANY(torch.Tensor  )},
										        {'''generated_token_ids''': ANY(torch.Tensor  )},
										    ]				,    )
										_SCREAMING_SNAKE_CASE			  =generator.model.config.eos_token_id
										_SCREAMING_SNAKE_CASE			  ='''<pad>'''
										_SCREAMING_SNAKE_CASE			  =generator(
										    ['''This is a test''', '''This is a second test''']				,    do_sample=_a				,    num_return_sequences=2				,    batch_size=2				,    return_tensors=_a				,    )
										self.assertEqual(
										    _a				,    [
										        [
										            {'''generated_token_ids''': ANY(torch.Tensor  )},
										            {'''generated_token_ids''': ANY(torch.Tensor  )},
										        ],
										        [
										            {'''generated_token_ids''': ANY(torch.Tensor  )},
										            {'''generated_token_ids''': ANY(torch.Tensor  )},
										        ],
										    ]				,    )




						@require_tf
						def 							__UpperCamelCase				(       self					:      int  )							->     Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =pipeline('''text2text-generation'''				,    model='''patrickvonplaten/t5-tiny-random'''				,    framework='''tf'''  )
										# do_sample=False necessary for reproducibility
										_SCREAMING_SNAKE_CASE			  =generator('''Something there'''				,    do_sample=_a  )
										self.assertEqual(_a				,    [{'''generated_text''': ''''''}]  )



import string

import numpy







def 						lowerCamelCase(   a__	,a__):
				return b if a == 0 else greatest_common_divisor(b % a	,a__)

class 						A__							:
						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 UpperCamelCase__  : x % 36  )

						UpperCAmelCase             =						numpy.vectorize(UpperCamelCase__  )




						def __init__(       self					:      int				,    _a					:      numpy.ndarray  )							->     None:


										"""simple docstring"""





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




						def 							__UpperCamelCase				(       self					:      Dict				,    _a					:      str  )							->     int:


										"""simple docstring"""





										return self.key_string.index(_a  )




						def 							__UpperCamelCase				(       self					:      List[str]				,    _a					:      int  )							->     str:


										"""simple docstring"""





										return self.key_string[round(_a  )]




						def 							__UpperCamelCase				(       self					:      int  )							->     None:


										"""simple docstring"""





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

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

										_SCREAMING_SNAKE_CASE			  =len(self.key_string  )
										if greatest_common_divisor(_a				,    len(self.key_string  )  ) != 1:
														_SCREAMING_SNAKE_CASE			  =(
														    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 							__UpperCamelCase				(       self					:      List[str]				,    _a					:      str  )							->     str:


										"""simple docstring"""





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

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

										return "".join(_a  )




						def 							__UpperCamelCase				(       self					:      List[str]				,    _a					:      str  )							->     str:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =self.process_text(text.upper()  )
										_SCREAMING_SNAKE_CASE			  =''''''

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

										return encrypted




						def 							__UpperCamelCase				(       self					:      Union[str, Any]  )							->     numpy.ndarray:


										"""simple docstring"""





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

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

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

										return self.to_int(self.modulus(_a  )  )




						def 							__UpperCamelCase				(       self					:      str				,    _a					:      str  )							->     str:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE			  =self.make_decrypt_key()
										_SCREAMING_SNAKE_CASE			  =self.process_text(text.upper()  )
										_SCREAMING_SNAKE_CASE			  =''''''

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

										return decrypted







def 						lowerCamelCase(   ):
				_SCREAMING_SNAKE_CASE			  =int(input('''Enter the order of the encryption key: '''))
				_SCREAMING_SNAKE_CASE			  =[]

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

				_SCREAMING_SNAKE_CASE			  =HillCipher(numpy.array(a__))

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


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							main()