


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       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		with open(SCREAMING_SNAKE_CASE						,    '''r'''						,    encoding='''utf-8'''						,    newline='''\n'''					) as f:
				lowercase__						=				f.read()
		lowercase__						=				REPLACE_PATTERNS[pattern]
		lowercase__						=				replace.replace('''VERSION'''						,    SCREAMING_SNAKE_CASE					)
		lowercase__						=				re_pattern.sub(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)
		with open(SCREAMING_SNAKE_CASE						,    '''w'''						,    encoding='''utf-8'''						,    newline='''\n'''					) as f:
				f.write(SCREAMING_SNAKE_CASE					)
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE					):
				# 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(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE					)						,    SCREAMING_SNAKE_CASE						,    pattern='''examples'''					)
def       _a			(				SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE=False					):


		"""simple docstring"""




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


		"""simple docstring"""




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

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

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

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


		"""simple docstring"""




		with open(REPLACE_FILES['''init''']						,    '''r'''					) as f:
				lowercase__						=				f.read()
		lowercase__						=				REPLACE_PATTERNS['init'][0].search(SCREAMING_SNAKE_CASE					).groups()[0]
		return packaging.version.parse(SCREAMING_SNAKE_CASE					)
def       _a			(				SCREAMING_SNAKE_CASE=False					):


		"""simple docstring"""




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

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

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


		"""simple docstring"""




		lowercase__						=				get_version()
		lowercase__						=				f'{current_version.major}.{current_version.minor + 1}.0.dev0'
		lowercase__						=				current_version.base_version

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

		print(f'Updating version to {version}.'					)
		global_version_update(SCREAMING_SNAKE_CASE					)
		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()



import os
import re
import shutil
from argparse import ArgumentParser, Namespace

from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger


lowerCAmelCase	=							'<<<<<<< This should probably be modified because it mentions: '

lowerCAmelCase	=							'=======\n>>>>>>>\n'

lowerCAmelCase	=							[
    'TextEncoderConfig',
    'ByteTextEncoder',
    'SubwordTextEncoder',
    'encoder_config',
    'maybe_build_from_corpus',
    'manual_dir',
]

lowerCAmelCase	=							[
    # (pattern, replacement)
    # Order is important here for some replacements
    (R'tfds\.core', R'datasets'),
    (R'tf\.io\.gfile\.GFile', R'open'),
    (R'tf\.([\w\d]+)', R'datasets.Value(\'\1\')'),
    (R'tfds\.features\.Text\(\)', R'datasets.Value(\'string\')'),
    (R'tfds\.features\.Text\(', R'datasets.Value(\'string\'),'),
    (R'features\s*=\s*tfds.features.FeaturesDict\(', R'features=datasets.Features('),
    (R'tfds\.features\.FeaturesDict\(', R'dict('),
    (R'The TensorFlow Datasets Authors', R'The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'),
    (R'tfds\.', R'datasets.'),
    (R'dl_manager\.manual_dir', R'self.config.data_dir'),
    (R'self\.builder_config', R'self.config'),
]
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




		return ConvertCommand(args.tfds_path						,    args.datasets_directory					)


