





'''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       __SCREAMING_SNAKE_CASE	:



       '''simple docstring'''






       def __init__(					self						,   lowerCamelCase						,   lowerCamelCase=99						,   lowerCamelCase=13						,   lowerCamelCase=16						,   lowerCamelCase=7						,   lowerCamelCase=True						,   lowerCamelCase=True						,   lowerCamelCase=True						,   lowerCamelCase=False						,   lowerCamelCase=True						,   lowerCamelCase=2						,   lowerCamelCase=32						,   lowerCamelCase=4						,   lowerCamelCase=4						,   lowerCamelCase=30						,   lowerCamelCase=0						,   lowerCamelCase=1						,   lowerCamelCase=2						,   lowerCamelCase=None						,   ):
         _snake_case     		=				parent
         _snake_case     		=				batch_size
         _snake_case     		=				decoder_seq_length
         # For common tests
         _snake_case     		=				self.decoder_seq_length
         _snake_case     		=				is_training
         _snake_case     		=				use_attention_mask
         _snake_case     		=				use_labels

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

         _snake_case     		=				None
         _snake_case     		=				decoder_seq_length
         _snake_case     		=				2
         _snake_case     		=				1

       def 	UpperCamelCase(					self	):
         _snake_case     		=				ids_tensor([self.batch_size, self.decoder_seq_length]						,   self.vocab_size	)

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

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

         _snake_case     		=				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						,   lowerCamelCase						,   lowerCamelCase						,   lowerCamelCase						,   lowerCamelCase						,   ):
         _snake_case     		=				True
         _snake_case     		=				TrOCRDecoder(config=__SCREAMING_SNAKE_CASE	).to(__SCREAMING_SNAKE_CASE	).eval()
         _snake_case     		=				input_ids[:2]

         input_ids[input_ids == 0] += 1
         # first forward pass
         _snake_case     		=				model(__SCREAMING_SNAKE_CASE						,   use_cache=__SCREAMING_SNAKE_CASE	)
         _snake_case     		=				model(__SCREAMING_SNAKE_CASE	)
         _snake_case     		=				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	)

         _snake_case     		=				outputs["past_key_values"]

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

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

         _snake_case     		=				model(__SCREAMING_SNAKE_CASE	)["last_hidden_state"]
         _snake_case     		=				model(__SCREAMING_SNAKE_CASE						,   past_key_values=__SCREAMING_SNAKE_CASE	)["last_hidden_state"]

         # select random slice
         _snake_case     		=				ids_tensor((1,)						,   output_from_past.shape[-1]	).item()
         _snake_case     		=				output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
         _snake_case     		=				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	):
         _snake_case     		=				self.prepare_config_and_inputs()
         _snake_case		,		_snake_case		,		_snake_case		,		_snake_case     		=				config_and_inputs

         _snake_case     		=				{"input_ids": input_ids, "attention_mask": attention_mask}
         return config, inputs_dict







@require_torch
class       __SCREAMING_SNAKE_CASE	(						__UpperCAmelCase					,    __UpperCAmelCase					,    __UpperCAmelCase					,    unittest.TestCase			):



       '''simple docstring'''






       UpperCAmelCase__       :						Optional[int]      =   (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
       UpperCAmelCase__       :						Optional[Any]      =   (TrOCRForCausalLM,) if is_torch_available() else ()
       UpperCAmelCase__       :						int      =   {'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
       UpperCAmelCase__       :						Optional[Any]      =   True
       UpperCAmelCase__       :						int      =   False

       def 	UpperCamelCase(					self	):
         _snake_case     		=				TrOCRStandaloneDecoderModelTester(self						,   is_training=__SCREAMING_SNAKE_CASE	)
         _snake_case     		=				ConfigTester(self						,   config_class=__SCREAMING_SNAKE_CASE	)

       def 	UpperCamelCase(					self	):
         pass

       def 	UpperCamelCase(					self	):
         pass

       def 	UpperCamelCase(					self	):
         pass

       def 	UpperCamelCase(					self	):
         self.config_tester.run_common_tests()

       def 	UpperCamelCase(					self	):
         _snake_case     		=				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_decoder_model_past(*__SCREAMING_SNAKE_CASE	)

       def 	UpperCamelCase(					self	):
         return






       @unittest.skip("The model doesn\'t support left padding"	)  # and it's not used enough to be worth fixing :)
       def 	UpperCamelCase(					self	):
         pass









'''simple docstring'''



from __future__ import annotations

from PIL import Image

# Define glider example
__magic_name__   :						str    =			[
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
]

# Define blinker example
__magic_name__   :						List[Any]    =			[[0, 1, 0], [0, 1, 0], [0, 1, 0]]




def 				snake_case_      (		SCREAMING_SNAKE_CASE__       ):







  '''simple docstring'''



  _snake_case     		=				[]
  for i in range(len(SCREAMING_SNAKE_CASE__       )       ):
    _snake_case     		=				[]
    for j in range(len(cells[i]       )       ):
      # Get the number of live neighbours
      _snake_case     		=				0
      if i > 0 and j > 0:
        neighbour_count += cells[i - 1][j - 1]
      if i > 0:
        neighbour_count += cells[i - 1][j]
      if i > 0 and j < len(cells[i]       ) - 1:
        neighbour_count += cells[i - 1][j + 1]
      if j > 0:
        neighbour_count += cells[i][j - 1]
      if j < len(cells[i]       ) - 1:
        neighbour_count += cells[i][j + 1]
      if i < len(SCREAMING_SNAKE_CASE__       ) - 1 and j > 0:
        neighbour_count += cells[i + 1][j - 1]
      if i < len(SCREAMING_SNAKE_CASE__       ) - 1:
        neighbour_count += cells[i + 1][j]
      if i < len(SCREAMING_SNAKE_CASE__       ) - 1 and j < len(cells[i]       ) - 1:
        neighbour_count += cells[i + 1][j + 1]

      # Rules of the game of life (excerpt from Wikipedia):
      # 1. Any live cell with two or three live neighbours survives.
      # 2. Any dead cell with three live neighbours becomes a live cell.
      # 3. All other live cells die in the next generation.
      #    Similarly, all other dead cells stay dead.
      _snake_case     		=				cells[i][j] == 1
      if (
          (alive and 2 <= neighbour_count <= 3)
          or not alive
          and neighbour_count == 3
      ):
        next_generation_row.append(1       )
      else:
        next_generation_row.append(0       )

    next_generation.append(SCREAMING_SNAKE_CASE__       )
  return next_generation




def 				snake_case_      (		SCREAMING_SNAKE_CASE__					,	SCREAMING_SNAKE_CASE__       ):







  '''simple docstring'''



  _snake_case     		=				[]
  for _ in range(SCREAMING_SNAKE_CASE__       ):
    # Create output image
    _snake_case     		=				Image.new("RGB"					,	(len(cells[0]       ), len(SCREAMING_SNAKE_CASE__       ))       )
    _snake_case     		=				img.load()

    # Save cells to image
    for x in range(len(SCREAMING_SNAKE_CASE__       )       ):
      for y in range(len(cells[0]       )       ):
        _snake_case     		=				2_55 - cells[y][x] * 2_55
        _snake_case     		=				(colour, colour, colour)

        # Save image
    images.append(SCREAMING_SNAKE_CASE__       )
    _snake_case     		=				new_generation(SCREAMING_SNAKE_CASE__       )
  return images


if __name__ == "__main__":
 __magic_name__   :						Optional[Any]    =			generate_images(GLIDER, 16)
 images[0].save("""out.gif""", save_all=True, append_images=images[1:])


