





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

import sentencepiece as spm

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


if is_torch_available():
     import torch


if TYPE_CHECKING:
     from transformers.pipelines.conversational import Conversation


UpperCAmelCase     :     int							=	logging.get_logger(__name__)
UpperCAmelCase     :     List[Any]							=	{"""vocab_file""": """spiece.model"""}

UpperCAmelCase     :     int							=	{
    """vocab_file""": {
        """AI-Sweden/gpt-sw3-126m""": """https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-350m""": """https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-1.6b""": """https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-6.7b""": """https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-20b""": """https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model""",
    }
}

UpperCAmelCase     :     str							=	{
    """AI-Sweden/gpt-sw3-126m""": 2048,
    """AI-Sweden/gpt-sw3-350m""": 2048,
    """AI-Sweden/gpt-sw3-1.6b""": 2048,
    """AI-Sweden/gpt-sw3-6.7b""": 2048,
    """AI-Sweden/gpt-sw3-20b""": 2048,
}







class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : int            =      VOCAB_FILES_NAMES
      _lowercase    : Optional[int]            =      PRETRAINED_VOCAB_FILES_MAP
      _lowercase    : Any            =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _lowercase    : List[str]            =      ["""input_ids""", """attention_mask"""]







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__=False		,				lowerCAmelCase__=False		,				lowerCAmelCase__=False		,				lowerCAmelCase__=None		,				lowerCAmelCase__=None		,				lowerCAmelCase__=None		,				lowerCAmelCase__=None		,				lowerCAmelCase__ = None		,				**lowerCAmelCase__		,				)       ->						None:



        '''simple docstring'''




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

        a__     : Any  =kwargs.get("name_or_path"							)
        if name_or_path is None:
          logger.warning(
              "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"
              " you are testing the model, this can safely be ignored"							)
          a__     : int  ="None"

        # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
        a__     : Dict  ="<|endoftext|>" if eos_token is None else eos_token
        a__     : Any  ="<unk>" if unk_token is None else unk_token
        if "gpt-sw3-7b" in name_or_path:
          a__     : Optional[int]  =unk_token if pad_token is None else pad_token
          a__     : List[str]  =eos_token if bos_token is None else bos_token
        else:
          a__     : Optional[int]  ="<pad>" if pad_token is None else pad_token
          a__     : Any  ="<s>" if bos_token is None else bos_token

        super().__init__(
            do_lower_case=lowerCAmelCase__		,				remove_space=lowerCAmelCase__		,				keep_accents=lowerCAmelCase__		,				bos_token=lowerCAmelCase__		,				eos_token=lowerCAmelCase__		,				unk_token=lowerCAmelCase__		,				pad_token=lowerCAmelCase__		,				sp_model_kwargs=self.sp_model_kwargs		,				**lowerCAmelCase__		,				)

        a__     : List[str]  =do_lower_case
        a__     : Union[str, Any]  =remove_space
        a__     : Union[str, Any]  =keep_accents
        a__     : int  =vocab_file

        a__     : Any  =spm.SentencePieceProcessor(**self.sp_model_kwargs							)
        self.sp_model.Load(lowerCAmelCase__							)

        # Used for whitespace normalization in input texts
        # fmt : off
        a__     : List[Any]  ={" ", " ", " ", " ", " ", "　", " ", " ", " ", " ", "￼", ""}
        # fmt : on

        # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
        a__     : Optional[Any]  =re.compile(
            F'''[{"".join(map(lowerCAmelCase__		,				list(range(0		,				9							)							) + list(range(1_1		,				3_2							)							) + list(range(1_2_7		,				1_6_0							)							) + [1_6_0, 1_7_3, 8_2_0_3]							)							)}]'''							)







      def __getstate__(   self							)       ->						str:



        '''simple docstring'''




        a__     : Dict  =self.__dict__.copy()
        a__     : Optional[int]  =None
        return state







      def __setstate__(   self		,				lowerCAmelCase__							)       ->						Optional[Any]:



        '''simple docstring'''




        a__     : List[Any]  =d

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

        a__     : Any  =spm.SentencePieceProcessor(**self.sp_model_kwargs							)
        self.sp_model.Load(self.vocab_file							)







      @property
      # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
      def        _lowercase  (   self							)       ->						int:



        '''simple docstring'''




        return len(self.sp_model							)







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        a__     : List[str]  =self.non_printing_characters_re.sub(""		,				lowerCAmelCase__							)

        # Normalize whitespaces
        a__     : Optional[int]  ="".join([char if char not in self.whitespaces else " " for char in text]							)

        # NFC Unicode normalization
        a__     : Optional[Any]  =unicodedata.normalize("NFC"		,				lowerCAmelCase__							)
        return text







      def        _lowercase  (   self		,				lowerCAmelCase__		,				**lowerCAmelCase__							)       ->						List[str]:



        '''simple docstring'''




        a__     : Dict  =self.preprocess_text(lowerCAmelCase__							)
        return self.sp_model.encode(lowerCAmelCase__		,				out_type=lowerCAmelCase__							)







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						int:



        '''simple docstring'''




        return self.sp_model.PieceToId(lowerCAmelCase__							)







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        return self.sp_model.IdToPiece(lowerCAmelCase__							)







      @staticmethod
      def        _lowercase  (   lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        return out_string







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        a__     : int  =[]
        a__     : List[Any]  =""
        a__     : Tuple  =False
        for token in tokens:
          # make sure that special tokens are not decoded using sentencepiece model
          if token in self.all_special_tokens:
            # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
            if not prev_is_special:
              out_string += " "

            out_string += self.sp_model.decode(lowerCAmelCase__							) + token
            a__     : Tuple  =True
            a__     : Any  =[]
          else:
            current_sub_tokens.append(lowerCAmelCase__							)
            a__     : List[str]  =False
        out_string += self.sp_model.decode(lowerCAmelCase__							)

        return out_string







      def        _lowercase  (   self							)       ->						Dict[str, int]:



        '''simple docstring'''




        a__     : List[str]  ={self.convert_ids_to_tokens(lowerCAmelCase__							): i for i in range(self.vocab_size							)}
        vocab.update(self.added_tokens_encoder							)
        return vocab







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__ = None							)       ->						Tuple[str]:



        '''simple docstring'''




        if not os.path.isdir(lowerCAmelCase__							):
          logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''							)
          return
        a__     : List[Any]  =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:
            a__     : List[str]  =self.sp_model.serialized_model_proto()
            fi.write(lowerCAmelCase__							)

        return (out_vocab_file,)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__ = False							)       ->						Union[List[int], List[List[int]], "torch.Tensor"]:



        '''simple docstring'''




        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : Tuple  =self.preprocess_text(lowerCAmelCase__							)
          a__     : str  =self.sp_model.encode(lowerCAmelCase__							)
        else:
          a__     : List[str]  =[self.preprocess_text(lowerCAmelCase__							) for t in text]
          a__     : int  =self.sp_model.encode(lowerCAmelCase__							)

        if return_tensors is True or return_tensors == "pt":
          a__     : Optional[int]  =torch.tensor(lowerCAmelCase__							)

        return token_ids







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        return self.sp_model.decode(lowerCAmelCase__							)







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						List[int]:



        '''simple docstring'''




        a__     : Tuple  =[F'''User: {text}''' if is_user else F'''Bot: {text}''' for is_user, text in conversation.iter_texts()]
        a__     : Tuple  =(
            F'''{self.eos_token}{self.bos_token}''' + F'''{self.bos_token}'''.join(lowerCAmelCase__							) + F'''{self.bos_token}Bot:'''
        )
        return self.encode(text=lowerCAmelCase__							)













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     :     Tuple							=	logging.get_logger(__name__)

