



"""simple docstring"""







import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


__snake_case	:				List[Any]  					=			get_logger(__name__)

# Datasets
__snake_case	:				Any  					=			'https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets'
__snake_case	:				Optional[int]  					=			'https://cdn-datasets.huggingface.co/datasets/datasets'
__snake_case	:				List[Any]  					=			'https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}'

# Metrics
__snake_case	:				Tuple  					=			'https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics'
__snake_case	:				List[Any]  					=			'https://cdn-datasets.huggingface.co/datasets/metric'
__snake_case	:				Union[str, Any]  					=			'https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}'

# Hub
__snake_case	:				List[str]  					=			os.environ.get('HF_ENDPOINT', 'https://huggingface.co')
__snake_case	:				Optional[int]  					=			HF_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}'
__snake_case	:				Tuple  					=			'main'

__snake_case	:				Optional[int]  					=			version.parse(platform.python_version())

if PY_VERSION < version.parse('3.8'):
 import importlib_metadata
else:
 import importlib.metadata as importlib_metadata

# General environment variables accepted values for booleans
__snake_case	:				Union[str, Any]  					=			{'1', 'ON', 'YES', 'TRUE'}
__snake_case	:				List[Any]  					=			ENV_VARS_TRUE_VALUES.union({'AUTO'})


# Imports
__snake_case	:				Any  					=			version.parse(importlib_metadata.version('dill'))
__snake_case	:				Union[str, Any]  					=			version.parse(importlib_metadata.version('pandas'))
__snake_case	:				List[Any]  					=			version.parse(importlib_metadata.version('pyarrow'))

__snake_case	:				Optional[Any]  					=			os.environ.get('USE_TF', 'AUTO').upper()
__snake_case	:				Optional[Any]  					=			os.environ.get('USE_TORCH', 'AUTO').upper()
__snake_case	:				Any  					=			os.environ.get('USE_JAX', 'AUTO').upper()

__snake_case	:				Any  					=			'N/A'
__snake_case	:				List[str]  					=			False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
 __snake_case	:				Union[str, Any]  					=			importlib.util.find_spec('torch') is not None
 if TORCH_AVAILABLE:
  try:
   __snake_case	:				Tuple  					=			version.parse(importlib_metadata.version('torch'))
   logger.info(f'PyTorch version {TORCH_VERSION} available.')
  except importlib_metadata.PackageNotFoundError:
   pass
else:
 logger.info('Disabling PyTorch because USE_TF is set')

__snake_case	:				Optional[int]  					=			'N/A'
__snake_case	:				List[str]  					=			False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
 __snake_case	:				List[Any]  					=			importlib.util.find_spec('tensorflow') is not None
 if TF_AVAILABLE:
  # For the metadata, we have to look for both tensorflow and tensorflow-cpu
  for package in [
      "tensorflow",
      "tensorflow-cpu",
      "tensorflow-gpu",
      "tf-nightly",
      "tf-nightly-cpu",
      "tf-nightly-gpu",
      "intel-tensorflow",
      "tensorflow-rocm",
      "tensorflow-macos",
  ]:
   try:
    __snake_case	:				Dict  					=			version.parse(importlib_metadata.version(package))
   except importlib_metadata.PackageNotFoundError:
    continue
   else:
    break
  else:
   __snake_case	:				List[str]  					=			False
 if TF_AVAILABLE:
  if TF_VERSION.major < 2:
   logger.info(f'TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.')
   __snake_case	:				List[Any]  					=			False
  else:
   logger.info(f'TensorFlow version {TF_VERSION} available.')
else:
 logger.info('Disabling Tensorflow because USE_TORCH is set')


__snake_case	:				Union[str, Any]  					=			'N/A'
__snake_case	:				List[Any]  					=			False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
 __snake_case	:				Optional[int]  					=			importlib.util.find_spec('jax') is not None and importlib.util.find_spec('jaxlib') is not None
 if JAX_AVAILABLE:
  try:
   __snake_case	:				int  					=			version.parse(importlib_metadata.version('jax'))
   logger.info(f'JAX version {JAX_VERSION} available.')
  except importlib_metadata.PackageNotFoundError:
   pass
