
"""simple docstring"""






import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


__SCREAMING_SNAKE_CASE							=     datasets.utils.logging.get_logger(__name__)





@dataclass
class 				a__					(						datasets.BuilderConfig       ):
     UpperCAmelCase__         =      None
     UpperCAmelCase__         =      "utf-8"
     UpperCAmelCase__         =      None
     UpperCAmelCase__         =      None
     UpperCAmelCase__         =      True  # deprecated
     UpperCAmelCase__         =      None  # deprecated
     UpperCAmelCase__         =      10 << 20  # 10MB
     UpperCAmelCase__         =      None





class 				a__					(						datasets.ArrowBasedBuilder       ):
     UpperCAmelCase__         =      JsonConfig



     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      if self.config.block_size is not None:
       logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'   )
       UpperCamelCase_     :					List[Any]   	=self.config.block_size
      if self.config.use_threads is not True:
       logger.warning(
           'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'   )
      if self.config.newlines_in_values is not None:
       raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported'   )
      return datasets.DatasetInfo(features=self.config.features   )



     def  lowerCamelCase_						(							self :Tuple      ,  _lowerCamelCase :List[str]   ):







      '''simple docstring'''



      if not self.config.data_files:
       raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''   )
      UpperCamelCase_     :					int   	=dl_manager.download_and_extract(self.config.data_files   )
      if isinstance(_lowerCamelCase      ,  (str, list, tuple)   ):
       UpperCamelCase_     :					Tuple   	=data_files
       if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ):
        UpperCamelCase_     :					Union[str, Any]   	=[files]
       UpperCamelCase_     :					List[str]   	=[dl_manager.iter_files(_lowerCamelCase   ) for file in files]
       return [datasets.SplitGenerator(name=datasets.Split.TRAIN      ,  gen_kwargs={'files': files}   )]
      UpperCamelCase_     :					Optional[Any]   	=[]
      for split_name, files in data_files.items():
       if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ):
        UpperCamelCase_     :					Tuple   	=[files]
       UpperCamelCase_     :					Optional[Any]   	=[dl_manager.iter_files(_lowerCamelCase   ) for file in files]
       splits.append(datasets.SplitGenerator(name=_lowerCamelCase      ,  gen_kwargs={'files': files}   )   )
      return splits



     def  lowerCamelCase_						(							self :int      ,  _lowerCamelCase :pa.Table   ):







      '''simple docstring'''



      if self.config.features is not None:
       # adding missing columns
       for column_name in set(self.config.features   ) - set(pa_table.column_names   ):
        UpperCamelCase_     :					Dict   	=self.config.features.arrow_schema.field(_lowerCamelCase   ).type
        UpperCamelCase_     :					Optional[Any]   	=pa_table.append_column(_lowerCamelCase      ,  pa.array([None] * len(_lowerCamelCase   )      ,  type=_lowerCamelCase   )   )
       # more expensive cast to support nested structures with keys in a different order
       # allows str <-> int/float or str to Audio for example
       UpperCamelCase_     :					int   	=table_cast(_lowerCamelCase      ,  self.config.features.arrow_schema   )
      return pa_table




     def  lowerCamelCase_						(							self :Dict      ,  _lowerCamelCase :Optional[int]   ):







      '''simple docstring'''



      for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase   )   ):
       # If the file is one json object and if we need to look at the list of items in one specific field
       if self.config.field is not None:
        with open(_lowerCamelCase      ,  encoding=self.config.encoding      ,  errors=self.config.encoding_errors   ) as f:
         UpperCamelCase_     :					List[str]   	=json.load(_lowerCamelCase   )

        # We keep only the field we are interested in
        UpperCamelCase_     :					Tuple   	=dataset[self.config.field]

        # We accept two format: a list of dicts or a dict of lists
        if isinstance(_lowerCamelCase      ,  (list, tuple)   ):
         UpperCamelCase_     :					Tuple   	=set().union(*[row.keys() for row in dataset]   )
         UpperCamelCase_     :					str   	={col: [row.get(_lowerCamelCase   ) for row in dataset] for col in keys}
        else:
         UpperCamelCase_     :					Any   	=dataset
        UpperCamelCase_     :					List[Any]   	=pa.Table.from_pydict(_lowerCamelCase   )
        yield file_idx, self._cast_table(_lowerCamelCase   )

       # If the file has one json object per line
       else:
        with open(_lowerCamelCase      ,  'rb'   ) as f:
         UpperCamelCase_     :					Any   	=0
         # Use block_size equal to the chunk size divided by 32 to leverage multithreading
         # Set a default minimum value of 16kB if the chunk size is really small
         UpperCamelCase_     :					List[str]   	=max(self.config.chunksize // 32      ,  16 << 10   )
         UpperCamelCase_     :					Dict   	=(
             self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
         )
         while True:
          UpperCamelCase_     :					Optional[Any]   	=f.read(self.config.chunksize   )
          if not batch:
           break
          # Finish current line
          try:
           batch += f.readline()
          except (AttributeError, io.UnsupportedOperation):
           batch += readline(_lowerCamelCase   )
          # PyArrow only accepts utf-8 encoded bytes
          if self.config.encoding != "utf-8":
           UpperCamelCase_     :					List[Any]   	=batch.decode(self.config.encoding      ,  errors=_lowerCamelCase   ).encode('utf-8'   )
          try:
           while True:
            try:
             UpperCamelCase_     :					str   	=paj.read_json(
                 io.BytesIO(_lowerCamelCase   )      ,  read_options=paj.ReadOptions(block_size=_lowerCamelCase   )   )
             break
            except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
             if (
                 isinstance(_lowerCamelCase      ,  pa.ArrowInvalid   )
                 and "straddling" not in str(_lowerCamelCase   )
                 or block_size > len(_lowerCamelCase   )
             ):
              raise
             else:
              # Increase the block size in case it was too small.
              # The block size will be reset for the next file.
              logger.debug(
                  f'''Batch of {len(_lowerCamelCase   )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.'''   )
              block_size *= 2
          except pa.ArrowInvalid as e:
           try:
            with open(
                _lowerCamelCase      ,  encoding=self.config.encoding      ,  errors=self.config.encoding_errors   ) as f:
             UpperCamelCase_     :					List[Any]   	=json.load(_lowerCamelCase   )
           except json.JSONDecodeError:
            logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase   )}: {e}'''   )
            raise e
           # If possible, parse the file as a list of json objects and exit the loop
           if isinstance(_lowerCamelCase      ,  _lowerCamelCase   ):  # list is the only sequence type supported in JSON
            try:
             UpperCamelCase_     :					str   	=set().union(*[row.keys() for row in dataset]   )
             UpperCamelCase_     :					List[Any]   	={col: [row.get(_lowerCamelCase   ) for row in dataset] for col in keys}
             UpperCamelCase_     :					Optional[Any]   	=pa.Table.from_pydict(_lowerCamelCase   )
            except (pa.ArrowInvalid, AttributeError) as e:
             logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase   )}: {e}'''   )
             raise ValueError(f'''Not able to read records in the JSON file at {file}.'''   ) from None
            yield file_idx, self._cast_table(_lowerCamelCase   )
            break
           else:
            logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase   )}: {e}'''   )
            raise ValueError(
                f'''Not able to read records in the JSON file at {file}. '''
                f'''You should probably indicate the field of the JSON file containing your records. '''
                f'''This JSON file contain the following fields: {str(list(dataset.keys()   )   )}. '''
                f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. '''   ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
          yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase   )
          batch_idx += 1


