





import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

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 import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
      from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Union[str, Any]   ,   SCREAMING_SNAKE_CASE		:Optional[Any]   ,   SCREAMING_SNAKE_CASE		:Any   ,   SCREAMING_SNAKE_CASE		:int=None   ,   SCREAMING_SNAKE_CASE		:Tuple=None   ,   SCREAMING_SNAKE_CASE		:Optional[int]=None   ,   SCREAMING_SNAKE_CASE		:int=None   ,   SCREAMING_SNAKE_CASE		:Dict=None   ,   )      ->   List[Any]:
 if attention_mask is None:
  __lowerCAmelCase					:	Dict      =       input_ids.ne(config.pad_token_id   )
 if decoder_attention_mask is None:
  __lowerCAmelCase					:	Optional[Any]      =       decoder_input_ids.ne(config.pad_token_id   )
 if head_mask is None:
  __lowerCAmelCase					:	Dict      =       torch.ones(config.encoder_layers   ,   config.encoder_attention_heads   ,   device=SCREAMING_SNAKE_CASE   )
 if decoder_head_mask is None:
  __lowerCAmelCase					:	Any      =       torch.ones(config.decoder_layers   ,   config.decoder_attention_heads   ,   device=SCREAMING_SNAKE_CASE   )
 if cross_attn_head_mask is None:
  __lowerCAmelCase					:	Any      =       torch.ones(config.decoder_layers   ,   config.decoder_attention_heads   ,   device=SCREAMING_SNAKE_CASE   )
 return {
     "input_ids": input_ids,
     "decoder_input_ids": decoder_input_ids,
     "attention_mask": attention_mask,
     "decoder_attention_mask": attention_mask,
     "head_mask": head_mask,
     "decoder_head_mask": decoder_head_mask,
     "cross_attn_head_mask": cross_attn_head_mask,
 }






