codingutf8 2021 tel aviv university allenai and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license fast tokenization classes for splinter import json from typing import list optional tuple from tokenizers import normalizers from tokenizationutilsfast import pretrainedtokenizerfast from utils import logging from tokenizationsplinter import splintertokenizer logger logging getloggername vocabfilesnames vocabfile vocab txt pretrainedvocabfilesmap vocabfile tausplinterbase https huggingface cotausplinterbaseresolvemainvocab txt tausplinterbaseqass https huggingface cotausplinterbaseqassresolvemainvocab txt tausplinterlarge https huggingface cotausplinterlargeresolvemainvocab txt tausplinterlargeqass https huggingface cotausplinterlargeqassresolvemainvocab txt pretrainedpositionalembeddingssizes tausplinterbase 512 tausplinterbaseqass 512 tausplinterlarge 512 tausplinterlargeqass 512 pretrainedinitconfiguration tausplinterbase dolowercase false tausplinterbaseqass dolowercase false tausplinterlarge dolowercase false tausplinterlargeqass dolowercase false class splintertokenizerfastpretrainedtokenizerfast r construct a fast splinter tokenizer backed by huggingface s tokenizers library based on wordpiece this tokenizer inherits from pretrainedtokenizerfast which contains most of the main methods users should refer to this superclass for more information regarding those methods args vocabfile str file containing the vocabulary dolowercase bool optional defaults to true whether or not to lowercase the input when tokenizing unktoken str optional defaults to unk the unknown token a token that is not in the vocabulary cannot be converted to an id and is set to be this token instead septoken str optional defaults to sep the separator token which is used when building a sequence from multiple sequences e g two sequences for sequence classification or for a text and a question for question answering it is also used as the last token of a sequence built with special tokens padtoken str optional defaults to pad the token used for padding for example when batching sequences of different lengths clstoken str optional defaults to cls the classifier token which is used when doing sequence classification classification of the whole sequence instead of pertoken classification it is the first token of the sequence when built with special tokens masktoken str optional defaults to mask the token used for masking values this is the token used when training this model with masked language modeling this is the token which the model will try to predict questiontoken str optional defaults to question the token used for constructing question representations cleantext bool optional defaults to true whether or not to clean the text before tokenization by removing any control characters and replacing all whitespaces by the classic one tokenizechinesechars bool optional defaults to true whether or not to tokenize chinese characters this should likely be deactivated for japanese see this issuehttps github comhuggingfacetransformersissues328 stripaccents bool optional whether or not to strip all accents if this option is not specified then it will be determined by the value for lowercase as in the original bert wordpiecesprefix str optional defaults to the prefix for subwords optionalint id of the question token in the vocabulary used to condition the answer on a question representation build model inputs from a pair of sequence for question answering tasks by concatenating and adding special tokens a splinter sequence has the following format single sequence cls x sep pair of sequences for question answering cls questiontokens question sep contexttokens sep args tokenids0 listint the question token ids if padonright else context tokens ids tokenids1 listint optional the context token ids if padonright else question token ids returns listint list of input ids glossaryinputids with the appropriate special tokens input is questionthencontext input is contextthenquestion create the token type ids corresponding to the sequences passed what are token type ids glossarytokentypeids should be overridden in a subclass if the model has a special way of building those args tokenids0 listint the first tokenized sequence tokenids1 listint optional the second tokenized sequence returns listint the token type ids input is questionthencontext input is contextthenquestion coding utf 8 2021 tel aviv university allenai and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license fast tokenization classes for splinter construct a fast splinter tokenizer backed by huggingface s tokenizers library based on wordpiece this tokenizer inherits from pretrainedtokenizerfast which contains most of the main methods users should refer to this superclass for more information regarding those methods args vocab_file str file containing the vocabulary do_lower_case bool optional defaults to true whether or not to lowercase the input when tokenizing unk_token str optional defaults to unk the unknown token a token that is not in the vocabulary cannot be converted to an id and is set to be this token instead sep_token str optional defaults to sep the separator token which is used when building a sequence from multiple sequences e g two sequences for sequence classification or for a text and a question for question answering it is also used as the last token of a sequence built with special tokens pad_token str optional defaults to pad the token used for padding for example when batching sequences of different lengths cls_token str optional defaults to cls the classifier token which is used when doing sequence classification classification of the whole sequence instead of per token classification it is the first token of the sequence when built with special tokens mask_token str optional defaults to mask the token used for masking values this is the token used when training this model with masked language modeling this is the token which the model will try to predict question_token str optional defaults to question the token used for constructing question representations clean_text bool optional defaults to true whether or not to clean the text before tokenization by removing any control characters and replacing all whitespaces by the classic one tokenize_chinese_chars bool optional defaults to true whether or not to tokenize chinese characters this should likely be deactivated for japanese see this issue https github com huggingface transformers issues 328 strip_accents bool optional whether or not to strip all accents if this option is not specified then it will be determined by the value for lowercase as in the original bert wordpieces_prefix str optional defaults to the prefix for subwords optional int id of the question token in the vocabulary used to condition the answer on a question representation build model inputs from a pair of sequence for question answering tasks by concatenating and adding special tokens a splinter sequence has the following format single sequence cls x sep pair of sequences for question answering cls question_tokens question sep context_tokens sep args token_ids_0 list int the question token ids if pad_on_right else context tokens ids token_ids_1 list int optional the context token ids if pad_on_right else question token ids returns list int list of input ids glossary input ids with the appropriate special tokens input is question then context input is context then question create the token type ids corresponding to the sequences passed what are token type ids glossary token type ids should be overridden in a subclass if the model has a special way of building those args token_ids_0 list int the first tokenized sequence token_ids_1 list int optional the second tokenized sequence returns list int the token type ids input is question then context input is context then question
import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_splinter import SplinterTokenizer


