





"""simple docstring"""


from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
  from PIL import Image

  from transformers import ViTImageProcessor



class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  def __init__(		self :							List[Any]       , __a :							List[str]       , __a :							List[Any]=13       , __a :							Optional[Any]=30       , __a :							List[Any]=2       , __a :							Tuple=3       , __a :							Union[str, Any]=True       , __a :							List[Any]=True       , __a :							Optional[int]=32       , __a :							Tuple=2       , __a :							List[str]=4       , __a :							Optional[int]=37       , __a :							int="gelu"       , __a :							Union[str, Any]=0.1       , __a :							Dict=0.1       , __a :							Optional[int]=10       , __a :							List[Any]=0.02       , __a :							str=3       , __a :							List[Any]=0.6       , __a :							Optional[Any]=None       , )		->					str:
        _UpperCamelCase   :						str    =							parent
        _UpperCamelCase   :						Tuple    =							batch_size
        _UpperCamelCase   :						Optional[Any]    =							image_size
        _UpperCamelCase   :						List[Any]    =							patch_size
        _UpperCamelCase   :						Union[str, Any]    =							num_channels
        _UpperCamelCase   :						Dict    =							is_training
        _UpperCamelCase   :						List[str]    =							use_labels
        _UpperCamelCase   :						int    =							hidden_size
        _UpperCamelCase   :						Any    =							num_hidden_layers
        _UpperCamelCase   :						List[Any]    =							num_attention_heads
        _UpperCamelCase   :						Dict    =							intermediate_size
        _UpperCamelCase   :						str    =							hidden_act
        _UpperCamelCase   :						Dict    =							hidden_dropout_prob
        _UpperCamelCase   :						Any    =							attention_probs_dropout_prob
        _UpperCamelCase   :						Any    =							type_sequence_label_size
        _UpperCamelCase   :						Any    =							initializer_range
        _UpperCamelCase   :						Optional[Any]    =							mask_ratio
        _UpperCamelCase   :						Tuple    =							scope

        # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
        # (we add 1 for the [CLS] token)
        _UpperCamelCase   :						Tuple    =							(image_size // patch_size) ** 2
        _UpperCamelCase   :						List[Any]    =							int(math.ceil((1 - mask_ratio) * (num_patches + 1)						)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					Optional[Any]:
        _UpperCamelCase   :						List[str]    =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

        _UpperCamelCase   :						str    =							None
        if self.use_labels:
              _UpperCamelCase   :						str    =							ids_tensor([self.batch_size]       , self.type_sequence_label_size						)

        _UpperCamelCase   :						int    =							self.get_config()

        return config, pixel_values, labels

  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					Tuple:
        return ViTMAEConfig(
            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       , decoder_hidden_size=self.hidden_size       , decoder_num_hidden_layers=self.num_hidden_layers       , decoder_num_attention_heads=self.num_attention_heads       , decoder_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       , mask_ratio=self.mask_ratio       , )

  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]       , __a :							Dict       , __a :							List[Any]       , __a :							Any						)		->					List[str]:
        _UpperCamelCase   :						Any    =							TFViTMAEModel(config=__a						)
        _UpperCamelCase   :						Tuple    =							model(__a       , training=__a						)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, self.seq_length, self.hidden_size)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple       , __a :							Dict       , __a :							Tuple       , __a :							int						)		->					Dict:
        _UpperCamelCase   :						Union[str, Any]    =							TFViTMAEForPreTraining(__a						)
        _UpperCamelCase   :						Any    =							model(__a       , training=__a						)
        # expected sequence length = num_patches
        _UpperCamelCase   :						int    =							(self.image_size // self.patch_size) ** 2
        _UpperCamelCase   :						List[str]    =							self.patch_size**2 * self.num_channels
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, num_patches, expected_num_channels)						)

        # test greyscale images
        _UpperCamelCase   :						int    =							1
        _UpperCamelCase   :						Tuple    =							TFViTMAEForPreTraining(__a						)

        _UpperCamelCase   :						List[str]    =							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
        _UpperCamelCase   :						int    =							model(__a       , training=__a						)
        _UpperCamelCase   :						Tuple    =							self.patch_size**2
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, num_patches, expected_num_channels)						)


  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					Union[str, Any]:
        _UpperCamelCase   :						Union[str, Any]    =							self.prepare_config_and_inputs()
        ((_UpperCamelCase),	(_UpperCamelCase),	(_UpperCamelCase))   :						int    =							config_and_inputs
        _UpperCamelCase   :						Any    =							{"pixel_values": pixel_values}
        return config, inputs_dict