class 	_a							(      UpperCamelCase__      ):

							@staticmethod
							def 				lowerCamelCase_			(							UpperCamelCase_:     ArgumentParser							)      ->       int:





									"""simple docstring"""







									lowercase__						=				parser.add_parser(
									    '''convert'''   ,						help='''Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.'''   ,						)
									train_parser.add_argument(
									    '''--tfds_path'''   ,						type=UpperCamelCase_   ,						required=UpperCamelCase_   ,						help='''Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.'''   ,						)
									train_parser.add_argument(
									    '''--datasets_directory'''   ,						type=UpperCamelCase_   ,						required=UpperCamelCase_   ,						help='''Path to the HuggingFace Datasets folder.'''							)
									train_parser.set_defaults(func=UpperCamelCase_							)

							def __init__(							self:     Dict   ,						UpperCamelCase_:     str   ,						UpperCamelCase_:     str   ,						*UpperCamelCase_:     Union[str, Any]							)      ->       List[str]:





									"""simple docstring"""







									lowercase__						=				get_logger('''datasets-cli/converting'''							)

									lowercase__						=				tfds_path
									lowercase__						=				datasets_directory


							def 				lowerCamelCase_			(							self:     str							)      ->       Dict:





									"""simple docstring"""







									if os.path.isdir(self._tfds_path							):
											lowercase__						=				os.path.abspath(self._tfds_path							)
									elif os.path.isfile(self._tfds_path							):
											lowercase__						=				os.path.dirname(self._tfds_path							)
									else:
											raise ValueError('''--tfds_path is neither a directory nor a file. Please check path.'''							)

									lowercase__						=				os.path.abspath(self._datasets_directory							)

									self._logger.info(f'Converting datasets from {abs_tfds_path} to {abs_datasets_path}'							)

									lowercase__						=				[]
									lowercase__						=				[]
									lowercase__						=				{}

									if os.path.isdir(self._tfds_path							):
											lowercase__						=				os.listdir(UpperCamelCase_							)
									else:
											lowercase__						=				[os.path.basename(self._tfds_path							)]

									for f_name in file_names:
											self._logger.info(f'Looking at file {f_name}'							)
											lowercase__						=				os.path.join(UpperCamelCase_   ,						UpperCamelCase_							)
											lowercase__						=				os.path.join(UpperCamelCase_   ,						UpperCamelCase_							)

											if not os.path.isfile(UpperCamelCase_							) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
													self._logger.info('''Skipping file'''							)
													continue

											with open(UpperCamelCase_   ,						encoding='''utf-8'''							) as f:
													lowercase__						=				f.readlines()

											lowercase__						=				[]
											lowercase__						=				False
											lowercase__						=				False
											lowercase__						=				[]
											for line in lines:
													lowercase__						=				line

													# Convert imports
													if "import tensorflow.compat.v2 as tf" in out_line:
															continue
													elif "@tfds.core" in out_line:
															continue
													elif "builder=self" in out_line:
															continue
													elif "import tensorflow_datasets.public_api as tfds" in out_line:
															lowercase__						=				'''import datasets\n'''
													elif "import tensorflow" in out_line:
															# order is important here
															lowercase__						=				''''''
															continue
													elif "from absl import logging" in out_line:
															lowercase__						=				'''from datasets import logging\n'''
													elif "getLogger" in out_line:
															lowercase__						=				out_line.replace('''getLogger'''   ,						'''get_logger'''							)
													elif any(expression in out_line for expression in TO_HIGHLIGHT							):
															lowercase__						=				True
															lowercase__						=				list(filter(lambda UpperCamelCase_							: e in out_line   ,						UpperCamelCase_							)							)
															out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(UpperCamelCase_							) + '''\n'''							)
															out_lines.append(UpperCamelCase_							)
															out_lines.append(UpperCamelCase_							)
															continue
													else:
															for pattern, replacement in TO_CONVERT:
																	lowercase__						=				re.sub(UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_							)

                # Take care of saving utilities (to later move them together with main script)
													if "tensorflow_datasets" in out_line:
															lowercase__						=				re.match(r'''from\stensorflow_datasets.*import\s([^\.\r\n]+)'''   ,						UpperCamelCase_							)
															tfds_imports.extend(imp.strip() for imp in match.group(1							).split(''','''							)							)
															lowercase__						=				'''from . import ''' + match.group(1							)

													# Check we have not forget anything
													if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
															raise ValueError(f'Error converting {out_line.strip()}'							)

													if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
															lowercase__						=				True
													out_lines.append(UpperCamelCase_							)

											if is_builder or "wmt" in f_name:
													# We create a new directory for each dataset
													lowercase__						=				f_name.replace('''.py'''   ,						''''''							)
													lowercase__						=				os.path.join(UpperCamelCase_   ,						UpperCamelCase_							)
													lowercase__						=				os.path.join(UpperCamelCase_   ,						UpperCamelCase_							)
													os.makedirs(UpperCamelCase_   ,						exist_ok=UpperCamelCase_							)
													self._logger.info(f'Adding directory {output_dir}'							)
													imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}							)
											else:
													# Utilities will be moved at the end
													utils_files.append(UpperCamelCase_							)

											if needs_manual_update:
													with_manual_update.append(UpperCamelCase_							)

											with open(UpperCamelCase_   ,						'''w'''   ,						encoding='''utf-8'''							) as f:
													f.writelines(UpperCamelCase_							)
											self._logger.info(f'Converted in {output_file}'							)

									for utils_file in utils_files:
											try:
													lowercase__						=				os.path.basename(UpperCamelCase_							)
													lowercase__						=				imports_to_builder_map[f_name.replace('''.py'''   ,						''''''							)]
													self._logger.info(f'Moving {dest_folder} to {utils_file}'							)
													shutil.copy(UpperCamelCase_   ,						UpperCamelCase_							)
											except KeyError:
													self._logger.error(f'Cannot find destination folder for {utils_file}. Please copy manually.'							)

									if with_manual_update:
											for file_path in with_manual_update:
													self._logger.warning(
													    f'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.'							)


