






"""simple docstring"""







import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


_UpperCamelCase					      =  logging.get_logger(__name__)

_UpperCamelCase					      =  list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_UpperCamelCase					      =  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class  lowerCamelCase__ :
    SCREAMING_SNAKE_CASE		=      field(
        default=snake_case   ,					metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(snake_case			)}			)
    SCREAMING_SNAKE_CASE		=      field(
        default=snake_case   ,					metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}			)
    SCREAMING_SNAKE_CASE		=      field(
        default=128   ,					metadata={
            '''help''': (
                '''The maximum total input sequence length after tokenization. Sequences longer '''
                '''than this will be truncated, sequences shorter will be padded.'''
            )
        }   ,					)
    SCREAMING_SNAKE_CASE		=      field(
        default=128   ,					metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}   ,					)
    SCREAMING_SNAKE_CASE		=      field(
        default=64   ,					metadata={
            '''help''': (
                '''The maximum number of tokens for the question. Questions longer than this will '''
                '''be truncated to this length.'''
            )
        }   ,					)
    SCREAMING_SNAKE_CASE		=      field(
        default=30   ,					metadata={
            '''help''': (
                '''The maximum length of an answer that can be generated. This is needed because the start '''
                '''and end predictions are not conditioned on one another.'''
            )
        }   ,					)
    SCREAMING_SNAKE_CASE		=      field(
        default=snake_case   ,					metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}			)
    SCREAMING_SNAKE_CASE		=      field(
        default=snake_case   ,					metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}			)
    SCREAMING_SNAKE_CASE		=      field(
        default=0.0   ,					metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}			)
    SCREAMING_SNAKE_CASE		=      field(
        default=20   ,					metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}			)
    SCREAMING_SNAKE_CASE		=      field(
        default=0   ,					metadata={
            '''help''': (
                '''language id of input for language-specific xlm models (see'''
                ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
            )
        }   ,					)
    SCREAMING_SNAKE_CASE		=      field(default=1   ,					metadata={'''help''': '''multiple threads for converting example to features'''}			)







class  lowerCamelCase__ (	snake_case			):
    SCREAMING_SNAKE_CASE		=      '''train'''
    SCREAMING_SNAKE_CASE		=      '''dev'''







