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

import sentencepiece as spm

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


__lowerCAmelCase					:			Optional[Any]			      =		logging.get_logger(__name__)

__lowerCAmelCase					:			Any			      =		"▁"

__lowerCAmelCase					:			Union[str, Any]			      =		{"vocab_file": "sentencepiece.bpe.model"}

__lowerCAmelCase					:			Tuple			      =		{
    "vocab_file": {
        "facebook/mbart-large-en-ro": (
            "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"
        ),
        "facebook/mbart-large-cc25": (
            "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"
        ),
    }
}

__lowerCAmelCase					:			Tuple			      =		{
    "facebook/mbart-large-en-ro": 1_024,
    "facebook/mbart-large-cc25": 1_024,
}

# fmt: off
__lowerCAmelCase					:			str			      =		["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"]


class 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Any        =    VOCAB_FILES_NAMES
      A__	:			Dict        =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      A__	:			Optional[int]        =    PRETRAINED_VOCAB_FILES_MAP
      A__	:			List[Any]        =    ['''input_ids''', '''attention_mask''']

      A__	:			List[int]        =    []
      A__	:			List[int]        =    []




      def __init__(      self		:       List[Any]				,       _snake_case		:       Optional[int]				,       _snake_case		:       List[str]="<s>"				,       _snake_case		:       str="</s>"				,       _snake_case		:       Tuple="</s>"				,       _snake_case		:       List[Any]="<s>"				,       _snake_case		:       int="<unk>"				,       _snake_case		:       List[str]="<pad>"				,       _snake_case		:       Optional[int]="<mask>"				,       _snake_case		:       Optional[int]=None				,       _snake_case		:       Dict=None				,       _snake_case		:       Optional[int]=None				,       _snake_case		:       Optional[Dict[str, Any]] = None				,       _snake_case		:       Optional[Any]=None				,       **_snake_case		:       List[str]				,       ):
          # Mask token behave like a normal word, i.e. include the space before it
          __lowercase		:			Optional[Any]	    =       AddedToken(_snake_case				,       lstrip=_snake_case				,       rstrip=_snake_case				) if isinstance(_snake_case				,       _snake_case				) else mask_token

          __lowercase		:			str	    =       {} if sp_model_kwargs is None else sp_model_kwargs

          super().__init__(
              bos_token=_snake_case				,       eos_token=_snake_case				,       unk_token=_snake_case				,       sep_token=_snake_case				,       cls_token=_snake_case				,       pad_token=_snake_case				,       mask_token=_snake_case				,       tokenizer_file=_snake_case				,       src_lang=_snake_case				,       tgt_lang=_snake_case				,       additional_special_tokens=_snake_case				,       sp_model_kwargs=self.sp_model_kwargs				,       **_snake_case				,       )

          __lowercase		:			int	    =       spm.SentencePieceProcessor(**self.sp_model_kwargs				)
          self.sp_model.Load(str(_snake_case				)				)
          __lowercase		:			Any	    =       vocab_file

          # Original fairseq vocab and spm vocab must be "aligned":
          # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
          # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
          # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
          # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

          # Mimic fairseq token-to-id alignment for the first 4 token
          __lowercase		:			Optional[Any]	    =       {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

          # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
          __lowercase		:			List[Any]	    =       1

          __lowercase		:			Tuple	    =       len(self.sp_model				)
          __lowercase		:			int	    =       {
              code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_snake_case				)
          }
          __lowercase		:			str	    =       {v: k for k, v in self.lang_code_to_id.items()}
          __lowercase		:			Optional[Any]	    =       len(self.sp_model				) + len(self.lang_code_to_id				) + self.fairseq_offset

          self.fairseq_tokens_to_ids.update(self.lang_code_to_id				)
          __lowercase		:			List[str]	    =       {v: k for k, v in self.fairseq_tokens_to_ids.items()}
          __lowercase		:			Tuple	    =       list(self.lang_code_to_id.keys()				)

          if additional_special_tokens is not None:
              # Only add those special tokens if they are not already there.
              self._additional_special_tokens.extend(
                  [t for t in additional_special_tokens if t not in self._additional_special_tokens]				)

          __lowercase		:			str	    =       src_lang if src_lang is not None else '''en_XX'''
          __lowercase		:			Any	    =       self.lang_code_to_id[self._src_lang]
          __lowercase		:			Dict	    =       tgt_lang
          self.set_src_lang_special_tokens(self._src_lang				)




      def __getstate__(      self		:       Tuple				):
          __lowercase		:			List[str]	    =       self.__dict__.copy()
          __lowercase		:			Optional[Any]	    =       None
          __lowercase		:			Dict	    =       self.sp_model.serialized_model_proto()
          return state




      def __setstate__(      self		:       Union[str, Any]				,       _snake_case		:       List[Any]				):
          __lowercase		:			Tuple	    =       d

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

          __lowercase		:			List[str]	    =       spm.SentencePieceProcessor(**self.sp_model_kwargs				)
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto				)




      @property
      def 		snake_case_			(      self		:       Union[str, Any]				):
          return len(self.sp_model				) + len(self.lang_code_to_id				) + self.fairseq_offset + 1  # Plus 1 for the mask token




      @property
      def 		snake_case_			(      self		:       str				):
          return self._src_lang




      @src_lang.setter
      def 		snake_case_			(      self		:       List[Any]				,       _snake_case		:       str				):
          __lowercase		:			Any	    =       new_src_lang
          self.set_src_lang_special_tokens(self._src_lang				)




      def 		snake_case_			(      self		:       int				,       _snake_case		:       List[int]				,       _snake_case		:       Optional[List[int]] = None				,       _snake_case		:       bool = False				):

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

          __lowercase		:			List[Any]	    =       [1] * len(self.prefix_tokens				)
          __lowercase		:			Union[str, Any]	    =       [1] * len(self.suffix_tokens				)
          if token_ids_a is None:
              return prefix_ones + ([0] * len(_snake_case				)) + suffix_ones
          return prefix_ones + ([0] * len(_snake_case				)) + ([0] * len(_snake_case				)) + suffix_ones




      def 		snake_case_			(      self		:       Union[str, Any]				,       _snake_case		:       List[int]				,       _snake_case		:       Optional[List[int]] = None				):
          if token_ids_a is None:
              return self.prefix_tokens + token_ids_a + self.suffix_tokens
          # We don't expect to process pairs, but leave the pair logic for API consistency
          return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens




      def 		snake_case_			(      self		:       Union[str, Any]				,       _snake_case		:       List[int]				,       _snake_case		:       Optional[List[int]] = None				):
          __lowercase		:			Optional[int]	    =       [self.sep_token_id]
          __lowercase		:			Any	    =       [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 + sep + token_ids_a + sep				) * [0]




      def 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				,       _snake_case		:       str				,       _snake_case		:       Optional[str]				,       _snake_case		:       Optional[str]				,       **_snake_case		:       Union[str, Any]				):
          if src_lang is None or tgt_lang is None:
              raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model'''				)
          __lowercase		:			str	    =       src_lang
          __lowercase		:			Optional[int]	    =       self(_snake_case				,       add_special_tokens=_snake_case				,       return_tensors=_snake_case				,       **_snake_case				)
          __lowercase		:			Optional[int]	    =       self.convert_tokens_to_ids(_snake_case				)
          __lowercase		:			List[Any]	    =       tgt_lang_id
          return inputs




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			List[str]	    =       {self.convert_ids_to_tokens(_snake_case				): i for i in range(self.vocab_size				)}
          vocab.update(self.added_tokens_encoder				)
          return vocab




      def 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				):
          return self.sp_model.encode(_snake_case				,       out_type=_snake_case				)




      def 		snake_case_			(      self		:       Any				,       _snake_case		:       Optional[Any]				):
          if token in self.fairseq_tokens_to_ids:
              return self.fairseq_tokens_to_ids[token]
          __lowercase		:			int	    =       self.sp_model.PieceToId(_snake_case				)

          # Need to return unknown token if the SP model returned 0
          return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




      def 		snake_case_			(      self		:       Union[str, Any]				,       _snake_case		:       Union[str, Any]				):
          if index in self.fairseq_ids_to_tokens:
              return self.fairseq_ids_to_tokens[index]
          return self.sp_model.IdToPiece(index - self.fairseq_offset				)




      def 		snake_case_			(      self		:       Dict				,       _snake_case		:       Tuple				):
          __lowercase		:			int	    =       ''''''.join(_snake_case				).replace(_snake_case				,       ''' '''				).strip()
          return out_string




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

          if os.path.abspath(self.vocab_file				) != os.path.abspath(_snake_case				) and os.path.isfile(self.vocab_file				):
              copyfile(self.vocab_file				,       _snake_case				)
          elif not os.path.isfile(self.vocab_file				):
              with open(_snake_case				,       '''wb'''				) as fi:
                  __lowercase		:			Optional[int]	    =       self.sp_model.serialized_model_proto()
                  fi.write(_snake_case				)

          return (out_vocab_file,)




      def 		snake_case_			(      self		:       Optional[int]				,       _snake_case		:       List[str]				,       _snake_case		:       str = "en_XX"				,       _snake_case		:       Optional[List[str]] = None				,       _snake_case		:       str = "ro_RO"				,       **_snake_case		:       Union[str, Any]				,       ):
          __lowercase		:			Tuple	    =       src_lang
          __lowercase		:			Any	    =       tgt_lang
          return super().prepare_seqaseq_batch(_snake_case				,       _snake_case				,       **_snake_case				)




      def 		snake_case_			(      self		:       Any				):
          return self.set_src_lang_special_tokens(self.src_lang				)




      def 		snake_case_			(      self		:       int				):
          return self.set_tgt_lang_special_tokens(self.tgt_lang				)




      def 		snake_case_			(      self		:       Dict				,       _snake_case		:       Tuple				):
          __lowercase		:			List[str]	    =       self.lang_code_to_id[src_lang]
          __lowercase		:			Dict	    =       []
          __lowercase		:			List[Any]	    =       [self.eos_token_id, self.cur_lang_code]




      def 		snake_case_			(      self		:       str				,       _snake_case		:       str				):
          __lowercase		:			str	    =       self.lang_code_to_id[lang]
          __lowercase		:			Union[str, Any]	    =       []
          __lowercase		:			Union[str, Any]	    =       [self.eos_token_id, self.cur_lang_code]




import itertools
from dataclasses import dataclass
from typing import Optional

import pandas as pd
import pyarrow as pa

import datasets
from datasets.table import table_cast


@dataclass
class 						__lowerCAmelCase	(	datasets.BuilderConfig      ):



      """simple docstring"""







      A__	:			Optional[datasets.Features]        =    None






class 						__lowerCAmelCase	(	datasets.ArrowBasedBuilder      ):



      """simple docstring"""







      A__	:			List[str]        =    PandasConfig




      def 		snake_case_			(      self		:       int				):
          return datasets.DatasetInfo(features=self.config.features				)




      def 		snake_case_			(      self		:       int				,       _snake_case		:       Optional[int]				):
          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}'				)
          __lowercase		:			Any	    =       dl_manager.download_and_extract(self.config.data_files				)
          if isinstance(_snake_case				,       (str, list, tuple)				):
              __lowercase		:			str	    =       data_files
              if isinstance(_snake_case				,       _snake_case				):
                  __lowercase		:			Any	    =       [files]
              # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
              __lowercase		:			Optional[int]	    =       [dl_manager.iter_files(_snake_case				) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN				,       gen_kwargs={'''files''': files}				)]
          __lowercase		:			str	    =       []
          for split_name, files in data_files.items():
              if isinstance(_snake_case				,       _snake_case				):
                  __lowercase		:			str	    =       [files]
              # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
              __lowercase		:			int	    =       [dl_manager.iter_files(_snake_case				) for file in files]
              splits.append(datasets.SplitGenerator(name=_snake_case				,       gen_kwargs={'''files''': files}				)				)
          return splits




      def 		snake_case_			(      self		:       Optional[int]				,       _snake_case		:       pa.Table				):
          if self.config.features is not None:
              # more expensive cast to support nested features with keys in a different order
              # allows str <-> int/float or str to Audio for example
              __lowercase		:			List[str]	    =       table_cast(_snake_case				,       self.config.features.arrow_schema				)
          return pa_table




      def 		snake_case_			(      self		:       int				,       _snake_case		:       Union[str, Any]				):
          for i, file in enumerate(itertools.chain.from_iterable(_snake_case				)				):
              with open(_snake_case				,       '''rb'''				) as f:
                  __lowercase		:			Dict	    =       pa.Table.from_pandas(pd.read_pickle(_snake_case				)				)
                  yield i, self._cast_table(_snake_case				)


