
"""simple docstring"""






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 			lowercase					:






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





				"""simple docstring"""


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

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

				lowerCAmelCase												=  None
				lowerCAmelCase												=  decoder_seq_length
				lowerCAmelCase												=  2
				lowerCAmelCase												=  1






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





				"""simple docstring"""


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

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

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

				lowerCAmelCase												=  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 					UpperCAmelCase							(self  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	int      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	int      ,)       ->	Union[str, Any]:





				"""simple docstring"""


				lowerCAmelCase												=  True
				lowerCAmelCase												=  TrOCRDecoder(config=SCREAMING_SNAKE_CASE_			).to(SCREAMING_SNAKE_CASE_			).eval()
				lowerCAmelCase												=  input_ids[:2]

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

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

				lowerCAmelCase												=  outputs['''past_key_values''']

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

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

				lowerCAmelCase												=  model(SCREAMING_SNAKE_CASE_			)['''last_hidden_state''']
				lowerCAmelCase												=  model(SCREAMING_SNAKE_CASE_      ,past_key_values=SCREAMING_SNAKE_CASE_			)['''last_hidden_state''']

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

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






			def 					UpperCAmelCase							(self  :	Dict			)       ->	int:





				"""simple docstring"""


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

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





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






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





				"""simple docstring"""


				lowerCAmelCase												=  TrOCRStandaloneDecoderModelTester(self      ,is_training=SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  ConfigTester(self      ,config_class=SCREAMING_SNAKE_CASE_			)






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





				"""simple docstring"""


				pass






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





				"""simple docstring"""


				pass






			def 					UpperCAmelCase							(self  :	Tuple			)       ->	Tuple:





				"""simple docstring"""


				pass






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





				"""simple docstring"""


				self.config_tester.run_common_tests()






			def 					UpperCAmelCase							(self  :	Union[str, Any]			)       ->	Optional[Any]:





				"""simple docstring"""


				lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_decoder_model_past(*SCREAMING_SNAKE_CASE_			)






			def 					UpperCAmelCase							(self  :	Tuple			)       ->	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 					UpperCAmelCase							(self  :	Any			)       ->	Optional[int]:





				"""simple docstring"""


				pass




"""simple docstring"""






from __future__ import annotations



class 			lowercase					:






			def __init__(self  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	int = 0			)       ->	List[Any]:





				"""simple docstring"""


				lowerCAmelCase												=  key






			def 					UpperCAmelCase							(self  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	list[str]:





				"""simple docstring"""


				assert isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  key or self.__key or 1

				# make sure key is an appropriate size
				key %= 255

				return [chr(ord(SCREAMING_SNAKE_CASE_			) ^ key			) for ch in content]






			def 					UpperCAmelCase							(self  :	int      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	list[str]:





				"""simple docstring"""


				assert isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  key or self.__key or 1

				# make sure key is an appropriate size
				key %= 255

				return [chr(ord(SCREAMING_SNAKE_CASE_			) ^ key			) for ch in content]






			def 					UpperCAmelCase							(self  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int = 0			)       ->	str:





				"""simple docstring"""


				assert isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  key or self.__key or 1

				# make sure key can be any size
				while key > 255:
					key -= 255

				# This will be returned
				lowerCAmelCase												=  ''''''

				for ch in content:
					ans += chr(ord(SCREAMING_SNAKE_CASE_			) ^ key			)

				return ans






			def 					UpperCAmelCase							(self  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int = 0			)       ->	str:





				"""simple docstring"""


				assert isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  key or self.__key or 1

				# make sure key can be any size
				while key > 255:
					key -= 255

				# This will be returned
				lowerCAmelCase												=  ''''''

				for ch in content:
					ans += chr(ord(SCREAMING_SNAKE_CASE_			) ^ key			)

				return ans






			def 					UpperCAmelCase							(self  :	List[str]      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int = 0			)       ->	bool:





				"""simple docstring"""


				assert isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				try:
					with open(SCREAMING_SNAKE_CASE_			) as fin, open('''encrypt.out'''      ,'''w+'''			) as fout:
						# actual encrypt-process
						for line in fin:
							fout.write(self.encrypt_string(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)			)

				except OSError:
					return False

				return True






			def 					UpperCAmelCase							(self  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	bool:





				"""simple docstring"""


				assert isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				try:
					with open(SCREAMING_SNAKE_CASE_			) as fin, open('''decrypt.out'''      ,'''w+'''			) as fout:
						# actual encrypt-process
						for line in fin:
							fout.write(self.decrypt_string(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)			)

				except OSError:
					return False

				return True


# Tests
# crypt = XORCipher()
# key = 67

# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))

# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))

# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))

# if (crypt.encrypt_file("test.txt",key)):
#       print("encrypt successful")
# else:
#       print("encrypt unsuccessful")

# if (crypt.decrypt_file("encrypt.out",key)):
#       print("decrypt successful")
# else:
#       print("decrypt unsuccessful")


