
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


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

_A						      =				["names", "prefix"]
_A						      =				["warn_bad_lines", "error_bad_lines", "mangle_dupe_cols"]
_A						      =				["encoding_errors", "on_bad_lines"]
_A						      =				["date_format"]







@dataclass
class   lowerCamelCase	(						datasets.BuilderConfig						):
     UpperCAmelCase__       :							str     =	","
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							Optional[Union[int, List[int], str]]     =	"infer"
     UpperCAmelCase__       :							Optional[List[str]]     =	None
     UpperCAmelCase__       :							Optional[List[str]]     =	None
     UpperCAmelCase__       :							Optional[Union[int, str, List[int], List[str]]]     =	None
     UpperCAmelCase__       :							Optional[Union[List[int], List[str]]]     =	None
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							Optional[Literal["c", "python", "pyarrow"]]     =	None
     UpperCAmelCase__       :							Dict[Union[int, str], Callable[[Any], Any]]     =	None
     UpperCAmelCase__       :							Optional[list]     =	None
     UpperCAmelCase__       :							Optional[list]     =	None
     UpperCAmelCase__       :							bool     =	False
     UpperCAmelCase__       :							Optional[Union[int, List[int]]]     =	None
     UpperCAmelCase__       :							Optional[int]     =	None
     UpperCAmelCase__       :							Optional[Union[str, List[str]]]     =	None
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							bool     =	False
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							str     =	"."
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							str     =	'"'
     UpperCAmelCase__       :							int     =	0
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							int     =	0
     UpperCAmelCase__       :							bool     =	True
     UpperCAmelCase__       :							bool     =	False
     UpperCAmelCase__       :							Optional[str]     =	None
     UpperCAmelCase__       :							int     =	1_00_00
     UpperCAmelCase__       :							Optional[datasets.Features]     =	None
     UpperCAmelCase__       :							Optional[str]     =	"strict"
     UpperCAmelCase__       :							Literal["error", "warn", "skip"]     =	"error"
     UpperCAmelCase__       :							Optional[str]     =	None





     def 	UpperCAmelCase(self   :					Dict     )		->		Optional[Any]:
         if self.delimiter is not None:
             snake_case				  =      self.delimiter
         if self.column_names is not None:
             snake_case				  =      self.column_names





     @property
     def 	UpperCAmelCase(self   :					Dict     )		->		Any:
         snake_case				  =      {
             "sep": self.sep,
             "header": self.header,
             "names": self.names,
             "index_col": self.index_col,
             "usecols": self.usecols,
             "prefix": self.prefix,
             "mangle_dupe_cols": self.mangle_dupe_cols,
             "engine": self.engine,
             "converters": self.converters,
             "true_values": self.true_values,
             "false_values": self.false_values,
             "skipinitialspace": self.skipinitialspace,
             "skiprows": self.skiprows,
             "nrows": self.nrows,
             "na_values": self.na_values,
             "keep_default_na": self.keep_default_na,
             "na_filter": self.na_filter,
             "verbose": self.verbose,
             "skip_blank_lines": self.skip_blank_lines,
             "thousands": self.thousands,
             "decimal": self.decimal,
             "lineterminator": self.lineterminator,
             "quotechar": self.quotechar,
             "quoting": self.quoting,
             "escapechar": self.escapechar,
             "comment": self.comment,
             "encoding": self.encoding,
             "dialect": self.dialect,
             "error_bad_lines": self.error_bad_lines,
             "warn_bad_lines": self.warn_bad_lines,
             "skipfooter": self.skipfooter,
             "doublequote": self.doublequote,
             "memory_map": self.memory_map,
             "float_precision": self.float_precision,
             "chunksize": self.chunksize,
             "encoding_errors": self.encoding_errors,
             "on_bad_lines": self.on_bad_lines,
             "date_format": self.date_format,
         }

         # some kwargs must not be passed if they don't have a default value
         # some others are deprecated and we can also not pass them if they are the default value
         for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
             if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()       ,					_A     ):
                 del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 2):
             for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                 del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
             for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                 del pd_read_csv_kwargs[pd_read_csv_parameter]

         return pd_read_csv_kwargs







