



import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
	import torch

	UpperCAmelCase :				Optional[Any]							=True
except ImportError:
	UpperCAmelCase :				Any							=False


try:
	from torch.hub import _get_torch_home

	UpperCAmelCase :				Tuple							=_get_torch_home()
except ImportError:
	UpperCAmelCase :				Optional[Any]							=os.path.expanduser(
	    os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
	)

UpperCAmelCase :				str							=os.path.join(torch_cache_home, """transformers""")

UpperCAmelCase :				List[str]							="""https://cdn.huggingface.co"""
UpperCAmelCase :				Optional[int]							="""https://s3.amazonaws.com/models.huggingface.co/bert"""
UpperCAmelCase :				Tuple							="""/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
UpperCAmelCase :				Tuple							=os.path.join(PATH, """config.yaml""")
UpperCAmelCase :				Union[str, Any]							=os.path.join(PATH, """attributes.txt""")
UpperCAmelCase :				Any							=os.path.join(PATH, """objects.txt""")
UpperCAmelCase :				str							=os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
UpperCAmelCase :				List[Any]							=os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
UpperCAmelCase :				str							=os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
UpperCAmelCase :				Any							="""pytorch_model.bin"""
UpperCAmelCase :				int							="""config.yaml"""



def  _lowerCAmelCase     (_lowerCAmelCase=OBJECTS ,						_lowerCAmelCase=ATTRIBUTES):
					UpperCamelCase_			= []
					with open(_lowerCAmelCase) as f:
										for object in f.readlines():
															vg_classes.append(object.split(",")[0].lower().strip())

					UpperCamelCase_			= []
					with open(_lowerCAmelCase) as f:
										for object in f.readlines():
															vg_attrs.append(object.split(",")[0].lower().strip())
					return vg_classes, vg_attrs



def  _lowerCAmelCase     (_lowerCAmelCase):
					UpperCamelCase_			= OrderedDict()
					with open(_lowerCAmelCase ,						"rb") as f:
										UpperCamelCase_			= pkl.load(_lowerCAmelCase)["model"]
					for k in copy.deepcopy(list(ckp.keys())):
										UpperCamelCase_			= ckp.pop(_lowerCAmelCase)
										if isinstance(_lowerCAmelCase ,						np.ndarray):
															UpperCamelCase_			= torch.tensor(_lowerCAmelCase)
										else:
															assert isinstance(_lowerCAmelCase ,						torch.tensor), type(_lowerCAmelCase)
										UpperCamelCase_			= v
					return r


class    _lowercase :
				'''simple docstring'''







				lowercase__     =    {}

				def __init__(			self  ,			snake_case__  ,			snake_case__ = "root"  ,			snake_case__=0     ):

									'''simple docstring'''


									UpperCamelCase_			= name
									UpperCamelCase_			= level
									UpperCamelCase_			= {}
									for k, v in dictionary.items():
														if v is None:
																			raise ValueError()
														UpperCamelCase_			= copy.deepcopy(snake_case__     )
														UpperCamelCase_			= copy.deepcopy(snake_case__     )
														if isinstance(snake_case__  ,			snake_case__     ):
																			UpperCamelCase_			= Config(snake_case__  ,			name=snake_case__  ,			level=level + 1     )
														UpperCamelCase_			= v
														setattr(self  ,			snake_case__  ,			snake_case__     )

									UpperCamelCase_			= d

				def __repr__(			self     ):

									'''simple docstring'''


									return str(list((self._pointer.keys())     )     )

				def __setattr__(			self  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									UpperCamelCase_			= val
									UpperCamelCase_			= val
									UpperCamelCase_			= key.split("."     )
									UpperCamelCase_			= len(snake_case__     ) - 1
									UpperCamelCase_			= self._pointer
									if len(snake_case__     ) > 1:
														for i, l in enumerate(snake_case__     ):
																			if hasattr(self  ,			snake_case__     ) and isinstance(getattr(self  ,			snake_case__     )  ,			snake_case__     ):
																								setattr(getattr(self  ,			snake_case__     )  ,			".".join(levels[i:]     )  ,			snake_case__     )
																			if l == last_level:
																								UpperCamelCase_			= val
																			else:
																								UpperCamelCase_			= pointer[l]

				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									return self._pointer

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									with open(F"""{file_name}"""  ,			"w"     ) as stream:
														dump(snake_case__  ,			snake_case__     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									with open(F"""{file_name}"""  ,			"w"     ) as stream:
														json.dump(snake_case__  ,			snake_case__     )

				@staticmethod
				def    _lowerCamelCase       (			snake_case__     ):

									'''simple docstring'''


									with open(snake_case__     ) as stream:
														UpperCamelCase_			= load(snake_case__  ,			Loader=snake_case__     )
									return data

				def __str__(			self     ):

									'''simple docstring'''


									UpperCamelCase_			= "    "
									if self._name != "root":
														UpperCamelCase_			= F"""{t * (self._level-1)}{self._name}:\n"""
									else:
														UpperCamelCase_			= ""
									UpperCamelCase_			= self._level
									for i, (k, v) in enumerate(self._pointer.items()     ):
														if isinstance(snake_case__  ,			snake_case__     ):
																			r += F"""{t * (self._level)}{v}\n"""
																			self._level += 1
														else:
																			r += F"""{t * (self._level)}{k}: {v} ({type(snake_case__     ).__name__})\n"""
														UpperCamelCase_			= level
									return r[:-1]

				@classmethod
				def    _lowerCamelCase       (			cls  ,			snake_case__  ,			**snake_case__     ):

									'''simple docstring'''


									UpperCamelCase_	,     UpperCamelCase_			= cls.get_config_dict(snake_case__  ,			**snake_case__     )
									return cls(snake_case__     )

				@classmethod
				def    _lowerCamelCase       (			cls  ,			snake_case__  ,			**snake_case__     ):

									'''simple docstring'''


									UpperCamelCase_			= kwargs.pop("cache_dir"  ,			snake_case__     )
									UpperCamelCase_			= kwargs.pop("force_download"  ,			snake_case__     )
									UpperCamelCase_			= kwargs.pop("resume_download"  ,			snake_case__     )
									UpperCamelCase_			= kwargs.pop("proxies"  ,			snake_case__     )
									UpperCamelCase_			= kwargs.pop("local_files_only"  ,			snake_case__     )

									if os.path.isdir(snake_case__     ):
														UpperCamelCase_			= os.path.join(snake_case__  ,			snake_case__     )
									elif os.path.isfile(snake_case__     ) or is_remote_url(snake_case__     ):
														UpperCamelCase_			= pretrained_model_name_or_path
									else:
														UpperCamelCase_			= hf_bucket_url(snake_case__  ,			filename=snake_case__  ,			use_cdn=snake_case__     )

									try:
														# Load from URL or cache if already cached
														UpperCamelCase_			= cached_path(
														    snake_case__  ,			cache_dir=snake_case__  ,			force_download=snake_case__  ,			proxies=snake_case__  ,			resume_download=snake_case__  ,			local_files_only=snake_case__  ,			)
														# Load config dict
														if resolved_config_file is None:
																			raise EnvironmentError

														UpperCamelCase_			= Config.load_yaml(snake_case__     )

									except EnvironmentError:
														UpperCamelCase_			= "Can't load config for"
														raise EnvironmentError(snake_case__     )

									if resolved_config_file == config_file:
														print("loading configuration file from path"     )
									else:
														print("loading configuration file cache"     )

									return Config.load_yaml(snake_case__     ), kwargs




def  _lowerCAmelCase     (_lowerCAmelCase):
					UpperCamelCase_			= torch.load("dump.pt" ,						map_location=in_tensor.device)
					UpperCamelCase_			= in_tensor.numpy()
					UpperCamelCase_			= out_tensor.numpy()[0]
					print(na.shape ,						na[0, 0, :5])
					print(na.shape ,						na[0, 0, :5])
					assert np.allclose(_lowerCAmelCase ,						_lowerCAmelCase ,						rtol=0.01 ,						atol=0.1), (
					    f"""{sum([1 for x in np.isclose(_lowerCAmelCase ,						_lowerCAmelCase ,						rtol=0.01 ,						atol=0.1).flatten() if x is False])/len(na.flatten())*1_00:.4f} %"""
					    " element-wise mismatch"
					)
					raise Exception("tensors are all good")

					# Hugging face functions below



def  _lowerCAmelCase     (_lowerCAmelCase):
					UpperCamelCase_			= urlparse(_lowerCAmelCase)
					return parsed.scheme in ("http", "https")



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase=True):
					UpperCamelCase_			= CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
					UpperCamelCase_			= "/" not in model_id
					if legacy_format:
										return f"""{endpoint}/{model_id}-{filename}"""
					else:
										return f"""{endpoint}/{model_id}/{filename}"""



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase=None ,						_lowerCAmelCase=0 ,						_lowerCAmelCase=None ,						):
					UpperCamelCase_			= "python/{}".format(sys.version.split()[0])
					if _torch_available:
										ua += "; torch/{}".format(torch.__version__)
					if isinstance(_lowerCAmelCase ,						_lowerCAmelCase):
										ua += "; " + "; ".join("{}/{}".format(_lowerCAmelCase ,						_lowerCAmelCase) for k, v in user_agent.items())
					elif isinstance(_lowerCAmelCase ,						_lowerCAmelCase):
										ua += "; " + user_agent
					UpperCamelCase_			= {"user-agent": ua}
					if resume_size > 0:
										UpperCamelCase_			= "bytes=%d-" % (resume_size,)
					UpperCamelCase_			= requests.get(_lowerCAmelCase ,						stream=_lowerCAmelCase ,						proxies=_lowerCAmelCase ,						headers=_lowerCAmelCase)
					if response.status_code == 4_16:  # Range not satisfiable
										return
					UpperCamelCase_			= response.headers.get("Content-Length")
					UpperCamelCase_			= resume_size + int(_lowerCAmelCase) if content_length is not None else None
					UpperCamelCase_			= tqdm(
					    unit="B" ,						unit_scale=_lowerCAmelCase ,						total=_lowerCAmelCase ,						initial=_lowerCAmelCase ,						desc="Downloading" ,						)
					for chunk in response.iter_content(chunk_size=10_24):
										if chunk:  # filter out keep-alive new chunks
															progress.update(len(_lowerCAmelCase))
															temp_file.write(_lowerCAmelCase)
					progress.close()



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase=None ,						_lowerCAmelCase=False ,						_lowerCAmelCase=None ,						_lowerCAmelCase=10 ,						_lowerCAmelCase=False ,						_lowerCAmelCase=None ,						_lowerCAmelCase=False ,						):
					if cache_dir is None:
										UpperCamelCase_			= TRANSFORMERS_CACHE
					if isinstance(_lowerCAmelCase ,						_lowerCAmelCase):
										UpperCamelCase_			= str(_lowerCAmelCase)

					os.makedirs(_lowerCAmelCase ,						exist_ok=_lowerCAmelCase)

					UpperCamelCase_			= None
					if not local_files_only:
										try:
															UpperCamelCase_			= requests.head(_lowerCAmelCase ,						allow_redirects=_lowerCAmelCase ,						proxies=_lowerCAmelCase ,						timeout=_lowerCAmelCase)
															if response.status_code == 2_00:
																				UpperCamelCase_			= response.headers.get("ETag")
										except (EnvironmentError, requests.exceptions.Timeout):
															# etag is already None
															pass

					UpperCamelCase_			= url_to_filename(_lowerCAmelCase ,						_lowerCAmelCase)

					# get cache path to put the file
					UpperCamelCase_			= os.path.join(_lowerCAmelCase ,						_lowerCAmelCase)

					# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
					# try to get the last downloaded one
					if etag is None:
										if os.path.exists(_lowerCAmelCase):
															return cache_path
										else:
															UpperCamelCase_			= [
															    file
															    for file in fnmatch.filter(os.listdir(_lowerCAmelCase) ,						filename + ".*")
															    if not file.endswith(".json") and not file.endswith(".lock")
															]
															if len(_lowerCAmelCase) > 0:
																				return os.path.join(_lowerCAmelCase ,						matching_files[-1])
															else:
																				# If files cannot be found and local_files_only=True,
																				# the models might've been found if local_files_only=False
																				# Notify the user about that
																				if local_files_only:
																									raise ValueError(
																									    "Cannot find the requested files in the cached path and outgoing traffic has been"
																									    " disabled. To enable model look-ups and downloads online, set 'local_files_only'"
																									    " to False.")
																				return None

    # From now on, etag is not None.
					if os.path.exists(_lowerCAmelCase) and not force_download:
										return cache_path

					# Prevent parallel downloads of the same file with a lock.
					UpperCamelCase_			= cache_path + ".lock"
					with FileLock(_lowerCAmelCase):
										# If the download just completed while the lock was activated.
										if os.path.exists(_lowerCAmelCase) and not force_download:
															# Even if returning early like here, the lock will be released.
															return cache_path

										if resume_download:
															UpperCamelCase_			= cache_path + ".incomplete"

															@contextmanager
															def _resumable_file_manager():
																				with open(_lowerCAmelCase ,						"a+b") as f:
																									yield f

															UpperCamelCase_			= _resumable_file_manager
															if os.path.exists(_lowerCAmelCase):
																				UpperCamelCase_			= os.stat(_lowerCAmelCase).st_size
															else:
																				UpperCamelCase_			= 0
										else:
															UpperCamelCase_			= partial(tempfile.NamedTemporaryFile ,						dir=_lowerCAmelCase ,						delete=_lowerCAmelCase)
															UpperCamelCase_			= 0

										# Download to temporary file, then copy to cache dir once finished.
										# Otherwise you get corrupt cache entries if the download gets interrupted.
										with temp_file_manager() as temp_file:
															print(
															    "%s not found in cache or force_download set to True, downloading to %s" ,						_lowerCAmelCase ,						temp_file.name ,						)

															http_get(
															    _lowerCAmelCase ,						_lowerCAmelCase ,						proxies=_lowerCAmelCase ,						resume_size=_lowerCAmelCase ,						user_agent=_lowerCAmelCase ,						)

										os.replace(temp_file.name ,						_lowerCAmelCase)

										UpperCamelCase_			= {"url": url, "etag": etag}
										UpperCamelCase_			= cache_path + ".json"
										with open(_lowerCAmelCase ,						"w") as meta_file:
															json.dump(_lowerCAmelCase ,						_lowerCAmelCase)

					return cache_path



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase=None):
					UpperCamelCase_			= url.encode("utf-8")
					UpperCamelCase_			= shaaaa(_lowerCAmelCase)
					UpperCamelCase_			= url_hash.hexdigest()

					if etag:
										UpperCamelCase_			= etag.encode("utf-8")
										UpperCamelCase_			= shaaaa(_lowerCAmelCase)
										filename += "." + etag_hash.hexdigest()

					if url.endswith(".h5"):
										filename += ".h5"

					return filename



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase=None ,						_lowerCAmelCase=False ,						_lowerCAmelCase=None ,						_lowerCAmelCase=False ,						_lowerCAmelCase=None ,						_lowerCAmelCase=False ,						_lowerCAmelCase=False ,						_lowerCAmelCase=False ,						):
					if cache_dir is None:
										UpperCamelCase_			= TRANSFORMERS_CACHE
					if isinstance(_lowerCAmelCase ,						_lowerCAmelCase):
										UpperCamelCase_			= str(_lowerCAmelCase)
					if isinstance(_lowerCAmelCase ,						_lowerCAmelCase):
										UpperCamelCase_			= str(_lowerCAmelCase)

					if is_remote_url(_lowerCAmelCase):
										# URL, so get it from the cache (downloading if necessary)
										UpperCamelCase_			= get_from_cache(
										    _lowerCAmelCase ,						cache_dir=_lowerCAmelCase ,						force_download=_lowerCAmelCase ,						proxies=_lowerCAmelCase ,						resume_download=_lowerCAmelCase ,						user_agent=_lowerCAmelCase ,						local_files_only=_lowerCAmelCase ,						)
					elif os.path.exists(_lowerCAmelCase):
										# File, and it exists.
										UpperCamelCase_			= url_or_filename
					elif urlparse(_lowerCAmelCase).scheme == "":
										# File, but it doesn't exist.
										raise EnvironmentError("file {} not found".format(_lowerCAmelCase))
					else:
										# Something unknown
										raise ValueError("unable to parse {} as a URL or as a local path".format(_lowerCAmelCase))

					if extract_compressed_file:
										if not is_zipfile(_lowerCAmelCase) and not tarfile.is_tarfile(_lowerCAmelCase):
															return output_path

										# Path where we extract compressed archives
										# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
										UpperCamelCase_	,     UpperCamelCase_			= os.path.split(_lowerCAmelCase)
										UpperCamelCase_			= output_file.replace("." ,						"-") + "-extracted"
										UpperCamelCase_			= os.path.join(_lowerCAmelCase ,						_lowerCAmelCase)

										if os.path.isdir(_lowerCAmelCase) and os.listdir(_lowerCAmelCase) and not force_extract:
															return output_path_extracted

										# Prevent parallel extractions
										UpperCamelCase_			= output_path + ".lock"
										with FileLock(_lowerCAmelCase):
															shutil.rmtree(_lowerCAmelCase ,						ignore_errors=_lowerCAmelCase)
															os.makedirs(_lowerCAmelCase)
															if is_zipfile(_lowerCAmelCase):
																				with ZipFile(_lowerCAmelCase ,						"r") as zip_file:
																									zip_file.extractall(_lowerCAmelCase)
																									zip_file.close()
															elif tarfile.is_tarfile(_lowerCAmelCase):
																				UpperCamelCase_			= tarfile.open(_lowerCAmelCase)
																				tar_file.extractall(_lowerCAmelCase)
																				tar_file.close()
															else:
																				raise EnvironmentError("Archive format of {} could not be identified".format(_lowerCAmelCase))

										return output_path_extracted

					return output_path



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase=","):
					assert isinstance(_lowerCAmelCase ,						_lowerCAmelCase)
					if os.path.isfile(_lowerCAmelCase):
										with open(_lowerCAmelCase) as f:
															UpperCamelCase_			= eval(f.read())
					else:
										UpperCamelCase_			= requests.get(_lowerCAmelCase)
										try:
															UpperCamelCase_			= requests.json()
										except Exception:
															UpperCamelCase_			= req.content.decode()
															assert data is not None, "could not connect"
															try:
																				UpperCamelCase_			= eval(_lowerCAmelCase)
															except Exception:
																				UpperCamelCase_			= data.split("\n")
										req.close()
					return data



def  _lowerCAmelCase     (_lowerCAmelCase):
					UpperCamelCase_			= requests.get(_lowerCAmelCase)
					UpperCamelCase_			= np.array(Image.open(BytesIO(response.content)))
					return img



def  _lowerCAmelCase     (_lowerCAmelCase):
					UpperCamelCase_			= url.split("/")[-1]
					if fn not in os.listdir(os.getcwd()):
										wget.download(_lowerCAmelCase)
					with open(_lowerCAmelCase ,						"rb") as stream:
										UpperCamelCase_			= pkl.load(_lowerCAmelCase)
					UpperCamelCase_			= weights.pop("model")
					UpperCamelCase_			= {}
					for k, v in model.items():
										UpperCamelCase_			= torch.from_numpy(_lowerCAmelCase)
										if "running_var" in k:
															UpperCamelCase_			= torch.tensor([0])
															UpperCamelCase_			= k.replace("running_var" ,						"num_batches_tracked")
															UpperCamelCase_			= zero
					return new



def  _lowerCAmelCase     ():
					print(f"""{os.path.abspath(os.path.join(_lowerCAmelCase ,						os.pardir))}/demo.ipynb""")



def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase="RGB"):
					assert isinstance(_lowerCAmelCase ,						_lowerCAmelCase)
					if os.path.isfile(_lowerCAmelCase):
										UpperCamelCase_			= cva.imread(_lowerCAmelCase)
					else:
										UpperCamelCase_			= get_image_from_url(_lowerCAmelCase)
										assert img is not None, f"""could not connect to: {im}"""
					UpperCamelCase_			= cva.cvtColor(_lowerCAmelCase ,						cva.COLOR_BGR2RGB)
					if input_format == "RGB":
										UpperCamelCase_			= img[:, :, ::-1]
					return img






def  _lowerCAmelCase     (_lowerCAmelCase ,						_lowerCAmelCase=1):
					return (images[i : i + batch] for i in range(0 ,						len(_lowerCAmelCase) ,						_lowerCAmelCase))






'''simple docstring'''

import json
import os
import re
import unicodedata
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils import logging


a__         =     logging.get_logger(__name__)

a__         =     {
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
}

a__         =     {
    '''vocab_file''': {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/vocab.json'''},
    '''merges_file''': {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/merges.txt'''},
}

a__         =     {
    '''openai-gpt''': 512,
}




def    snake_case__     (  a	)			->       Tuple:





			'''simple docstring'''






			snake_case__          =						text.strip()
			if not text:
						return []
			snake_case__          =						text.split()
			return tokens





class __magic_name__(						__lowerCAmelCase      ):






						def __init__(   self						:						Any					,   __UpperCamelCase						:						str=True					,   __UpperCamelCase						:						Dict=None					,   __UpperCamelCase						:						Union[str, Any]=True					,   __UpperCamelCase						:						List[str]=None					,   __UpperCamelCase						:						Optional[int]=True					,   ):



									'''simple docstring'''






									if never_split is None:
												snake_case__          =						[]
									snake_case__          =						do_lower_case
									snake_case__          =						set(__UpperCamelCase       )
									snake_case__          =						tokenize_chinese_chars
									snake_case__          =						strip_accents
									snake_case__          =						do_split_on_punc






						def       __lowerCAmelCase(   self						:						str					,   __UpperCamelCase						:						Optional[int]					,   __UpperCamelCase						:						Any=None       ):



									'''simple docstring'''






									snake_case__          =						self.never_split.union(set(__UpperCamelCase       )       ) if never_split else self.never_split
									snake_case__          =						self._clean_text(__UpperCamelCase       )

									# This was added on November 1st, 2018 for the multilingual and Chinese
									# models. This is also applied to the English models now, but it doesn't
									# matter since the English models were not trained on any Chinese data
									# and generally don't have any Chinese data in them (there are Chinese
									# characters in the vocabulary because Wikipedia does have some Chinese
									# words in the English Wikipedia.).
									if self.tokenize_chinese_chars:
												snake_case__          =						self._tokenize_chinese_chars(__UpperCamelCase       )
									# prevents treating the same character with different unicode codepoints as different characters
									snake_case__          =						unicodedata.normalize("""NFC"""					,   __UpperCamelCase       )
									snake_case__          =						whitespace_tokenize(__UpperCamelCase       )
									snake_case__          =						[]
									for token in orig_tokens:
												if token not in never_split:
															if self.do_lower_case:
																		snake_case__          =						token.lower()
																		if self.strip_accents is not False:
																					snake_case__          =						self._run_strip_accents(__UpperCamelCase       )
															elif self.strip_accents:
																		snake_case__          =						self._run_strip_accents(__UpperCamelCase       )
												split_tokens.extend(self._run_split_on_punc(__UpperCamelCase					,   __UpperCamelCase       )       )

									snake_case__          =						whitespace_tokenize(""" """.join(__UpperCamelCase       )       )
									return output_tokens






						def       __lowerCAmelCase(   self						:						Optional[Any]					,   __UpperCamelCase						:						Tuple       ):



									'''simple docstring'''






									snake_case__          =						unicodedata.normalize("""NFD"""					,   __UpperCamelCase       )
									snake_case__          =						[]
									for char in text:
												snake_case__          =						unicodedata.category(__UpperCamelCase       )
												if cat == "Mn":
															continue
												output.append(__UpperCamelCase       )
									return "".join(__UpperCamelCase       )






						def       __lowerCAmelCase(   self						:						Optional[Any]					,   __UpperCamelCase						:						Any					,   __UpperCamelCase						:						int=None       ):



									'''simple docstring'''






									if not self.do_split_on_punc or (never_split is not None and text in never_split):
												return [text]
									snake_case__          =						list(__UpperCamelCase       )
									snake_case__          =						0
									snake_case__          =						True
									snake_case__          =						[]
									while i < len(__UpperCamelCase       ):
												snake_case__          =						chars[i]
												if _is_punctuation(__UpperCamelCase       ):
															output.append([char]       )
															snake_case__          =						True
												else:
															if start_new_word:
																		output.append([]       )
															snake_case__          =						False
															output[-1].append(__UpperCamelCase       )
												i += 1

									return ["".join(__UpperCamelCase       ) for x in output]






						def       __lowerCAmelCase(   self						:						Tuple					,   __UpperCamelCase						:						Optional[Any]       ):



									'''simple docstring'''






									snake_case__          =						[]
									for char in text:
												snake_case__          =						ord(__UpperCamelCase       )
												if self._is_chinese_char(__UpperCamelCase       ):
															output.append(""" """       )
															output.append(__UpperCamelCase       )
															output.append(""" """       )
												else:
															output.append(__UpperCamelCase       )
									return "".join(__UpperCamelCase       )






						def       __lowerCAmelCase(   self						:						Any					,   __UpperCamelCase						:						str       ):



									'''simple docstring'''






									if (
									    (cp >= 0X4_e00 and cp <= 0X9_fff)
									    or (cp >= 0X3_400 and cp <= 0X4_dbf)  #
									    or (cp >= 0X20_000 and cp <= 0X2a_6df)  #
									    or (cp >= 0X2a_700 and cp <= 0X2b_73f)  #
									    or (cp >= 0X2b_740 and cp <= 0X2b_81f)  #
									    or (cp >= 0X2b_820 and cp <= 0X2c_eaf)  #
									    or (cp >= 0Xf_900 and cp <= 0Xf_aff)
									    or (cp >= 0X2f_800 and cp <= 0X2f_a1f)  #
									):  #
												return True

									return False







						def       __lowerCAmelCase(   self						:						str					,   __UpperCamelCase						:						Any       ):



									'''simple docstring'''






									snake_case__          =						[]
									for char in text:
												snake_case__          =						ord(__UpperCamelCase       )
												if cp == 0 or cp == 0Xf_ffd or _is_control(__UpperCamelCase       ):
															continue
												if _is_whitespace(__UpperCamelCase       ):
															output.append(""" """       )
												else:
															output.append(__UpperCamelCase       )
									return "".join(__UpperCamelCase       )







def    snake_case__     (  a	)			->       int:





			'''simple docstring'''






			snake_case__          =						set()
			snake_case__          =						word[0]
			for char in word[1:]:
						pairs.add((prev_char, char)	)
						snake_case__          =						char
			return pairs




def    snake_case__     (  a	)			->       Union[str, Any]:





			'''simple docstring'''






			snake_case__          =						text.replace("""—"""       ,      """-"""	)
			snake_case__          =						text.replace("""–"""       ,      """-"""	)
			snake_case__          =						text.replace("""―"""       ,      """-"""	)
			snake_case__          =						text.replace("""…"""       ,      """..."""	)
			snake_case__          =						text.replace("""´"""       ,      """'"""	)
			snake_case__          =						re.sub(R"""(-+|~+|!+|\"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)"""       ,      R""" \1 """       ,      a	)
			snake_case__          =						re.sub(R"""\s*\n\s*"""       ,      """ \n """       ,      a	)
			snake_case__          =						re.sub(R"""[^\S\n]+"""       ,      """ """       ,      a	)
			return text.strip()





