



"""simple docstring"""


import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput

def 				_lowerCAmelCase   (     lowercase_	,			lowercase_=0.9_9_9	,			lowercase_="cosine"	,			):
						if alpha_transform_type == "cosine":

												def alpha_bar_fn(lowercase_		):
																		return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2		) ** 2

						elif alpha_transform_type == "exp":

												def alpha_bar_fn(lowercase_		):
																		return math.exp(t * -1_2.0		)

						else:
												raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}"""		)

						UpperCAmelCase    =				[]
						for i in range(lowercase_		):
												UpperCAmelCase    =				i / num_diffusion_timesteps
												UpperCAmelCase    =				(i + 1) / num_diffusion_timesteps
												betas.append(min(1 - alpha_bar_fn(lowercase_		) / alpha_bar_fn(lowercase_		)	,			lowercase_		)		)
						return torch.tensor(lowercase_	,			dtype=torch.floataa		)







class    A_    (  SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_       ):



						"""simple docstring"""
						__UpperCamelCase	       =							[e.name for e in KarrasDiffusionSchedulers]
						__UpperCamelCase	       =							2






						@register_to_config
						def __init__(      self				:Dict     ,						lowercase_				:int = 10_00     ,						lowercase_				:float = 0.0_0085     ,						lowercase_				:float = 0.012     ,						lowercase_				:str = "linear"     ,						lowercase_				:Optional[Union[np.ndarray, List[float]]] = None     ,						lowercase_				:str = "epsilon"     ,						lowercase_				:str = "linspace"     ,						lowercase_				:int = 0     ,						)       ->    Optional[int]:
												if trained_betas is not None:
																		UpperCAmelCase    =				torch.tensor(lowercase_     ,						dtype=torch.floataa      )
												elif beta_schedule == "linear":
																		UpperCAmelCase    =				torch.linspace(lowercase_     ,						lowercase_     ,						lowercase_     ,						dtype=torch.floataa      )
												elif beta_schedule == "scaled_linear":
																		# this schedule is very specific to the latent diffusion model.
																		UpperCAmelCase    =				(
																		    torch.linspace(beta_start**0.5     ,						beta_end**0.5     ,						lowercase_     ,						dtype=torch.floataa      ) ** 2
																		)
												elif beta_schedule == "squaredcos_cap_v2":
																		# Glide cosine schedule
																		UpperCAmelCase    =				betas_for_alpha_bar(lowercase_      )
												else:
																		raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""      )

												UpperCAmelCase    =				1.0 - self.betas
												UpperCAmelCase    =				torch.cumprod(self.alphas     ,						dim=0      )

												#  set all values
												self.set_timesteps(lowercase_     ,						lowercase_     ,						lowercase_      )






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:Optional[int]     ,						lowercase_				:Optional[int]=None      )       ->    List[str]:
												if schedule_timesteps is None:
																		UpperCAmelCase    =				self.timesteps

												UpperCAmelCase    =				(schedule_timesteps == timestep).nonzero()

												# The sigma index that is taken for the **very** first `step`
												# is always the second index (or the last index if there is only 1)
												# This way we can ensure we don't accidentally skip a sigma in
												# case we start in the middle of the denoising schedule (e.g. for image-to-image)
												if len(self._index_counter      ) == 0:
																		UpperCAmelCase    =				1 if len(lowercase_      ) > 1 else 0
												else:
																		UpperCAmelCase    =				timestep.cpu().item() if torch.is_tensor(lowercase_      ) else timestep
																		UpperCAmelCase    =				self._index_counter[timestep_int]

												return indices[pos].item()






						@property
						def 			UpperCAmelCase__  (      self				:Union[str, Any]      )       ->    Union[str, Any]:
												# standard deviation of the initial noise distribution
												if self.config.timestep_spacing in ["linspace", "trailing"]:
																		return self.sigmas.max()

												return (self.sigmas.max() ** 2 + 1) ** 0.5






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:torch.FloatTensor     ,						lowercase_				:Union[float, torch.FloatTensor]     ,						)       ->    torch.FloatTensor:
												UpperCAmelCase    =				self.index_for_timestep(lowercase_      )

												if self.state_in_first_order:
																		UpperCAmelCase    =				self.sigmas[step_index]
												else:
																		UpperCAmelCase    =				self.sigmas_interpol[step_index - 1]

												UpperCAmelCase    =				sample / ((sigma**2 + 1) ** 0.5)
												return sample






						def 			UpperCAmelCase__  (      self				:str     ,						lowercase_				:int     ,						lowercase_				:Union[str, torch.device] = None     ,						lowercase_				:Optional[int] = None     ,						)       ->    Optional[Any]:
												UpperCAmelCase    =				num_inference_steps

												UpperCAmelCase    =				num_train_timesteps or self.config.num_train_timesteps

												# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
												if self.config.timestep_spacing == "linspace":
																		UpperCAmelCase    =				np.linspace(0     ,						num_train_timesteps - 1     ,						lowercase_     ,						dtype=lowercase_      )[::-1].copy()
												elif self.config.timestep_spacing == "leading":
																		UpperCAmelCase    =				num_train_timesteps // self.num_inference_steps
																		# creates integer timesteps by multiplying by ratio
																		# casting to int to avoid issues when num_inference_step is power of 3
																		UpperCAmelCase    =				(np.arange(0     ,						lowercase_      ) * step_ratio).round()[::-1].copy().astype(lowercase_      )
																		timesteps += self.config.steps_offset
												elif self.config.timestep_spacing == "trailing":
																		UpperCAmelCase    =				num_train_timesteps / self.num_inference_steps
																		# creates integer timesteps by multiplying by ratio
																		# casting to int to avoid issues when num_inference_step is power of 3
																		UpperCAmelCase    =				(np.arange(lowercase_     ,						0     ,						-step_ratio      )).round().copy().astype(lowercase_      )
																		timesteps -= 1
												else:
																		raise ValueError(
																		    f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""      )

												UpperCAmelCase    =				np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5      )
												UpperCAmelCase    =				torch.from_numpy(np.log(lowercase_      )      ).to(lowercase_      )

												UpperCAmelCase    =				np.interp(lowercase_     ,						np.arange(0     ,						len(lowercase_      )      )     ,						lowercase_      )
												UpperCAmelCase    =				np.concatenate([sigmas, [0.0]]      ).astype(np.floataa      )
												UpperCAmelCase    =				torch.from_numpy(lowercase_      ).to(device=lowercase_      )

												# compute up and down sigmas
												UpperCAmelCase    =				sigmas.roll(-1      )
												UpperCAmelCase    =				0.0
												UpperCAmelCase    =				(sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
												UpperCAmelCase    =				(sigmas_next**2 - sigmas_up**2) ** 0.5
												UpperCAmelCase    =				0.0

												# compute interpolated sigmas
												UpperCAmelCase    =				sigmas.log().lerp(sigmas_down.log()     ,						0.5      ).exp()
												UpperCAmelCase    =				0.0

												# set sigmas
												UpperCAmelCase    =				torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2      ), sigmas[-1:]]      )
												UpperCAmelCase    =				torch.cat(
												    [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2      ), sigmas_interpol[-1:]]      )
												UpperCAmelCase    =				torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2      ), sigmas_up[-1:]]      )
												UpperCAmelCase    =				torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2      ), sigmas_down[-1:]]      )

												if str(lowercase_      ).startswith('mps'      ):
																		# mps does not support float64
																		UpperCAmelCase    =				torch.from_numpy(lowercase_      ).to(lowercase_     ,						dtype=torch.floataa      )
												else:
																		UpperCAmelCase    =				torch.from_numpy(lowercase_      ).to(lowercase_      )

												UpperCAmelCase    =				self.sigma_to_t(lowercase_      ).to(lowercase_     ,						dtype=timesteps.dtype      )
												UpperCAmelCase    =				torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])     ,						dim=-1      ).flatten()

												UpperCAmelCase    =				torch.cat([timesteps[:1], interleaved_timesteps]      )

												UpperCAmelCase    =				None

												# for exp beta schedules, such as the one for `pipeline_shap_e.py`
												# we need an index counter
												UpperCAmelCase    =				defaultdict(lowercase_      )






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:Optional[int]      )       ->    List[str]:
												# get log sigma
												UpperCAmelCase    =				sigma.log()

												# get distribution
												UpperCAmelCase    =				log_sigma - self.log_sigmas[:, None]

												# get sigmas range
												UpperCAmelCase    =				dists.ge(0      ).cumsum(dim=0      ).argmax(dim=0      ).clamp(max=self.log_sigmas.shape[0] - 2      )
												UpperCAmelCase    =				low_idx + 1

												UpperCAmelCase    =				self.log_sigmas[low_idx]
												UpperCAmelCase    =				self.log_sigmas[high_idx]

												# interpolate sigmas
												UpperCAmelCase    =				(low - log_sigma) / (low - high)
												UpperCAmelCase    =				w.clamp(0     ,						1      )

												# transform interpolation to time range
												UpperCAmelCase    =				(1 - w) * low_idx + w * high_idx
												UpperCAmelCase    =				t.view(sigma.shape      )
												return t






						@property
						def 			UpperCAmelCase__  (      self				:Union[str, Any]      )       ->    Optional[int]:
												return self.sample is None






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:Union[torch.FloatTensor, np.ndarray]     ,						lowercase_				:Union[float, torch.FloatTensor]     ,						lowercase_				:Union[torch.FloatTensor, np.ndarray]     ,						lowercase_				:Optional[torch.Generator] = None     ,						lowercase_				:bool = True     ,						)       ->    Union[SchedulerOutput, Tuple]:
												UpperCAmelCase    =				self.index_for_timestep(lowercase_      )

												# advance index counter by 1
												UpperCAmelCase    =				timestep.cpu().item() if torch.is_tensor(lowercase_      ) else timestep
												self._index_counter[timestep_int] += 1

												if self.state_in_first_order:
																		UpperCAmelCase    =				self.sigmas[step_index]
																		UpperCAmelCase    =				self.sigmas_interpol[step_index]
																		UpperCAmelCase    =				self.sigmas_up[step_index]
																		UpperCAmelCase    =				self.sigmas_down[step_index - 1]
												else:
																		# 2nd order / KPDM2's method
																		UpperCAmelCase    =				self.sigmas[step_index - 1]
																		UpperCAmelCase    =				self.sigmas_interpol[step_index - 1]
																		UpperCAmelCase    =				self.sigmas_up[step_index - 1]
																		UpperCAmelCase    =				self.sigmas_down[step_index - 1]

												# currently only gamma=0 is supported. This usually works best anyways.
												# We can support gamma in the future but then need to scale the timestep before
												# passing it to the model which requires a change in API
												UpperCAmelCase    =				0
												UpperCAmelCase    =				sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

												UpperCAmelCase    =				model_output.device
												UpperCAmelCase    =				randn_tensor(model_output.shape     ,						dtype=model_output.dtype     ,						device=lowercase_     ,						generator=lowercase_      )

												# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
												if self.config.prediction_type == "epsilon":
																		UpperCAmelCase    =				sigma_hat if self.state_in_first_order else sigma_interpol
																		UpperCAmelCase    =				sample - sigma_input * model_output
												elif self.config.prediction_type == "v_prediction":
																		UpperCAmelCase    =				sigma_hat if self.state_in_first_order else sigma_interpol
																		UpperCAmelCase    =				model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
																		    sample / (sigma_input**2 + 1)
																		)
												elif self.config.prediction_type == "sample":
																		raise NotImplementedError('prediction_type not implemented yet: sample'      )
												else:
																		raise ValueError(
																		    f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""      )

												if self.state_in_first_order:
																		# 2. Convert to an ODE derivative for 1st order
																		UpperCAmelCase    =				(sample - pred_original_sample) / sigma_hat
																		# 3. delta timestep
																		UpperCAmelCase    =				sigma_interpol - sigma_hat

																		# store for 2nd order step
																		UpperCAmelCase    =				sample
																		UpperCAmelCase    =				dt
																		UpperCAmelCase    =				sample + derivative * dt
												else:
																		# DPM-Solver-2
																		# 2. Convert to an ODE derivative for 2nd order
																		UpperCAmelCase    =				(sample - pred_original_sample) / sigma_interpol
																		# 3. delta timestep
																		UpperCAmelCase    =				sigma_down - sigma_hat

																		UpperCAmelCase    =				self.sample
																		UpperCAmelCase    =				None

																		UpperCAmelCase    =				sample + derivative * dt
																		UpperCAmelCase    =				prev_sample + noise * sigma_up

												if not return_dict:
																		return (prev_sample,)

												return SchedulerOutput(prev_sample=lowercase_      )






						def 			UpperCAmelCase__  (      self				:str     ,						lowercase_				:torch.FloatTensor     ,						lowercase_				:torch.FloatTensor     ,						lowercase_				:torch.FloatTensor     ,						)       ->    torch.FloatTensor:
												# Make sure sigmas and timesteps have the same device and dtype as original_samples
												UpperCAmelCase    =				self.sigmas.to(device=original_samples.device     ,						dtype=original_samples.dtype      )
												if original_samples.device.type == "mps" and torch.is_floating_point(lowercase_      ):
																		# mps does not support float64
																		UpperCAmelCase    =				self.timesteps.to(original_samples.device     ,						dtype=torch.floataa      )
																		UpperCAmelCase    =				timesteps.to(original_samples.device     ,						dtype=torch.floataa      )
												else:
																		UpperCAmelCase    =				self.timesteps.to(original_samples.device      )
																		UpperCAmelCase    =				timesteps.to(original_samples.device      )

												UpperCAmelCase    =				[self.index_for_timestep(lowercase_     ,						lowercase_      ) for t in timesteps]

												UpperCAmelCase    =				sigmas[step_indices].flatten()
												while len(sigma.shape      ) < len(original_samples.shape      ):
																		UpperCAmelCase    =				sigma.unsqueeze(-1      )

												UpperCAmelCase    =				original_samples + noise * sigma
												return noisy_samples






						def __len__(      self				:Optional[Any]      )       ->    Optional[Any]:
												return self.config.num_train_timesteps










"""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