else:
 logger.info('Disabling JAX because USE_JAX is set to False')


__snake_case	:				Optional[int]  					=			os.environ.get('USE_BEAM', 'AUTO').upper()
__snake_case	:				Optional[int]  					=			'N/A'
__snake_case	:				Optional[Any]  					=			False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
 try:
  __snake_case	:				Union[str, Any]  					=			version.parse(importlib_metadata.version('apache_beam'))
  __snake_case	:				Optional[int]  					=			True
  logger.info(f'Apache Beam version {BEAM_VERSION} available.')
 except importlib_metadata.PackageNotFoundError:
  pass
else:
 logger.info('Disabling Apache Beam because USE_BEAM is set to False')


# Optional tools for data loading
__snake_case	:				List[str]  					=			importlib.util.find_spec('sqlalchemy') is not None

# Optional tools for feature decoding
__snake_case	:				Optional[Any]  					=			importlib.util.find_spec('PIL') is not None
__snake_case	:				Tuple  					=			importlib.util.find_spec('soundfile') is not None and version.parse(
    importlib.import_module('soundfile').__libsndfile_version__
) >= version.parse('1.0.31')
__snake_case	:				str  					=			importlib.util.find_spec('soundfile') is not None and version.parse(
    importlib.import_module('soundfile').__libsndfile_version__
) >= version.parse('1.1.0')

# Optional compression tools
__snake_case	:				Tuple  					=			importlib.util.find_spec('rarfile') is not None
__snake_case	:				Union[str, Any]  					=			importlib.util.find_spec('zstandard') is not None
__snake_case	:				str  					=			importlib.util.find_spec('lz4') is not None
__snake_case	:				Union[str, Any]  					=			importlib.util.find_spec('py7zr') is not None


# Cache location
__snake_case	:				Union[str, Any]  					=			'~/.cache'
__snake_case	:				Tuple  					=			os.getenv('XDG_CACHE_HOME', DEFAULT_XDG_CACHE_HOME)
__snake_case	:				Optional[Any]  					=			os.path.join(XDG_CACHE_HOME, 'huggingface')
__snake_case	:				Tuple  					=			os.path.expanduser(os.getenv('HF_HOME', DEFAULT_HF_CACHE_HOME))

__snake_case	:				Union[str, Any]  					=			os.path.join(HF_CACHE_HOME, 'datasets')
__snake_case	:				List[Any]  					=			Path(os.getenv('HF_DATASETS_CACHE', DEFAULT_HF_DATASETS_CACHE))

__snake_case	:				Optional[int]  					=			os.path.join(HF_CACHE_HOME, 'metrics')
__snake_case	:				str  					=			Path(os.getenv('HF_METRICS_CACHE', DEFAULT_HF_METRICS_CACHE))

__snake_case	:				Any  					=			os.path.join(HF_CACHE_HOME, 'modules')
__snake_case	:				Union[str, Any]  					=			Path(os.getenv('HF_MODULES_CACHE', DEFAULT_HF_MODULES_CACHE))

__snake_case	:				List[str]  					=			'downloads'
__snake_case	:				Any  					=			os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
__snake_case	:				Union[str, Any]  					=			Path(os.getenv('HF_DATASETS_DOWNLOADED_DATASETS_PATH', DEFAULT_DOWNLOADED_DATASETS_PATH))

