





"""simple docstring"""




import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / '''utils'''))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
		from test_module.custom_tokenization_fast import CustomTokenizerFast


class        __UpperCamelCase				(						unittest.TestCase						):






							def     __a   (   self      )	-> List[Any]:
								# A mock response for an HTTP head request to emulate server down
								a      :		Optional[int]	=				mock.Mock()
								a      :		Any	=				500
								a      :		Dict	=				{}
								a      :		Union[str, Any]	=				HTTPError
								a      :		Tuple	=				{}

								# Download this model to make sure it's in the cache.
								a      :		Union[str, Any]	=				BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"      )

								# Under the mock environment we get a 500 error when trying to reach the tokenizer.
								with mock.patch("requests.Session.request"      ,					return_value=lowerCAmelCase__      ) as mock_head:
									a      :		Optional[int]	=				BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"      )
									# This check we did call the fake head request
									mock_head.assert_called()






							@require_tokenizers
							def     __a   (   self      )	-> Tuple:
								# A mock response for an HTTP head request to emulate server down
								a      :		List[Any]	=				mock.Mock()
								a      :		Union[str, Any]	=				500
								a      :		str	=				{}
								a      :		Dict	=				HTTPError
								a      :		Tuple	=				{}

								# Download this model to make sure it's in the cache.
								a      :		Dict	=				GPTaTokenizerFast.from_pretrained("gpt2"      )

								# Under the mock environment we get a 500 error when trying to reach the tokenizer.
								with mock.patch("requests.Session.request"      ,					return_value=lowerCAmelCase__      ) as mock_head:
									a      :		Union[str, Any]	=				GPTaTokenizerFast.from_pretrained("gpt2"      )
									# This check we did call the fake head request
									mock_head.assert_called()






							def     __a   (   self      )	-> List[Any]:
								# This test is for deprecated behavior and can be removed in v5
								try:
									a      :		Dict	=				tempfile.mktemp()
									with open(lowerCAmelCase__      ,					"wb"      ) as f:
										http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"      ,					lowerCAmelCase__      )

									a      :		int	=				AlbertTokenizer.from_pretrained(lowerCAmelCase__      )
								finally:
									os.remove(lowerCAmelCase__      )

								# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
								# the current folder and have the right name.
								if os.path.isfile("tokenizer.json"      ):
									# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
									return
								try:
									with open("tokenizer.json"      ,					"wb"      ) as f:
										http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json"      ,					lowerCAmelCase__      )
									a      :		Tuple	=				AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2"      )
									# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
									self.assertEqual(tokenizer.vocab_size      ,					1000      )
									# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

								finally:
									os.remove("tokenizer.json"      )






							def     __a   (   self      )	-> Optional[Any]:
								# This test is for deprecated behavior and can be removed in v5
								a      :		Dict	=				AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"      )


