





"""simple docstring"""


import os
import re
import shutil
import sys
import tempfile
import unittest

import black


lowerCamelCase__						= os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
lowerCamelCase__						= "    def __init__(self, config):\n        super().__init__()\n        self.transform = BertPredictionHeadTransform(config)\n\n        # The output weights are the same as the input embeddings, but there is\n        # an output-only bias for each token.\n        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n        self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n        self.decoder.bias = self.bias\n\n    def forward(self, hidden_states):\n        hidden_states = self.transform(hidden_states)\n        hidden_states = self.decoder(hidden_states)\n        return hidden_states\n"



class   __SCREAMING_SNAKE_CASE     (    unittest.TestCase ):







  '''simple docstring'''


  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					str:
        _UpperCamelCase   :						Optional[Any]    =							tempfile.mkdtemp()
        os.makedirs(os.path.join(self.transformer_dir       , "models/bert/"						)						)
        _UpperCamelCase   :						int    =							self.transformer_dir
        shutil.copy(
            os.path.join(__a       , "src/transformers/models/bert/modeling_bert.py"						)       , os.path.join(self.transformer_dir       , "models/bert/modeling_bert.py"						)       , )

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Any:
        _UpperCamelCase   :						Tuple    =							"src/transformers"
        shutil.rmtree(self.transformer_dir						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Any       , __a :							Tuple       , __a :							Optional[int]       , __a :							Union[str, Any]       , __a :							str=None						)		->					str:
        _UpperCamelCase   :						Optional[int]    =							comment + F'''\nclass {class_name}(nn.Module):\n''' + class_code
        if overwrite_result is not None:
              _UpperCamelCase   :						int    =							comment + F'''\nclass {class_name}(nn.Module):\n''' + overwrite_result
        _UpperCamelCase   :						Optional[int]    =							black.Mode(target_versions={black.TargetVersion.PYaa}       , line_length=119						)
        _UpperCamelCase   :						Tuple    =							black.format_str(__a       , mode=__a						)
        _UpperCamelCase   :						List[str]    =							os.path.join(self.transformer_dir       , "new_code.py"						)
        with open(__a       , "w"       , newline="\n"						) as f:
              f.write(__a						)
        if overwrite_result is None:
              self.assertTrue(len(check_copies.is_copy_consistent(__a						)						) == 0						)
        else:
              check_copies.is_copy_consistent(f.name       , overwrite=__a						)
              with open(__a       , "r"						) as f:
                    self.assertTrue(f.read()       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					Union[str, Any]:
        _UpperCamelCase   :						str    =							check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead"						)
        self.assertEqual(__a       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]						)		->					Union[str, Any]:
        # Base copy consistency
        self.check_copy_consistency(
            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"       , "BertLMPredictionHead"       , REFERENCE_CODE + "\n"       , )

        # With no empty line at the end
        self.check_copy_consistency(
            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"       , "BertLMPredictionHead"       , __a       , )

        # Copy consistency with rename
        self.check_copy_consistency(
            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"       , "TestModelLMPredictionHead"       , re.sub("Bert"       , "TestModel"       , __a						)       , )

        # Copy consistency with a really long name
        _UpperCamelCase   :						Optional[Any]    =							"TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"
        self.check_copy_consistency(
            F'''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}'''       , F'''{long_class_name}LMPredictionHead'''       , re.sub("Bert"       , __a       , __a						)       , )

        # Copy consistency with overwrite
        self.check_copy_consistency(
            "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"       , "TestModelLMPredictionHead"       , __a       , overwrite_result=re.sub("Bert"       , "TestModel"       , __a						)       , )


  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					List[str]:
        _UpperCamelCase   :						Tuple    =							check_copies.LOCALIZED_READMES["README_zh-hans.md"]

        _UpperCamelCase   :						str    =							(
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
            " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
            " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
            " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."
            " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"
            " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
            " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"
            " method has been applied to compress GPT2 into"
            " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
            " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
            " Multilingual BERT into"
            " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
            " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"
            " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"
            " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"
            " Luong, Quoc V. Le, Christopher D. Manning."
        )
        _UpperCamelCase   :						Optional[Any]    =							(
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
        )
        _UpperCamelCase   :						int    =							(
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."
            " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"
            " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
            " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"
            " method has been applied to compress GPT2 into"
            " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
            " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
            " Multilingual BERT into"
            " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
            " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"
            " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"
            " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"
            " Christopher D. Manning 发布。\n"
        )

        _UpperCamelCase,	_UpperCamelCase   :						List[Any]    =							check_copies.convert_to_localized_md(
            __a       , __a       , localized_readme["format_model_list"]						)

        self.assertFalse(__a						)
        self.assertEqual(__a       , __a						)

        _UpperCamelCase,	_UpperCamelCase   :						Optional[int]    =							check_copies.convert_to_localized_md(
            __a       , __a       , localized_readme["format_model_list"]						)

        # Check whether the number of models is equal to README.md after conversion.
        self.assertTrue(__a						)

        _UpperCamelCase   :						str    =							(
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
            " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
            " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
            " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
        )
        _UpperCamelCase   :						List[str]    =							(
            "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"
            " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
        )
        _UpperCamelCase   :						Optional[Any]    =							(
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
        )

        _UpperCamelCase,	_UpperCamelCase   :						Dict    =							check_copies.convert_to_localized_md(
            __a       , __a       , localized_readme["format_model_list"]						)

        # Check if the model link is synchronized.
        self.assertEqual(__a       , __a						)







"""simple docstring"""


import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


lowerCamelCase__						= False
try:
  lowerCamelCase__						= _is_package_available("google.colab")
except ModuleNotFoundError:
  pass



@input.register
class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  def __init__(		self :							Union[str, Any]       , __a :							str = None       , __a :							list = []						)		->					Union[str, Any]:
        _UpperCamelCase   :						Any    =							0
        _UpperCamelCase   :						Any    =							choices
        _UpperCamelCase   :						Tuple    =							prompt
        if sys.platform == "win32":
              _UpperCamelCase   :						str    =							"*"
        else:
              _UpperCamelCase   :						Dict    =							"➔ "

  def  __SCREAMING_SNAKE_CASE					(		self :							int       , __a :							Tuple       , __a :							str = ""						)		->					Dict:
        if sys.platform != "win32":
              writeColor(self.choices[index]       , 32       , __a						)
        else:
              forceWrite(self.choices[index]       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple       , __a :							int						)		->					Dict:
        if index == self.position:
              forceWrite(F''' {self.arrow_char} '''						)
              self.write_choice(__a						)
        else:
              forceWrite(F'''    {self.choices[index]}'''						)
        reset_cursor()

  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]       , __a :							Direction       , __a :							int = 1						)		->					List[str]:
        _UpperCamelCase   :						Tuple    =							self.position
        if direction == Direction.DOWN:
              if self.position + 1 >= len(self.choices						):
                    return
              self.position += num_spaces
        else:
              if self.position - 1 < 0:
                    return
              self.position -= num_spaces
        clear_line()
        self.print_choice(__a						)
        move_cursor(__a       , direction.name						)
        self.print_choice(self.position						)

  @input.mark(KEYMAP["up"]						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					Any:
        self.move_direction(Direction.UP						)

  @input.mark(KEYMAP["down"]						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					List[Any]:
        self.move_direction(Direction.DOWN						)

  @input.mark(KEYMAP["newline"]						)
  def  __SCREAMING_SNAKE_CASE					(		self :							int						)		->					str:
        move_cursor(len(self.choices						) - self.position       , "DOWN"						)
        return self.position

  @input.mark(KEYMAP["interrupt"]						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Tuple:
        move_cursor(len(self.choices						) - self.position       , "DOWN"						)
        raise KeyboardInterrupt

  @input.mark_multiple(*[KEYMAP[str(__a						)] for number in range(10						)]						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					List[str]:
        _UpperCamelCase   :						Union[str, Any]    =							int(chr(self.current_selection						)						)
        _UpperCamelCase   :						List[str]    =							index - self.position
        if index == self.position:
              return
        if index < len(self.choices						):
              if self.position > index:
                    self.move_direction(Direction.UP       , -movement						)
              elif self.position < index:
                    self.move_direction(Direction.DOWN       , __a						)
              else:
                    return
        else:
              return


  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]       , __a :							int = 0						)		->					List[Any]:
        if self.prompt:
              linebreak()
              forceWrite(self.prompt       , "\n"						)
              if in_colab:
                    forceWrite("Please input a choice index (starting from 0), and press enter"       , "\n"						)
              else:
                    forceWrite("Please select a choice using the arrow or number keys, and selecting with enter"       , "\n"						)
        _UpperCamelCase   :						int    =							default_choice
        for i in range(len(self.choices						)						):
              self.print_choice(__a						)
              forceWrite("\n"						)
        move_cursor(len(self.choices						) - self.position       , "UP"						)
        with cursor.hide():
              while True:
                    if in_colab:
                          try:
                                _UpperCamelCase   :						Union[str, Any]    =							int(builtins.input()						)
                          except ValueError:
                                _UpperCamelCase   :						int    =							default_choice
                    else:
                          _UpperCamelCase   :						Any    =							self.handle_input()
                    if choice is not None:
                          reset_cursor()
                          for _ in range(len(self.choices						) + 1						):
                                move_cursor(1       , "UP"						)
                                clear_line()
                          self.write_choice(__a       , "\n"						)
                          return choice