class   lowerCamelCase	(						datasets.ArrowBasedBuilder						):
     UpperCAmelCase__       :							str     =	CsvConfig





     def 	UpperCAmelCase(self   :					Dict     )		->		int:
         return datasets.DatasetInfo(features=self.config.features     )





     def 	UpperCAmelCase(self   :					Optional[Any]       ,					_A   :					List[str]     )		->		Dict:
         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}'     )
         snake_case				  =      dl_manager.download_and_extract(self.config.data_files     )
         if isinstance(_A       ,					(str, list, tuple)     ):
             snake_case				  =      data_files
             if isinstance(_A       ,					_A     ):
                 snake_case				  =      [files]
             snake_case				  =      [dl_manager.iter_files(_A     ) for file in files]
             return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,					gen_kwargs={"files": files}     )]
         snake_case				  =      []
         for split_name, files in data_files.items():
             if isinstance(_A       ,					_A     ):
                 snake_case				  =      [files]
             snake_case				  =      [dl_manager.iter_files(_A     ) for file in files]
             splits.append(datasets.SplitGenerator(name=_A       ,					gen_kwargs={"files": files}     )     )
         return splits





     def 	UpperCAmelCase(self   :					Optional[int]       ,					_A   :					pa.Table     )		->		pa.Table:
         if self.config.features is not None:
             snake_case				  =      self.config.features.arrow_schema
             if all(not require_storage_cast(_A     ) for feature in self.config.features.values()     ):
                 # cheaper cast
                 snake_case				  =      pa.Table.from_arrays([pa_table[field.name] for field in schema]       ,					schema=_A     )
             else:
                 # more expensive cast; allows str <-> int/float or str to Audio for example
                 snake_case				  =      table_cast(_A       ,					_A     )
         return pa_table





     def 	UpperCAmelCase(self   :					Optional[int]       ,					_A   :					Union[str, Any]     )		->		Optional[int]:
         snake_case				  =      self.config.features.arrow_schema if self.config.features else None
         # dtype allows reading an int column as str
         snake_case				  =      (
             {
                 name: dtype.to_pandas_dtype() if not require_storage_cast(_A     ) else object
                 for name, dtype, feature in zip(schema.names       ,					schema.types       ,					self.config.features.values()     )
             }
             if schema is not None
             else None
         )
         for file_idx, file in enumerate(itertools.chain.from_iterable(_A     )     ):
             snake_case				  =      pd.read_csv(_A       ,					iterator=_A       ,					dtype=_A       ,					**self.config.pd_read_csv_kwargs     )
             try:
                 for batch_idx, df in enumerate(_A     ):
                     snake_case				  =      pa.Table.from_pandas(_A     )
                     # 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(_A     )
             except ValueError as e:
                 logger.error(f'Failed to read file \'{file}\' with error {type(_A     )}: {e}'     )
                 raise



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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_A						      =				"▁"

_A						      =				{"vocab_file": "spiece.model"}

_A						      =				{
    "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"}
}

_A						      =				{
    "google/pegasus-xsum": 5_12,
}


_A						      =				logging.get_logger(__name__)