@is_staging_test
class        __UpperCamelCase				(						unittest.TestCase						):
							lowerCamelCase   :					List[str]      					=["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]






							@classmethod
							def     __a   (   cls      )	-> Union[str, Any]:
								a      :		List[Any]	=				TOKEN
								HfFolder.save_token(lowerCAmelCase__      )






							@classmethod
							def     __a   (   cls      )	-> Any:
								try:
									delete_repo(token=cls._token      ,					repo_id="test-tokenizer"      )
								except HTTPError:
									pass

								try:
									delete_repo(token=cls._token      ,					repo_id="valid_org/test-tokenizer-org"      )
								except HTTPError:
									pass

								try:
									delete_repo(token=cls._token      ,					repo_id="test-dynamic-tokenizer"      )
								except HTTPError:
									pass






							def     __a   (   self      )	-> Union[str, Any]:
								with tempfile.TemporaryDirectory() as tmp_dir:
									a      :		Tuple	=				os.path.join(lowerCAmelCase__      ,					"vocab.txt"      )
									with open(lowerCAmelCase__      ,					"w"      ,					encoding="utf-8"      ) as vocab_writer:
										vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]      )      )
									a      :		Tuple	=				BertTokenizer(lowerCAmelCase__      )

								tokenizer.push_to_hub("test-tokenizer"      ,					use_auth_token=self._token      )
								a      :		Dict	=				BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer"""      )
								self.assertDictEqual(new_tokenizer.vocab      ,					tokenizer.vocab      )

								# Reset repo
								delete_repo(token=self._token      ,					repo_id="test-tokenizer"      )

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
									tokenizer.save_pretrained(lowerCAmelCase__      ,					repo_id="test-tokenizer"      ,					push_to_hub=lowerCAmelCase__      ,					use_auth_token=self._token      )

								a      :		List[Any]	=				BertTokenizer.from_pretrained(f"""{USER}/test-tokenizer"""      )
								self.assertDictEqual(new_tokenizer.vocab      ,					tokenizer.vocab      )






							def     __a   (   self      )	-> Union[str, Any]:
								with tempfile.TemporaryDirectory() as tmp_dir:
									a      :		List[Any]	=				os.path.join(lowerCAmelCase__      ,					"vocab.txt"      )
									with open(lowerCAmelCase__      ,					"w"      ,					encoding="utf-8"      ) as vocab_writer:
										vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]      )      )
									a      :		int	=				BertTokenizer(lowerCAmelCase__      )

								tokenizer.push_to_hub("valid_org/test-tokenizer-org"      ,					use_auth_token=self._token      )
								a      :		Any	=				BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"      )
								self.assertDictEqual(new_tokenizer.vocab      ,					tokenizer.vocab      )

								# Reset repo
								delete_repo(token=self._token      ,					repo_id="valid_org/test-tokenizer-org"      )

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
									tokenizer.save_pretrained(
									    lowerCAmelCase__      ,					repo_id="valid_org/test-tokenizer-org"      ,					push_to_hub=lowerCAmelCase__      ,					use_auth_token=self._token      )

								a      :		str	=				BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"      )
								self.assertDictEqual(new_tokenizer.vocab      ,					tokenizer.vocab      )






							@require_tokenizers
							def     __a   (   self      )	-> Optional[int]:
								CustomTokenizer.register_for_auto_class()
								with tempfile.TemporaryDirectory() as tmp_dir:
									a      :		List[Any]	=				os.path.join(lowerCAmelCase__      ,					"vocab.txt"      )
									with open(lowerCAmelCase__      ,					"w"      ,					encoding="utf-8"      ) as vocab_writer:
										vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]      )      )
									a      :		str	=				CustomTokenizer(lowerCAmelCase__      )

								# No fast custom tokenizer
								tokenizer.push_to_hub("test-dynamic-tokenizer"      ,					use_auth_token=self._token      )

								a      :		Tuple	=				AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer"""      ,					trust_remote_code=lowerCAmelCase__      )
								# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
								self.assertEqual(tokenizer.__class__.__name__      ,					"CustomTokenizer"      )

								# Fast and slow custom tokenizer
								CustomTokenizerFast.register_for_auto_class()
								with tempfile.TemporaryDirectory() as tmp_dir:
									a      :		Optional[Any]	=				os.path.join(lowerCAmelCase__      ,					"vocab.txt"      )
									with open(lowerCAmelCase__      ,					"w"      ,					encoding="utf-8"      ) as vocab_writer:
										vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]      )      )

									a      :		Optional[int]	=				BertTokenizerFast.from_pretrained(lowerCAmelCase__      )
									bert_tokenizer.save_pretrained(lowerCAmelCase__      )
									a      :		Optional[Any]	=				CustomTokenizerFast.from_pretrained(lowerCAmelCase__      )

								tokenizer.push_to_hub("test-dynamic-tokenizer"      ,					use_auth_token=self._token      )

								a      :		Dict	=				AutoTokenizer.from_pretrained(f"""{USER}/test-dynamic-tokenizer"""      ,					trust_remote_code=lowerCAmelCase__      )
								# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
								self.assertEqual(tokenizer.__class__.__name__      ,					"CustomTokenizerFast"      )
								a      :		Optional[int]	=				AutoTokenizer.from_pretrained(
								    f"""{USER}/test-dynamic-tokenizer"""      ,					use_fast=lowerCAmelCase__      ,					trust_remote_code=lowerCAmelCase__      )
								# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
								self.assertEqual(tokenizer.__class__.__name__      ,					"CustomTokenizer"      )


