



"""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  _lowerCAmelCase     :





		"""simple docstring"""






		def __init__(       self				,     _lowercase				,     _lowercase=9_9				,     _lowercase=1_3				,     _lowercase=1_6				,     _lowercase=7				,     _lowercase=True				,     _lowercase=True				,     _lowercase=True				,     _lowercase=False				,     _lowercase=True				,     _lowercase=2				,     _lowercase=3_2				,     _lowercase=4				,     _lowercase=4				,     _lowercase=3_0				,     _lowercase=0				,     _lowercase=1				,     _lowercase=2				,     _lowercase=None				,     )			->    str:







								'''simple docstring'''

								snake_case_ :			Union[str, Any]            =      parent
								snake_case_ :			List[Any]            =      batch_size
								snake_case_ :			Union[str, Any]            =      decoder_seq_length
								# For common tests
								snake_case_ :			Optional[Any]            =      self.decoder_seq_length
								snake_case_ :			Union[str, Any]            =      is_training
								snake_case_ :			Optional[Any]            =      use_attention_mask
								snake_case_ :			Any            =      use_labels

								snake_case_ :			List[str]            =      vocab_size
								snake_case_ :			Optional[int]            =      d_model
								snake_case_ :			Dict            =      d_model
								snake_case_ :			Optional[int]            =      decoder_layers
								snake_case_ :			List[Any]            =      decoder_layers
								snake_case_ :			Optional[Any]            =      decoder_ffn_dim
								snake_case_ :			Optional[int]            =      decoder_attention_heads
								snake_case_ :			Tuple            =      decoder_attention_heads
								snake_case_ :			Tuple            =      eos_token_id
								snake_case_ :			Optional[Any]            =      bos_token_id
								snake_case_ :			str            =      pad_token_id
								snake_case_ :			List[str]            =      decoder_start_token_id
								snake_case_ :			List[Any]            =      use_cache
								snake_case_ :			Optional[int]            =      max_position_embeddings

								snake_case_ :			str            =      None
								snake_case_ :			int            =      decoder_seq_length
								snake_case_ :			int            =      2
								snake_case_ :			Dict            =      1





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







								'''simple docstring'''

								snake_case_ :			Union[str, Any]            =      ids_tensor([self.batch_size, self.decoder_seq_length]				,     self.vocab_size )

								snake_case_ :			List[str]            =      None
								if self.use_attention_mask:
														snake_case_ :			Tuple            =      ids_tensor([self.batch_size, self.decoder_seq_length]				,     vocab_size=2 )

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

								snake_case_ :			Optional[int]            =      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				,     _lowercase				,     _lowercase				,     _lowercase				,     _lowercase				,     )			->    Optional[int]:







								'''simple docstring'''

								snake_case_ :			Optional[int]            =      True
								snake_case_ :			Tuple            =      TrOCRDecoder(config=_lowercase ).to(_lowercase ).eval()
								snake_case_ :			Optional[int]            =      input_ids[:2]

								input_ids[input_ids == 0] += 1
								# first forward pass
								snake_case_ :			Any            =      model(_lowercase				,     use_cache=_lowercase )
								snake_case_ :			Union[str, Any]            =      model(_lowercase )
								snake_case_ :			str            =      model(_lowercase				,     use_cache=_lowercase )

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

								snake_case_ :			str            =      outputs["""past_key_values"""]

								# create hypothetical next token and extent to next_input_ids
								snake_case_ :			List[Any]            =      ids_tensor((2, 1)				,     config.vocab_size - 1 ) + 1

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

								snake_case_ :			Union[str, Any]            =      model(_lowercase )["""last_hidden_state"""]
								snake_case_ :			Optional[Any]            =      model(_lowercase				,     past_key_values=_lowercase )["""last_hidden_state"""]

								# select random slice
								snake_case_ :			Optional[Any]            =      ids_tensor((1,)				,     output_from_past.shape[-1] ).item()
								snake_case_ :			Dict            =      output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
								snake_case_ :			Optional[int]            =      output_from_past[:, 0, random_slice_idx].detach()

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





		def  UpperCAmelCase__				(       self )			->    str:







								'''simple docstring'''

								snake_case_ :			int            =      self.prepare_config_and_inputs()
								snake_case_      ,		snake_case_      ,		snake_case_      ,		snake_case_ :			Optional[Any]            =      config_and_inputs

								snake_case_ :			Dict            =      {"""input_ids""": input_ids, """attention_mask""": attention_mask}
								return config, inputs_dict




@require_torch
class  _lowerCAmelCase     (					SCREAMING_SNAKE_CASE__	,					SCREAMING_SNAKE_CASE__	,					SCREAMING_SNAKE_CASE__	,					unittest.TestCase		):





		"""simple docstring"""






		_lowerCamelCase      	=							(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
		_lowerCamelCase      	=							(TrOCRForCausalLM,) if is_torch_available() else ()
		_lowerCamelCase      	=							{'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
		_lowerCamelCase      	=							True
		_lowerCamelCase      	=							False





		def  UpperCAmelCase__				(       self )			->    Dict:







								'''simple docstring'''

								snake_case_ :			List[str]            =      TrOCRStandaloneDecoderModelTester(self				,     is_training=_lowercase )
								snake_case_ :			int            =      ConfigTester(self				,     config_class=_lowercase )





		def  UpperCAmelCase__				(       self )			->    List[str]:







								'''simple docstring'''

								pass





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







								'''simple docstring'''

								pass





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







								'''simple docstring'''

								pass





		def  UpperCAmelCase__				(       self )			->    List[Any]:







								'''simple docstring'''

								self.config_tester.run_common_tests()





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







								'''simple docstring'''

								snake_case_ :			Any            =      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_decoder_model_past(*_lowercase )





		def  UpperCAmelCase__				(       self )			->    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 )			->    int:







								'''simple docstring'''

								pass



from __future__ import annotations




class 					lowerCamelCase__				:




	'''simple docstring'''




	def __init__(   self						:Dict	,  a						:str	,  a						:str		)						->					Union[str, Any]:
								__UpperCamelCase  ,		__UpperCamelCase      :  Optional[int]       =   text, pattern
								__UpperCamelCase  ,		__UpperCamelCase      :  Tuple       =   len(a		), len(a		)







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

								for i in range(self.patLen - 1	,  -1	,  -1		):
															if char == self.pattern[i]:
																						return i
								return -1







	def   _lowerCamelCase							(   self						:str	,  a						:int		)						->					int:

								for i in range(self.patLen - 1	,  -1	,  -1		):
															if self.pattern[i] != self.text[current_pos + i]:
																						return current_pos + i
								return -1







	def   _lowerCamelCase							(   self						:Union[str, Any]		)						->					list[int]:
								# searches pattern in text and returns index positions
								__UpperCamelCase      :  Any       =   []
								for i in range(self.textLen - self.patLen + 1		):
															__UpperCamelCase      :  List[Any]       =   self.mismatch_in_text(a		)
															if mismatch_index == -1:
																						positions.append(a		)
															else:
																						__UpperCamelCase      :  Any       =   self.match_in_pattern(self.text[mismatch_index]		)
																						__UpperCamelCase      :  Dict       =   (
																						    mismatch_index - match_index
																						)  # shifting index lgtm [py/multiple-definition]
								return positions
lowercase    :   Any						=			'ABAABA'
lowercase    :   str						=			'AB'
lowercase    :   str						=			BoyerMooreSearch(text, pattern)
lowercase    :   Union[str, Any]						=			bms.bad_character_heuristic()

if len(positions) == 0:
		print('No match found')
else:
		print('Pattern found in following positions: ')
		print(positions)