class  lowerCamelCase__ (	snake_case			):
    SCREAMING_SNAKE_CASE		=      42
    SCREAMING_SNAKE_CASE		=      42
    SCREAMING_SNAKE_CASE		=      42
    SCREAMING_SNAKE_CASE		=      42






    def __init__(			self     ,A     ,A     ,A = None     ,A = Split.train     ,A = False     ,A = None     ,A = "pt"     ,):
          UpperCAmelCase          =	args
          UpperCAmelCase          =	is_language_sensitive
          UpperCAmelCase          =	SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
          if isinstance(A     ,A ):
                try:
                      UpperCAmelCase          =	Split[mode]
                except KeyError:
                      raise KeyError("""mode is not a valid split name""" )
          UpperCAmelCase          =	mode
          # Load data features from cache or dataset file
          UpperCAmelCase          =	"""v2""" if args.version_2_with_negative else """v1"""
          UpperCAmelCase          =	os.path.join(
              cache_dir if cache_dir is not None else args.data_dir     ,F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''     ,)

          # Make sure only the first process in distributed training processes the dataset,
          # and the others will use the cache.
          UpperCAmelCase          =	cached_features_file + """.lock"""
          with FileLock(A ):
                if os.path.exists(A ) and not args.overwrite_cache:
                      UpperCAmelCase          =	time.time()
                      UpperCAmelCase          =	torch.load(A )

                      # Legacy cache files have only features, while new cache files
                      # will have dataset and examples also.
                      UpperCAmelCase          =	self.old_features["""features"""]
                      UpperCAmelCase          =	self.old_features.get("""dataset"""     ,A )
                      UpperCAmelCase          =	self.old_features.get("""examples"""     ,A )
                      logger.info(
                          F'''Loading features from cached file {cached_features_file} [took %.3f s]'''     ,time.time() - start )

                      if self.dataset is None or self.examples is None:
                            logger.warning(
                                F'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
                                """ future run""" )
                else:
                      if mode == Split.dev:
                            UpperCAmelCase          =	self.processor.get_dev_examples(args.data_dir )
                      else:
                            UpperCAmelCase          =	self.processor.get_train_examples(args.data_dir )

                      UpperCAmelCase      , UpperCAmelCase          =	squad_convert_examples_to_features(
                          examples=self.examples     ,tokenizer=A     ,max_seq_length=args.max_seq_length     ,doc_stride=args.doc_stride     ,max_query_length=args.max_query_length     ,is_training=mode == Split.train     ,threads=args.threads     ,return_dataset=A     ,)

                      UpperCAmelCase          =	time.time()
                      torch.save(
                          {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}     ,A     ,)
                      # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                      logger.info(
                          F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' )






    def __len__(			self ):
          return len(self.features )






    def __getitem__(			self     ,A ):
          # Convert to Tensors and build dataset
          UpperCAmelCase          =	self.features[i]

          UpperCAmelCase          =	torch.tensor(feature.input_ids     ,dtype=torch.long )
          UpperCAmelCase          =	torch.tensor(feature.attention_mask     ,dtype=torch.long )
          UpperCAmelCase          =	torch.tensor(feature.token_type_ids     ,dtype=torch.long )
          UpperCAmelCase          =	torch.tensor(feature.cls_index     ,dtype=torch.long )
          UpperCAmelCase          =	torch.tensor(feature.p_mask     ,dtype=torch.float )
          UpperCAmelCase          =	torch.tensor(feature.is_impossible     ,dtype=torch.float )

          UpperCAmelCase          =	{
              """input_ids""": input_ids,
              """attention_mask""": attention_mask,
              """token_type_ids""": token_type_ids,
          }

          if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
                del inputs["token_type_ids"]

          if self.args.model_type in ["xlnet", "xlm"]:
                inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask} )
                if self.args.version_2_with_negative:
                      inputs.update({"""is_impossible""": is_impossible} )
                if self.is_language_sensitive:
                      inputs.update({"""langs""": (torch.ones(input_ids.shape     ,dtype=torch.intaa ) * self.args.lang_id)} )

          if self.mode == Split.train:
                UpperCAmelCase          =	torch.tensor(feature.start_position     ,dtype=torch.long )
                UpperCAmelCase          =	torch.tensor(feature.end_position     ,dtype=torch.long )
                inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} )

          return inputs











"""simple docstring"""







import os
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


_UpperCamelCase					      =  logging.get_logger(__name__)

_UpperCamelCase					      =  """▁"""

_UpperCamelCase					      =  {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""}

_UpperCamelCase					      =  {
    """vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""",
    },
    """monolingual_vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""",
    },
}

_UpperCamelCase					      =  {"""vinai/bartpho-syllable""": 1024}







