'''simple docstring'''


import json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List

from ..utils import logging
from . import BaseTransformersCLICommand


try:
					from cookiecutter.main import cookiecutter

					__lowerCAmelCase	:       Dict						       =	True
except ImportError:
					__lowerCAmelCase	:       Any						       =	False

__lowerCAmelCase	:       Tuple						       =	logging.get_logger(__name__)  # pylint: disable=invalid-name





def       lowerCAmelCase					(		UpperCamelCase__				:   Namespace       ):


	"""simple docstring"""
	return AddNewModelCommand(args.testing    ,					args.testing_file    ,					path=args.path       )






class 						A   (   _UpperCAmelCase   ):





							@staticmethod
							def       snake_case__						(      __a				:							ArgumentParser	)							->	Optional[Any]:
								__UpperCAmelCase							=			parser.add_parser('''add-new-model'''	)
								add_new_model_parser.add_argument('''--testing'''     ,		action='''store_true'''     ,		help='''If in testing mode.'''	)
								add_new_model_parser.add_argument('''--testing_file'''     ,		type=lowercase_     ,		help='''Configuration file on which to run.'''	)
								add_new_model_parser.add_argument(
								    '''--path'''     ,		type=lowercase_     ,		help='''Path to cookiecutter. Should only be used for testing purposes.'''	)
								add_new_model_parser.set_defaults(func=lowercase_	)





							def __init__(      self				:							Optional[int]     ,		__a				:							bool     ,		__a				:							str     ,		__a				:							Union[str, Any]=None     ,		*__a				:							Dict	)							->	Dict:
								__UpperCAmelCase							=			testing
								__UpperCAmelCase							=			testing_file
								__UpperCAmelCase							=			path






							def       snake_case__						(      self				:							Any	)							->	Any:
								warnings.warn(
								    '''The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. '''
								    '''It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality '''
								    '''checks, you should use `transformers-cli add-new-model-like` instead.'''	)
								if not _has_cookiecutter:
									raise ImportError(
									    '''Model creation dependencies are required to use the `add_new_model` command. Install them by running '''
									    '''the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n'''	)
								# Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
								__UpperCAmelCase							=			[directory for directory in os.listdir() if """cookiecutter-template-""" == directory[:2_2]]
								if len(lowercase_	) > 0:
									raise ValueError(
									    '''Several directories starting with `cookiecutter-template-` in current working directory. '''
									    '''Please clean your directory by removing all folders starting with `cookiecutter-template-` or '''
									    '''change your working directory.'''	)

								__UpperCAmelCase							=			(
								    Path(lowercase_	).parent.parent.parent.parent if self._path is None else Path(self._path	).parent.parent
								)
								__UpperCAmelCase							=			path_to_transformer_root / """templates""" / """adding_a_new_model"""

								# Execute cookiecutter
								if not self._testing:
									cookiecutter(str(lowercase_	)	)
								else:
									with open(self._testing_file     ,		'''r'''	) as configuration_file:
										__UpperCAmelCase							=			json.load(lowercase_	)

									cookiecutter(
									    str(path_to_cookiecutter if self._path is None else self._path	)     ,		no_input=lowercase_     ,		extra_context=lowercase_     ,		)

								__UpperCAmelCase							=			[directory for directory in os.listdir() if """cookiecutter-template-""" in directory[:2_2]][0]

								# Retrieve configuration
								with open(directory + '''/configuration.json'''     ,		'''r'''	) as configuration_file:
									__UpperCAmelCase							=			json.load(lowercase_	)

								__UpperCAmelCase							=			configuration["""lowercase_modelname"""]
								__UpperCAmelCase							=			configuration["""generate_tensorflow_pytorch_and_flax"""]
								os.remove(f"""{directory}/configuration.json"""	)

								__UpperCAmelCase							=			"""PyTorch""" in generate_tensorflow_pytorch_and_flax
								__UpperCAmelCase							=			"""TensorFlow""" in generate_tensorflow_pytorch_and_flax
								__UpperCAmelCase							=			"""Flax""" in generate_tensorflow_pytorch_and_flax

								__UpperCAmelCase							=			f"""{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}"""
								os.makedirs(lowercase_     ,		exist_ok=lowercase_	)
								os.makedirs(f"""{path_to_transformer_root}/tests/models/{lowercase_model_name}"""     ,		exist_ok=lowercase_	)

								# Tests require submodules as they have parent imports
								with open(f"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py"""     ,		'''w'''	):
									pass

								shutil.move(
								    f"""{directory}/__init__.py"""     ,		f"""{model_dir}/__init__.py"""     ,		)
								shutil.move(
								    f"""{directory}/configuration_{lowercase_model_name}.py"""     ,		f"""{model_dir}/configuration_{lowercase_model_name}.py"""     ,		)

								def remove_copy_lines(__a				:							int	):
									with open(lowercase_     ,		'''r'''	) as f:
										__UpperCAmelCase							=			f.readlines()
									with open(lowercase_     ,		'''w'''	) as f:
										for line in lines:
											if "# Copied from transformers." not in line:
												f.write(lowercase_	)

								if output_pytorch:
									if not self._testing:
										remove_copy_lines(f"""{directory}/modeling_{lowercase_model_name}.py"""	)

									shutil.move(
									    f"""{directory}/modeling_{lowercase_model_name}.py"""     ,		f"""{model_dir}/modeling_{lowercase_model_name}.py"""     ,		)

									shutil.move(
									    f"""{directory}/test_modeling_{lowercase_model_name}.py"""     ,		f"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py"""     ,		)
								else:
									os.remove(f"""{directory}/modeling_{lowercase_model_name}.py"""	)
									os.remove(f"""{directory}/test_modeling_{lowercase_model_name}.py"""	)

								if output_tensorflow:
									if not self._testing:
										remove_copy_lines(f"""{directory}/modeling_tf_{lowercase_model_name}.py"""	)

									shutil.move(
									    f"""{directory}/modeling_tf_{lowercase_model_name}.py"""     ,		f"""{model_dir}/modeling_tf_{lowercase_model_name}.py"""     ,		)

									shutil.move(
									    f"""{directory}/test_modeling_tf_{lowercase_model_name}.py"""     ,		f"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py"""     ,		)
								else:
									os.remove(f"""{directory}/modeling_tf_{lowercase_model_name}.py"""	)
									os.remove(f"""{directory}/test_modeling_tf_{lowercase_model_name}.py"""	)

								if output_flax:
									if not self._testing:
										remove_copy_lines(f"""{directory}/modeling_flax_{lowercase_model_name}.py"""	)

									shutil.move(
									    f"""{directory}/modeling_flax_{lowercase_model_name}.py"""     ,		f"""{model_dir}/modeling_flax_{lowercase_model_name}.py"""     ,		)

									shutil.move(
									    f"""{directory}/test_modeling_flax_{lowercase_model_name}.py"""     ,		f"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py"""     ,		)
								else:
									os.remove(f"""{directory}/modeling_flax_{lowercase_model_name}.py"""	)
									os.remove(f"""{directory}/test_modeling_flax_{lowercase_model_name}.py"""	)

								shutil.move(
								    f"""{directory}/{lowercase_model_name}.md"""     ,		f"""{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md"""     ,		)

								shutil.move(
								    f"""{directory}/tokenization_{lowercase_model_name}.py"""     ,		f"""{model_dir}/tokenization_{lowercase_model_name}.py"""     ,		)

								shutil.move(
								    f"""{directory}/tokenization_fast_{lowercase_model_name}.py"""     ,		f"""{model_dir}/tokenization_{lowercase_model_name}_fast.py"""     ,		)

								from os import fdopen, remove
								from shutil import copymode, move
								from tempfile import mkstemp

								def replace(__a				:							str     ,		__a				:							str     ,		__a				:							List[str]	):
									# Create temp file
									__UpperCAmelCase							=			mkstemp()
									__UpperCAmelCase							=			False
									with fdopen(lowercase_     ,		'''w'''	) as new_file:
										with open(lowercase_	) as old_file:
											for line in old_file:
												new_file.write(lowercase_	)
												if line_to_copy_below in line:
													__UpperCAmelCase							=			True
													for line_to_copy in lines_to_copy:
														new_file.write(lowercase_	)

									if not line_found:
										raise ValueError(f"""Line {line_to_copy_below} was not found in file."""	)

									# Copy the file permissions from the old file to the new file
									copymode(lowercase_     ,		lowercase_	)
									# Remove original file
									remove(lowercase_	)
									# Move new file
									move(lowercase_     ,		lowercase_	)

								def skip_units(__a				:							str	):
									return (
									    ("generating PyTorch" in line and not output_pytorch)
									    or ("generating TensorFlow" in line and not output_tensorflow)
									    or ("generating Flax" in line and not output_flax)
									)

								def replace_in_files(__a				:							int	):
									with open(lowercase_	) as datafile:
										__UpperCAmelCase							=			[]
										__UpperCAmelCase							=			False
										__UpperCAmelCase							=			False
										for line in datafile:
											if "# To replace in: " in line and "##" not in line:
												__UpperCAmelCase							=			line.split('''\"'''	)[1]
												__UpperCAmelCase							=			skip_units(lowercase_	)
											elif "# Below: " in line and "##" not in line:
												__UpperCAmelCase							=			line.split('''\"'''	)[1]
												__UpperCAmelCase							=			skip_units(lowercase_	)
											elif "# End." in line and "##" not in line:
												if not skip_file and not skip_snippet:
													replace(lowercase_     ,		lowercase_     ,		lowercase_	)

												__UpperCAmelCase							=			[]
											elif "# Replace with" in line and "##" not in line:
												__UpperCAmelCase							=			[]
											elif "##" not in line:
												lines_to_copy.append(lowercase_	)

									remove(lowercase_	)

								replace_in_files(f"""{directory}/to_replace_{lowercase_model_name}.py"""	)
								os.rmdir(lowercase_	)