UpperCAmelCase     :     List[Any]							=	list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase     :     Dict							=	tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class     __lowerCAmelCase	:
      _lowercase    : str            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """Model type selected in the list: """ + """, """.join(UpperCamelCase__)})
      _lowercase    : str            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""})
      _lowercase    : int            =      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."""
              )
          }						,    )
      _lowercase    : int            =      field(
          default=128						,    metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}						,    )
      _lowercase    : int            =      field(
          default=64						,    metadata={
              """help""": (
                  """The maximum number of tokens for the question. Questions longer than this will """
                  """be truncated to this length."""
              )
          }						,    )
      _lowercase    : int            =      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."""
              )
          }						,    )
      _lowercase    : bool            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """Overwrite the cached training and evaluation sets"""})
      _lowercase    : bool            =      field(
          default=UpperCamelCase__						,    metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""})
      _lowercase    : float            =      field(
          default=0.0						,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""})
      _lowercase    : int            =      field(
          default=20						,    metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""})
      _lowercase    : int            =      field(
          default=0						,    metadata={
              """help""": (
                  """language id of input for language-specific xlm models (see"""
                  """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
              )
          }						,    )
      _lowercase    : int            =      field(default=1						,    metadata={"""help""": """multiple threads for converting example to features"""})







class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : List[Any]            =      """train"""
      _lowercase    : Any            =      """dev"""







class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : SquadDataTrainingArguments
      _lowercase    : List[SquadFeatures]
      _lowercase    : Split
      _lowercase    : bool







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = Split.train		,				lowerCAmelCase__ = False		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = "pt"		,				)       ->						str:



        '''simple docstring'''




        a__     : List[Any]  =args
        a__     : int  =is_language_sensitive
        a__     : List[str]  =SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          try:
            a__     : str  =Split[mode]
          except KeyError:
            raise KeyError("mode is not a valid split name"							)
        a__     : Any  =mode
        # Load data features from cache or dataset file
        a__     : str  ="v2" if args.version_2_with_negative else "v1"
        a__     : str  =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.
        a__     : Dict  =cached_features_file + ".lock"
        with FileLock(lowerCAmelCase__							):
          if os.path.exists(lowerCAmelCase__							) and not args.overwrite_cache:
            a__     : Any  =time.time()
            a__     : List[Any]  =torch.load(lowerCAmelCase__							)

            # Legacy cache files have only features, while new cache files
            # will have dataset and examples also.
            a__     : str  =self.old_features["features"]
            a__     : str  =self.old_features.get("dataset"		,				lowerCAmelCase__							)
            a__     : Optional[int]  =self.old_features.get("examples"		,				lowerCAmelCase__							)
            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:
              a__     : Dict  =self.processor.get_dev_examples(args.data_dir							)
            else:
              a__     : str  =self.processor.get_train_examples(args.data_dir							)

            a__ ,							a__     : Union[str, Any]  =squad_convert_examples_to_features(
                examples=self.examples		,				tokenizer=lowerCAmelCase__		,				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=lowerCAmelCase__		,				)

            a__     : Any  =time.time()
            torch.save(
                {"features": self.features, "dataset": self.dataset, "examples": self.examples}		,				lowerCAmelCase__		,				)
            # ^ 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							)       ->						Tuple:



        '''simple docstring'''




        return len(self.features							)







      def __getitem__(   self		,				lowerCAmelCase__							)       ->						Dict[str, torch.Tensor]:



        '''simple docstring'''




        a__     : str  =self.features[i]

        a__     : Optional[Any]  =torch.tensor(feature.input_ids		,				dtype=torch.long							)
        a__     : List[Any]  =torch.tensor(feature.attention_mask		,				dtype=torch.long							)
        a__     : int  =torch.tensor(feature.token_type_ids		,				dtype=torch.long							)
        a__     : List[str]  =torch.tensor(feature.cls_index		,				dtype=torch.long							)
        a__     : int  =torch.tensor(feature.p_mask		,				dtype=torch.float							)
        a__     : Tuple  =torch.tensor(feature.is_impossible		,				dtype=torch.float							)

        a__     : Tuple  ={
            "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:
          a__     : int  =torch.tensor(feature.start_position		,				dtype=torch.long							)
          a__     : Any  =torch.tensor(feature.end_position		,				dtype=torch.long							)
          inputs.update({"start_positions": start_positions, "end_positions": end_positions}							)

        return inputs