@require_tf
class   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase		,	_UpperCamelCase		,	unittest.TestCase ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:Optional[Any]						  =       (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
  SCREAMING_SNAKE_CASE__				:Tuple						  =       {"feature-extraction": TFViTMAEModel} if is_tf_available() else {}

  SCREAMING_SNAKE_CASE__				:str						  =       False
  SCREAMING_SNAKE_CASE__				:List[str]						  =       False
  SCREAMING_SNAKE_CASE__				:Tuple						  =       False
  SCREAMING_SNAKE_CASE__				:List[str]						  =       False

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Optional[Any]:
        _UpperCamelCase   :						Any    =							TFViTMAEModelTester(self						)
        _UpperCamelCase   :						List[Any]    =							ConfigTester(self       , config_class=__a       , has_text_modality=__a       , hidden_size=37						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					Tuple:
        self.config_tester.run_common_tests()

  @unittest.skip(reason="ViTMAE does not use inputs_embeds"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					List[str]:
        pass

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					str:
        _UpperCamelCase,	_UpperCamelCase   :						Tuple    =							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()       , (tf.keras.layers.Layer)						)
              _UpperCamelCase   :						Optional[int]    =							model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(__a       , tf.keras.layers.Layer						)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					Optional[Any]:
        _UpperCamelCase,	_UpperCamelCase   :						List[str]    =							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						Any    =							model_class(__a						)
              _UpperCamelCase   :						List[Any]    =							inspect.signature(model.call						)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              _UpperCamelCase   :						int    =							[*signature.parameters.keys()]

              _UpperCamelCase   :						Dict    =							["pixel_values"]
              self.assertListEqual(arg_names[:1]       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple						)		->					Optional[int]:
        _UpperCamelCase   :						Union[str, Any]    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					str:
        _UpperCamelCase   :						Optional[Any]    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*__a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					Dict:
        # make the mask reproducible
        np.random.seed(2						)

        _UpperCamelCase,	_UpperCamelCase   :						Optional[Any]    =							self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase   :						str    =							int((config.image_size // config.patch_size) ** 2						)
        _UpperCamelCase   :						Any    =							np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						Optional[Any]    =							model_class(__a						)
              _UpperCamelCase   :						Tuple    =							self._prepare_for_class(__a       , __a						)

              _UpperCamelCase   :						Union[str, Any]    =							model(__a       , noise=__a						)

              _UpperCamelCase   :						Any    =							copy.deepcopy(self._prepare_for_class(__a       , __a						)						)
              _UpperCamelCase   :						Union[str, Any]    =							model(**__a       , noise=__a						)
              _UpperCamelCase   :						Tuple    =							outputs_dict[0].numpy()
              _UpperCamelCase   :						List[str]    =							outputs_keywords[0].numpy()

              self.assertLess(np.sum(np.abs(output_dict - output_keywords						)						)       , 1e-6						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					str:
        # make the mask reproducible
        np.random.seed(2						)

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

        _UpperCamelCase   :						List[str]    =							int((config.image_size // config.patch_size) ** 2						)
        _UpperCamelCase   :						str    =							np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

        def prepare_numpy_arrays(__a :							List[Any]						):
              _UpperCamelCase   :						Dict    =							{}
              for k, v in inputs_dict.items():
                    if tf.is_tensor(__a						):
                          _UpperCamelCase   :						Any    =							v.numpy()
                    else:
                          _UpperCamelCase   :						Optional[int]    =							np.array(__a						)

              return inputs_np_dict

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						List[Any]    =							model_class(__a						)

              _UpperCamelCase   :						Any    =							self._prepare_for_class(__a       , __a						)
              _UpperCamelCase   :						str    =							prepare_numpy_arrays(__a						)

              _UpperCamelCase   :						str    =							model(__a       , noise=__a						)
              _UpperCamelCase   :						List[str]    =							model(**__a       , noise=__a						)
              self.assert_outputs_same(__a       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]       , __a :							List[str]       , __a :							Optional[Any]       , __a :							Union[str, Any]						)		->					Any:
        # make masks reproducible
        np.random.seed(2						)

        _UpperCamelCase   :						int    =							int((tf_model.config.image_size // tf_model.config.patch_size) ** 2						)
        _UpperCamelCase   :						Dict    =							np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)
        _UpperCamelCase   :						List[Any]    =							tf.constant(__a						)

        # Add `noise` argument.
        # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
        _UpperCamelCase   :						Dict    =							tf_noise

        super().check_pt_tf_models(__a       , __a       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple						)		->					str:
        # make mask reproducible
        np.random.seed(2						)

        _UpperCamelCase,	_UpperCamelCase   :						Tuple    =							self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase   :						Union[str, Any]    =							{
            module_member
            for model_class in self.all_model_classes
            for module in (import_module(model_class.__module__						),)
            for module_member_name in dir(__a						)
            if module_member_name.endswith("MainLayer"						)
            # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
            and module_member_name[: -len("MainLayer"						)] == model_class.__name__[: -len("Model"						)]
            for module_member in (getattr(__a       , __a						),)
            if isinstance(__a       , __a						)
            and tf.keras.layers.Layer in module_member.__bases__
            and getattr(__a       , "_keras_serializable"       , __a						)
        }

        _UpperCamelCase   :						Optional[Any]    =							int((config.image_size // config.patch_size) ** 2						)
        _UpperCamelCase   :						str    =							np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)
        _UpperCamelCase   :						str    =							tf.convert_to_tensor(__a						)
        inputs_dict.update({"noise": noise}						)

        for main_layer_class in tf_main_layer_classes:
              _UpperCamelCase   :						Union[str, Any]    =							main_layer_class(__a						)

              _UpperCamelCase   :						Any    =							{
                  name: tf.keras.Input(tensor.shape[1:]       , dtype=tensor.dtype						) for name, tensor in inputs_dict.items()
              }

              _UpperCamelCase   :						Any    =							tf.keras.Model(__a       , outputs=main_layer(__a						)						)
              _UpperCamelCase   :						Dict    =							model(__a						)

              with tempfile.TemporaryDirectory() as tmpdirname:
                    _UpperCamelCase   :						Any    =							os.path.join(__a       , "keras_model.h5"						)
                    model.save(__a						)
                    _UpperCamelCase   :						Optional[Any]    =							tf.keras.models.load_model(
                        __a       , custom_objects={main_layer_class.__name__: main_layer_class}						)
                    assert isinstance(__a       , tf.keras.Model						)
                    _UpperCamelCase   :						List[str]    =							model(__a						)
                    self.assert_outputs_same(__a       , __a						)

  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					Tuple:
        # make mask reproducible
        np.random.seed(2						)

        _UpperCamelCase,	_UpperCamelCase   :						Union[str, Any]    =							self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase   :						List[Any]    =							int((config.image_size // config.patch_size) ** 2						)
        _UpperCamelCase   :						Dict    =							np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						Dict    =							model_class(__a						)
              _UpperCamelCase   :						Union[str, Any]    =							self._prepare_for_class(__a       , __a						)
              _UpperCamelCase   :						Any    =							model(__a       , noise=__a						)

              if model_class.__name__ == "TFViTMAEModel":
                    _UpperCamelCase   :						Union[str, Any]    =							outputs.last_hidden_state.numpy()
                    _UpperCamelCase   :						Optional[Any]    =							0
              else:
                    _UpperCamelCase   :						str    =							outputs.logits.numpy()
                    _UpperCamelCase   :						str    =							0

              with tempfile.TemporaryDirectory() as tmpdirname:
                    model.save_pretrained(__a       , saved_model=__a						)
                    _UpperCamelCase   :						List[str]    =							model_class.from_pretrained(__a						)
                    _UpperCamelCase   :						Tuple    =							model(__a       , noise=__a						)

                    if model_class.__name__ == "TFViTMAEModel":
                          _UpperCamelCase   :						Optional[int]    =							after_outputs["last_hidden_state"].numpy()
                          _UpperCamelCase   :						Tuple    =							0
                    else:
                          _UpperCamelCase   :						str    =							after_outputs["logits"].numpy()
                          _UpperCamelCase   :						Optional[Any]    =							0

                    _UpperCamelCase   :						Any    =							np.amax(np.abs(out_a - out_a						)						)
                    self.assertLessEqual(__a       , 1e-5						)

  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]						)		->					Any:
        # make mask reproducible
        np.random.seed(2						)

        _UpperCamelCase,	_UpperCamelCase   :						Any    =							self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase   :						Union[str, Any]    =							int((config.image_size // config.patch_size) ** 2						)
        _UpperCamelCase   :						List[Any]    =							np.random.uniform(size=(self.model_tester.batch_size, num_patches)						)

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						List[Any]    =							model_class(__a						)
              _UpperCamelCase   :						List[str]    =							self._prepare_for_class(__a       , __a						)

              _UpperCamelCase   :						Dict    =							model(__a       , noise=__a						)
              _UpperCamelCase   :						int    =							model.get_config()
              # make sure that returned config is jsonifiable, which is required by keras
              json.dumps(__a						)
              _UpperCamelCase   :						Optional[int]    =							model_class.from_config(model.get_config()						)
              # make sure it also accepts a normal config
              _UpperCamelCase   :						int    =							model_class.from_config(model.config						)
              _UpperCamelCase   :						Dict    =							new_model(__a						)  # Build model
              new_model.set_weights(model.get_weights()						)
              _UpperCamelCase   :						List[Any]    =							new_model(__a       , noise=__a						)

              self.assert_outputs_same(__a       , __a						)

  @unittest.skip(
      reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n    to get deterministic results."						)
  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					int:
        pass

  @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					Union[str, Any]:
        pass


  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					Optional[int]:
        _UpperCamelCase   :						str    =							TFViTMAEModel.from_pretrained("google/vit-base-patch16-224"						)
        self.assertIsNotNone(__a						)





def        lowercase__     (       )       ->		List[str]:




      """simple docstring"""

      _UpperCamelCase   :						Optional[int]    =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
      return image



@require_tf
@require_vision
class   __SCREAMING_SNAKE_CASE     (    unittest.TestCase ):







  '''simple docstring'''


  @cached_property
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					str:
        return ViTImageProcessor.from_pretrained("facebook/vit-mae-base"						) if is_vision_available() else None


  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					Union[str, Any]:
        # make random mask reproducible across the PT and TF model
        np.random.seed(2						)

        _UpperCamelCase   :						Dict    =							TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base"						)

        _UpperCamelCase   :						Dict    =							self.default_image_processor
        _UpperCamelCase   :						Optional[Any]    =							prepare_img()
        _UpperCamelCase   :						Tuple    =							image_processor(images=__a       , return_tensors="tf"						)

        # prepare a noise vector that will be also used for testing the TF model
        # (this way we can ensure that the PT and TF models operate on the same inputs)
        _UpperCamelCase   :						Optional[int]    =							ViTMAEConfig()
        _UpperCamelCase   :						List[str]    =							int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2						)
        _UpperCamelCase   :						Any    =							np.random.uniform(size=(1, num_patches)						)

        # forward pass
        _UpperCamelCase   :						Union[str, Any]    =							model(**__a       , noise=__a						)

        # verify the logits
        _UpperCamelCase   :						Tuple    =							tf.convert_to_tensor([1, 196, 768]						)
        self.assertEqual(outputs.logits.shape       , __a						)

        _UpperCamelCase   :						Optional[int]    =							tf.convert_to_tensor(
            [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]]						)

        tf.debugging.assert_near(outputs.logits[0, :3, :3]       , __a       , atol=1e-4						)







"""simple docstring"""


import argparse
import os
import re

import packaging.version


lowerCamelCase__						= "examples/"
lowerCamelCase__						= {
    "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
lowerCamelCase__						= {
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
lowerCamelCase__						= "README.md"




def        lowercase__     (       lowercase_		,lowercase_		,lowercase_      )       ->		Dict:




      """simple docstring"""

      with open(lowercase_		,"r"		,encoding="utf-8"		,newline="\n"      ) as f:
            _UpperCamelCase   :						Any    =							f.read()
      _UpperCamelCase,	_UpperCamelCase   :						str    =							REPLACE_PATTERNS[pattern]
      _UpperCamelCase   :						List[str]    =							replace.replace("VERSION"		,lowercase_      )
      _UpperCamelCase   :						Any    =							re_pattern.sub(lowercase_		,lowercase_      )
      with open(lowercase_		,"w"		,encoding="utf-8"		,newline="\n"      ) as f:
            f.write(lowercase_      )




def        lowercase__     (       lowercase_      )       ->		str:




      """simple docstring"""

      for folder, directories, fnames in os.walk(lowercase_      ):
            # Removing some of the folders with non-actively maintained examples from the walk
            if "research_projects" in directories:
                  directories.remove("research_projects"      )
            if "legacy" in directories:
                  directories.remove("legacy"      )
            for fname in fnames:
                  if fname.endswith(".py"      ):
                        update_version_in_file(os.path.join(lowercase_		,lowercase_      )		,lowercase_		,pattern="examples"      )




def        lowercase__     (       lowercase_		,lowercase_=False      )       ->		Any:




      """simple docstring"""

      for pattern, fname in REPLACE_FILES.items():
            update_version_in_file(lowercase_		,lowercase_		,lowercase_      )
      if not patch:
            update_version_in_examples(lowercase_      )




def        lowercase__     (       )       ->		List[str]:




      """simple docstring"""

      _UpperCamelCase   :						int    =							"🤗 Transformers currently provides the following architectures"
      _UpperCamelCase   :						int    =							"1. Want to contribute a new model?"
      with open(lowercase_		,"r"		,encoding="utf-8"		,newline="\n"      ) as f:
            _UpperCamelCase   :						int    =							f.readlines()

      # Find the start of the list.
      _UpperCamelCase   :						Optional[Any]    =							0
      while not lines[start_index].startswith(_start_prompt      ):
            start_index += 1
      start_index += 1

      _UpperCamelCase   :						Any    =							start_index
      # Update the lines in the model list.
      while not lines[index].startswith(_end_prompt      ):
            if lines[index].startswith("1."      ):
                  _UpperCamelCase   :						Dict    =							lines[index].replace(
                      "https://huggingface.co/docs/transformers/main/model_doc"		,"https://huggingface.co/docs/transformers/model_doc"		,)
            index += 1

      with open(lowercase_		,"w"		,encoding="utf-8"		,newline="\n"      ) as f:
            f.writelines(lowercase_      )




def        lowercase__     (       )       ->		List[str]:




      """simple docstring"""

      with open(REPLACE_FILES["init"]		,"r"      ) as f:
            _UpperCamelCase   :						Dict    =							f.read()
      _UpperCamelCase   :						List[str]    =							REPLACE_PATTERNS["init"][0].search(lowercase_      ).groups()[0]
      return packaging.version.parse(lowercase_      )




def        lowercase__     (       lowercase_=False      )       ->		Any:




      """simple docstring"""

      _UpperCamelCase   :						Tuple    =							get_version()
      if patch and default_version.is_devrelease:
            raise ValueError("Can't create a patch version from the dev branch, checkout a released version!"      )
      if default_version.is_devrelease:
            _UpperCamelCase   :						Union[str, Any]    =							default_version.base_version
      elif patch:
            _UpperCamelCase   :						Union[str, Any]    =							F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
      else:
            _UpperCamelCase   :						Any    =							F'''{default_version.major}.{default_version.minor + 1}.0'''

      # Now let's ask nicely if that's the right one.
      _UpperCamelCase   :						List[str]    =							input(F'''Which version are you releasing? [{default_version}]'''      )
      if len(lowercase_      ) == 0:
            _UpperCamelCase   :						Any    =							default_version

      print(F'''Updating version to {version}.'''      )
      global_version_update(lowercase_		,patch=lowercase_      )
      if not patch:
            print("Cleaning main README, don't forget to run `make fix-copies`."      )
            clean_main_ref_in_model_list()




def        lowercase__     (       )       ->		List[Any]:




      """simple docstring"""

      _UpperCamelCase   :						List[Any]    =							get_version()
      _UpperCamelCase   :						List[Any]    =							F'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
      _UpperCamelCase   :						Tuple    =							current_version.base_version

      # Check with the user we got that right.
      _UpperCamelCase   :						Union[str, Any]    =							input(F'''Which version are we developing now? [{dev_version}]'''      )
      if len(lowercase_      ) == 0:
            _UpperCamelCase   :						Optional[int]    =							dev_version

      print(F'''Updating version to {version}.'''      )
      global_version_update(lowercase_      )
      print("Cleaning main README, don't forget to run `make fix-copies`."      )
      clean_main_ref_in_model_list()


if __name__ == "__main__":
  lowerCamelCase__						= argparse.ArgumentParser()
  parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
  parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
  lowerCamelCase__						= parser.parse_args()
  if not args.post_release:
    pre_release_work(patch=args.patch)
  elif args.patch:
    print("Nothing to do after a patch :-)")
  else:
    post_release_work()