'''simple docstring'''


import argparse
import os
import re

import packaging.version


__lowerCAmelCase	:       Optional[int]						       =	"examples/"
__lowerCAmelCase	:       Dict						       =	{
    "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	:       List[str]						       =	{
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
__lowerCAmelCase	:       int						       =	"README.md"





def       lowerCAmelCase					(		UpperCamelCase__				:   List[str]    ,					UpperCamelCase__				:   int    ,					UpperCamelCase__				:   Tuple       ):


	"""simple docstring"""
	with open(UpperCamelCase__    ,					'''r'''    ,					encoding='''utf-8'''    ,					newline='''\n'''       ) as f:
		__UpperCAmelCase							=			f.read()
	__UpperCAmelCase				,			__UpperCAmelCase							=			REPLACE_PATTERNS[pattern]
	__UpperCAmelCase							=			replace.replace('''VERSION'''    ,					UpperCamelCase__       )
	__UpperCAmelCase							=			re_pattern.sub(UpperCamelCase__    ,					UpperCamelCase__       )
	with open(UpperCamelCase__    ,					'''w'''    ,					encoding='''utf-8'''    ,					newline='''\n'''       ) as f:
		f.write(UpperCamelCase__       )





def       lowerCAmelCase					(		UpperCamelCase__				:   Optional[int]       ):


	"""simple docstring"""
	for folder, directories, fnames in os.walk(UpperCamelCase__       ):
		# 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(UpperCamelCase__    ,					UpperCamelCase__       )    ,					UpperCamelCase__    ,					pattern='''examples'''       )





def       lowerCAmelCase					(		UpperCamelCase__				:   Any    ,					UpperCamelCase__				:   Any=False       ):


	"""simple docstring"""
	for pattern, fname in REPLACE_FILES.items():
		update_version_in_file(UpperCamelCase__    ,					UpperCamelCase__    ,					UpperCamelCase__       )
	if not patch:
		update_version_in_examples(UpperCamelCase__       )





def       lowerCAmelCase					(		):


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

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

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

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





def       lowerCAmelCase					(		):


	"""simple docstring"""
	with open(REPLACE_FILES['''init''']    ,					'''r'''       ) as f:
		__UpperCAmelCase							=			f.read()
	__UpperCAmelCase							=			REPLACE_PATTERNS['''init'''][0].search(UpperCamelCase__       ).groups()[0]
	return packaging.version.parse(UpperCamelCase__       )





def       lowerCAmelCase					(		UpperCamelCase__				:   Any=False       ):


	"""simple docstring"""
	__UpperCAmelCase							=			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							=			default_version.base_version
	elif patch:
		__UpperCAmelCase							=			f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
	else:
		__UpperCAmelCase							=			f"""{default_version.major}.{default_version.minor + 1}.0"""

	# Now let's ask nicely if that's the right one.
	__UpperCAmelCase							=			input(f"""Which version are you releasing? [{default_version}]"""       )
	if len(UpperCamelCase__       ) == 0:
		__UpperCAmelCase							=			default_version

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





def       lowerCAmelCase					(		):


	"""simple docstring"""
	__UpperCAmelCase							=			get_version()
	__UpperCAmelCase							=			f"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
	__UpperCAmelCase							=			current_version.base_version

	# Check with the user we got that right.
	__UpperCAmelCase							=			input(f"""Which version are we developing now? [{dev_version}]"""       )
	if len(UpperCamelCase__       ) == 0:
		__UpperCAmelCase							=			dev_version

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


if __name__ == "__main__":
					__lowerCAmelCase	:       Tuple						       =	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	:       Tuple						       =	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()