class        snake_case_    :






  def __init__(							self			:					Any       ,  _snake_case			:					Union[str, Any]       ,  _snake_case			:					List[Any]=13       ,  _snake_case			:					Optional[int]=7       ,  _snake_case			:					List[Any]=True       ,  _snake_case			:					int=False       ,  _snake_case			:					List[Any]=99       ,  _snake_case			:					Tuple=16       ,  _snake_case			:					Any=2       ,  _snake_case			:					int=4       ,  _snake_case			:					Union[str, Any]=4       ,  _snake_case			:					Optional[Any]="relu"       ,  _snake_case			:					Optional[int]=0.1       ,  _snake_case			:					Union[str, Any]=0.1       ,  _snake_case			:					List[str]=0.0       ,  _snake_case			:					List[str]=0.0       ,  _snake_case			:					Dict=20       ,  _snake_case			:					str=2       ,  _snake_case			:					Union[str, Any]=1       ,  _snake_case			:					Tuple=0       ,  )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       parent
   __lowerCAmelCase					:	Dict      =       batch_size
   __lowerCAmelCase					:	List[str]      =       seq_length
   __lowerCAmelCase					:	int      =       is_training
   __lowerCAmelCase					:	int      =       use_labels
   __lowerCAmelCase					:	List[Any]      =       vocab_size
   __lowerCAmelCase					:	Optional[int]      =       hidden_size
   __lowerCAmelCase					:	Dict      =       num_hidden_layers
   __lowerCAmelCase					:	Tuple      =       num_attention_heads
   __lowerCAmelCase					:	Optional[int]      =       intermediate_size
   __lowerCAmelCase					:	Tuple      =       hidden_act
   __lowerCAmelCase					:	int      =       hidden_dropout_prob
   __lowerCAmelCase					:	Any      =       attention_probs_dropout_prob
   __lowerCAmelCase					:	Tuple      =       encoder_layerdrop
   __lowerCAmelCase					:	List[Any]      =       decoder_layerdrop
   __lowerCAmelCase					:	int      =       max_position_embeddings
   __lowerCAmelCase					:	Dict      =       eos_token_id
   __lowerCAmelCase					:	int      =       pad_token_id
   __lowerCAmelCase					:	int      =       bos_token_id






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






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size      )
   __lowerCAmelCase					:	str      =       self.eos_token_id  # Eos Token
   __lowerCAmelCase					:	Any      =       ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size      )

   # we need to clamp the input ids here to avoid having pad token in between
   # this is because for M2M100 the position_ids are prepared such that
   # all pad tokens have pos id = 2 and rest are between 2..seq_length
   # and the seq_length here is seq_length - num_pad_tokens
   # but when using past, there is no way of knowing if the past input ids had
   # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
   # position_ids being off by num_pad_tokens in past input
   __lowerCAmelCase					:	Optional[Any]      =       input_ids.clamp(self.pad_token_id + 1      )
   __lowerCAmelCase					:	int      =       decoder_input_ids.clamp(self.pad_token_id + 1      )

   __lowerCAmelCase					:	Tuple      =       self.get_config()
   __lowerCAmelCase					:	str      =       prepare_mam_aaa_inputs_dict(_snake_case       ,  _snake_case       ,  _snake_case      )
   return config, inputs_dict






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






   '''simple docstring'''

   return MaMaaaConfig(
       vocab_size=self.vocab_size       ,  d_model=self.hidden_size       ,  encoder_layers=self.num_hidden_layers       ,  decoder_layers=self.num_hidden_layers       ,  encoder_attention_heads=self.num_attention_heads       ,  decoder_attention_heads=self.num_attention_heads       ,  encoder_ffn_dim=self.intermediate_size       ,  decoder_ffn_dim=self.intermediate_size       ,  dropout=self.hidden_dropout_prob       ,  attention_dropout=self.attention_probs_dropout_prob       ,  encoder_layerdrop=self.encoder_layerdrop       ,  decoder_layerdrop=self.decoder_layerdrop       ,  max_position_embeddings=self.max_position_embeddings       ,  eos_token_id=self.eos_token_id       ,  bos_token_id=self.bos_token_id       ,  pad_token_id=self.pad_token_id       ,  )






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






   '''simple docstring'''

   __lowerCAmelCase ,					__lowerCAmelCase					:	Optional[Any]      =       self.prepare_config_and_inputs()
   return config, inputs_dict






  def 				UpperCAmelCase__						(							self			:					Tuple       ,  _snake_case			:					List[Any]       ,  _snake_case			:					str      )->Tuple:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       MaMaaaModel(config=_snake_case      ).get_decoder().to(_snake_case      ).eval()
   __lowerCAmelCase					:	Dict      =       inputs_dict["""input_ids"""]
   __lowerCAmelCase					:	Dict      =       inputs_dict["""attention_mask"""]
   __lowerCAmelCase					:	Union[str, Any]      =       inputs_dict["""head_mask"""]

   # first forward pass
   __lowerCAmelCase					:	Optional[Any]      =       model(_snake_case       ,  attention_mask=_snake_case       ,  head_mask=_snake_case       ,  use_cache=_snake_case      )

   __lowerCAmelCase ,					__lowerCAmelCase					:	Any      =       outputs.to_tuple()

   # create hypothetical multiple next token and extent to next_input_ids
   __lowerCAmelCase					:	Optional[Any]      =       ids_tensor((self.batch_size, 3)       ,  config.vocab_size      )
   __lowerCAmelCase					:	Union[str, Any]      =       ids_tensor((self.batch_size, 3)       ,  2      )

   # append to next input_ids and
   __lowerCAmelCase					:	int      =       torch.cat([input_ids, next_tokens]       ,  dim=-1      )
   __lowerCAmelCase					:	Optional[Any]      =       torch.cat([attention_mask, next_attn_mask]       ,  dim=-1      )

   __lowerCAmelCase					:	int      =       model(_snake_case       ,  attention_mask=_snake_case      )["""last_hidden_state"""]
   __lowerCAmelCase					:	Any      =       model(_snake_case       ,  attention_mask=_snake_case       ,  past_key_values=_snake_case      )[
       """last_hidden_state"""
   ]

   # select random slice
   __lowerCAmelCase					:	Dict      =       ids_tensor((1,)       ,  output_from_past.shape[-1]      ).item()
   __lowerCAmelCase					:	List[str]      =       output_from_no_past[:, -3:, random_slice_idx].detach()
   __lowerCAmelCase					:	Dict      =       output_from_past[:, :, random_slice_idx].detach()

   self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]      )

   # test that outputs are equal for slice
   self.parent.assertTrue(torch.allclose(_snake_case       ,  _snake_case       ,  atol=1E-2      )      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       MaMaaaModel(config=_snake_case      ).to(_snake_case      ).eval()
   __lowerCAmelCase					:	Union[str, Any]      =       model(**_snake_case      )

   __lowerCAmelCase					:	Optional[int]      =       outputs.encoder_last_hidden_state
   __lowerCAmelCase					:	Tuple      =       outputs.last_hidden_state

   with tempfile.TemporaryDirectory() as tmpdirname:
    __lowerCAmelCase					:	Union[str, Any]      =       model.get_encoder()
    encoder.save_pretrained(_snake_case      )
    __lowerCAmelCase					:	Union[str, Any]      =       MaMaaaEncoder.from_pretrained(_snake_case      ).to(_snake_case      )

   __lowerCAmelCase					:	Union[str, Any]      =       encoder(inputs_dict["""input_ids"""]       ,  attention_mask=inputs_dict["""attention_mask"""]      )[
       0
   ]

   self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3      )

   with tempfile.TemporaryDirectory() as tmpdirname:
    __lowerCAmelCase					:	str      =       model.get_decoder()
    decoder.save_pretrained(_snake_case      )
    __lowerCAmelCase					:	Optional[Any]      =       MaMaaaDecoder.from_pretrained(_snake_case      ).to(_snake_case      )

   __lowerCAmelCase					:	Union[str, Any]      =       decoder(
       input_ids=inputs_dict["""decoder_input_ids"""]       ,  attention_mask=inputs_dict["""decoder_attention_mask"""]       ,  encoder_hidden_states=_snake_case       ,  encoder_attention_mask=inputs_dict["""attention_mask"""]       ,  )[0]

   self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3      )