logger = logging.get_logger(__name__)

VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}

PRETRAINED_VOCAB_FILES_MAP = {
    "vocab_file": {
        "tau/splinter-base": "https://huggingface.co/tau/splinter-base/resolve/main/vocab.txt",
        "tau/splinter-base-qass": "https://huggingface.co/tau/splinter-base-qass/resolve/main/vocab.txt",
        "tau/splinter-large": "https://huggingface.co/tau/splinter-large/resolve/main/vocab.txt",
        "tau/splinter-large-qass": "https://huggingface.co/tau/splinter-large-qass/resolve/main/vocab.txt",
    }
}

PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
    "tau/splinter-base": 512,
    "tau/splinter-base-qass": 512,
    "tau/splinter-large": 512,
    "tau/splinter-large-qass": 512,
}

PRETRAINED_INIT_CONFIGURATION = {
    "tau/splinter-base": {"do_lower_case": False},
    "tau/splinter-base-qass": {"do_lower_case": False},
    "tau/splinter-large": {"do_lower_case": False},
    "tau/splinter-large-qass": {"do_lower_case": False},
}


class SplinterTokenizerFast(PreTrainedTokenizerFast):
    r

    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    slow_tokenizer_class = SplinterTokenizer

    def __init__(
        self,
        vocab_file=None,
        tokenizer_file=None,
        do_lower_case=True,
        unk_token="[UNK]",
        sep_token="[SEP]",
        pad_token="[PAD]",
        cls_token="[CLS]",
        mask_token="[MASK]",
        question_token="[QUESTION]",
        tokenize_chinese_chars=True,
        strip_accents=None,
        **kwargs,
    ):
        super().__init__(
            vocab_file,
            tokenizer_file=tokenizer_file,
            do_lower_case=do_lower_case,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            tokenize_chinese_chars=tokenize_chinese_chars,
            strip_accents=strip_accents,
            additional_special_tokens=(question_token,),
            **kwargs,
        )

        pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
        if (
            pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
            or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
        ):
            pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
            pre_tok_state["lowercase"] = do_lower_case
            pre_tok_state["strip_accents"] = strip_accents
            self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)

        self.do_lower_case = do_lower_case

    @property
    def question_token_id(self):
        
        return self.convert_tokens_to_ids(self.question_token)

    def build_inputs_with_special_tokens(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        
        if token_ids_1 is None:
            return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]

        cls = [self.cls_token_id]
        sep = [self.sep_token_id]
        question_suffix = [self.question_token_id] + [self.convert_tokens_to_ids(".")]
        if self.padding_side == "right":
            
            return cls + token_ids_0 + question_suffix + sep + token_ids_1 + sep
        else:
            
            return cls + token_ids_0 + sep + token_ids_1 + question_suffix + sep

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]
        question_suffix = [self.question_token_id] + [self.convert_tokens_to_ids(".")]
        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]

        if self.padding_side == "right":
            
            return len(cls + token_ids_0 + question_suffix + sep) * [0] + len(token_ids_1 + sep) * [1]
        else:
            
            return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + question_suffix + sep) * [1]

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        files = self._tokenizer.model.save(save_directory, name=filename_prefix)
        return tuple(files)