class   lowerCamelCase	(						A_						):
     UpperCAmelCase__       :							Tuple     =	VOCAB_FILES_NAMES

     UpperCAmelCase__       :							Tuple     =	VOCAB_FILES_NAMES
     UpperCAmelCase__       :							List[str]     =	PRETRAINED_VOCAB_FILES_MAP
     UpperCAmelCase__       :							Optional[int]     =	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     UpperCAmelCase__       :							Optional[Any]     =	["input_ids", "attention_mask"]





     def __init__(self   :					Optional[Any]       ,					_A   :					Any       ,					_A   :					List[Any]="<pad>"       ,					_A   :					int="</s>"       ,					_A   :					Dict="<unk>"       ,					_A   :					str="<mask_2>"       ,					_A   :					Optional[int]="<mask_1>"       ,					_A   :					Optional[Any]=None       ,					_A   :					Tuple=1_0_3       ,					_A   :					Optional[Dict[str, Any]] = None       ,					**_A   :					List[str]       ,					)		->		None:
         snake_case				  =      offset
         if additional_special_tokens is not None:
             if not isinstance(_A       ,					_A     ):
                 raise TypeError(
                     f'additional_special_tokens should be of type {type(_A     )}, but is'
                     f' {type(_A     )}'     )

             snake_case				  =      (
                 ([mask_token_sent] + additional_special_tokens)
                 if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
                 else additional_special_tokens
             )
             # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
             additional_special_tokens_extended += [
                 f'<unk_{i}>' for i in range(len(_A     )       ,					self.offset - 1     )
             ]

             if len(set(_A     )     ) != len(_A     ):
                 raise ValueError(
                     "Please make sure that the provided additional_special_tokens do not contain an incorrectly"
                     f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.'     )
             snake_case				  =      additional_special_tokens_extended
         else:
             snake_case				  =      [mask_token_sent] if mask_token_sent is not None else []
             additional_special_tokens += [f'<unk_{i}>' for i in range(2       ,					self.offset     )]

         snake_case				  =      {} if sp_model_kwargs is None else sp_model_kwargs

         super().__init__(
             eos_token=_A       ,					unk_token=_A       ,					mask_token=_A       ,					pad_token=_A       ,					mask_token_sent=_A       ,					offset=_A       ,					additional_special_tokens=_A       ,					sp_model_kwargs=self.sp_model_kwargs       ,					**_A       ,					)
         snake_case				  =      mask_token_sent
         snake_case				  =      vocab_file
         snake_case				  =      spm.SentencePieceProcessor(**self.sp_model_kwargs     )
         self.sp_model.Load(_A     )

         # add special tokens to encoder dict
         snake_case				  =      {
             0: self.pad_token,
             1: self.eos_token,
         }

         if self.mask_token_sent is not None:
             self.encoder.update(
                 {
                     2: self.mask_token_sent,
                     3: self.mask_token,
                 }     )

         if self.offset > 0:
             # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102
             # mask_token_sent is already added to list -> so start at 1
             self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1       ,					self.offset - 1     )}     )

         snake_case				  =      {v: k for k, v in self.encoder.items()}





     @property
     def 	UpperCAmelCase(self   :					str     )		->		int:
         return len(self.sp_model     ) + self.offset





     def 	UpperCAmelCase(self   :					List[str]     )		->		Dict[str, int]:
         snake_case				  =      {self.convert_ids_to_tokens(_A     ): i for i in range(self.vocab_size     )}
         vocab.update(self.added_tokens_encoder     )
         return vocab





     def __getstate__(self   :					Any     )		->		List[Any]:
         snake_case				  =      self.__dict__.copy()
         snake_case				  =      None
         return state





     def __setstate__(self   :					str       ,					_A   :					Union[str, Any]     )		->		Tuple:
         snake_case				  =      d

         # for backward compatibility
         if not hasattr(self       ,					"sp_model_kwargs"     ):
             snake_case				  =      {}

         snake_case				  =      spm.SentencePieceProcessor(**self.sp_model_kwargs     )
         self.sp_model.Load(self.vocab_file     )





     def 	UpperCAmelCase(self   :					List[Any]       ,					_A   :					str     )		->		List[str]:
         return self.sp_model.encode(_A       ,					out_type=_A     )





     def 	UpperCAmelCase(self   :					List[str]       ,					_A   :					str     )		->		int:
         if token in self.decoder:
             return self.decoder[token]
         elif token in self.added_tokens_decoder:
             return self.added_tokens_decoder[token]
         snake_case				  =      self.sp_model.piece_to_id(_A     )
         return sp_id + self.offset





     def 	UpperCAmelCase(self   :					Union[str, Any]       ,					_A   :					int     )		->		str:
         if index in self.encoder:
             return self.encoder[index]
         elif index in self.added_tokens_encoder:
             return self.added_tokens_encoder[index]
         else:
             snake_case				  =      self.sp_model.IdToPiece(index - self.offset     )
         return token





     def 	UpperCAmelCase(self   :					List[Any]       ,					_A   :					Tuple     )		->		Tuple:
         snake_case				  =      []
         snake_case				  =      ""
         for token in tokens:
             # make sure that special tokens are not decoded using sentencepiece model
             if token in self.all_special_tokens:
                 out_string += self.sp_model.decode(_A     ) + token
                 snake_case				  =      []
             else:
                 current_sub_tokens.append(_A     )
         out_string += self.sp_model.decode(_A     )
         return out_string.strip()





     def 	UpperCAmelCase(self   :					List[Any]       ,					_A   :					Tuple=False     )		->		Tuple:
         return 1





     def 	UpperCAmelCase(self   :					Tuple       ,					_A   :					Optional[int]     )		->		Tuple:
         snake_case				  =      set(self.all_special_ids     )  # call it once instead of inside list comp
         all_special_ids.remove(self.unk_token_id     )  # <unk> is only sometimes special

         return [1 if x in all_special_ids else 0 for x in seq]





     def 	UpperCAmelCase(self   :					str       ,					_A   :					List       ,					_A   :					Optional[List] = None       ,					_A   :					bool = False     )		->		List[int]:
         if already_has_special_tokens:
             return self._special_token_mask(_A     )
         elif token_ids_a is None:
             return self._special_token_mask(_A     ) + [1]
         else:
             return self._special_token_mask(token_ids_a + token_ids_a     ) + [1]





     def 	UpperCAmelCase(self   :					int       ,					_A   :					Dict       ,					_A   :					List[Any]=None     )		->		List[int]:
         if token_ids_a is None:
             return token_ids_a + [self.eos_token_id]
         # We don't expect to process pairs, but leave the pair logic for API consistency
         return token_ids_a + token_ids_a + [self.eos_token_id]





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

         if os.path.abspath(self.vocab_file     ) != os.path.abspath(_A     ) and os.path.isfile(self.vocab_file     ):
             copyfile(self.vocab_file       ,					_A     )
         elif not os.path.isfile(self.vocab_file     ):
             with open(_A       ,					"wb"     ) as fi:
                 snake_case				  =      self.sp_model.serialized_model_proto()
                 fi.write(_A     )

         return (out_vocab_file,)

