




import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
				from comet_ml import OfflineExperiment

if is_tensorboard_available():
				import struct

				import tensorboard.compat.proto.event_pba as event_pba

lowercase_			:       List[Any]						       =				logging.getLogger(__name__)






@require_tensorboard
class 					__lowerCAmelCase				( unittest.TestCase				):







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  "test_project_with_config"
									with tempfile.TemporaryDirectory() as dirpath:
															_UpperCAmelCase									=  Accelerator(log_with="tensorboard"					,					project_dir=snake_case__   )
															_UpperCAmelCase									=  {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
															accelerator.init_trackers(snake_case__					,					snake_case__   )
															accelerator.end_training()
															for child in Path(F"""{dirpath}/{project_name}"""   ).glob("*/**"   ):
																					_UpperCAmelCase									=  list(filter(lambda snake_case__   : x.is_file()					,					child.iterdir()   )   )[0]
															self.assertNotEqual(str(snake_case__   )					,					""   )







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  "test_project_with_log"
									with tempfile.TemporaryDirectory() as dirpath:
															_UpperCAmelCase									=  Accelerator(log_with="tensorboard"					,					project_dir=snake_case__   )
															accelerator.init_trackers(snake_case__   )
															_UpperCAmelCase									=  {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
															accelerator.log(snake_case__					,					step=0   )
															accelerator.end_training()
															# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
															# Names are randomly generated each time
															_UpperCAmelCase									=  list(filter(lambda snake_case__   : x.is_file()					,					Path(F"""{dirpath}/{project_name}"""   ).iterdir()   )   )[0]
															self.assertNotEqual(str(snake_case__   )					,					""   )







			def UpperCamelCase    ( self					:    Optional[Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  "test_project_with_log"
									with tempfile.TemporaryDirectory() as dirpath:
															_UpperCAmelCase									=  Accelerator(log_with="tensorboard"					,					project_dir=snake_case__   )
															accelerator.init_trackers(snake_case__   )
															_UpperCAmelCase									=  {"tensor": torch.tensor(1   )}
															accelerator.log(snake_case__					,					step=0   )
															accelerator.end_training()
															# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
															# Names are randomly generated each time
															_UpperCAmelCase									=  list(filter(lambda snake_case__   : x.is_file()					,					Path(F"""{dirpath}/{project_name}"""   ).iterdir()   )   )[0]
															# Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
															with open(snake_case__					,					"rb"   ) as f:
																					_UpperCAmelCase									=  f.read()
															_UpperCAmelCase									=  False
															while data:
																					_UpperCAmelCase									=  struct.unpack("Q"					,					data[:8]   )

																					_UpperCAmelCase									=  data[12 : 12 + int(header[0]   )]  # 8+4
																					_UpperCAmelCase									=  data[12 + int(header[0]   ) + 4 :]
																					_UpperCAmelCase									=  event_pba.Event()

																					event.ParseFromString(snake_case__   )
																					if event.HasField("summary"   ):
																											for value in event.summary.value:
																																	if value.simple_value == 1.0 and value.tag == "tensor":
																																							_UpperCAmelCase									=  True
															self.assertTrue(snake_case__					,					"Converted tensor was not found in the log file!"   )







			def UpperCamelCase    ( self					:    Optional[int]   ):




									"""simple docstring"""


									with self.assertRaisesRegex(snake_case__					,					"Logging with `tensorboard` requires a `logging_dir`"   ):
															_UpperCAmelCase									=  Accelerator(log_with="tensorboard"   )
									with tempfile.TemporaryDirectory() as dirpath:
															_UpperCAmelCase									=  Accelerator(log_with="tensorboard"					,					project_dir=snake_case__   )







			def UpperCamelCase    ( self					:    Any   ):




									"""simple docstring"""


									_UpperCAmelCase									=  ProjectConfiguration(total_limit=30   )
									with tempfile.TemporaryDirectory() as dirpath:
															_UpperCAmelCase									=  Accelerator(log_with="tensorboard"					,					project_dir=snake_case__					,					project_config=snake_case__   )






@require_wandb
@mock.patch.dict(os.environ      ,	{"WANDB_MODE": "offline"}				)
class 					__lowerCAmelCase				( UpperCAmelCase__      ,	UpperCAmelCase__				):







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									super().setUp()
									# wandb let's us override where logs are stored to via the WANDB_DIR env var
									self.add_mocks(mock.patch.dict(os.environ					,					{"WANDB_DIR": self.tmpdir}   )   )







			@staticmethod
			def UpperCamelCase    ( snake_case__					:    str					,					snake_case__					:    str					,					snake_case__					:    bool = True   ):




									"""simple docstring"""


									_UpperCAmelCase									=  RF"""{section} ([\S\s]*?)\n\n"""
									if record:
															_UpperCAmelCase									=  RF"""Record: {pattern}"""
									_UpperCAmelCase									=  re.findall(snake_case__					,					snake_case__   )[0]
									# A config
									if section == "config" or section == "history":
															_UpperCAmelCase									=  re.findall(R"\"([a-zA-Z0-9_.,]+)"					,					snake_case__   )
															return {key: val for key, val in zip(cleaned_record[0::2]					,					cleaned_record[1::2]   )}
									# Everything else
									else:
															return dict(re.findall(R"(\w+): \"([^\s]+)\""					,					snake_case__   )   )







			@skip
			def UpperCamelCase    ( self					:    str   ):




									"""simple docstring"""


									_UpperCAmelCase									=  "test_project_with_config"
									_UpperCAmelCase									=  Accelerator(log_with="wandb"   )
									_UpperCAmelCase									=  {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
									_UpperCAmelCase									=  {"wandb": {"tags": ["my_tag"]}}
									accelerator.init_trackers(snake_case__					,					snake_case__					,					snake_case__   )
									_UpperCAmelCase									=  {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
									accelerator.log(snake_case__					,					step=0   )
									accelerator.end_training()
									# The latest offline log is stored at wandb/latest-run/*.wandb
									for child in Path(F"""{self.tmpdir}/wandb/latest-run"""   ).glob("*"   ):
															if child.is_file() and child.suffix == ".wandb":
																					_UpperCAmelCase									=  subprocess.check_output(
																					    ["wandb", "sync", "--view", "--verbose", str(snake_case__   )]					,					env=os.environ.copy()   ).decode("utf8"					,					"ignore"   )
																					break

        # Check HPS through careful parsing and cleaning
									_UpperCAmelCase									=  self.parse_log(snake_case__					,					"config"   )
									self.assertEqual(logged_items["num_iterations"]					,					"12"   )
									self.assertEqual(logged_items["learning_rate"]					,					"0.01"   )
									self.assertEqual(logged_items["some_boolean"]					,					"false"   )
									self.assertEqual(logged_items["some_string"]					,					"some_value"   )
									self.assertEqual(logged_items["some_string"]					,					"some_value"   )

									# Run tags
									_UpperCAmelCase									=  self.parse_log(snake_case__					,					"run"					,					snake_case__   )
									self.assertEqual(logged_items["tags"]					,					"my_tag"   )

									# Actual logging
									_UpperCAmelCase									=  self.parse_log(snake_case__					,					"history"   )
									self.assertEqual(logged_items["total_loss"]					,					"0.1"   )
									self.assertEqual(logged_items["iteration"]					,					"1"   )
									self.assertEqual(logged_items["my_text"]					,					"some_value"   )
									self.assertEqual(logged_items["_step"]					,					"0"   )




def 							__SCREAMING_SNAKE_CASE						(    self			,					snake_case_			,					snake_case_		):

						'''simple docstring'''


						_UpperCAmelCase									=  run_name
						_UpperCAmelCase									=  OfflineExperiment(project_name=snake_case_			,					offline_directory=snake_case_		)
						logger.info(f"""Initialized offline CometML project {self.run_name}"""		)
						logger.info("Make sure to log any initial configurations with `self.store_init_configuration` before training!"		)






@require_comet_ml
@mock.patch.object(UpperCAmelCase__      ,	"__init__"      ,	UpperCAmelCase__				)
class 					__lowerCAmelCase				( unittest.TestCase				):







			@staticmethod
			def UpperCamelCase    ( snake_case__					:    Dict					,					snake_case__					:    str					,					snake_case__					:    bool = False   ):




									"""simple docstring"""


									for log in log_list:
															_UpperCAmelCase									=  json.loads(snake_case__   )["payload"]
															if is_param and "param" in j.keys():
																					if j["param"]["paramName"] == key:
																											return j["param"]["paramValue"]
															if "log_other" in j.keys():
																					if j["log_other"]["key"] == key:
																											return j["log_other"]["val"]
															if "metric" in j.keys():
																					if j["metric"]["metricName"] == key:
																											return j["metric"]["metricValue"]







			def UpperCamelCase    ( self					:    Any   ):




									"""simple docstring"""


									with tempfile.TemporaryDirectory() as d:
															_UpperCAmelCase									=  CometMLTracker("test_project_with_config"					,					snake_case__   )
															_UpperCAmelCase									=  Accelerator(log_with=snake_case__   )
															_UpperCAmelCase									=  {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
															accelerator.init_trackers(snake_case__					,					snake_case__   )
															accelerator.end_training()
															_UpperCAmelCase									=  os.listdir(snake_case__   )[0]  # Comet is nice, it's just a zip file here
															# We parse the raw logs
															_UpperCAmelCase									=  os.path.join(snake_case__					,					snake_case__   )
															_UpperCAmelCase									=  zipfile.ZipFile(snake_case__					,					"r"   )
															_UpperCAmelCase									=  archive.open("messages.json"   ).read().decode("utf-8"   )
									_UpperCAmelCase									=  log.split("\n"   )[:-1]
									self.assertEqual(self.get_value_from_key(snake_case__					,					"num_iterations"					,					snake_case__   )					,					12   )
									self.assertEqual(self.get_value_from_key(snake_case__					,					"learning_rate"					,					snake_case__   )					,					0.01   )
									self.assertEqual(self.get_value_from_key(snake_case__					,					"some_boolean"					,					snake_case__   )					,					snake_case__   )
									self.assertEqual(self.get_value_from_key(snake_case__					,					"some_string"					,					snake_case__   )					,					"some_value"   )







			def UpperCamelCase    ( self					:    List[str]   ):




									"""simple docstring"""


									with tempfile.TemporaryDirectory() as d:
															_UpperCAmelCase									=  CometMLTracker("test_project_with_config"					,					snake_case__   )
															_UpperCAmelCase									=  Accelerator(log_with=snake_case__   )
															accelerator.init_trackers(snake_case__   )
															_UpperCAmelCase									=  {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
															accelerator.log(snake_case__					,					step=0   )
															accelerator.end_training()
															_UpperCAmelCase									=  os.listdir(snake_case__   )[0]  # Comet is nice, it's just a zip file here
															# We parse the raw logs
															_UpperCAmelCase									=  os.path.join(snake_case__					,					snake_case__   )
															_UpperCAmelCase									=  zipfile.ZipFile(snake_case__					,					"r"   )
															_UpperCAmelCase									=  archive.open("messages.json"   ).read().decode("utf-8"   )
									_UpperCAmelCase									=  log.split("\n"   )[:-1]
									self.assertEqual(self.get_value_from_key(snake_case__					,					"curr_step"					,					snake_case__   )					,					0   )
									self.assertEqual(self.get_value_from_key(snake_case__					,					"total_loss"   )					,					0.1   )
									self.assertEqual(self.get_value_from_key(snake_case__					,					"iteration"   )					,					1   )
									self.assertEqual(self.get_value_from_key(snake_case__					,					"my_text"   )					,					"some_value"   )






class 					__lowerCAmelCase				( UpperCAmelCase__				):
			snake_case_   :				Optional[Any]						  =  [
			    "total_loss",
			    "iteration",
			    "my_text",
			    "learning_rate",
			    "num_iterations",
			    "some_boolean",
			    "some_string",
			]

			snake_case_   :				Optional[Any]						  =  "my_custom_tracker"
			snake_case_   :				int						  =  False







			def __init__( self					:    Dict					,					snake_case__					:    str   ):




									"""simple docstring"""


									_UpperCAmelCase									=  open(F"""{dir}/log.csv"""					,					"w+"   )
									_UpperCAmelCase									=  csv.DictWriter(self.f					,					fieldnames=self._col_names   )
									self.writer.writeheader()







			@property
			def UpperCamelCase    ( self					:    Any   ):




									"""simple docstring"""


									return self.writer







			def UpperCamelCase    ( self					:    Any					,					snake_case__					:    dict   ):




									"""simple docstring"""


									logger.info("Call init"   )
									self.writer.writerow(snake_case__   )







			def UpperCamelCase    ( self					:    Optional[int]					,					snake_case__					:    dict					,					snake_case__					:    Optional[int]   ):




									"""simple docstring"""


									logger.info("Call log"   )
									self.writer.writerow(snake_case__   )







			def UpperCamelCase    ( self					:    List[Any]   ):




									"""simple docstring"""


									self.f.close()






class 					__lowerCAmelCase				( unittest.TestCase				):







			def UpperCamelCase    ( self					:    str   ):




									"""simple docstring"""


									with tempfile.TemporaryDirectory() as d:
															_UpperCAmelCase									=  MyCustomTracker(snake_case__   )
															_UpperCAmelCase									=  Accelerator(log_with=snake_case__   )
															_UpperCAmelCase									=  {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
															accelerator.init_trackers("Some name"					,					snake_case__   )
															accelerator.end_training()
															with open(F"""{d}/log.csv"""					,					"r"   ) as f:
																					_UpperCAmelCase									=  csv.DictReader(snake_case__   )
																					_UpperCAmelCase									=  next(snake_case__   )
																					_UpperCAmelCase									=  {
																					    "total_loss": "",
																					    "iteration": "",
																					    "my_text": "",
																					    "learning_rate": "0.01",
																					    "num_iterations": "12",
																					    "some_boolean": "False",
																					    "some_string": "some_value",
																					}
																					self.assertDictEqual(snake_case__					,					snake_case__   )







			def UpperCamelCase    ( self					:    Optional[int]   ):




									"""simple docstring"""


									with tempfile.TemporaryDirectory() as d:
															_UpperCAmelCase									=  MyCustomTracker(snake_case__   )
															_UpperCAmelCase									=  Accelerator(log_with=snake_case__   )
															accelerator.init_trackers("Some name"   )
															_UpperCAmelCase									=  {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
															accelerator.log(snake_case__					,					step=0   )
															accelerator.end_training()
															with open(F"""{d}/log.csv"""					,					"r"   ) as f:
																					_UpperCAmelCase									=  csv.DictReader(snake_case__   )
																					_UpperCAmelCase									=  next(snake_case__   )
																					_UpperCAmelCase									=  {
																					    "total_loss": "0.1",
																					    "iteration": "1",
																					    "my_text": "some_value",
																					    "learning_rate": "",
																					    "num_iterations": "",
																					    "some_boolean": "",
																					    "some_string": "",
																					}
																					self.assertDictEqual(snake_case__					,					snake_case__   )










import os
import unittest

from transformers import ElectraTokenizerFast
from transformers.models.electra.tokenization_electra import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    ElectraTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english






@require_tokenizers
class 					__lowerCAmelCase				( UpperCAmelCase__      ,	unittest.TestCase				):
			snake_case_   :				Optional[Any]				  =  ElectraTokenizer
			snake_case_   :				Dict				  =  ElectraTokenizerFast
			snake_case_   :				Optional[Any]				  =  True
			snake_case_   :				List[Any]				  =  True
			snake_case_   :				Optional[Any]				  =  filter_non_english







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									super().setUp()

									_UpperCAmelCase									=  [
									    "[UNK]",
									    "[CLS]",
									    "[SEP]",
									    "[PAD]",
									    "[MASK]",
									    "want",
									    "##want",
									    "##ed",
									    "wa",
									    "un",
									    "runn",
									    "##ing",
									    ",",
									    "low",
									    "lowest",
									]
									_UpperCAmelCase									=  os.path.join(self.tmpdirname					,					VOCAB_FILES_NAMES["vocab_file"]   )
									with open(self.vocab_file					,					"w"					,					encoding="utf-8"   ) as vocab_writer:
															vocab_writer.write("".join([x + "\n" for x in vocab_tokens]   )   )







			def UpperCamelCase    ( self					:    Optional[Any]					,					snake_case__					:    Union[str, Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  "UNwant\u00E9d,running"
									_UpperCAmelCase									=  "unwanted, running"
									return input_text, output_text







			def UpperCamelCase    ( self					:    Optional[int]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  self.tokenizer_class(self.vocab_file   )

									_UpperCAmelCase									=  tokenizer.tokenize("UNwant\u00E9d,running"   )
									self.assertListEqual(snake_case__					,					["un", "##want", "##ed", ",", "runn", "##ing"]   )
									self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__   )					,					[9, 6, 7, 12, 10, 11]   )







			def UpperCamelCase    ( self					:    int   ):




									"""simple docstring"""


									if not self.test_rust_tokenizer:
															return

									_UpperCAmelCase									=  self.get_tokenizer()
									_UpperCAmelCase									=  self.get_rust_tokenizer()

									_UpperCAmelCase									=  "UNwant\u00E9d,running"

									_UpperCAmelCase									=  tokenizer.tokenize(snake_case__   )
									_UpperCAmelCase									=  rust_tokenizer.tokenize(snake_case__   )
									self.assertListEqual(snake_case__					,					snake_case__   )

									_UpperCAmelCase									=  tokenizer.encode(snake_case__					,					add_special_tokens=snake_case__   )
									_UpperCAmelCase									=  rust_tokenizer.encode(snake_case__					,					add_special_tokens=snake_case__   )
									self.assertListEqual(snake_case__					,					snake_case__   )

									_UpperCAmelCase									=  self.get_rust_tokenizer()
									_UpperCAmelCase									=  tokenizer.encode(snake_case__   )
									_UpperCAmelCase									=  rust_tokenizer.encode(snake_case__   )
									self.assertListEqual(snake_case__					,					snake_case__   )

									# With lower casing
									_UpperCAmelCase									=  self.get_tokenizer(do_lower_case=snake_case__   )
									_UpperCAmelCase									=  self.get_rust_tokenizer(do_lower_case=snake_case__   )

									_UpperCAmelCase									=  "UNwant\u00E9d,running"

									_UpperCAmelCase									=  tokenizer.tokenize(snake_case__   )
									_UpperCAmelCase									=  rust_tokenizer.tokenize(snake_case__   )
									self.assertListEqual(snake_case__					,					snake_case__   )

									_UpperCAmelCase									=  tokenizer.encode(snake_case__					,					add_special_tokens=snake_case__   )
									_UpperCAmelCase									=  rust_tokenizer.encode(snake_case__					,					add_special_tokens=snake_case__   )
									self.assertListEqual(snake_case__					,					snake_case__   )

									_UpperCAmelCase									=  self.get_rust_tokenizer()
									_UpperCAmelCase									=  tokenizer.encode(snake_case__   )
									_UpperCAmelCase									=  rust_tokenizer.encode(snake_case__   )
									self.assertListEqual(snake_case__					,					snake_case__   )







			def UpperCamelCase    ( self					:    int   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer()

									self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"   )					,					["ah", "\u535A", "\u63A8", "zz"]   )







			def UpperCamelCase    ( self					:    List[Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  "   )					,					["hello", "!", "how", "are", "you", "?"]   )
									self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )					,					["hello"]   )







			def UpperCamelCase    ( self					:    Dict   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__					,					strip_accents=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )					,					["hällo", "!", "how", "are", "you", "?"]   )
									self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )					,					["h\u00E9llo"]   )







			def UpperCamelCase    ( self					:    Optional[Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__					,					strip_accents=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )					,					["hallo", "!", "how", "are", "you", "?"]   )
									self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )					,					["hello"]   )







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )					,					["hallo", "!", "how", "are", "you", "?"]   )
									self.assertListEqual(tokenizer.tokenize("H\u00E9llo"   )					,					["hello"]   )







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  "   )					,					["HeLLo", "!", "how", "Are", "yoU", "?"]   )







			def UpperCamelCase    ( self					:    Dict   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__					,					strip_accents=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )					,					["HäLLo", "!", "how", "Are", "yoU", "?"]   )







			def UpperCamelCase    ( self					:    Optional[Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__					,					strip_accents=snake_case__   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHäLLo!how  \n Are yoU?  "   )					,					["HaLLo", "!", "how", "Are", "yoU", "?"]   )







			def UpperCamelCase    ( self					:    List[str]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  BasicTokenizer(do_lower_case=snake_case__					,					never_split=["[UNK]"]   )

									self.assertListEqual(
									    tokenizer.tokenize(" \tHeLLo!how  \n Are yoU? [UNK]"   )					,					["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"]   )







			def UpperCamelCase    ( self					:    Optional[int]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]

									_UpperCAmelCase									=  {}
									for i, token in enumerate(snake_case__   ):
															_UpperCAmelCase									=  i
									_UpperCAmelCase									=  WordpieceTokenizer(vocab=snake_case__					,					unk_token="[UNK]"   )

									self.assertListEqual(tokenizer.tokenize(""   )					,					[]   )

									self.assertListEqual(tokenizer.tokenize("unwanted running"   )					,					["un", "##want", "##ed", "runn", "##ing"]   )

									self.assertListEqual(tokenizer.tokenize("unwantedX running"   )					,					["[UNK]", "runn", "##ing"]   )







			def UpperCamelCase    ( self					:    str   ):




									"""simple docstring"""


									self.assertTrue(_is_whitespace(" "   )   )
									self.assertTrue(_is_whitespace("\t"   )   )
									self.assertTrue(_is_whitespace("\r"   )   )
									self.assertTrue(_is_whitespace("\n"   )   )
									self.assertTrue(_is_whitespace("\u00A0"   )   )

									self.assertFalse(_is_whitespace("A"   )   )
									self.assertFalse(_is_whitespace("-"   )   )







			def UpperCamelCase    ( self					:    Optional[int]   ):




									"""simple docstring"""


									self.assertTrue(_is_control("\u0005"   )   )

									self.assertFalse(_is_control("A"   )   )
									self.assertFalse(_is_control(" "   )   )
									self.assertFalse(_is_control("\t"   )   )
									self.assertFalse(_is_control("\r"   )   )







			def UpperCamelCase    ( self					:    int   ):




									"""simple docstring"""


									self.assertTrue(_is_punctuation("-"   )   )
									self.assertTrue(_is_punctuation("$"   )   )
									self.assertTrue(_is_punctuation("`"   )   )
									self.assertTrue(_is_punctuation("."   )   )

									self.assertFalse(_is_punctuation("A"   )   )
									self.assertFalse(_is_punctuation(" "   )   )







			def UpperCamelCase    ( self					:    int   ):




									"""simple docstring"""


									_UpperCAmelCase									=  self.get_tokenizer()
									_UpperCAmelCase									=  self.get_rust_tokenizer()

									# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
									self.assertListEqual([tokenizer.tokenize(snake_case__   ) for t in ["Test", "\xad", "test"]]					,					[["[UNK]"], [], ["[UNK]"]]   )

									self.assertListEqual(
									    [rust_tokenizer.tokenize(snake_case__   ) for t in ["Test", "\xad", "test"]]					,					[["[UNK]"], [], ["[UNK]"]]   )







			@slow
			def UpperCamelCase    ( self					:    str   ):




									"""simple docstring"""


									_UpperCAmelCase									=  self.tokenizer_class.from_pretrained("google/electra-base-discriminator"   )

									_UpperCAmelCase									=  tokenizer.encode("sequence builders"					,					add_special_tokens=snake_case__   )
									_UpperCAmelCase									=  tokenizer.encode("multi-sequence build"					,					add_special_tokens=snake_case__   )

									_UpperCAmelCase									=  tokenizer.build_inputs_with_special_tokens(snake_case__   )
									_UpperCAmelCase									=  tokenizer.build_inputs_with_special_tokens(snake_case__					,					snake_case__   )

									assert encoded_sentence == [101] + text + [102]
									assert encoded_pair == [101] + text + [102] + text_a + [102]







			def UpperCamelCase    ( self					:    List[Any]   ):




									"""simple docstring"""


									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""   ):
																					_UpperCAmelCase									=  self.rust_tokenizer_class.from_pretrained(snake_case__					,					**snake_case__   )

																					_UpperCAmelCase									=  F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
																					_UpperCAmelCase									=  tokenizer_r.encode_plus(
																					    snake_case__					,					return_attention_mask=snake_case__					,					return_token_type_ids=snake_case__					,					return_offsets_mapping=snake_case__					,					add_special_tokens=snake_case__					,					)

																					_UpperCAmelCase									=  tokenizer_r.do_lower_case if hasattr(snake_case__					,					"do_lower_case"   ) else False
																					_UpperCAmelCase									=  (
																					    [
																					        ((0, 0), tokenizer_r.cls_token),
																					        ((0, 1), "A"),
																					        ((1, 2), ","),
																					        ((3, 5), "na"),
																					        ((5, 6), "##ï"),
																					        ((6, 8), "##ve"),
																					        ((9, 15), tokenizer_r.mask_token),
																					        ((16, 21), "Allen"),
																					        ((21, 23), "##NL"),
																					        ((23, 24), "##P"),
																					        ((25, 33), "sentence"),
																					        ((33, 34), "."),
																					        ((0, 0), tokenizer_r.sep_token),
																					    ]
																					    if not do_lower_case
																					    else [
																					        ((0, 0), tokenizer_r.cls_token),
																					        ((0, 1), "a"),
																					        ((1, 2), ","),
																					        ((3, 8), "naive"),
																					        ((9, 15), tokenizer_r.mask_token),
																					        ((16, 21), "allen"),
																					        ((21, 23), "##nl"),
																					        ((23, 24), "##p"),
																					        ((25, 33), "sentence"),
																					        ((33, 34), "."),
																					        ((0, 0), tokenizer_r.sep_token),
																					    ]
																					)

																					self.assertEqual(
																					    [e[1] for e in expected_results]					,					tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]   )   )
																					self.assertEqual([e[0] for e in expected_results]					,					tokens["offset_mapping"]   )







			def UpperCamelCase    ( self					:    Union[str, Any]   ):




									"""simple docstring"""


									_UpperCAmelCase									=  ["的", "人", "有"]
									_UpperCAmelCase									=  "".join(snake_case__   )
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""   ):
																					_UpperCAmelCase									=  True
																					_UpperCAmelCase									=  self.tokenizer_class.from_pretrained(snake_case__					,					**snake_case__   )
																					_UpperCAmelCase									=  self.rust_tokenizer_class.from_pretrained(snake_case__					,					**snake_case__   )

																					_UpperCAmelCase									=  tokenizer_p.encode(snake_case__					,					add_special_tokens=snake_case__   )
																					_UpperCAmelCase									=  tokenizer_r.encode(snake_case__					,					add_special_tokens=snake_case__   )

																					_UpperCAmelCase									=  tokenizer_r.convert_ids_to_tokens(snake_case__   )
																					_UpperCAmelCase									=  tokenizer_p.convert_ids_to_tokens(snake_case__   )

																					# it is expected that each Chinese character is not preceded by "##"
																					self.assertListEqual(snake_case__					,					snake_case__   )
																					self.assertListEqual(snake_case__					,					snake_case__   )

																					_UpperCAmelCase									=  False
																					_UpperCAmelCase									=  self.rust_tokenizer_class.from_pretrained(snake_case__					,					**snake_case__   )
																					_UpperCAmelCase									=  self.tokenizer_class.from_pretrained(snake_case__					,					**snake_case__   )

																					_UpperCAmelCase									=  tokenizer_r.encode(snake_case__					,					add_special_tokens=snake_case__   )
																					_UpperCAmelCase									=  tokenizer_p.encode(snake_case__					,					add_special_tokens=snake_case__   )

																					_UpperCAmelCase									=  tokenizer_r.convert_ids_to_tokens(snake_case__   )
																					_UpperCAmelCase									=  tokenizer_p.convert_ids_to_tokens(snake_case__   )

																					# it is expected that only the first Chinese character is not preceded by "##".
																					_UpperCAmelCase									=  [
																					    F"""##{token}""" if idx != 0 else token for idx, token in enumerate(snake_case__   )
																					]
																					self.assertListEqual(snake_case__					,					snake_case__   )
																					self.assertListEqual(snake_case__					,					snake_case__   )




