


import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import (
     MODEL_MAPPING,
     BeitForImageClassification,
     BeitForMaskedImageModeling,
     BeitForSemanticSegmentation,
     BeitModel,
 )
 from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 import PIL
 from PIL import Image

 from transformers import BeitImageProcessor


class 		_SCREAMING_SNAKE_CASE     :


     def __init__(  self							,					A_							,					A_=1_00							,					A_=13							,					A_=30							,					A_=2							,					A_=3							,					A_=True							,					A_=True							,					A_=32							,					A_=4							,					A_=4							,					A_=37							,					A_="gelu"							,					A_=0.1							,					A_=0.1							,					A_=10							,					A_=0.0_2							,					A_=3							,					A_=None							,					A_=[0, 1, 2, 3]							,					):
       _UpperCAmelCase		:							Optional[Any]							=     parent
       _UpperCAmelCase		:							Optional[Any]							=     1_00
       _UpperCAmelCase		:							Any							=     batch_size
       _UpperCAmelCase		:							int							=     image_size
       _UpperCAmelCase		:							Optional[Any]							=     patch_size
       _UpperCAmelCase		:							str							=     num_channels
       _UpperCAmelCase		:							List[str]							=     is_training
       _UpperCAmelCase		:							str							=     use_labels
       _UpperCAmelCase		:							List[str]							=     hidden_size
       _UpperCAmelCase		:							List[str]							=     num_hidden_layers
       _UpperCAmelCase		:							List[Any]							=     num_attention_heads
       _UpperCAmelCase		:							List[Any]							=     intermediate_size
       _UpperCAmelCase		:							int							=     hidden_act
       _UpperCAmelCase		:							List[str]							=     hidden_dropout_prob
       _UpperCAmelCase		:							int							=     attention_probs_dropout_prob
       _UpperCAmelCase		:							Optional[Any]							=     type_sequence_label_size
       _UpperCAmelCase		:							str							=     initializer_range
       _UpperCAmelCase		:							Optional[int]							=     scope
       _UpperCAmelCase		:							Optional[int]							=     out_indices
       _UpperCAmelCase		:							List[str]							=     num_labels

       # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       _UpperCAmelCase		:							Union[str, Any]							=     (image_size // patch_size) ** 2
       _UpperCAmelCase		:							Union[str, Any]							=     num_patches + 1


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

       _UpperCAmelCase		:							Union[str, Any]							=     None
       _UpperCAmelCase		:							Optional[Any]							=     None
       if self.use_labels:
         _UpperCAmelCase		:							Optional[int]							=     ids_tensor([self.batch_size]							,					self.type_sequence_label_size    )
         _UpperCAmelCase		:							Optional[Any]							=     ids_tensor([self.batch_size, self.image_size, self.image_size]							,					self.num_labels    )

       _UpperCAmelCase		:							str							=     self.get_config()

       return config, pixel_values, labels, pixel_labels


     def        __snake_case(  self    ):
       return BeitConfig(
           vocab_size=self.vocab_size							,					image_size=self.image_size							,					patch_size=self.patch_size							,					num_channels=self.num_channels							,					hidden_size=self.hidden_size							,					num_hidden_layers=self.num_hidden_layers							,					num_attention_heads=self.num_attention_heads							,					intermediate_size=self.intermediate_size							,					hidden_act=self.hidden_act							,					hidden_dropout_prob=self.hidden_dropout_prob							,					attention_probs_dropout_prob=self.attention_probs_dropout_prob							,					is_decoder=A_							,					initializer_range=self.initializer_range							,					out_indices=self.out_indices							,					)


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       _UpperCAmelCase		:							Optional[Any]							=     BeitModel(config=A_    )
       model.to(A_    )
       model.eval()
       _UpperCAmelCase		:							int							=     model(A_    )
       self.parent.assertEqual(result.last_hidden_state.shape							,					(self.batch_size, self.seq_length, self.hidden_size)    )


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       _UpperCAmelCase		:							List[Any]							=     BeitForMaskedImageModeling(config=A_    )
       model.to(A_    )
       model.eval()
       _UpperCAmelCase		:							int							=     model(A_    )
       self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.seq_length - 1, self.vocab_size)    )


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       _UpperCAmelCase		:							List[str]							=     self.type_sequence_label_size
       _UpperCAmelCase		:							Dict							=     BeitForImageClassification(A_    )
       model.to(A_    )
       model.eval()
       _UpperCAmelCase		:							Optional[Any]							=     model(A_							,					labels=A_    )
       self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)    )

       # test greyscale images
       _UpperCAmelCase		:							int							=     1
       _UpperCAmelCase		:							Union[str, Any]							=     BeitForImageClassification(A_    )
       model.to(A_    )
       model.eval()

       _UpperCAmelCase		:							Tuple							=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
       _UpperCAmelCase		:							Optional[Any]							=     model(A_							,					labels=A_    )
       self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)    )


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       _UpperCAmelCase		:							Any							=     self.num_labels
       _UpperCAmelCase		:							Any							=     BeitForSemanticSegmentation(A_    )
       model.to(A_    )
       model.eval()
       _UpperCAmelCase		:							List[Any]							=     model(A_    )
       self.parent.assertEqual(
           result.logits.shape							,					(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )
       _UpperCAmelCase		:							List[Any]							=     model(A_							,					labels=A_    )
       self.parent.assertEqual(
           result.logits.shape							,					(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )




     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Optional[int]							=     self.prepare_config_and_inputs()
       _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:							Optional[Any]							=     config_and_inputs
       _UpperCAmelCase		:							Optional[Any]							=     {"""pixel_values""": pixel_values}
       return config, inputs_dict


@require_torch
class 		_SCREAMING_SNAKE_CASE     (						A							,	A							,	unittest.TestCase     ):
     __SCREAMING_SNAKE_CASE     					=    (
         (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     __SCREAMING_SNAKE_CASE     					=    (
         {
             '''feature-extraction''': BeitModel,
             '''image-classification''': BeitForImageClassification,
             '''image-segmentation''': BeitForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     __SCREAMING_SNAKE_CASE     					=    False
     __SCREAMING_SNAKE_CASE     					=    False
     __SCREAMING_SNAKE_CASE     					=    False


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Any							=     BeitModelTester(self    )
       _UpperCAmelCase		:							Any							=     ConfigTester(self							,					config_class=A_							,					has_text_modality=A_							,					hidden_size=37    )


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


     @unittest.skip(reason="""BEiT does not use inputs_embeds"""    )
     def        __snake_case(  self    ):
       pass


     @require_torch_multi_gpu
     @unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""    )
     def        __snake_case(  self    ):
       pass


     def        __snake_case(  self    ):
       _UpperCAmelCase,_UpperCAmelCase		:							int							=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _UpperCAmelCase		:							Dict							=     model_class(A_    )
         self.assertIsInstance(model.get_input_embeddings()							,					(nn.Module)    )
         _UpperCAmelCase		:							int							=     model.get_output_embeddings()
         self.assertTrue(x is None or isinstance(A_							,					nn.Linear    )    )


     def        __snake_case(  self    ):
       _UpperCAmelCase,_UpperCAmelCase		:							Union[str, Any]							=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _UpperCAmelCase		:							Union[str, Any]							=     model_class(A_    )
         _UpperCAmelCase		:							Optional[int]							=     inspect.signature(model.forward    )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _UpperCAmelCase		:							Optional[Any]							=     [*signature.parameters.keys()]

         _UpperCAmelCase		:							List[Any]							=     ["""pixel_values"""]
         self.assertListEqual(arg_names[:1]							,					A_    )


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Union[str, Any]							=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_    )


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*A_    )


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_    )


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*A_    )


     def        __snake_case(  self    ):
       if not self.model_tester.is_training:
         return

       _UpperCAmelCase,_UpperCAmelCase		:							Any							=     self.model_tester.prepare_config_and_inputs_for_common()
       _UpperCAmelCase		:							Any							=     True

       for model_class in self.all_model_classes:
         # we don't test BeitForMaskedImageModeling
         if model_class in [*get_values(A_    ), BeitForMaskedImageModeling]:
           continue

         _UpperCAmelCase		:							Optional[int]							=     model_class(A_    )
         model.to(A_    )
         model.train()
         _UpperCAmelCase		:							int							=     self._prepare_for_class(A_							,					A_							,					return_labels=A_    )
         _UpperCAmelCase		:							List[str]							=     model(**A_    ).loss
         loss.backward()


     def        __snake_case(  self    ):
       _UpperCAmelCase,_UpperCAmelCase		:							Optional[Any]							=     self.model_tester.prepare_config_and_inputs_for_common()
       if not self.model_tester.is_training:
         return

       _UpperCAmelCase		:							Tuple							=     False
       _UpperCAmelCase		:							Optional[Any]							=     True

       for model_class in self.all_model_classes:
         # we don't test BeitForMaskedImageModeling
         if (
             model_class in [*get_values(A_    ), BeitForMaskedImageModeling]
             or not model_class.supports_gradient_checkpointing
         ):
           continue

         _UpperCAmelCase		:							Dict							=     model_class(A_    )
         model.gradient_checkpointing_enable()
         model.to(A_    )
         model.train()
         _UpperCAmelCase		:							Dict							=     self._prepare_for_class(A_							,					A_							,					return_labels=A_    )
         _UpperCAmelCase		:							int							=     model(**A_    ).loss
         loss.backward()


     def        __snake_case(  self    ):
       _UpperCAmelCase,_UpperCAmelCase		:							List[Any]							=     self.model_tester.prepare_config_and_inputs_for_common()

       _UpperCAmelCase		:							Any							=     _config_zero_init(A_    )
       for model_class in self.all_model_classes:
         _UpperCAmelCase		:							Tuple							=     model_class(config=A_    )
         for name, param in model.named_parameters():
           # we skip lambda parameters as these require special initial values
           # determined by config.layer_scale_init_value
           if "lambda" in name:
             continue
           if param.requires_grad:
             self.assertIn(
                 ((param.data.mean() * 1e9).round() / 1e9).item()							,					[0.0, 1.0]							,					msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''							,					)




     @slow
     def        __snake_case(  self    ):
       for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _UpperCAmelCase		:							Optional[int]							=     BeitModel.from_pretrained(A_    )
         self.assertIsNotNone(A_    )




def    a__    (		):
  _UpperCAmelCase		:							List[str]							=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
  return image





@require_torch
@require_vision
class 		_SCREAMING_SNAKE_CASE     (						unittest.TestCase     ):


     @cached_property
     def        __snake_case(  self    ):
       return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224"""    ) if is_vision_available() else None


     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Optional[int]							=     BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""    ).to(A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     self.default_image_processor
       _UpperCAmelCase		:							Tuple							=     prepare_img()
       _UpperCAmelCase		:							Optional[int]							=     image_processor(images=A_							,					return_tensors="""pt"""    ).pixel_values.to(A_    )

       # prepare bool_masked_pos
       _UpperCAmelCase		:							Optional[Any]							=     torch.ones((1, 1_96)							,					dtype=torch.bool    ).to(A_    )

       # forward pass
       with torch.no_grad():
         _UpperCAmelCase		:							str							=     model(pixel_values=A_							,					bool_masked_pos=A_    )
       _UpperCAmelCase		:							List[str]							=     outputs.logits

       # verify the logits
       _UpperCAmelCase		:							Tuple							=     torch.Size((1, 1_96, 81_92)    )
       self.assertEqual(logits.shape							,					A_    )

       _UpperCAmelCase		:							Optional[Any]							=     torch.tensor(
           [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]    ).to(A_    )

       self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]							,					A_							,					atol=1e-2    )    )


     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""    ).to(A_    )

       _UpperCAmelCase		:							Optional[int]							=     self.default_image_processor
       _UpperCAmelCase		:							Tuple							=     prepare_img()
       _UpperCAmelCase		:							str							=     image_processor(images=A_							,					return_tensors="""pt"""    ).to(A_    )

       # forward pass
       with torch.no_grad():
         _UpperCAmelCase		:							List[str]							=     model(**A_    )
       _UpperCAmelCase		:							List[Any]							=     outputs.logits

       # verify the logits
       _UpperCAmelCase		:							Any							=     torch.Size((1, 10_00)    )
       self.assertEqual(logits.shape							,					A_    )

       _UpperCAmelCase		:							List[str]							=     torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]    ).to(A_    )

       self.assertTrue(torch.allclose(logits[0, :3]							,					A_							,					atol=1e-4    )    )

       _UpperCAmelCase		:							Tuple							=     2_81
       self.assertEqual(logits.argmax(-1    ).item()							,					A_    )


     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							int							=     BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""    ).to(
           A_    )

       _UpperCAmelCase		:							List[str]							=     self.default_image_processor
       _UpperCAmelCase		:							Dict							=     prepare_img()
       _UpperCAmelCase		:							str							=     image_processor(images=A_							,					return_tensors="""pt"""    ).to(A_    )

       # forward pass
       with torch.no_grad():
         _UpperCAmelCase		:							List[Any]							=     model(**A_    )
       _UpperCAmelCase		:							Any							=     outputs.logits

       # verify the logits
       _UpperCAmelCase		:							Optional[int]							=     torch.Size((1, 2_18_41)    )
       self.assertEqual(logits.shape							,					A_    )

       _UpperCAmelCase		:							Any							=     torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]    ).to(A_    )

       self.assertTrue(torch.allclose(logits[0, :3]							,					A_							,					atol=1e-4    )    )

       _UpperCAmelCase		:							Any							=     23_96
       self.assertEqual(logits.argmax(-1    ).item()							,					A_    )


     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Optional[Any]							=     BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""    )
       _UpperCAmelCase		:							Union[str, Any]							=     model.to(A_    )

       _UpperCAmelCase		:							List[Any]							=     BeitImageProcessor(do_resize=A_							,					size=6_40							,					do_center_crop=A_    )

       _UpperCAmelCase		:							List[Any]							=     load_dataset("""hf-internal-testing/fixtures_ade20k"""							,					split="""test"""    )
       _UpperCAmelCase		:							Any							=     Image.open(ds[0]["""file"""]    )
       _UpperCAmelCase		:							int							=     image_processor(images=A_							,					return_tensors="""pt"""    ).to(A_    )

       # forward pass
       with torch.no_grad():
         _UpperCAmelCase		:							List[Any]							=     model(**A_    )
       _UpperCAmelCase		:							str							=     outputs.logits

       # verify the logits
       _UpperCAmelCase		:							Union[str, Any]							=     torch.Size((1, 1_50, 1_60, 1_60)    )
       self.assertEqual(logits.shape							,					A_    )

       _UpperCAmelCase		:							Optional[int]							=     version.parse(PIL.__version__    ) < version.parse("""9.0.0"""    )

       if is_pillow_less_than_a:
         _UpperCAmelCase		:							Any							=     torch.tensor(
             [
                 [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
                 [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
                 [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
             ]							,					device=A_							,					)
       else:
         _UpperCAmelCase		:							Union[str, Any]							=     torch.tensor(
             [
                 [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]],
                 [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]],
                 [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]],
             ]							,					device=A_							,					)

       self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,					A_							,					atol=1e-4    )    )




     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Optional[int]							=     BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""    )
       _UpperCAmelCase		:							List[str]							=     model.to(A_    )

       _UpperCAmelCase		:							Optional[int]							=     BeitImageProcessor(do_resize=A_							,					size=6_40							,					do_center_crop=A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     load_dataset("""hf-internal-testing/fixtures_ade20k"""							,					split="""test"""    )
       _UpperCAmelCase		:							str							=     Image.open(ds[0]["""file"""]    )
       _UpperCAmelCase		:							Optional[int]							=     image_processor(images=A_							,					return_tensors="""pt"""    ).to(A_    )

       # forward pass
       with torch.no_grad():
         _UpperCAmelCase		:							str							=     model(**A_    )

       _UpperCAmelCase		:							List[Any]							=     outputs.logits.detach().cpu()

       _UpperCAmelCase		:							str							=     image_processor.post_process_semantic_segmentation(outputs=A_							,					target_sizes=[(5_00, 3_00)]    )
       _UpperCAmelCase		:							List[str]							=     torch.Size((5_00, 3_00)    )
       self.assertEqual(segmentation[0].shape							,					A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     image_processor.post_process_semantic_segmentation(outputs=A_    )
       _UpperCAmelCase		:							Optional[Any]							=     torch.Size((1_60, 1_60)    )
       self.assertEqual(segmentation[0].shape							,					A_    )









import os
import string
import sys


SCREAMING_SNAKE_CASE__					:     List[str]       =     1 << 8

SCREAMING_SNAKE_CASE__					:     str       =     {
    'tab': ord('\t'),
    'newline': ord('\r'),
    'esc': 27,
    'up': 65 + ARROW_KEY_FLAG,
    'down': 66 + ARROW_KEY_FLAG,
    'right': 67 + ARROW_KEY_FLAG,
    'left': 68 + ARROW_KEY_FLAG,
    'mod_int': 91,
    'undefined': sys.maxsize,
    'interrupt': 3,
    'insert': 50,
    'delete': 51,
    'pg_up': 53,
    'pg_down': 54,
}

SCREAMING_SNAKE_CASE__					:     List[str]       =     KEYMAP['up']
SCREAMING_SNAKE_CASE__					:     Optional[int]       =     KEYMAP['left']

if sys.platform == "win32":
 SCREAMING_SNAKE_CASE__					:     Union[str, Any]       =     []
 SCREAMING_SNAKE_CASE__					:     Dict       =     {
     b'\xe0H': KEYMAP['up'] - ARROW_KEY_FLAG,
     b'\x00H': KEYMAP['up'] - ARROW_KEY_FLAG,
     b'\xe0P': KEYMAP['down'] - ARROW_KEY_FLAG,
     b'\x00P': KEYMAP['down'] - ARROW_KEY_FLAG,
     b'\xe0M': KEYMAP['right'] - ARROW_KEY_FLAG,
     b'\x00M': KEYMAP['right'] - ARROW_KEY_FLAG,
     b'\xe0K': KEYMAP['left'] - ARROW_KEY_FLAG,
     b'\x00K': KEYMAP['left'] - ARROW_KEY_FLAG,
 }

for i in range(10):
 SCREAMING_SNAKE_CASE__					:     List[str]       =     ord(str(i))




def    a__    (		):
  if os.name == "nt":
    import msvcrt

    _UpperCAmelCase		:							int							=     """mbcs"""
    # Flush the keyboard buffer
    while msvcrt.kbhit():
      msvcrt.getch()
    if len(snake_case__     ) == 0:
      # Read the keystroke
      _UpperCAmelCase		:							Any							=     msvcrt.getch()

      # If it is a prefix char, get second part
      if ch in (b"\x00", b"\xe0"):
        _UpperCAmelCase		:							str							=     ch + msvcrt.getch()
        # Translate actual Win chars to bullet char types
        try:
          _UpperCAmelCase		:							Optional[int]							=     chr(WIN_KEYMAP[cha]     )
          WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""]     )     )
          WIN_CH_BUFFER.append(snake_case__     )
          if ord(snake_case__     ) in (
              KEYMAP["insert"] - 1 << 9,
              KEYMAP["delete"] - 1 << 9,
              KEYMAP["pg_up"] - 1 << 9,
              KEYMAP["pg_down"] - 1 << 9,
          ):
            WIN_CH_BUFFER.append(chr(126     )     )
          _UpperCAmelCase		:							Any							=     chr(KEYMAP["""esc"""]     )
        except KeyError:
          _UpperCAmelCase		:							Optional[int]							=     cha[1]
      else:
        _UpperCAmelCase		:							Union[str, Any]							=     ch.decode(snake_case__     )
    else:
      _UpperCAmelCase		:							Optional[int]							=     WIN_CH_BUFFER.pop(0     )
  elif os.name == "posix":
    import termios
    import tty

    _UpperCAmelCase		:							List[str]							=     sys.stdin.fileno()
    _UpperCAmelCase		:							Optional[Any]							=     termios.tcgetattr(snake_case__     )
    try:
      tty.setraw(snake_case__     )
      _UpperCAmelCase		:							Tuple							=     sys.stdin.read(1     )
    finally:
      termios.tcsetattr(snake_case__						,   termios.TCSADRAIN						,   snake_case__     )
  return ch





def    a__    (		):
  _UpperCAmelCase		:							int							=     get_raw_chars()
  if ord(snake_case__     ) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
    return char

  elif ord(snake_case__     ) == KEYMAP["esc"]:
    _UpperCAmelCase		:							int							=     get_raw_chars()
    if ord(snake_case__     ) == KEYMAP["mod_int"]:
      _UpperCAmelCase		:							Optional[Any]							=     get_raw_chars()
      if ord(snake_case__     ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(snake_case__     ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
        return chr(ord(snake_case__     ) + ARROW_KEY_FLAG     )
      else:
        return KEYMAP["undefined"]
    else:
      return get_raw_chars()

  else:
    if char in string.printable:
      return char
    else:
      return KEYMAP["undefined"]