class        __UpperCamelCase				(						unittest.TestCase						):






							def     __a   (   self      )	-> Union[str, Any]:
								a      :		Any	=				Trie()
								trie.add("Hello 友達"      )
								self.assertEqual(trie.data      ,					{"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}      )
								trie.add("Hello"      )
								trie.data
								self.assertEqual(trie.data      ,					{"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}      )






							def     __a   (   self      )	-> Dict:
								a      :		int	=				Trie()
								self.assertEqual(trie.split("[CLS] This is a extra_id_100"      )      ,					["[CLS] This is a extra_id_100"]      )
								trie.add("[CLS]"      )
								trie.add("extra_id_1"      )
								trie.add("extra_id_100"      )
								self.assertEqual(trie.split("[CLS] This is a extra_id_100"      )      ,					["[CLS]", " This is a ", "extra_id_100"]      )






							def     __a   (   self      )	-> Union[str, Any]:
								a      :		Tuple	=				Trie()
								trie.add("A"      )
								self.assertEqual(trie.split("ABC"      )      ,					["A", "BC"]      )
								self.assertEqual(trie.split("BCA"      )      ,					["BC", "A"]      )






							def     __a   (   self      )	-> Optional[Any]:
								a      :		List[str]	=				Trie()
								trie.add("TOKEN]"      )
								trie.add("[SPECIAL_TOKEN]"      )
								self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"      )      ,					["This is something ", "[SPECIAL_TOKEN]"]      )






							def     __a   (   self      )	-> Optional[Any]:
								a      :		str	=				Trie()
								trie.add("A"      )
								trie.add("P"      )
								trie.add("[SPECIAL_TOKEN]"      )
								self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"      )      ,					["This is something ", "[SPECIAL_TOKEN]"]      )






							def     __a   (   self      )	-> List[Any]:
								a      :		Optional[Any]	=				Trie()
								trie.add("AB"      )
								trie.add("B"      )
								trie.add("C"      )
								self.assertEqual(trie.split("ABC"      )      ,					["AB", "C"]      )






							def     __a   (   self      )	-> Any:
								a      :		Dict	=				Trie()
								trie.add("ABC"      )
								trie.add("B"      )
								trie.add("CD"      )
								self.assertEqual(trie.split("ABCD"      )      ,					["ABC", "D"]      )






							def     __a   (   self      )	-> Union[str, Any]:
								# Even if the offsets are wrong, we necessarily output correct string
								# parts.
								a      :		Tuple	=				Trie()
								a      :		Union[str, Any]	=				trie.cut_text("ABC"      ,					[0, 0, 2, 1, 2, 3]      )
								self.assertEqual(lowerCAmelCase__      ,					["AB", "C"]      )









"""simple docstring"""




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

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


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

a						: Tuple     	=			'''=======
>>>>>>>
'''

a						: List[Any]     	=			[
    '''TextEncoderConfig''',
    '''ByteTextEncoder''',
    '''SubwordTextEncoder''',
    '''encoder_config''',
    '''maybe_build_from_corpus''',
    '''manual_dir''',
]

a						: Union[str, Any]     	=			[
    # (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       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Namespace					) ->Any:






	'''simple docstring'''






	return ConvertCommand(args.tfds_path    ,       args.datasets_directory					)







class        __UpperCamelCase				(						a__						):






							@staticmethod
							def     __a   (   lowerCAmelCase__      )	-> int:
								a      :		Any	=				parser.add_parser(
								    "convert"      ,					help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset."      ,					)
								train_parser.add_argument(
								    "--tfds_path"      ,					type=lowerCAmelCase__      ,					required=lowerCAmelCase__      ,					help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert."      ,					)
								train_parser.add_argument(
								    "--datasets_directory"      ,					type=lowerCAmelCase__      ,					required=lowerCAmelCase__      ,					help="Path to the HuggingFace Datasets folder."      )
								train_parser.set_defaults(func=lowerCAmelCase__      )






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					*lowerCAmelCase__      )	-> Tuple:
								a      :		List[str]	=				get_logger("datasets-cli/converting"      )

								a      :		Optional[int]	=				tfds_path
								a      :		str	=				datasets_directory






							def     __a   (   self      )	-> str:
								if os.path.isdir(self._tfds_path      ):
									a      :		int	=				os.path.abspath(self._tfds_path      )
								elif os.path.isfile(self._tfds_path      ):
									a      :		Optional[Any]	=				os.path.dirname(self._tfds_path      )
								else:
									raise ValueError("--tfds_path is neither a directory nor a file. Please check path."      )

								a      :		str	=				os.path.abspath(self._datasets_directory      )

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

								a      :		str	=				[]
								a      :		Union[str, Any]	=				[]
								a      :		str	=				{}

								if os.path.isdir(self._tfds_path      ):
									a      :		Dict	=				os.listdir(lowerCAmelCase__      )
								else:
									a      :		Dict	=				[os.path.basename(self._tfds_path      )]

								for f_name in file_names:
									self._logger.info(f"""Looking at file {f_name}"""      )
									a      :		Any	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )
									a      :		Dict	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )

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

									with open(lowerCAmelCase__      ,					encoding="utf-8"      ) as f:
										a      :		Any	=				f.readlines()

									a      :		Tuple	=				[]
									a      :		Any	=				False
									a      :		Dict	=				False
									a      :		Dict	=				[]
									for line in lines:
										a      :		Tuple	=				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:
											a      :		Optional[int]	=				"import datasets\n"
										elif "import tensorflow" in out_line:
											# order is important here
											a      :		Optional[Any]	=				""
											continue
										elif "from absl import logging" in out_line:
											a      :		Any	=				"from datasets import logging\n"
										elif "getLogger" in out_line:
											a      :		int	=				out_line.replace("getLogger"      ,					"get_logger"      )
										elif any(expression in out_line for expression in TO_HIGHLIGHT      ):
											a      :		Optional[Any]	=				True
											a      :		Optional[Any]	=				list(filter(lambda lowerCAmelCase__      : e in out_line      ,					lowerCAmelCase__      )      )
											out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowerCAmelCase__      ) + "\n"      )
											out_lines.append(lowerCAmelCase__      )
											out_lines.append(lowerCAmelCase__      )
											continue
										else:
											for pattern, replacement in TO_CONVERT:
												a      :		int	=				re.sub(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )

                # Take care of saving utilities (to later move them together with main script)
										if "tensorflow_datasets" in out_line:
											a      :		int	=				re.match(R"from\stensorflow_datasets.*import\s([^\.\r\n]+)"      ,					lowerCAmelCase__      )
											tfds_imports.extend(imp.strip() for imp in match.group(1      ).split(","      )      )
											a      :		List[str]	=				"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:
											a      :		str	=				True
										out_lines.append(lowerCAmelCase__      )

									if is_builder or "wmt" in f_name:
										# We create a new directory for each dataset
										a      :		Tuple	=				f_name.replace(".py"      ,					""      )
										a      :		Optional[Any]	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )
										a      :		Dict	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )
										os.makedirs(lowerCAmelCase__      ,					exist_ok=lowerCAmelCase__      )
										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(lowerCAmelCase__      )

									if needs_manual_update:
										with_manual_update.append(lowerCAmelCase__      )

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

								for utils_file in utils_files:
									try:
										a      :		int	=				os.path.basename(lowerCAmelCase__      )
										a      :		int	=				imports_to_builder_map[f_name.replace(".py"      ,					""      )]
										self._logger.info(f"""Moving {dest_folder} to {utils_file}"""      )
										shutil.copy(lowerCAmelCase__      ,					lowerCAmelCase__      )
									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'."""      )