snake_case_         = logging.get_logger(__name__)

snake_case_         = {
    """vocab_file""": """vocab.json""",
    """merges_file""": """merges.txt""",
}

snake_case_         = {
    """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"""},
}

snake_case_         = {
    """openai-gpt""": 512,
}

def 				_lowerCAmelCase   (     lowercase_		):
						UpperCAmelCase    =				text.strip()
						if not text:
												return []
						UpperCAmelCase    =				text.split()
						return tokens







class    A_    (  SCREAMING_SNAKE_CASE_       ):



						"""simple docstring"""






						def __init__(      self				:Dict     ,						lowercase_				:int=True     ,						lowercase_				:Union[str, Any]=None     ,						lowercase_				:List[Any]=True     ,						lowercase_				:List[str]=None     ,						lowercase_				:Optional[int]=True     ,						)       ->    Any:
												if never_split is None:
																		UpperCAmelCase    =				[]
												UpperCAmelCase    =				do_lower_case
												UpperCAmelCase    =				set(lowercase_      )
												UpperCAmelCase    =				tokenize_chinese_chars
												UpperCAmelCase    =				strip_accents
												UpperCAmelCase    =				do_split_on_punc






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:Optional[int]     ,						lowercase_				:int=None      )       ->    List[Any]:
												UpperCAmelCase    =				self.never_split.union(set(lowercase_      )      ) if never_split else self.never_split
												UpperCAmelCase    =				self._clean_text(lowercase_      )

												# 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:
																		UpperCAmelCase    =				self._tokenize_chinese_chars(lowercase_      )
												# prevents treating the same character with different unicode codepoints as different characters
												UpperCAmelCase    =				unicodedata.normalize('NFC'     ,						lowercase_      )
												UpperCAmelCase    =				whitespace_tokenize(lowercase_      )
												UpperCAmelCase    =				[]
												for token in orig_tokens:
																		if token not in never_split:
																								if self.do_lower_case:
																														UpperCAmelCase    =				token.lower()
																														if self.strip_accents is not False:
																																				UpperCAmelCase    =				self._run_strip_accents(lowercase_      )
																								elif self.strip_accents:
																														UpperCAmelCase    =				self._run_strip_accents(lowercase_      )
																		split_tokens.extend(self._run_split_on_punc(lowercase_     ,						lowercase_      )      )

												UpperCAmelCase    =				whitespace_tokenize(' '.join(lowercase_      )      )
												return output_tokens






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:int      )       ->    Tuple:
												UpperCAmelCase    =				unicodedata.normalize('NFD'     ,						lowercase_      )
												UpperCAmelCase    =				[]
												for char in text:
																		UpperCAmelCase    =				unicodedata.category(lowercase_      )
																		if cat == "Mn":
																								continue
																		output.append(lowercase_      )
												return "".join(lowercase_      )






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:Tuple     ,						lowercase_				:Optional[Any]=None      )       ->    Optional[int]:
												if not self.do_split_on_punc or (never_split is not None and text in never_split):
																		return [text]
												UpperCAmelCase    =				list(lowercase_      )
												UpperCAmelCase    =				0
												UpperCAmelCase    =				True
												UpperCAmelCase    =				[]
												while i < len(lowercase_      ):
																		UpperCAmelCase    =				chars[i]
																		if _is_punctuation(lowercase_      ):
																								output.append([char]      )
																								UpperCAmelCase    =				True
																		else:
																								if start_new_word:
																														output.append([]      )
																								UpperCAmelCase    =				False
																								output[-1].append(lowercase_      )
																		i += 1

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






						def 			UpperCAmelCase__  (      self				:Optional[int]     ,						lowercase_				:str      )       ->    int:
												UpperCAmelCase    =				[]
												for char in text:
																		UpperCAmelCase    =				ord(lowercase_      )
																		if self._is_chinese_char(lowercase_      ):
																								output.append(' '      )
																								output.append(lowercase_      )
																								output.append(' '      )
																		else:
																								output.append(lowercase_      )
												return "".join(lowercase_      )






						def 			UpperCAmelCase__  (      self				:List[Any]     ,						lowercase_				:int      )       ->    Optional[Any]:
												# This defines a "chinese character" as anything in the CJK Unicode block:
												#   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
												#
												# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
												# despite its name. The modern Korean Hangul alphabet is a different block,
												# as is Japanese Hiragana and Katakana. Those alphabets are used to write
												# space-separated words, so they are not treated specially and handled
												# like the all of the other languages.
												if (
												    (cp >= 0x4E00 and cp <= 0x9FFF)
												    or (cp >= 0x3400 and cp <= 0x4DBF)  #
												    or (cp >= 0x20000 and cp <= 0x2A6DF)  #
												    or (cp >= 0x2A700 and cp <= 0x2B73F)  #
												    or (cp >= 0x2B740 and cp <= 0x2B81F)  #
												    or (cp >= 0x2B820 and cp <= 0x2CEAF)  #
												    or (cp >= 0xF900 and cp <= 0xFAFF)
												    or (cp >= 0x2F800 and cp <= 0x2FA1F)  #
												):  #
																		return True

												return False






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:int      )       ->    List[Any]:
												UpperCAmelCase    =				[]
												for char in text:
																		UpperCAmelCase    =				ord(lowercase_      )
																		if cp == 0 or cp == 0xFFFD or _is_control(lowercase_      ):
																								continue
																		if _is_whitespace(lowercase_      ):
																								output.append(' '      )
																		else:
																								output.append(lowercase_      )
												return "".join(lowercase_      )