class  lowerCamelCase__ (	snake_case			):
    SCREAMING_SNAKE_CASE		=      VOCAB_FILES_NAMES
    SCREAMING_SNAKE_CASE		=      PRETRAINED_VOCAB_FILES_MAP
    SCREAMING_SNAKE_CASE		=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    SCREAMING_SNAKE_CASE		=      ['''input_ids''', '''attention_mask''']






    def __init__(			self     ,A     ,A     ,A="<s>"     ,A="</s>"     ,A="</s>"     ,A="<s>"     ,A="<unk>"     ,A="<pad>"     ,A="<mask>"     ,A = None     ,**A     ,):
          # Mask token behave like a normal word, i.e. include the space before it
          UpperCAmelCase          =	AddedToken(A     ,lstrip=A     ,rstrip=A ) if isinstance(A     ,A ) else mask_token

          UpperCAmelCase          =	{} if sp_model_kwargs is None else sp_model_kwargs

          super().__init__(
              bos_token=A     ,eos_token=A     ,unk_token=A     ,sep_token=A     ,cls_token=A     ,pad_token=A     ,mask_token=A     ,sp_model_kwargs=self.sp_model_kwargs     ,**A     ,)

          UpperCAmelCase          =	vocab_file
          UpperCAmelCase          =	monolingual_vocab_file
          UpperCAmelCase          =	spm.SentencePieceProcessor(**self.sp_model_kwargs )
          self.sp_model.Load(str(A ) )

          # Load the reduced vocab

          # Keep order of special tokens for backward compatibility
          UpperCAmelCase          =	{}
          UpperCAmelCase          =	0
          for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
                if str(A ) not in self.fairseq_tokens_to_ids:
                      UpperCAmelCase          =	cnt
                      cnt += 1
          with open(A     ,"""r"""     ,encoding="""utf-8""" ) as f:
                for line in f.readlines():
                      UpperCAmelCase          =	line.strip().split()[0]
                      UpperCAmelCase          =	len(self.fairseq_tokens_to_ids )
          if str(A ) not in self.fairseq_tokens_to_ids:
                UpperCAmelCase          =	len(self.fairseq_tokens_to_ids )

          UpperCAmelCase          =	{v: k for k, v in self.fairseq_tokens_to_ids.items()}






    def __getstate__(			self ):
          UpperCAmelCase          =	self.__dict__.copy()
          UpperCAmelCase          =	None
          UpperCAmelCase          =	self.sp_model.serialized_model_proto()
          return state






    def __setstate__(			self     ,A ):
          UpperCAmelCase          =	d

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

          UpperCAmelCase          =	spm.SentencePieceProcessor(**self.sp_model_kwargs )
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto )






    def     _UpperCamelCase							(			self     ,A     ,A = None ):

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






    def     _UpperCamelCase							(			self     ,A     ,A = None     ,A = False ):

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

          if token_ids_a is None:
                return [1] + ([0] * len(A )) + [1]
          return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1]






    def     _UpperCamelCase							(			self     ,A     ,A = None ):
          UpperCAmelCase          =	[self.sep_token_id]
          UpperCAmelCase          =	[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]






    @property
    def     _UpperCamelCase							(			self ):
          return len(self.fairseq_ids_to_tokens )






    def     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	{self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )}
          vocab.update(self.added_tokens_encoder )
          return vocab






    def     _UpperCamelCase							(			self     ,A ):
          return self.sp_model.encode(A     ,out_type=A )






    def     _UpperCamelCase							(			self     ,A ):
          if token in self.fairseq_tokens_to_ids:
                return self.fairseq_tokens_to_ids[token]
          else:
                return self.unk_token_id






    def     _UpperCamelCase							(			self     ,A ):
          return self.fairseq_ids_to_tokens[index]






    def     _UpperCamelCase							(			self     ,A ):
          UpperCAmelCase          =	"""""".join(A ).replace(A     ,""" """ ).strip()
          return out_string






    def     _UpperCamelCase							(			self     ,A     ,A = None ):
          if not os.path.isdir(A ):
                logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
                return
          UpperCAmelCase          =	os.path.join(
              A     ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
          UpperCAmelCase          =	os.path.join(
              A     ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""monolingual_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:
                      UpperCAmelCase          =	self.sp_model.serialized_model_proto()
                      fi.write(A )

          if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath(
              A ) and os.path.isfile(self.monolingual_vocab_file ):
                copyfile(self.monolingual_vocab_file     ,A )
          elif not os.path.isfile(self.monolingual_vocab_file ):
                with open(A     ,"""w"""     ,encoding="""utf-8""" ) as fp:
                      for token in self.fairseq_tokens_to_ids:
                            if token not in self.all_special_tokens:
                                  fp.write(F'''{str(A )} \n''' )

          return out_vocab_file, out_monolingual_vocab_file