"""simple docstring"""






import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__SCREAMING_SNAKE_CASE							=     logging.get_logger(__name__)
__SCREAMING_SNAKE_CASE							=     {'vocab_file': 'spiece.model'}

__SCREAMING_SNAKE_CASE							=     {
    'vocab_file': {
        'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model',
        'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model',
        'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model',
        'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model',
        'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model',
        'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model',
        'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model',
        'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model',
    }
}

__SCREAMING_SNAKE_CASE							=     {
    'albert-base-v1': 512,
    'albert-large-v1': 512,
    'albert-xlarge-v1': 512,
    'albert-xxlarge-v1': 512,
    'albert-base-v2': 512,
    'albert-large-v2': 512,
    'albert-xlarge-v2': 512,
    'albert-xxlarge-v2': 512,
}

__SCREAMING_SNAKE_CASE							=     '▁'





class 				a__					(						A__       ):
     UpperCAmelCase__         =      VOCAB_FILES_NAMES
     UpperCAmelCase__         =      PRETRAINED_VOCAB_FILES_MAP
     UpperCAmelCase__         =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES



     def __init__(							self :Optional[Any]      ,  _lowerCamelCase :int      ,  _lowerCamelCase :List[Any]=True      ,  _lowerCamelCase :int=True      ,  _lowerCamelCase :Tuple=False      ,  _lowerCamelCase :Optional[Any]="[CLS]"      ,  _lowerCamelCase :List[Any]="[SEP]"      ,  _lowerCamelCase :Dict="<unk>"      ,  _lowerCamelCase :int="[SEP]"      ,  _lowerCamelCase :int="<pad>"      ,  _lowerCamelCase :Optional[Any]="[CLS]"      ,  _lowerCamelCase :str="[MASK]"      ,  _lowerCamelCase :Optional[Dict[str, Any]] = None      ,  **_lowerCamelCase :Union[str, Any]      ,  ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=(
          AddedToken(_lowerCamelCase      ,  lstrip=_lowerCamelCase      ,  rstrip=_lowerCamelCase      ,  normalized=_lowerCamelCase   )
          if isinstance(_lowerCamelCase      ,  _lowerCamelCase   )
          else mask_token
      )

      UpperCamelCase_     :					Any   	={} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          do_lower_case=_lowerCamelCase      ,  remove_space=_lowerCamelCase      ,  keep_accents=_lowerCamelCase      ,  bos_token=_lowerCamelCase      ,  eos_token=_lowerCamelCase      ,  unk_token=_lowerCamelCase      ,  sep_token=_lowerCamelCase      ,  pad_token=_lowerCamelCase      ,  cls_token=_lowerCamelCase      ,  mask_token=_lowerCamelCase      ,  sp_model_kwargs=self.sp_model_kwargs      ,  **_lowerCamelCase      ,  )

      UpperCamelCase_     :					str   	=do_lower_case
      UpperCamelCase_     :					Any   	=remove_space
      UpperCamelCase_     :					List[Any]   	=keep_accents
      UpperCamelCase_     :					Optional[Any]   	=vocab_file

      UpperCamelCase_     :					List[str]   	=spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(_lowerCamelCase   )



     @property
     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      return len(self.sp_model   )



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[int]   	={self.convert_ids_to_tokens(_lowerCamelCase   ): i for i in range(self.vocab_size   )}
      vocab.update(self.added_tokens_encoder   )
      return vocab



     def __getstate__(							self :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=self.__dict__.copy()
      UpperCamelCase_     :					Optional[Any]   	=None
      return state



     def __setstate__(							self :List[Any]      ,  _lowerCamelCase :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=d

      # for backward compatibility
      if not hasattr(self      ,  'sp_model_kwargs'   ):
       UpperCamelCase_     :					Tuple   	={}

      UpperCamelCase_     :					List[Any]   	=spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(self.vocab_file   )



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :Tuple   ):







      '''simple docstring'''



      if self.remove_space:
       UpperCamelCase_     :					Union[str, Any]   	=' '.join(inputs.strip().split()   )
      else:
       UpperCamelCase_     :					List[Any]   	=inputs
      UpperCamelCase_     :					Optional[int]   	=outputs.replace('``'      ,  '"'   ).replace('\'\''      ,  '"'   )

      if not self.keep_accents:
       UpperCamelCase_     :					Optional[Any]   	=unicodedata.normalize('NFKD'      ,  _lowerCamelCase   )
       UpperCamelCase_     :					Tuple   	=''.join([c for c in outputs if not unicodedata.combining(_lowerCamelCase   )]   )
      if self.do_lower_case:
       UpperCamelCase_     :					Optional[Any]   	=outputs.lower()

      return outputs



     def  lowerCamelCase_						(							self :Dict      ,  _lowerCamelCase :str   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=self.preprocess_text(_lowerCamelCase   )
      UpperCamelCase_     :					Any   	=self.sp_model.encode(_lowerCamelCase      ,  out_type=_lowerCamelCase   )
      UpperCamelCase_     :					int   	=[]
      for piece in pieces:
       if len(_lowerCamelCase   ) > 1 and piece[-1] == str(','   ) and piece[-2].isdigit():
        UpperCamelCase_     :					Union[str, Any]   	=self.sp_model.EncodeAsPieces(piece[:-1].replace(_lowerCamelCase      ,  ''   )   )
        if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
         if len(cur_pieces[0]   ) == 1:
          UpperCamelCase_     :					Any   	=cur_pieces[1:]
         else:
          UpperCamelCase_     :					List[str]   	=cur_pieces[0][1:]
        cur_pieces.append(piece[-1]   )
        new_pieces.extend(_lowerCamelCase   )
       else:
        new_pieces.append(_lowerCamelCase   )

      return new_pieces



     def  lowerCamelCase_						(							self :Dict      ,  _lowerCamelCase :List[str]   ):







      '''simple docstring'''



      return self.sp_model.PieceToId(_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Optional[Any]      ,  _lowerCamelCase :Union[str, Any]   ):







      '''simple docstring'''



      return self.sp_model.IdToPiece(_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					int   	=[]
      UpperCamelCase_     :					int   	=''
      UpperCamelCase_     :					int   	=False
      for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
        if not prev_is_special:
         out_string += " "
        out_string += self.sp_model.decode(_lowerCamelCase   ) + token
        UpperCamelCase_     :					List[Any]   	=True
        UpperCamelCase_     :					str   	=[]
       else:
        current_sub_tokens.append(_lowerCamelCase   )
        UpperCamelCase_     :					List[Any]   	=False
      out_string += self.sp_model.decode(_lowerCamelCase   )
      return out_string.strip()



     def  lowerCamelCase_						(							self :Optional[int]      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=[self.sep_token_id]
      UpperCamelCase_     :					Tuple   	=[self.cls_token_id]
      if token_ids_a is None:
       return cls + token_ids_a + sep
      return cls + token_ids_a + sep + token_ids_a + sep



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None      ,  _lowerCamelCase :bool = False   ):







      '''simple docstring'''



      if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=_lowerCamelCase      ,  token_ids_a=_lowerCamelCase      ,  already_has_special_tokens=_lowerCamelCase   )

      if token_ids_a is not None:
       return [1] + ([0] * len(_lowerCamelCase   )) + [1] + ([0] * len(_lowerCamelCase   )) + [1]
      return [1] + ([0] * len(_lowerCamelCase   )) + [1]



     def  lowerCamelCase_						(							self :List[Any]      ,  _lowerCamelCase :List[int]      ,  _lowerCamelCase :Optional[List[int]] = None   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=[self.sep_token_id]
      UpperCamelCase_     :					List[str]   	=[self.cls_token_id]

      if token_ids_a is None:
       return len(cls + token_ids_a + sep   ) * [0]
      return len(cls + token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]




     def  lowerCamelCase_						(							self :Tuple      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Optional[str] = None   ):







      '''simple docstring'''



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

      if os.path.abspath(self.vocab_file   ) != os.path.abspath(_lowerCamelCase   ) and os.path.isfile(self.vocab_file   ):
       copyfile(self.vocab_file      ,  _lowerCamelCase   )
      elif not os.path.isfile(self.vocab_file   ):
       with open(_lowerCamelCase      ,  'wb'   ) as fi:
        UpperCamelCase_     :					Dict   	=self.sp_model.serialized_model_proto()
        fi.write(_lowerCamelCase   )

      return (out_vocab_file,)