@require_torch
class        snake_case_    (		__lowercase					,__lowercase					,__lowercase					,unittest.TestCase						):
  A_      							=   (
      (
          MaMaaaModel,
          MaMaaaForConditionalGeneration,
      )
      if is_torch_available()
      else ()
  )
  A_      							=   (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
  A_      							=   (
      {
          'conversational': MaMaaaForConditionalGeneration,
          'feature-extraction': MaMaaaModel,
          'summarization': MaMaaaForConditionalGeneration,
          'text2text-generation': MaMaaaForConditionalGeneration,
          'translation': MaMaaaForConditionalGeneration,
      }
      if is_torch_available()
      else {}
  )
  A_      							=   True
  A_      							=   True
  A_      							=   False
  A_      							=   False






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






   '''simple docstring'''

   if pipeline_test_casse_name == "TranslationPipelineTests":
    # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
    # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
    return True

   return False






  def 				UpperCAmelCase__						(							self			:					Dict      )->int:






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       MaMaaaModelTester(self      )
   __lowerCAmelCase					:	Dict      =       ConfigTester(self       ,  config_class=_snake_case      )






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






   '''simple docstring'''

   self.config_tester.run_common_tests()






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






   '''simple docstring'''

   __lowerCAmelCase ,					__lowerCAmelCase					:	int      =       self.model_tester.prepare_config_and_inputs()
   for model_class in self.all_model_classes:
    __lowerCAmelCase					:	Dict      =       model_class(_snake_case      )

    with tempfile.TemporaryDirectory() as tmpdirname:
     model.save_pretrained(_snake_case      )
     __lowerCAmelCase ,					__lowerCAmelCase					:	Any      =       model_class.from_pretrained(_snake_case       ,  output_loading_info=_snake_case      )
    self.assertEqual(info["""missing_keys"""]       ,  []      )






  def 				UpperCAmelCase__						(							self			:					str      )->int:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_decoder_model_past_large_inputs(*_snake_case      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       self.model_tester.prepare_config_and_inputs_for_common()
   self.model_tester.check_encoder_decoder_model_standalone(*_snake_case      )






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






   '''simple docstring'''

   __lowerCAmelCase ,					__lowerCAmelCase					:	Optional[int]      =       self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
    __lowerCAmelCase					:	List[Any]      =       model_class(_snake_case      )
    model.to(_snake_case      )
    model.eval()

    __lowerCAmelCase					:	List[str]      =       copy.deepcopy(self._prepare_for_class(_snake_case       ,  _snake_case      )      )

    if not self.is_encoder_decoder:
     __lowerCAmelCase					:	List[str]      =       inputs["""input_ids"""]
     del inputs["input_ids"]
    else:
     __lowerCAmelCase					:	Tuple      =       inputs["""input_ids"""]
     __lowerCAmelCase					:	Any      =       inputs.get("""decoder_input_ids"""       ,  _snake_case      )
     del inputs["input_ids"]
     inputs.pop("""decoder_input_ids"""       ,  _snake_case      )

    __lowerCAmelCase					:	Union[str, Any]      =       model.get_input_embeddings()
    if not self.is_encoder_decoder:
     __lowerCAmelCase					:	str      =       wte(_snake_case      )
    else:
     __lowerCAmelCase					:	int      =       wte(_snake_case      )
     __lowerCAmelCase					:	str      =       wte(_snake_case      )

    with torch.no_grad():
     model(**_snake_case      )[0]






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






   '''simple docstring'''

   __lowerCAmelCase ,					__lowerCAmelCase					:	Tuple      =       self.model_tester.prepare_config_and_inputs()
   __lowerCAmelCase					:	Optional[Any]      =       input_dict["""input_ids"""]
   __lowerCAmelCase					:	int      =       input_ids.ne(1      ).to(_snake_case      )
   __lowerCAmelCase					:	Any      =       MaMaaaForConditionalGeneration(_snake_case      ).eval().to(_snake_case      )
   if torch_device == "cuda":
    model.half()
   model.generate(_snake_case       ,  attention_mask=_snake_case      )
   model.generate(num_beams=4       ,  do_sample=_snake_case       ,  early_stopping=_snake_case       ,  num_return_sequences=3      )






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:Union[str, Any]   )      ->   Dict:
 return torch.tensor(SCREAMING_SNAKE_CASE   ,   dtype=torch.long   ,   device=SCREAMING_SNAKE_CASE   )


_UpperCAmelCase             =							1e-4







@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class        snake_case_    (		unittest.TestCase						):






  @cached_property
  def 				UpperCAmelCase__						(							self			:					Any      )->str:






   '''simple docstring'''

   return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""      )






  def 				UpperCAmelCase__						(							self			:					str      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""      ).to(_snake_case      )
   __lowerCAmelCase					:	Dict      =       _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]      )
   __lowerCAmelCase					:	Union[str, Any]      =       _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]      )
   __lowerCAmelCase					:	Dict      =       prepare_mam_aaa_inputs_dict(model.config       ,  _snake_case       ,  _snake_case      )
   with torch.no_grad():
    __lowerCAmelCase					:	str      =       model(**_snake_case      )[0]
   __lowerCAmelCase					:	Any      =       torch.Size((1, 11, 1024)      )
   self.assertEqual(output.shape       ,  _snake_case      )
   # change to expected output here
   __lowerCAmelCase					:	int      =       torch.tensor(
       [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]]       ,  device=_snake_case      )
   self.assertTrue(torch.allclose(output[:, :3, :3]       ,  _snake_case       ,  atol=_snake_case      )      )






  def 				UpperCAmelCase__						(							self			:					Any      )->Dict:






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""      ).to(_snake_case      )

   # change to intended input
   __lowerCAmelCase					:	Union[str, Any]      =       _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]      )
   __lowerCAmelCase					:	Union[str, Any]      =       _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]      )
   __lowerCAmelCase					:	Dict      =       prepare_mam_aaa_inputs_dict(model.config       ,  _snake_case       ,  _snake_case      )
   with torch.no_grad():
    __lowerCAmelCase					:	List[str]      =       model(**_snake_case      )[0]
   __lowerCAmelCase					:	Dict      =       torch.Size((1, 11, model.config.vocab_size)      )
   self.assertEqual(output.shape       ,  _snake_case      )
   # change to expected output here
   __lowerCAmelCase					:	str      =       torch.tensor(
       [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]]       ,  device=_snake_case      )
   self.assertTrue(torch.allclose(output[:, :3, :3]       ,  _snake_case       ,  atol=_snake_case      )      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""      ).to(_snake_case      )
   __lowerCAmelCase					:	Union[str, Any]      =       MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""       ,  src_lang="""fr"""       ,  tgt_lang="""en"""      )

   __lowerCAmelCase					:	Any      =       [
       """L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
       """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
       """Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"""
       """ Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"""
       """ l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""",
   ]

   # The below article tests that we don't add any hypotheses outside of the top n_beams
   __lowerCAmelCase					:	Optional[int]      =       tokenizer(_snake_case       ,  padding=_snake_case       ,  return_tensors="""pt"""      )

   __lowerCAmelCase					:	str      =       model.generate(
       input_ids=dct["""input_ids"""].to(_snake_case      )       ,  attention_mask=dct["""attention_mask"""].to(_snake_case      )       ,  num_beams=5       ,  forced_bos_token_id=tokenizer.get_lang_id("""en"""      )       ,  )

   __lowerCAmelCase					:	List[Any]      =       [
       """The NSA case highlights the total absence of intelligence debate""",
       """I think there are two levels of response from the French government.""",
       """When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."""
       """ Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"""
       """ communications in France.""",
   ]

   __lowerCAmelCase					:	List[Any]      =       tokenizer.batch_decode(
       hypotheses_batch.tolist()       ,  clean_up_tokenization_spaces=_snake_case       ,  skip_special_tokens=_snake_case      )
   assert generated == expected_en






