
"""simple docstring"""




import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple

import numpy as np

from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation


A__      :	str   		=    logging.get_logger(__name__)

A__      :	Any   		=    {"""vocab_file""": """vocab.txt""", """emoji_file""": """emoji.json"""}

A__      :	int   		=    {
    """vocab_file""": {
        """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt""",
    },
    """emoji_file""": {
        """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json""",
    },
}

A__      :	Dict   		=    {
    """abeja/gpt-neox-japanese-2.7b""": 2_048,
}



def 							a__ (				lowerCAmelCase	:       Optional[int]       ,    lowerCAmelCase	:       Optional[Any]		):






     '''simple docstring'''
     with open(lowerCAmelCase       ,    "r"       ,    encoding="utf-8"		) as f:
          UpperCAmelCase__							: Optional[Any] 							=						json.loads(f.read()		)

     UpperCAmelCase__							: Optional[int] 							=						collections.OrderedDict()
     UpperCAmelCase__							: List[str] 							=						collections.OrderedDict()
     UpperCAmelCase__							: int 							=						collections.OrderedDict()
     with open(lowerCAmelCase       ,    "r"       ,    encoding="utf-8"		) as f:
          UpperCAmelCase__							: Dict 							=						f.readlines()
     UpperCAmelCase__							: List[str] 							=						[[t.rstrip("\n"		)] if (t == "," or "," not in t) else t.rstrip("\n"		).split(","		) for t in token]
     for idx, b in enumerate(lowerCAmelCase		):
          UpperCAmelCase__							: List[Any] 							=						b
          UpperCAmelCase__							: str 							=						idx
          for wd in b:
               UpperCAmelCase__							: str 							=						idx

     return vocab, raw_vocab, ids_to_tokens, emoji







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							VOCAB_FILES_NAMES
     _A								=							PRETRAINED_VOCAB_FILES_MAP
     _A								=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _A								=							['input_ids', 'attention_mask']



     def __init__(      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase="<|endoftext|>" ,			__UpperCamelCase="<|endoftext|>" ,			__UpperCamelCase="<|startoftext|>" ,			__UpperCamelCase="<|endoftext|>" ,			__UpperCamelCase=False ,			**__UpperCamelCase ,			)->					Dict:
          super().__init__(
              unk_token=__UpperCamelCase ,			pad_token=__UpperCamelCase ,			bos_token=__UpperCamelCase ,			eos_token=__UpperCamelCase ,			do_clean_text=__UpperCamelCase ,			**__UpperCamelCase ,			)
          if not os.path.isfile(__UpperCamelCase  ):
               raise ValueError(
                   F"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
                   " model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"  )
          if not os.path.isfile(__UpperCamelCase  ):
               raise ValueError(
                   F"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"
                   " pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"  )
          UpperCAmelCase__							: List[Any] 							=						do_clean_text
          UpperCAmelCase__							: int 							=						load_vocab_and_emoji(__UpperCamelCase ,			__UpperCamelCase  )
          UpperCAmelCase__							: Tuple 							=						SubWordJapaneseTokenizer(
              vocab=self.vocab ,			ids_to_tokens=self.ids_to_tokens ,			emoji=self.emoji  )



     @property
     def  lowerCAmelCase__       (      self  )->					Union[str, Any]:
          # self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
          return len(self.raw_vocab  )



     def  lowerCAmelCase__       (      self  )->					Optional[Any]:
          return dict(self.raw_vocab ,			**self.added_tokens_encoder  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					int:
          return self.subword_tokenizer.tokenize(__UpperCamelCase ,			clean=self.do_clean_text  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Optional[int]:
          return self.vocab.get(__UpperCamelCase ,			self.vocab.get(self.unk_token  )  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Union[str, Any]:
          return self.subword_tokenizer.convert_id_to_token(__UpperCamelCase  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Optional[Any]:
          UpperCAmelCase__							: str 							=						"".join(__UpperCamelCase  ).strip()
          return out_string



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					List[int]:
          UpperCAmelCase__							: Dict 							=						[]
          for is_user, text in conversation.iter_texts():
               input_ids.extend(self.encode(__UpperCamelCase ,			add_special_tokens=__UpperCamelCase  ) + [self.eos_token_id]  )

          if len(__UpperCamelCase  ) > self.model_max_length:
               UpperCAmelCase__							: List[str] 							=						input_ids[-self.model_max_length :]
          return input_ids



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase = None  )->					Tuple[str]:
          UpperCAmelCase__							: Any 							=						0
          if os.path.isdir(__UpperCamelCase  ):
               UpperCAmelCase__							: Optional[int] 							=						os.path.join(
                   __UpperCamelCase ,			(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]  )
               UpperCAmelCase__							: Any 							=						os.path.join(
                   __UpperCamelCase ,			(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]  )
          else:
               UpperCAmelCase__							: Tuple 							=						(
                   (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
               )
               UpperCAmelCase__							: List[str] 							=						(
                   (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
               )
          with open(__UpperCamelCase ,			"w" ,			encoding="utf-8"  ) as writer:
               for token_index, token in self.ids_to_tokens.items():
                    if index != token_index:
                         logger.warning(
                             F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
                             " Please check that the vocabulary is not corrupted!"  )
                         UpperCAmelCase__							: str 							=						token_index
                    writer.write(",".join(__UpperCamelCase  ) + "\n"  )
                    index += 1
          with open(__UpperCamelCase ,			"w" ,			encoding="utf-8"  ) as writer:
               json.dump(self.emoji ,			__UpperCamelCase  )
          return vocab_file, emoji_file







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     def __init__(      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					Optional[int]:
          UpperCAmelCase__							: Dict 							=						vocab  # same as swe
          UpperCAmelCase__							: Optional[int] 							=						ids_to_tokens  # same as bpe
          UpperCAmelCase__							: str 							=						emoji
          UpperCAmelCase__							: List[Any] 							=						np.max([len(__UpperCamelCase  ) for w in self.vocab.keys()]  )
          UpperCAmelCase__							: Tuple 							=						re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)"  )
          UpperCAmelCase__							: Optional[int] 							=						re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*"  )
          UpperCAmelCase__							: List[str] 							=						re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}"  )
          UpperCAmelCase__							: Any 							=						re.compile(
              r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"  )
          UpperCAmelCase__							: List[str] 							=						re.compile(
              r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"  )
          UpperCAmelCase__							: int 							=						re.compile(
              r"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*"  )
          UpperCAmelCase__							: List[str] 							=						"─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
          UpperCAmelCase__							: Tuple 							=						"▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
          UpperCAmelCase__							: Optional[int] 							=						str.maketrans({k: "<BLOCK>" for k in keisen + blocks}  )



     def __len__(      self  )->					List[Any]:
          return len(self.ids_to_tokens  )



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Dict:
          UpperCAmelCase__							: Optional[int] 							=						self.content_repattera.sub("<URL>" ,			__UpperCamelCase  )
          UpperCAmelCase__							: Any 							=						self.content_repattera.sub("<EMAIL>" ,			__UpperCamelCase  )
          UpperCAmelCase__							: str 							=						self.content_repattera.sub("<TEL>" ,			__UpperCamelCase  )
          UpperCAmelCase__							: Optional[int] 							=						self.content_repattera.sub("<DATE>" ,			__UpperCamelCase  )
          UpperCAmelCase__							: Optional[Any] 							=						self.content_repattera.sub("<DATE>" ,			__UpperCamelCase  )
          UpperCAmelCase__							: Optional[int] 							=						self.content_repattera.sub("<PRICE>" ,			__UpperCamelCase  )
          UpperCAmelCase__							: List[str] 							=						content.translate(self.content_transa  )
          while "<BLOCK><BLOCK>" in content:
               UpperCAmelCase__							: Union[str, Any] 							=						content.replace("<BLOCK><BLOCK>" ,			"<BLOCK>"  )
          return content



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase=False  )->					List[Any]:
          UpperCAmelCase__							: Optional[int] 							=						text.replace(" " ,			"<SP>"  )
          UpperCAmelCase__							: Any 							=						text.replace("　" ,			"<SP>"  )
          UpperCAmelCase__							: Union[str, Any] 							=						text.replace("\r\n" ,			"<BR>"  )
          UpperCAmelCase__							: List[str] 							=						text.replace("\n" ,			"<BR>"  )
          UpperCAmelCase__							: Any 							=						text.replace("\r" ,			"<BR>"  )
          UpperCAmelCase__							: int 							=						text.replace("\t" ,			"<TAB>"  )
          UpperCAmelCase__							: str 							=						text.replace("—" ,			"ー"  )
          UpperCAmelCase__							: Optional[Any] 							=						text.replace("−" ,			"ー"  )
          for k, v in self.emoji["emoji"].items():
               if k in text:
                    UpperCAmelCase__							: Any 							=						text.replace(__UpperCamelCase ,			__UpperCamelCase  )
          if clean:
               UpperCAmelCase__							: Any 							=						self.clean_text(__UpperCamelCase  )

          def check_simbol(__UpperCamelCase  ):
               UpperCAmelCase__							: Dict 							=						x.encode()
               if len(__UpperCamelCase  ) == 1 and len(__UpperCamelCase  ) == 2:
                    UpperCAmelCase__							: Optional[Any] 							=						(int(e[0]  ) << 8) + int(e[1]  )
                    if (
                        (c >= 0Xc2a1 and c <= 0Xc2bf)
                        or (c >= 0Xc780 and c <= 0Xc783)
                        or (c >= 0Xcab9 and c <= 0Xcbbf)
                        or (c >= 0Xcc80 and c <= 0Xcda2)
                    ):
                         return True
               return False

          def checkuae(__UpperCamelCase  ):
               UpperCAmelCase__							: Any 							=						x.encode()
               if len(__UpperCamelCase  ) == 1 and len(__UpperCamelCase  ) == 3:
                    UpperCAmelCase__							: Optional[int] 							=						(int(e[0]  ) << 16) + (int(e[1]  ) << 8) + int(e[2]  )
                    if c >= 0Xe2_8080 and c <= 0Xe2_b07f:
                         return True
               return False

          UpperCAmelCase__							: Any 							=						0
          UpperCAmelCase__							: str 							=						[]
          while pos < len(__UpperCamelCase  ):
               UpperCAmelCase__							: Any 							=						min(len(__UpperCamelCase  ) ,			pos + self.maxlen + 1  ) if text[pos] == "<" else pos + 3
               UpperCAmelCase__							: Any 							=						[]  # (token_id, token, pos)
               for e in range(__UpperCamelCase ,			__UpperCamelCase ,			-1  ):
                    UpperCAmelCase__							: str 							=						text[pos:e]
                    if wd in self.vocab:
                         if wd[0] == "<" and len(__UpperCamelCase  ) > 2:
                              UpperCAmelCase__							: Optional[int] 							=						[(self.vocab[wd], wd, e)]
                              break
                         else:
                              candidates.append((self.vocab[wd], wd, e)  )
               if len(__UpperCamelCase  ) > 0:
                    # the smallest token_id is adopted
                    UpperCAmelCase__							: List[str] 							=						sorted(__UpperCamelCase ,			key=lambda __UpperCamelCase  : x[0]  )[0]
                    result.append(__UpperCamelCase  )
                    UpperCAmelCase__							: List[Any] 							=						e
               else:
                    UpperCAmelCase__							: Union[str, Any] 							=						pos + 1
                    UpperCAmelCase__							: Optional[int] 							=						text[pos:end]
                    if check_simbol(__UpperCamelCase  ):
                         result.append("<KIGOU>"  )
                    elif checkuae(__UpperCamelCase  ):
                         result.append("<U2000U2BFF>"  )
                    else:
                         for i in wd.encode("utf-8"  ):
                              result.append("<|byte%d|>" % i  )
                    UpperCAmelCase__							: List[Any] 							=						end
          return result



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase="\n"  )->					Union[str, Any]:
          UpperCAmelCase__							: Optional[Any] 							=						[]
          UpperCAmelCase__							: str 							=						[]
          UpperCAmelCase__							: List[Any] 							=						self.ids_to_tokens[index][0]
          if word[:6] == "<|byte" and word[-2:] == "|>":
               byte_tokens.append(int(word[6:-2]  )  )
          else:
               if len(__UpperCamelCase  ) > 0:
                    words.append(bytearray(__UpperCamelCase  ).decode("utf-8" ,			errors="replace"  )  )
                    UpperCAmelCase__							: Dict 							=						[]
               if word[:7] == "<|emoji" and word[-2:] == "|>":
                    words.append(self.emoji["emoji_inv"][word]  )
               elif word == "<SP>":
                    words.append(" "  )
               elif word == "<BR>":
                    words.append(__UpperCamelCase  )
               elif word == "<TAB>":
                    words.append("\t"  )
               elif word == "<BLOCK>":
                    words.append("▀"  )
               elif word == "<KIGOU>":
                    words.append("ǀ"  )
               elif word == "<U2000U2BFF>":
                    words.append("‖"  )
               else:
                    words.append(__UpperCamelCase  )
          if len(__UpperCamelCase  ) > 0:
               words.append(bytearray(__UpperCamelCase  ).decode("utf-8" ,			errors="replace"  )  )
          UpperCAmelCase__							: str 							=						"".join(__UpperCamelCase  )
          return text





"""simple docstring"""




import timeit

import numpy as np

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD



def 							a__ (				lowerCAmelCase	:       List[str]		):






     '''simple docstring'''
     def wrapper(*lowerCAmelCase	:       Any       ,    **lowerCAmelCase	:       Tuple		):
          UpperCAmelCase__							: Optional[int] 							=						timeit.default_timer()
          UpperCAmelCase__							: int 							=						func(*lowerCAmelCase       ,    **lowerCAmelCase		)
          UpperCAmelCase__							: List[Any] 							=						timeit.default_timer() - starttime
          return delta

     UpperCAmelCase__							: int 							=						func.__name__

     return wrapper



def 							a__ (				lowerCAmelCase	:       dict       ,    lowerCAmelCase	:       Optional[int]=100       ,    lowerCAmelCase	:       List[str]=None		):






     '''simple docstring'''
     UpperCAmelCase__							: str 							=						[]
     UpperCAmelCase__							: Optional[Any] 							=						seq_shapes or {}
     for i in range(lowerCAmelCase		):
          UpperCAmelCase__							: int 							=						{}
          for col_id, (k, v) in enumerate(features.items()		):
               if isinstance(lowerCAmelCase       ,    _ArrayXD		):
                    UpperCAmelCase__							: List[str] 							=						np.random.rand(*v.shape		).astype(v.dtype		)
               elif isinstance(lowerCAmelCase       ,    datasets.Value		):
                    if v.dtype == "string":
                         UpperCAmelCase__							: Dict 							=						"The small grey turtle was surprisingly fast when challenged."
                    else:
                         UpperCAmelCase__							: str 							=						np.random.randint(10       ,    size=1		).astype(v.dtype		).item()
               elif isinstance(lowerCAmelCase       ,    datasets.Sequence		):
                    while isinstance(lowerCAmelCase       ,    datasets.Sequence		):
                         UpperCAmelCase__							: List[str] 							=						v.feature
                    UpperCAmelCase__							: Optional[int] 							=						seq_shapes[k]
                    UpperCAmelCase__							: Optional[int] 							=						np.random.rand(*lowerCAmelCase		).astype(v.dtype		)
               UpperCAmelCase__							: Union[str, Any] 							=						data

          dummy_data.append((i, example)		)

     return dummy_data



def 							a__ (				lowerCAmelCase	:       List[str]       ,    lowerCAmelCase	:       Tuple       ,    lowerCAmelCase	:       List[str]=100       ,    lowerCAmelCase	:       Optional[int]=None		):






     '''simple docstring'''
     UpperCAmelCase__							: int 							=						generate_examples(lowerCAmelCase       ,    num_examples=lowerCAmelCase       ,    seq_shapes=lowerCAmelCase		)

     with ArrowWriter(features=lowerCAmelCase       ,    path=lowerCAmelCase		) as writer:
          for key, record in dummy_data:
               UpperCAmelCase__							: List[Any] 							=						features.encode_example(lowerCAmelCase		)
               writer.write(lowerCAmelCase		)

          UpperCAmelCase__							,	UpperCAmelCase__							: Optional[Any] 							=						writer.finalize()

     if not num_final_examples == num_examples:
          raise ValueError(
              F"Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}."		)

     UpperCAmelCase__							: Optional[int] 							=						datasets.Dataset.from_file(filename=lowerCAmelCase       ,    info=datasets.DatasetInfo(features=lowerCAmelCase		)		)

     return dataset