__snake_case	:				Union[str, Any]  					=			'extracted'
__snake_case	:				Dict  					=			os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
__snake_case	:				List[Any]  					=			Path(os.getenv('HF_DATASETS_EXTRACTED_DATASETS_PATH', DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
__snake_case	:				str  					=			(
    os.environ.get('HF_UPDATE_DOWNLOAD_COUNTS', 'AUTO').upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
__snake_case	:				Tuple  					=			1_000

# Size of the preloaded record batch in `Dataset.__iter__`
__snake_case	:				Optional[int]  					=			10

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
__snake_case	:				Dict  					=			4 << 30

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
__snake_case	:				Dict  					=			'500MB'

# Parquet configuration
__snake_case	:				Optional[Any]  					=			100
__snake_case	:				Any  					=			100
__snake_case	:				Optional[int]  					=			100

# Offline mode
__snake_case	:				List[Any]  					=			os.environ.get('HF_DATASETS_OFFLINE', 'AUTO').upper() in ENV_VARS_TRUE_VALUES

# In-memory
__snake_case	:				List[str]  					=			0  # Disabled
__snake_case	:				List[str]  					=			float(os.environ.get('HF_DATASETS_IN_MEMORY_MAX_SIZE', DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
__snake_case	:				Optional[int]  					=			'dataset.arrow'
__snake_case	:				Union[str, Any]  					=			'indices.arrow'
__snake_case	:				List[Any]  					=			'state.json'
__snake_case	:				List[Any]  					=			'dataset_info.json'
__snake_case	:				List[Any]  					=			'dataset_infos.json'
__snake_case	:				Dict  					=			'LICENSE'
__snake_case	:				List[str]  					=			'metric_info.json'
__snake_case	:				Dict  					=			'dataset_dict.json'

__snake_case	:				List[Any]  					=			'datasets_modules'

__snake_case	:				Optional[int]  					=			255

# Streaming
__snake_case	:				List[str]  					=			20
__snake_case	:				Tuple  					=			5

# Datasets without script
__snake_case	:				Union[str, Any]  					=			200
__snake_case	:				Tuple  					=			10
__snake_case	:				Any  					=			200

# Progress bars
__snake_case	:				Any  					=			0.05  # 20 progress updates per sec








"""simple docstring"""







from collections import Counter
import datasets
import transformers
from transformers.convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS

from transformers.utils import logging

logging.set_verbosity_info()

__snake_case	:				Union[str, Any]  					=			{
    name: (getattr(transformers, name), getattr(transformers, name + 'Fast')) for name in SLOW_TO_FAST_CONVERTERS
}

__snake_case	:				List[Any]  					=			datasets.load_dataset('xnli', split='test+validation')

__snake_case	:				int  					=			0
__snake_case	:				int  					=			0
__snake_case	:				int  					=			0
__snake_case	:				Optional[int]  					=			0



def   a_	(			__a		,							__a		,							__a		,							__a      ):
     if spm_diff == list(reversed(__a      )      ):
          # AAA -> AA+A vs A+AA case.
          return True
     elif len(__a      ) == len(__a      ) and fast.decode(__a      ) == fast.decode(__a      ):
          # Second order OK
          # Barrich -> Barr + ich vs Bar + rich
          return True
     A__				=   slow.encode(slow.decode(__a      )      )
     A__				=   fast.encode(fast.decode(__a      )      )
     if spm_reencoded != spm_diff and spm_reencoded == tok_reencoded:
          # Type 3 error.
          # Snehagatha ->
          #       Sne, h, aga, th, a
          #       Sne, ha, gat, ha
          # Encoding the wrong with sp does not even recover what spm gave us
          # It fits tokenizer however...
          return True
     return False



def   a_	(			__a		,							__a		,							__a      ):
     A__				=   fast.encode_plus(__a      )[0]
     A__				=   enc.offsets
     A__	,     A__				=   offsets[idx], offsets[idx - 1]
     if curr is not None and line[curr[0] : curr[1]] == "\u200f":
          return True
     if prev is not None and line[prev[0] : prev[1]] == "\u200f":
          return True



def   a_	(			__a		,							__a		,							__a		,							__a		,							__a      ):
     # Encoding can be the same with same result AAA -> A + AA vs AA + A
     # We can check that we use at least exactly the same number of tokens.
     for i, (spm_id, tok_id) in enumerate(zip(__a		,							__a      )      ):
          if spm_id != tok_id:
               break
     A__				=   i
     for i, (spm_id, tok_id) in enumerate(zip(reversed(__a      )		,							reversed(__a      )      )      ):
          if spm_id != tok_id:
               break
     A__				=   len(__a      ) - i

     A__				=   spm_ids[first:last]
     A__				=   tok_ids[first:last]

     if check_diff(__a		,							__a		,							__a		,							__a      ):
          return True

     if check_LTR_mark(__a		,							__a		,							__a      ):
          return True

     if last - first > 5:
          # We might have twice a single problem, attempt to subdivide the disjointed tokens into smaller problems
          A__				=   Counter(spm_ids[first:last]      )
          A__				=   Counter(tok_ids[first:last]      )

          A__				=   {spm_ for (spm_, si) in spms.items() if toks.get(spm_		,							0      ) == si}
          A__				=   3
          for i in range(last - first - min_width      ):
               if all(spm_ids[first + i + j] in removable_tokens for j in range(__a      )      ):
                    A__				=   [
                        k
                        for k in range(last - first - min_width      )
                        if tok_ids[first + k : first + k + min_width] == spm_ids[first + i : first + i + min_width]
                    ]
                    for j in possible_matches:
                         if check_diff(spm_ids[first : first + i]		,							tok_ids[first : first + j]		,							__a		,							__a      ) and check_details(
                             __a		,							spm_ids[first + i : last]		,							tok_ids[first + j : last]		,							__a		,							__a		,							):
                              return True

     print(f'''Spm: {[fast.decode([spm_ids[i]]      ) for i in range(__a		,							__a      )]}'''      )
     try:
          print(f'''Tok: {[fast.decode([tok_ids[i]]      ) for i in range(__a		,							__a      )]}'''      )
     except Exception:
          pass

     A__				=   fast.decode(spm_ids[:first]      )
     A__				=   fast.decode(spm_ids[last:]      )
     A__				=   fast.decode(spm_ids[first:last]      )
     print()
     print(__a      )
     return False



def   a_	(			__a		,							__a		,							__a      ):
     global perfect
     global imperfect
     global wrong
     global total

     A__				=   slow.encode(__a      )
     A__				=   fast.encode(__a      )

     A__				=   False
     total += 1

     if slow_ids != fast_ids:
          if check_details(__a		,							__a		,							__a		,							__a		,							__a      ):
               A__				=   True
               imperfect += 1
          else:
               wrong += 1
     else:
          perfect += 1

     if total % 1_0000 == 0:
          print(f'''({perfect} / {imperfect} / {wrong} ----- {perfect + imperfect + wrong})'''      )

     if skip_assert:
          return

     assert (
         slow_ids == fast_ids
     ), f'''line {text} : \n\n{slow_ids}\n{fast_ids}\n\n{slow.tokenize(__a      )}\n{fast.tokenize(__a      )}'''



def   a_	(			__a		,							__a      ):
     global batch_total
     for i in range(len(__a      )      ):
          # premise, all languages
          for text in dataset[i]["premise"].values():
               test_string(__a		,							__a		,							__a      )

          # hypothesis, all languages
          for text in dataset[i]["hypothesis"]["translation"]:
               test_string(__a		,							__a		,							__a      )


if __name__ == "__main__":
 for name, (slow_class, fast_class) in TOKENIZER_CLASSES.items():
  __snake_case	:				int  					=			list(slow_class.max_model_input_sizes.keys())
  for checkpoint in checkpoint_names:
   __snake_case	:				Union[str, Any]  					=			0
   __snake_case	:				Optional[Any]  					=			0
   __snake_case	:				List[Any]  					=			0
   __snake_case	:				List[str]  					=			0

   print(f'========================== Checking {name}: {checkpoint} ==========================')
   __snake_case	:				Union[str, Any]  					=			slow_class.from_pretrained(checkpoint, force_download=True)
   __snake_case	:				Optional[Any]  					=			fast_class.from_pretrained(checkpoint, force_download=True)
   test_tokenizer(slow, fast)
   print(f'Accuracy {perfect * 100 / total:.2f}')