from __future__ import annotations






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:list[list[int]]   )      ->   bool:
 __lowerCAmelCase					:	Tuple      =       len(SCREAMING_SNAKE_CASE   )
 # We need to create solution object to save path.
 __lowerCAmelCase					:	str      =       [[0 for _ in range(SCREAMING_SNAKE_CASE   )] for _ in range(SCREAMING_SNAKE_CASE   )]
 __lowerCAmelCase					:	str      =       run_maze(SCREAMING_SNAKE_CASE   ,   0   ,   0   ,   SCREAMING_SNAKE_CASE   )
 if solved:
  print("""\n""".join(str(SCREAMING_SNAKE_CASE   ) for row in solutions   )   )
 else:
  print("""No solution exists!"""   )
 return solved






def 	_SCREAMING_SNAKE_CASE		(      SCREAMING_SNAKE_CASE		:list[list[int]]   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:int   ,   SCREAMING_SNAKE_CASE		:list[list[int]]   )      ->   bool:
 __lowerCAmelCase					:	List[str]      =       len(SCREAMING_SNAKE_CASE   )
 # Final check point.
 if i == j == (size - 1):
  __lowerCAmelCase					:	str      =       1
  return True

 __lowerCAmelCase					:	Optional[Any]      =       (not i < 0) and (not j < 0)  # Check lower bounds
 __lowerCAmelCase					:	Optional[Any]      =       (i < size) and (j < size)  # Check upper bounds

 if lower_flag and upper_flag:
  # check for already visited and block points.
  __lowerCAmelCase					:	int      =       (not solutions[i][j]) and (not maze[i][j])
  if block_flag:
   # check visited
   __lowerCAmelCase					:	Tuple      =       1

   # check for directions
   if (
       run_maze(SCREAMING_SNAKE_CASE   ,   i + 1   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
       or run_maze(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   j + 1   ,   SCREAMING_SNAKE_CASE   )
       or run_maze(SCREAMING_SNAKE_CASE   ,   i - 1   ,   SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   )
       or run_maze(SCREAMING_SNAKE_CASE   ,   SCREAMING_SNAKE_CASE   ,   j - 1   ,   SCREAMING_SNAKE_CASE   )
   ):
    return True

   __lowerCAmelCase					:	Tuple      =       0
   return False
 return False


if __name__ == "__main__":
      import doctest

      doctest.testmod()