def 				_lowerCAmelCase   (     lowercase_		):
						UpperCAmelCase    =				set()
						UpperCAmelCase    =				word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)		)
												UpperCAmelCase    =				char
						return pairs

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







class    A_    (  SCREAMING_SNAKE_CASE_       ):



						"""simple docstring"""
						__UpperCamelCase	       =							VOCAB_FILES_NAMES
						__UpperCamelCase	       =							PRETRAINED_VOCAB_FILES_MAP
						__UpperCamelCase	       =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						__UpperCamelCase	       =							["""input_ids""", """attention_mask"""]






						def __init__(      self				:Dict     ,						lowercase_				:Optional[int]     ,						lowercase_				:Dict     ,						lowercase_				:List[str]="<unk>"     ,						**lowercase_				:Tuple      )       ->    Dict:
												super().__init__(unk_token=lowercase_     ,						**lowercase_      )

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

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

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






						@property
						def 			UpperCAmelCase__  (      self				:Union[str, Any]      )       ->    List[Any]:
												return True






						@property
						def 			UpperCAmelCase__  (      self				:str      )       ->    str:
												return len(self.encoder      )






						def 			UpperCAmelCase__  (      self				:Optional[int]      )       ->    Optional[Any]:
												return dict(self.encoder     ,						**self.added_tokens_encoder      )






						def 			UpperCAmelCase__  (      self				:Union[str, Any]     ,						lowercase_				:List[Any]      )       ->    int:
												UpperCAmelCase    =				tuple(token[:-1]      ) + (token[-1] + '</w>',)
												if token in self.cache:
																		return self.cache[token]
												UpperCAmelCase    =				get_pairs(lowercase_      )

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

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

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






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:Union[str, Any]      )       ->    str:
												UpperCAmelCase    =				[]
												if self.fix_text is None:
																		# Using BERT's BasicTokenizer
																		UpperCAmelCase    =				self.nlp.tokenize(lowercase_      )
																		for token in text:
																								split_tokens.extend(list(self.bpe(lowercase_      ).split(' '      )      )      )
												else:
																		# Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
																		UpperCAmelCase    =				self.nlp(text_standardize(self.fix_text(lowercase_      )      )      )
																		for token in text:
																								split_tokens.extend(list(self.bpe(token.text.lower()      ).split(' '      )      )      )
												return split_tokens






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:Optional[Any]      )       ->    Tuple:
												return self.encoder.get(lowercase_     ,						self.encoder.get(self.unk_token      )      )






						def 			UpperCAmelCase__  (      self				:List[Any]     ,						lowercase_				:str      )       ->    Union[str, Any]:
												return self.decoder.get(lowercase_     ,						self.unk_token      )






						def 			UpperCAmelCase__  (      self				:Tuple     ,						lowercase_				:Optional[Any]      )       ->    Tuple:
												UpperCAmelCase    =				''.join(lowercase_      ).replace('</w>'     ,						' '      ).strip()
												return out_string






						def 			UpperCAmelCase__  (      self				:List[str]     ,						lowercase_				:str     ,						lowercase_				:Optional[str] = None      )       ->    Tuple[str]:
												if not os.path.isdir(lowercase_      ):
																		logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""      )
																		return
												UpperCAmelCase    =				os.path.join(
												    lowercase_     ,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']      )
												UpperCAmelCase    =				os.path.join(
												    lowercase_     ,						(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']      )

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

												UpperCAmelCase    =				0
												with open(lowercase_     ,						'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 lowercase_      : 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!'      )
																														UpperCAmelCase    =				token_index
																								writer.write(' '.join(lowercase_      ) + '\n'      )
																								index += 1

												return vocab_file, merge_file





