



"""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	:				List[Any]  					=			logging.get_logger(__name__)

__snake_case	:				Optional[int]  					=			{
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
}

__snake_case	:				List[Any]  					=			{
    '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	:				Dict  					=			{
    'openai-gpt': 512,
}



def   a_	(			__a      ):
     A__				=   text.strip()
     if not text:
          return []
     A__				=   text.split()
     return tokens

class       UpperCamelCase  (					a				):





     """simple docstring"""






     def __init__(					self :							Dict	,      _lowerCamelCase :							Optional[int]=True	,      _lowerCamelCase :							List[Any]=None	,      _lowerCamelCase :							int=True	,      _lowerCamelCase :							Optional[int]=None	,      _lowerCamelCase :							str=True	,      ):
          if never_split is None:
               A__				=   []
          A__				=   do_lower_case
          A__				=   set(_lowerCamelCase )
          A__				=   tokenize_chinese_chars
          A__				=   strip_accents
          A__				=   do_split_on_punc





     def 						A__  (					self :							Any	,      _lowerCamelCase :							Union[str, Any]	,      _lowerCamelCase :							Union[str, Any]=None ):
          A__				=   self.never_split.union(set(_lowerCamelCase ) ) if never_split else self.never_split
          A__				=   self._clean_text(_lowerCamelCase )

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

          A__				=   whitespace_tokenize(''' '''.join(_lowerCamelCase ) )
          return output_tokens





     def 						A__  (					self :							int	,      _lowerCamelCase :							Any ):
          A__				=   unicodedata.normalize('''NFD'''	,      _lowerCamelCase )
          A__				=   []
          for char in text:
               A__				=   unicodedata.category(_lowerCamelCase )
               if cat == "Mn":
                    continue
               output.append(_lowerCamelCase )
          return "".join(_lowerCamelCase )





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

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





     def 						A__  (					self :							Dict	,      _lowerCamelCase :							List[Any] ):
          A__				=   []
          for char in text:
               A__				=   ord(_lowerCamelCase )
               if self._is_chinese_char(_lowerCamelCase ):
                    output.append(''' ''' )
                    output.append(_lowerCamelCase )
                    output.append(''' ''' )
               else:
                    output.append(_lowerCamelCase )
          return "".join(_lowerCamelCase )





     def 						A__  (					self :							Optional[Any]	,      _lowerCamelCase :							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 >= 0x2_0000 and cp <= 0x2_A6DF)  #
              or (cp >= 0x2_A700 and cp <= 0x2_B73F)  #
              or (cp >= 0x2_B740 and cp <= 0x2_B81F)  #
              or (cp >= 0x2_B820 and cp <= 0x2_CEAF)  #
              or (cp >= 0xF900 and cp <= 0xFAFF)
              or (cp >= 0x2_F800 and cp <= 0x2_FA1F)  #
          ):  #
               return True

          return False





     def 						A__  (					self :							Any	,      _lowerCamelCase :							str ):
          A__				=   []
          for char in text:
               A__				=   ord(_lowerCamelCase )
               if cp == 0 or cp == 0xFFFD or _is_control(_lowerCamelCase ):
                    continue
               if _is_whitespace(_lowerCamelCase ):
                    output.append(''' ''' )
               else:
                    output.append(_lowerCamelCase )
          return "".join(_lowerCamelCase )



def   a_	(			__a      ):
     A__				=   set()
     A__				=   word[0]
     for char in word[1:]:
          pairs.add((prev_char, char)      )
          A__				=   char
     return pairs



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

class       UpperCamelCase  (					a				):





     """simple docstring"""






     _lowerCamelCase					: Any				   =VOCAB_FILES_NAMES
     _lowerCamelCase					: Any				   =PRETRAINED_VOCAB_FILES_MAP
     _lowerCamelCase					: Any				   =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _lowerCamelCase					: Tuple				   =["input_ids", "attention_mask"]





     def __init__(					self :							Union[str, Any]	,      _lowerCamelCase :							Optional[Any]	,      _lowerCamelCase :							Any	,      _lowerCamelCase :							List[str]="<unk>"	,      **_lowerCamelCase :							Optional[int] ):
          super().__init__(unk_token=_lowerCamelCase	,      **_lowerCamelCase )

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

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

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





     @property
     def 						A__  (					self :							List[str] ):
          return True





     @property
     def 						A__  (					self :							Tuple ):
          return len(self.encoder )





     def 						A__  (					self :							Union[str, Any] ):
          return dict(self.encoder	,      **self.added_tokens_encoder )





     def 						A__  (					self :							int	,      _lowerCamelCase :							Any ):
          A__				=   tuple(token[:-1] ) + (token[-1] + '''</w>''',)
          if token in self.cache:
               return self.cache[token]
          A__				=   get_pairs(_lowerCamelCase )

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

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

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





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





     def 						A__  (					self :							Tuple	,      _lowerCamelCase :							Optional[Any] ):
          return self.encoder.get(_lowerCamelCase	,      self.encoder.get(self.unk_token ) )





     def 						A__  (					self :							str	,      _lowerCamelCase :							Tuple ):
          return self.decoder.get(_lowerCamelCase	,      self.unk_token )





     def 						A__  (					self :							Optional[Any]	,      _lowerCamelCase :							List[str] ):
          A__				=   ''''''.join(_lowerCamelCase ).replace('''</w>'''	,      ''' ''' ).strip()
          return out_string





     def 						A__  (					self :							Dict	,      _lowerCamelCase :							str	,      _lowerCamelCase :							Optional[str] = None ):
          if not os.path.isdir(_lowerCamelCase ):
               logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
               return
          A__				=   os.path.join(
              _lowerCamelCase	,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
          A__				=   os.path.join(
              _lowerCamelCase	,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] )

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

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

          return vocab_file, merge_file








"""simple docstring"""







import json
import os
import tempfile

import datasets
from utils import generate_example_dataset, get_duration


__snake_case	:				Optional[Any]  					=			500_000

__snake_case					,  __snake_case	:				Any  					=			os.path.split(__file__)
__snake_case	:				Optional[Any]  					=			os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json'))



@get_duration
def   a_	(			__a      ):
     A__				=   dataset.select(range(0		,							len(__a      )		,							2      )      )



@get_duration
def   a_	(			__a      ):
     A__				=   dataset.sort('''numbers'''      )



@get_duration
def   a_	(			__a      ):
     A__				=   dataset.shuffle()



@get_duration
def   a_	(			__a      ):
     A__				=   dataset.train_test_split(0.1      )



@get_duration
def   a_	(			__a		,							__a=10      ):
     for shard_id in range(__a      ):
          A__				=   dataset.shard(__a		,							__a      )



def   a_	(			):
     A__				=   {'''num examples''': SPEED_TEST_N_EXAMPLES}
     A__				=   (select, sort, shuffle, train_test_split, shard)
     with tempfile.TemporaryDirectory() as tmp_dir:
          print('''generating dataset'''      )
          A__				=   datasets.Features({'''text''': datasets.Value('''string'''      ), '''numbers''': datasets.Value('''float32'''      )}      )
          A__				=   generate_example_dataset(
              os.path.join(__a		,							'''dataset.arrow'''      )		,							__a		,							num_examples=__a      )
          print('''Functions'''      )
          for func in functions:
               print(func.__name__      )
               A__				=   func(__a      )

     with open(__a		,							'''wb'''      ) as f:
          f.write(json.dumps(__a      ).encode('''utf-8'''      )      )


if __name__ == "__main__":  # useful to run the profiler
 benchmark_indices_mapping()