class __magic_name__(						__lowerCAmelCase      ):
						UpperCAmelCase_		:					str    =  VOCAB_FILES_NAMES
						UpperCAmelCase_		:					Dict    =  PRETRAINED_VOCAB_FILES_MAP
						UpperCAmelCase_		:					Optional[Any]    =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						UpperCAmelCase_		:					List[str]    =  ["""input_ids""", """attention_mask"""]






						def __init__(   self						:						int					,   __UpperCamelCase						:						Optional[int]					,   __UpperCamelCase						:						str					,   __UpperCamelCase						:						Dict="<unk>"					,   **__UpperCamelCase						:						Optional[Any]       ):



									'''simple docstring'''






									super().__init__(unk_token=__UpperCamelCase					,   **__UpperCamelCase       )

									try:
												import ftfy
												from spacy.lang.en import English

												snake_case__          =						English()
												snake_case__          =						_nlp.tokenizer
												snake_case__          =						ftfy.fix_text
									except ImportError:
												logger.warning("""ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy."""       )
												snake_case__          =						BasicTokenizer(do_lower_case=__UpperCamelCase       )
												snake_case__          =						None

									with open(__UpperCamelCase					,   encoding="""utf-8"""       ) as vocab_handle:
												snake_case__          =						json.load(__UpperCamelCase       )
									snake_case__          =						{v: k for k, v in self.encoder.items()}
									with open(__UpperCamelCase					,   encoding="""utf-8"""       ) as merges_handle:
												snake_case__          =						merges_handle.read().split("""\n"""       )[1:-1]
									snake_case__          =						[tuple(merge.split()       ) for merge in merges]
									snake_case__          =						dict(zip(__UpperCamelCase					,   range(len(__UpperCamelCase       )       )       )       )
									snake_case__          =						{}






						@property
						def       __lowerCAmelCase(   self						:						str       ):



									'''simple docstring'''






									return True






						@property
						def       __lowerCAmelCase(   self						:						str       ):



									'''simple docstring'''






									return len(self.encoder       )






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



									'''simple docstring'''






									return dict(self.encoder					,   **self.added_tokens_encoder       )






						def       __lowerCAmelCase(   self						:						Optional[Any]					,   __UpperCamelCase						:						Optional[int]       ):



									'''simple docstring'''






									snake_case__          =						tuple(token[:-1]       ) + (token[-1] + """</w>""",)
									if token in self.cache:
												return self.cache[token]
									snake_case__          =						get_pairs(__UpperCamelCase       )

									if not pairs:
												return token + "</w>"

									while True:
												snake_case__          =						min(__UpperCamelCase					,   key=lambda __UpperCamelCase       : self.bpe_ranks.get(__UpperCamelCase					,   float("""inf"""       )       )       )
												if bigram not in self.bpe_ranks:
															break
												snake_case__    ,			snake_case__          =						bigram
												snake_case__          =						[]
												snake_case__          =						0
												while i < len(__UpperCamelCase       ):
															try:
																		snake_case__          =						word.index(__UpperCamelCase					,   __UpperCamelCase       )
															except ValueError:
																		new_word.extend(word[i:]       )
																		break
															else:
																		new_word.extend(word[i:j]       )
																		snake_case__          =						j

															if word[i] == first and i < len(__UpperCamelCase       ) - 1 and word[i + 1] == second:
																		new_word.append(first + second       )
																		i += 2
															else:
																		new_word.append(word[i]       )
																		i += 1
												snake_case__          =						tuple(__UpperCamelCase       )
												snake_case__          =						new_word
												if len(__UpperCamelCase       ) == 1:
															break
												else:
															snake_case__          =						get_pairs(__UpperCamelCase       )
									snake_case__          =						""" """.join(__UpperCamelCase       )
									if word == "\n  </w>":
												snake_case__          =						"""\n</w>"""
									snake_case__          =						word
									return word






						def       __lowerCAmelCase(   self						:						str					,   __UpperCamelCase						:						Optional[int]       ):



									'''simple docstring'''






									snake_case__          =						[]
									if self.fix_text is None:
												# Using BERT's BasicTokenizer
												snake_case__          =						self.nlp.tokenize(__UpperCamelCase       )
												for token in text:
															split_tokens.extend(list(self.bpe(__UpperCamelCase       ).split(""" """       )       )       )
									else:
												# Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
												snake_case__          =						self.nlp(text_standardize(self.fix_text(__UpperCamelCase       )       )       )
												for token in text:
															split_tokens.extend(list(self.bpe(token.text.lower()       ).split(""" """       )       )       )
									return split_tokens






						def       __lowerCAmelCase(   self						:						List[Any]					,   __UpperCamelCase						:						str       ):



									'''simple docstring'''






									return self.encoder.get(__UpperCamelCase					,   self.encoder.get(self.unk_token       )       )






						def       __lowerCAmelCase(   self						:						str					,   __UpperCamelCase						:						str       ):



									'''simple docstring'''






									return self.decoder.get(__UpperCamelCase					,   self.unk_token       )






						def       __lowerCAmelCase(   self						:						Union[str, Any]					,   __UpperCamelCase						:						int       ):



									'''simple docstring'''






									snake_case__          =						"""""".join(__UpperCamelCase       ).replace("""</w>"""					,   """ """       ).strip()
									return out_string







						def       __lowerCAmelCase(   self						:						Any					,   __UpperCamelCase						:						str					,   __UpperCamelCase						:						Optional[str] = None       ):



									'''simple docstring'''






									if not os.path.isdir(__UpperCamelCase       ):
												logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""       )
												return
									snake_case__          =						os.path.join(
									    __UpperCamelCase					,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]       )
									snake_case__          =						os.path.join(
									    __UpperCamelCase					,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]       )

									with open(__UpperCamelCase					,   """w"""					,   encoding="""utf-8"""       ) as f:
												f.write(json.dumps(self.encoder					,   indent=2					,   sort_keys=__UpperCamelCase					,   ensure_ascii=__UpperCamelCase       ) + """\n"""       )

									snake_case__          =						0
									with open(__UpperCamelCase					,   """w"""					,   encoding="""utf-8"""       ) as writer:
												writer.write("""#version: 0.2\n"""       )
												for bpe_tokens, token_index in sorted(self.bpe_ranks.items()					,   key=lambda __UpperCamelCase       : kv[1]       ):
															if index != token_index:
																		logger.warning(
																		    f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
																		    """ Please check that the tokenizer is not corrupted!"""       )
																		snake_case__          =						token_index
															writer.write(""" """.join(__UpperCamelCase       ) + """\n"""       )
															index += 1

									return vocab_file, merge_file