U
    ,-eM                    @   s@  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZ ddlZddlZddlmZ ddlmZmZmZmZmZmZmZmZmZmZ dd	lm Z m!Z!m"Z"m#Z# e#$e%Z&ee'e'f Z(e
e( Z)e*Z+e
e+ Z,d
dddZ-ddddddddddZ.dddZ/dZ0e dd Z1dd Z2G dd deZ3dS )zTokenization classes for LUKE.    N)Mapping)	lru_cache)DictListOptionalTupleUnion   )PreTrainedTokenizer)
ENCODE_KWARGS_DOCSTRING
AddedTokenBatchEncodingEncodedInputPaddingStrategy
TensorType	TextInputTextInputPairTruncationStrategy	to_py_obj)add_end_docstringsis_tf_tensoris_torch_tensorloggingz
vocab.jsonz
merges.txtzentity_vocab.json)
vocab_filemerges_fileentity_vocab_filezEhttps://huggingface.co/studio-ousia/luke-base/resolve/main/vocab.jsonzFhttps://huggingface.co/studio-ousia/luke-large/resolve/main/vocab.json)zstudio-ousia/luke-basezstudio-ousia/luke-largezEhttps://huggingface.co/studio-ousia/luke-base/resolve/main/merges.txtzFhttps://huggingface.co/studio-ousia/luke-large/resolve/main/merges.txtzLhttps://huggingface.co/studio-ousia/luke-base/resolve/main/entity_vocab.jsonzMhttps://huggingface.co/studio-ousia/luke-large/resolve/main/entity_vocab.jsoni   av  
            return_token_type_ids (`bool`, *optional*):
                Whether to return token type IDs. If left to the default, will return the token type IDs according to
                the specific tokenizer's default, defined by the `return_outputs` attribute.

                [What are token type IDs?](../glossary#token-type-ids)
            return_attention_mask (`bool`, *optional*):
                Whether to return the attention mask. If left to the default, will return the attention mask according
                to the specific tokenizer's default, defined by the `return_outputs` attribute.

                [What are attention masks?](../glossary#attention-mask)
            return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
                of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
                of returning overflowing tokens.
            return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
                Whether or not to return special tokens mask information.
            return_offsets_mapping (`bool`, *optional*, defaults to `False`):
                Whether or not to return `(char_start, char_end)` for each token.

                This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
                Python's tokenizer, this method will raise `NotImplementedError`.
            return_length  (`bool`, *optional*, defaults to `False`):
                Whether or not to return the lengths of the encoded inputs.
            verbose (`bool`, *optional*, defaults to `True`):
                Whether or not to print more information and warnings.
            **kwargs: passed to the `self.tokenize()` method

        Return:
            [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:

            - **input_ids** -- List of token ids to be fed to a model.

              [What are input IDs?](../glossary#input-ids)

            - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
              if *"token_type_ids"* is in `self.model_input_names`).

              [What are token type IDs?](../glossary#token-type-ids)

            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).

              [What are attention masks?](../glossary#attention-mask)

            - **entity_ids** -- List of entity ids to be fed to a model.

              [What are input IDs?](../glossary#input-ids)

            - **entity_position_ids** -- List of entity positions in the input sequence to be fed to a model.

            - **entity_token_type_ids** -- List of entity token type ids to be fed to a model (when
              `return_token_type_ids=True` or if *"entity_token_type_ids"* is in `self.model_input_names`).

              [What are token type IDs?](../glossary#token-type-ids)

            - **entity_attention_mask** -- List of indices specifying which entities should be attended to by the model
              (when `return_attention_mask=True` or if *"entity_attention_mask"* is in `self.model_input_names`).

              [What are attention masks?](../glossary#attention-mask)

            - **entity_start_positions** -- List of the start positions of entities in the word token sequence (when
              `task="entity_span_classification"`).
            - **entity_end_positions** -- List of the end positions of entities in the word token sequence (when
              `task="entity_span_classification"`).
            - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
              `return_overflowing_tokens=True`).
            - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
              `return_overflowing_tokens=True`).
            - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
              regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
            - **length** -- The length of the inputs (when `return_length=True`)

c                  C   s   t ttdtdd t ttdtdd  t ttdtdd  } | dd }d	}td
D ],}|| krf| | |d
|  |d7 }qfdd |D }tt| |S )a8  
    Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
    characters the bpe code barfs on.

    The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
    if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
    decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
    tables between utf-8 bytes and unicode strings.
    !~      ¡   ¬   ®   ÿNr      c                 S   s   g | ]}t |qS  )chr).0nr$   r$   k/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/luke/tokenization_luke.py
<listcomp>   s     z$bytes_to_unicode.<locals>.<listcomp>)listrangeordappenddictzip)bscsr'   br$   r$   r(   bytes_to_unicode   s    L

r3   c                 C   s6   t  }| d }| dd D ]}|||f |}q|S )z
    Return set of symbol pairs in a word.

    Word is represented as tuple of symbols (symbols being variable-length strings).
    r   r   N)setadd)wordpairsZ	prev_charcharr$   r$   r(   	get_pairs   s    r9   c                       s  e Zd ZdZeZeZeZ	ddgZ
dN fdd	Zedd Zdd Zdd Zdd Zdd Zd d! Zd"d# ZdOee eee  ee d$d%d&ZdPee eee  eee d' fd(d)ZdQee eee  ee d$d*d+ZdRd,d-ZeeedSee ee  f eee ee  f  eee!ee! f  eee!ee! f  eee"ee" f  eee"ee" f  eeee#e$f eee#e%f ee ee eee ee eee#e&f  ee ee eeeeee'd0d1d2Z(dddddd.e$j)e%j*ddd/dddddddddd.fee  eee   ee! ee! ee" ee" ee$e%ee ee eee ee eee#e&f  ee ee eeeeee'd3d4d5Z+ddd.e$j)e%j*ddd/dddddddddd.feee  ee, f eeee! ee-e!e!f  f  eeee" ee-e"e"f  f  ee$e%ee ee eee ee eee#e&f  ee ee eeeeee'd6d7d8Z.ee" ee! d9d:d;Z/dTee  eee   ee" ee" ee! ee! e-e0e0e0e0e0e0f d<d=d>Z1eeed.e$j)e%j*ddd/dddddddd.fee-ee df  ee-eee  eee  f  ee-eee-eef   eee-eef   f  ee$e%ee ee eee ee# ee ee eeeee'd?d@dAZ2eeedUee eee  eee  eee  eee-eef   eee-eef   eeee#e$f eee#e%f ee ee eee eee#e&f  ee ee eeeeeee'dBdCdDZ3dVee'ee' e4e#e5f e4e#ee5 f ee4e#e5f  f eee#e$f ee ee ee ee eee#e&f  ee'dE	dFdGZ6dde$j)ddfee4e#e5f e'f ee ee e$ee ee e7dHdIdJZ8dWe#ee# e-e# dKdLdMZ9  Z:S )XLukeTokenizera"  
    Constructs a LUKE tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.

    This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
    be encoded differently whether it is at the beginning of the sentence (without space) or not:

    ```python
    >>> from transformers import LukeTokenizer

    >>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base")
    >>> tokenizer("Hello world")["input_ids"]
    [0, 31414, 232, 2]

    >>> tokenizer(" Hello world")["input_ids"]
    [0, 20920, 232, 2]
    ```

    You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
    call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

    <Tip>

    When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).

    </Tip>

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    this superclass for more information regarding those methods. It also creates entity sequences, namely
    `entity_ids`, `entity_attention_mask`, `entity_token_type_ids`, and `entity_position_ids` to be used by the LUKE
    model.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        entity_vocab_file (`str`):
            Path to the entity vocabulary file.
        task (`str`, *optional*):
            Task for which you want to prepare sequences. One of `"entity_classification"`,
            `"entity_pair_classification"`, or `"entity_span_classification"`. If you specify this argument, the entity
            sequence is automatically created based on the given entity span(s).
        max_entity_length (`int`, *optional*, defaults to 32):
            The maximum length of `entity_ids`.
        max_mention_length (`int`, *optional*, defaults to 30):
            The maximum number of tokens inside an entity span.
        entity_token_1 (`str`, *optional*, defaults to `<ent>`):
            The special token used to represent an entity span in a word token sequence. This token is only used when
            `task` is set to `"entity_classification"` or `"entity_pair_classification"`.
        entity_token_2 (`str`, *optional*, defaults to `<ent2>`):
            The special token used to represent an entity span in a word token sequence. This token is only used when
            `task` is set to `"entity_pair_classification"`.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_token`.

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            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.
        cls_token (`str`, *optional*, defaults to `"<s>"`):
            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.
        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.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
        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.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word. (LUKE tokenizer detect beginning of words by the preceding space).
    	input_idsattention_maskN       <ent><ent2>[UNK][PAD][MASK][MASK2]replace<s></s><unk><pad><mask>Fc                    s  t |trt|dddn|}t |tr4t|dddn|}t |trPt|dddn|}t |trlt|dddn|}t |trt|dddn|}t |trt|dddn|}t |trt|dddn|}t|dd}t|| _W 5 Q R X dd | j D | _|| _	t
 | _dd | j D | _t|dd}| d	d
d }W 5 Q R X dd |D }tt|tt|| _i | _|| _td| _t |trt|dddn|}t |trt|dddn|}|dg |d< |d  ||g7  < t|dd}t|| _W 5 Q R X |	|
||fD ](}|| jkrtd| d| dq| j|	 | _| j|
 | _| j| | _| j| | _|| _ |d ks|dkr|| _!n4|dkrd
| _!n"|dkrd| _!ntd| d|| _"t# j$f ||||||||||dddd|	|
||d| d S )NF)lstriprstripTutf-8encodingc                 S   s   i | ]\}}||qS r$   r$   r&   kvr$   r$   r(   
<dictcomp>K  s      z*LukeTokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r$   r$   rP   r$   r$   r(   rS   N  s      
r   c                 S   s   g | ]}t | qS r$   )tuplesplit)r&   merger$   r$   r(   r)   Q  s     z*LukeTokenizer.__init__.<locals>.<listcomp>zJ's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+Zadditional_special_tokensz!Specified entity special token ``zT`` is not found in entity_vocab. Probably an incorrect entity vocab file is loaded: .entity_span_classificationentity_classificationentity_pair_classification   Task z| not supported. Select task from ['entity_classification', 'entity_pair_classification', 'entity_span_classification'] only.r=   r>   r?   r@   )errors	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenadd_prefix_spacetaskmax_entity_lengthmax_mention_lengthentity_token_1entity_token_2entity_unk_tokenentity_pad_tokenentity_mask_tokenentity_mask2_token)%
isinstancestrr   openjsonloadencoderitemsdecoderr_   r3   byte_encoderbyte_decoderreadrW   r.   r/   r+   len	bpe_rankscacherg   recompilepatgetentity_vocab
ValueErrorentity_unk_token_identity_pad_token_identity_mask_token_identity_mask2_token_idrh   ri   rj   super__init__)selfr   r   r   rh   ri   rj   rk   rl   rm   rn   ro   rp   r_   r`   ra   rc   rd   rb   re   rf   rg   kwargsZvocab_handleZmerges_handleZ
bpe_mergesZentity_vocab_handleZentity_special_token	__class__r$   r(   r   &  s     


zLukeTokenizer.__init__c                 C   s
   t | jS N)r|   rv   r   r$   r$   r(   
vocab_size  s    zLukeTokenizer.vocab_sizec                 C   s   t | j }|| j |S r   )r.   rv   copyupdateZadded_tokens_encoder)r   Zvocabr$   r$   r(   	get_vocab  s    zLukeTokenizer.get_vocabc           
         sd  | j kr j | S t|}t|}|s,|S t| fddd}| jkrNqL|\}}g }d}|t|k r"z|||}	W n, tk
r   |||d   Y q"Y nX ||||	  |	}|| |kr
|t|d k r
||d  |kr
|	||  |d7 }q^|	||  |d7 }q^t|}|}t|dkrBqLq,t|}q,d
|}| j |< |S )Nc                    s    j | tdS )Ninf)r}   r   floatpairr   r$   r(   <lambda>      z#LukeTokenizer.bpe.<locals>.<lambda>keyr   r   r]    )r~   rV   r9   minr}   r|   indexr   extendr-   join)
r   tokenr6   r7   ZbigramfirstsecondZnew_wordijr$   r   r(   bpe  sB    


2




zLukeTokenizer.bpec                    sZ   g }t  j|D ]B}d fdd|dD }|dd  |dD  q|S )zTokenize a string. c                 3   s   | ]} j | V  qd S r   )ry   )r&   r2   r   r$   r(   	<genexpr>  s    z*LukeTokenizer._tokenize.<locals>.<genexpr>rM   c                 s   s   | ]
}|V  qd S r   r$   )r&   Z	bpe_tokenr$   r$   r(   r     s     r   )r   findallr   r   encoder   r   rW   )r   text
bpe_tokensr   r$   r   r(   	_tokenize  s    "zLukeTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)rv   r   rb   )r   r   r$   r$   r(   _convert_token_to_id  s    z"LukeTokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)rx   r   )r   r   r$   r$   r(   _convert_id_to_token  s    z"LukeTokenizer._convert_id_to_tokenc                    s0   d |}t fdd|D jd jd}|S )z:Converts a sequence of tokens (string) in a single string.r   c                    s   g | ]} j | qS r$   )rz   )r&   cr   r$   r(   r)     s     z:LukeTokenizer.convert_tokens_to_string.<locals>.<listcomp>rM   )r_   )r   	bytearraydecoder_   )r   tokensr   r$   r   r(   convert_tokens_to_string  s    
"z&LukeTokenizer.convert_tokens_to_string)token_ids_0token_ids_1returnc                 C   sD   |dkr| j g| | jg S | j g}| jg}|| | | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A LUKE sequence has the following format:

        - single sequence: `<s> X </s>`
        - pair of sequences: `<s> A </s></s> B </s>`

        Args:
            token_ids_0 (`List[int]`):
                List of IDs to which the special tokens will be added.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        N)cls_token_idsep_token_id)r   r   r   clssepr$   r$   r(    build_inputs_with_special_tokens  s
    z.LukeTokenizer.build_inputs_with_special_tokens)r   r   already_has_special_tokensr   c                    sh   |rt  j||ddS |dkr8dgdgt|  dg S dgdgt|  ddg dgt|  dg S )a  
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        T)r   r   r   Nr   r   )r   get_special_tokens_maskr|   )r   r   r   r   r   r$   r(   r     s      z%LukeTokenizer.get_special_tokens_maskc                 C   sP   | j g}| jg}|dkr.t|| | dg S t|| | | | | dg S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. LUKE does not
        make use of token type ids, therefore a list of zeros is returned.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of zeros.
        Nr   )r   r   r|   )r   r   r   r   r   r$   r$   r(   $create_token_type_ids_from_sequences#  s
    z2LukeTokenizer.create_token_type_ids_from_sequencesc                 K   s>   | d| j}|s|r6t|dkr6|d  s6d| }||fS )Nrg   r   r   )poprg   r|   isspace)r   r   is_split_into_wordsr   rg   r$   r$   r(   prepare_for_tokenization;  s     z&LukeTokenizer.prepare_for_tokenizationTr   )r   	text_pairentity_spansentity_spans_pairentitiesentities_pairadd_special_tokenspadding
truncation
max_lengthri   strider   pad_to_multiple_ofreturn_tensorsreturn_token_type_idsreturn_attention_maskreturn_overflowing_tokensreturn_special_tokens_maskreturn_offsets_mappingreturn_lengthverboser   c                  K   s  t |t}t |ttfo0t|dkp0t |d t}|sB|sBtdt |t}t |ttfort|dkprt |d t}|dks|s|stdtt |ttf}|rH|dk	rtt||n|}|dkrd}n|dk	rtt||n|}|dkrd}n|dk	rtt||n|}| jf ||||||	|
||||||||||||d|S | j	f |||||||||	|
||||||||||||d|S dS )a  
        Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
        sequences, depending on the task you want to prepare them for.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
                tokenizer does not support tokenization based on pretokenized strings.
            text_pair (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
                tokenizer does not support tokenization based on pretokenized strings.
            entity_spans (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
                The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
                with two integers denoting character-based start and end positions of entities. If you specify
                `"entity_classification"` or `"entity_pair_classification"` as the `task` argument in the constructor,
                the length of each sequence must be 1 or 2, respectively. If you specify `entities`, the length of each
                sequence must be equal to the length of each sequence of `entities`.
            entity_spans_pair (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
                The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
                with two integers denoting character-based start and end positions of entities. If you specify the
                `task` argument in the constructor, this argument is ignored. If you specify `entities_pair`, the
                length of each sequence must be equal to the length of each sequence of `entities_pair`.
            entities (`List[str]`, `List[List[str]]`, *optional*):
                The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
                representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
                Angeles). This argument is ignored if you specify the `task` argument in the constructor. The length of
                each sequence must be equal to the length of each sequence of `entity_spans`. If you specify
                `entity_spans` without specifying this argument, the entity sequence or the batch of entity sequences
                is automatically constructed by filling it with the [MASK] entity.
            entities_pair (`List[str]`, `List[List[str]]`, *optional*):
                The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
                representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
                Angeles). This argument is ignored if you specify the `task` argument in the constructor. The length of
                each sequence must be equal to the length of each sequence of `entity_spans_pair`. If you specify
                `entity_spans_pair` without specifying this argument, the entity sequence or the batch of entity
                sequences is automatically constructed by filling it with the [MASK] entity.
            max_entity_length (`int`, *optional*):
                The maximum length of `entity_ids`.
        r   zItext input must be of type `str` (single example) or `List[str]` (batch).NzNtext_pair input must be of type `str` (single example) or `List[str]` (batch).)batch_text_or_text_pairs(batch_entity_spans_or_entity_spans_pairs batch_entities_or_entities_pairsr   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   )
rq   rr   r*   rV   r|   r   boolr/   Zbatch_encode_plusZencode_plus) r   r   r   r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   r   Zis_valid_single_textZis_valid_batch_textZis_valid_single_text_pairZis_valid_batch_text_pairZ
is_batchedr   r   r   r$   r$   r(   __call__A  s    C
(
zLukeTokenizer.__call__)r   r   r   r   r   r   r   padding_strategytruncation_strategyr   ri   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sz   |rt d|rt d| jf ||||||d|\}}}}}}| j||||||||j|	j|
||||d||||||dS )Na  return_offset_mapping is not available when using Python tokenizers. To use this feature, change your tokenizer to one deriving from transformers.PreTrainedTokenizerFast. More information on available tokenizers at https://github.com/huggingface/transformers/pull/26747is_split_into_words is not supported in this tokenizer.r   r   r   r   r   r   T)pair_ids
entity_idspair_entity_idsentity_token_spanspair_entity_token_spansr   r   r   r   ri   r   r   r   prepend_batch_axisr   r   r   r   r   r   )NotImplementedError_create_input_sequenceprepare_for_modelvalue)r   r   r   r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   r   	first_ids
second_idsfirst_entity_idssecond_entity_idsfirst_entity_token_spanssecond_entity_token_spansr$   r$   r(   _encode_plus  s\    	zLukeTokenizer._encode_plus)r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   r   c           )      K   sf  |rt d|
rt dg }g }g }t|D ]\}}t|ttfsP|d  }}n|\}}d\}}|d k	r|| }|rt|d tr|d  }}n|\}}d\}} |d k	r|| }!t|!dkrt|!d tr|!\}} n
|!d  }} | jf |||||| d|\}"}#}$}%}&}'||"|#f ||$|%f ||&|'f q,| j	|||||||||	||||||||d}(t
|(S )Nzreturn_offset_mapping is not available when using Python tokenizers. To use this feature, change your tokenizer to one deriving from transformers.PreTrainedTokenizerFast.r   NNr   r   )batch_entity_ids_pairsbatch_entity_token_spans_pairsr   r   r   r   ri   r   r   r   r   r   r   r   r   r   )r   	enumeraterq   r*   rV   rr   r|   r   r-   _batch_prepare_for_modelr   ))r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   r   r;   r   r   r   Ztext_or_text_pairr   r   r   r   Zentities_or_entities_pairsr   r   Z"entity_spans_or_entity_spans_pairsr   r   r   r   r   r   batch_outputsr$   r$   r(   _batch_encode_plus#  s     

	
z LukeTokenizer._batch_encode_plus)r   r   c                 C   s   t |tstdn"t|dkr6t |d ts6td|d k	rt |tsPtdt|dkrrt |d tsrtdt|t|krtdd S )Nz&entity_spans should be given as a listr   z_entity_spans should be given as a list of tuples containing the start and end character indicesz7If you specify entities, they should be given as a listzGIf you specify entities, they should be given as a list of entity nameszJIf you specify entities, entities and entity_spans must be the same length)rq   r*   r   r|   rV   rr   )r   r   r   r$   r$   r(   _check_entity_input_format  s    


z(LukeTokenizer._check_entity_input_format)r   r   r   r   r   r   r   c                    s  fdd  fdd}d\}	}
d\}}d\}}j d kr|d krN |}	nF|| |||\}	}|d krjgt| }nfdd|D }|d k	r|d kr |}
nF|| |||\}
}|d krjgt| }nfdd|D }nj d	krt|tr.t|d
kr.t|d ts6tdjg}|||\}	}|d \}}|	d | jd g |	|d   }	|	d | jd g |	|d   }	||d fg}nڈj dkrt|trt|dkrt|d trt|d
 ts td|\}}jj	g}|||\}	}|\}}|jd f|jd
 fg}|d |d k r|d |d
 d f|d< |d d |d
 d f|d
< t
|}n4|d d |d
 d f|d< |d |d
 d f|d
< |D ]J\\}}}|	d | |g |	|d   }	|	d | |g |	|d   }	qnpj dkrzt|trRt|dkrRt|d tsZtd|||\}	}jgt| }ntdj  d|	|
||||fS )Nc                    s   j | f }|S r   )tokenizeZconvert_tokens_to_ids)r   r   )r   r   r$   r(   get_input_ids  s    z;LukeTokenizer._create_input_sequence.<locals>.get_input_idsc                    s   |d kr| d fS d}g }d gt | }tttj| }i  |D ]T}|}|dkrl| |d  dkrl|d8 }||kr|| || 7 }|}t | |< qD|| |d  7 } fdd|D }||fS )Nr   r   r   c                    s    g | ]\}} |  | fqS r$   r$   )r&   Z
char_startZchar_endZchar_pos2token_posr$   r(   r)     s    zfLukeTokenizer._create_input_sequence.<locals>.get_input_ids_and_entity_token_spans.<locals>.<listcomp>)r|   sorted	frozenset	itertoolschain)r   r   curr;   r   Zsplit_char_positionsZsplit_char_positionZorig_split_char_position)r   r   r(   $get_input_ids_and_entity_token_spans  s.    
zRLukeTokenizer._create_input_sequence.<locals>.get_input_ids_and_entity_token_spansr   c                    s   g | ]} j | jqS r$   r   r   r   r&   entityr   r$   r(   r)     s     z8LukeTokenizer._create_input_sequence.<locals>.<listcomp>c                    s   g | ]} j | jqS r$   r  r  r   r$   r(   r)     s    r[   r   r   zsEntity spans should be a list containing a single tuple containing the start and end character indices of an entityr]   r\   zEntity spans should be provided as a list of two tuples, each tuple containing the start and end character indices of an entity   rZ   z{Entity spans should be provided as a list of tuples, each tuple containing the start and end character indices of an entityr^   z not supported)rh   r   r   r|   rq   r*   rV   r   Zadditional_special_tokens_idsr   reversed)r   r   r   r   r   r   r   r   r  r   r   r   r   r   r   Zentity_token_startZentity_token_endZ	head_spanZ	tail_spanZhead_token_spanZtail_token_spanZ!token_span_with_special_token_idsZspecial_token_idr$   )r   r   r   r(   r     s    



 

*"




$*z$LukeTokenizer._create_input_sequence)batch_ids_pairsr   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   c                 C   s   i }t |||D ]\}}}|\}}|\}}|\}}| j|||||||tjj|j|||	dd||||dd|d}| D ]&\}}||krg ||< || | qtq| j||j||
|d}t||d}|S )a  
        Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
        adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
        manages a moving window (with user defined stride) for overflowing tokens


        Args:
            batch_ids_pairs: list of tokenized input ids or input ids pairs
            batch_entity_ids_pairs: list of entity ids or entity ids pairs
            batch_entity_token_spans_pairs: list of entity spans or entity spans pairs
            max_entity_length: The maximum length of the entity sequence.
        NF)r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   tensor_type)	r/   r   r   
DO_NOT_PADr   rw   r-   padr   )r   r  r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r;   r   Zentity_token_span_pairsr   r   r   r   r   r   outputsr   r   r$   r$   r(   r   9  sZ    "  z&LukeTokenizer._batch_prepare_for_model)idsr   r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   r   c           5         s  | j f ||	|
||d|\}}}
}tdk	}t }|rDtnd}|rX|sXtd|rv|tjkrvdk	rvtd|dkrd| jk}|dkrd| jk}i }|| |r| j|dnd }g }|tjkr|
r||
kr| j	 ||
 ||d	\ }|r||d
< ||
 |d< |r<| 
 } |  }!d}"t d }#nD|rJ  n } dgt  |rndgt ng  }!d}"t }#| |d< |r|!|d< |r|r|  |d< ndgt|  |d< |s| j}|dk	rd}$d}% fddt||D }& fdd|D }'|$t|&7 }$|%t|t|& 7 }%d\}(})|dk	rfddt||D }(fdd|D })|$t|(7 }$|%t|t|( 7 }%|%dkrt|% d |tjkr|$|kr| j	|&|(|$| ||d	\}&}(}*|'dt|& }'|)dk	r|)dt|( })|r|*|d< |$| |d< |(r*|&|( n|&}+t|+|d< g },g }-g }.|'|"f|)|#ffD ]\}/}0|/dk	rV|/D ]l\}1}2|1|07 }1|2|07 }2tt|1|2d| j }3|3dg| j|2 |1  7 }3|,|3 |-|1 |.|2d  qlqV|,|d< | jdkr|-|d< |.|d< |rdgt|d  |d< | |d |
| |tjksB|rZ| j||
||j||d }|rpt|d |d!< t|||d"}4|4S )#ah  
        Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids,
        entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing
        while taking into account the special tokens and manages a moving window (with user defined stride) for
        overflowing tokens. Please Note, for *pair_ids* different than `None` and *truncation_strategy = longest_first*
        or `True`, it is not possible to return overflowing tokens. Such a combination of arguments will raise an
        error.

        Args:
            ids (`List[int]`):
                Tokenized input ids of the first sequence.
            pair_ids (`List[int]`, *optional*):
                Tokenized input ids of the second sequence.
            entity_ids (`List[int]`, *optional*):
                Entity ids of the first sequence.
            pair_entity_ids (`List[int]`, *optional*):
                Entity ids of the second sequence.
            entity_token_spans (`List[Tuple[int, int]]`, *optional*):
                Entity spans of the first sequence.
            pair_entity_token_spans (`List[Tuple[int, int]]`, *optional*):
                Entity spans of the second sequence.
            max_entity_length (`int`, *optional*):
                The maximum length of the entity sequence.
        )r   r   r   r   r   Nr   zAsking to return token_type_ids while setting add_special_tokens to False results in an undefined behavior. Please set add_special_tokens to True or set return_token_type_ids to None.zNot possible to return overflowing tokens for pair of sequences with the `longest_first`. Please select another truncation strategy than `longest_first`, for instance `only_second` or `only_first`.token_type_idsr<   r   )r   Znum_tokens_to_remover   r   overflowing_tokensZnum_truncated_tokensr   r	   r;   special_tokens_maskc                    s$   g | ]\}}|d  t  kr|qS r   r|   r&   Zent_idspanr  r$   r(   r)     s      z3LukeTokenizer.prepare_for_model.<locals>.<listcomp>c                    s    g | ]}|d  t  kr|qS r  r  r&   r  r  r$   r(   r)     s      r   c                    s$   g | ]\}}|d  t  kr|qS r  r  r  r   r$   r(   r)     s   c                    s    g | ]}|d  t  kr|qS r  r  r  r  r$   r(   r)   $  s      zb entities are ignored because their entity spans are invalid due to the truncation of input tokensoverflowing_entitiesZnum_truncated_entitiesr   rU   entity_position_idsrZ   entity_start_positionsentity_end_positionsentity_token_type_ids)r   ri   r   r   r   length)r
  r   )"_get_padding_truncation_strategiesr   r|   r   r   ZLONGEST_FIRSTmodel_input_namesZnum_special_tokens_to_addDO_NOT_TRUNCATEZtruncate_sequencesr   r   r   ri   r/   loggerwarningr*   r+   rj   r-   rh   Z&_eventual_warn_about_too_long_sequencer   r  r  r   r   )5r   r  r   r   r   r   r   r   r   r   r   ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zlen_idsZlen_pair_idsencoded_inputsZ	total_lenr  sequencer  Zentity_token_offsetZpair_entity_token_offsetZtotal_entity_lenZnum_invalid_entitiesZvalid_entity_idsZvalid_entity_token_spansZvalid_pair_entity_idsZvalid_pair_entity_token_spansr  Zfinal_entity_idsr  r  r  Ztoken_spansoffsetstartendZposition_idsr   r$   )r  r   r(   r     s   5


&







	  zLukeTokenizer.prepare_for_model)	r$  r   r   ri   r   r   r   r   r   c	              	      s  t ttfr6t d tr6fddd  D | jd krftd| jd  dt  | jd  }	|	s|rg d< S |	d }
t |
ttfrd}t|	| dkr|d7 }q|t|	k r|	| d }
t |
tttfs|t	|
r|dkrd	n|}nZt
|
r |dkrd
n|}n<t |
tjrB|dkr<dn|}ntd|
 dt|
 d D ]\}}t||< qd| j|||d\}}}}|dkr| j}| jd  }	|	rt |	d ttfs| j|||||dt|dS t|	 t fdd D rtd|tjkrbtdd |	D }dkrXtdd d D nd}tj}i }t D ]ffdd D }| j||||||d}| D ]*\}}||krg ||< || | qqnt||dS )a  
        Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
        in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with
        `self.padding_side`, `self.pad_token_id` and `self.pad_token_type_id`) .. note:: If the `encoded_inputs` passed
        are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the result will use the same type unless
        you provide a different tensor type with `return_tensors`. In the case of PyTorch tensors, you will lose the
        specific device of your tensors however.

        Args:
            encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
                Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
                tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
                List[int]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
                collate function. Instead of `List[int]` you can have tensors (numpy arrays, PyTorch tensors or
                TensorFlow tensors), see the note above for the return type.
            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
                 Select a strategy to pad the returned sequences (according to the model's padding side and padding
                 index) among:

                - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
                  sequence if provided).
                - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
                  acceptable input length for the model if that argument is not provided.
                - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
                  lengths).
            max_length (`int`, *optional*):
                Maximum length of the returned list and optionally padding length (see above).
            max_entity_length (`int`, *optional*):
                The maximum length of the entity sequence.
            pad_to_multiple_of (`int`, *optional*):
                If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
                the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
            return_attention_mask (`bool`, *optional*):
                Whether to return the attention mask. If left to the default, will return the attention mask according
                to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention
                masks?](../glossary#attention-mask)
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
            verbose (`bool`, *optional*, defaults to `True`):
                Whether or not to print more information and warnings.
        r   c                    s    i | ]   fd dD qS )c                    s   g | ]}|  qS r$   r$   )r&   Zexampler   r$   r(   r)     s     z0LukeTokenizer.pad.<locals>.<dictcomp>.<listcomp>r$   )r&   )r$  r   r(   rS     s      z%LukeTokenizer.pad.<locals>.<dictcomp>zRYou should supply an encoding or a list of encodings to this method that includes z, but you provided r<   r   Ntfptnpztype of z
 unknown: zA. Should be one of a python, numpy, pytorch or tensorflow object.)r   r   r   )r   ri   r   r   r   r	  c                 3   s   | ]}t | kV  qd S r   r  )r&   rR   )
batch_sizer$   r(   r     s     z$LukeTokenizer.pad.<locals>.<genexpr>zLSome items in the output dictionary have a different batch size than others.c                 s   s   | ]}t |V  qd S r   r  r&   inputsr$   r$   r(   r     s     r   c                 s   s   | ]}t |V  qd S r   r  r-  r$   r$   r(   r     s     c                    s   i | ]\}}||  qS r$   r$   rP   )r   r$   r(   rS      s      )rq   r*   rV   r   keysr   r   r|   intr   r   r+  Zndarraytyperw   r   r  ri   _padr   anyvaluesr   LONGESTmaxZ
MAX_LENGTHr+   r-   )r   r$  r   r   ri   r   r   r   r   Zrequired_inputZfirst_elementr   r   r   r   _r   r.  r  r$   )r,  r$  r   r(   r  q  s    @


  
"	
zLukeTokenizer.pad)r$  r   ri   r   r   r   r   c                 C   s  t d|k}|dkrd| jk}|tjkrDt|d }|rDt|d }|dk	rp|dk	rp|| dkrp|| d | }|r|dk	r|dk	r|| dkr|| d | }|tjkot|d |kp|ot|d |k}|rd|krdgt|d  |d< |r|rd|krdgt|d  |d< |r|t|d  }	|rH|t|d  }
| jdkrx|r|d dg|	  |d< |r|d dg|
  |d< d	|kr|d	 dg|	  |d	< |r|d
 dg|
  |d
< d|kr|d dg|	  |d< |d | jg|	  |d< |r|d | jg|
  |d< |d dg| j	 g|
  |d< | j
dkr|d dg|
  |d< |d dg|
  |d< n@| jdkr|rdg|	 |d  |d< |rdg|
 |d  |d< d	|krdg|	 |d	  |d	< |rdg|
 |d
  |d
< d|krdg|	 |d  |d< | jg|	 |d  |d< |r| jg|
 |d  |d< dg| j	 g|
 |d  |d< | j
dkrdg|
 |d  |d< dg|
 |d  |d< ntdt| j |S )a  
        Pad encoded inputs (on left/right and up to predefined length or max length in the batch)


        Args:
            encoded_inputs:
                Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
            max_length: maximum length of the returned list and optionally padding length (see below).
                Will truncate by taking into account the special tokens.
            max_entity_length: The maximum length of the entity sequence.
            padding_strategy: PaddingStrategy to use for padding.


                - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
                - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
                - PaddingStrategy.DO_NOT_PAD: Do not pad
                The tokenizer padding sides are defined in self.padding_side:


                    - 'left': pads on the left of the sequences
                    - 'right': pads on the right of the sequences
            pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
                This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
                `>= 7.5` (Volta).
            return_attention_mask:
                (optional) Set to False to avoid returning attention mask (default: set to model specifics)
        r   Nr<   r;   r   r   Zentity_attention_maskrightr  r  r  r  rU   rZ   r  r  leftzInvalid padding strategy:)r   r   r   r5  r|   r  Zpadding_sideZpad_token_idr   rj   rh   r   rr   )r   r$  r   ri   r   r   r   Zentities_providedZneeds_to_be_padded
differenceZentity_differencer$   r$   r(   r2    s    $

















zLukeTokenizer._pad)save_directoryfilename_prefixr   c              	   C   s  t j|s"td| d d S t j||r6|d ndtd  }t j||rX|d ndtd  }t|ddd	$}|t	j
| jd
dddd  W 5 Q R X d}t|ddd	j}|d t| j dd dD ]B\}}	||	krtd| d |	}|d|d  |d7 }qW 5 Q R X t j||r6|d ndtd  }
t|
ddd	$}|t	j
| jd
dddd  W 5 Q R X |||
fS )NzVocabulary path (z) should be a directory-r   r   r   wrM   rN   r]   TF)indent	sort_keysensure_asciirT   r   z#version: 0.2
c                 S   s   | d S )Nr   r$   )kvr$   r$   r(   r     r   z/LukeTokenizer.save_vocabulary.<locals>.<lambda>r   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!r   r   r   )ospathisdirr"  errorr   VOCAB_FILES_NAMESrs   writert   dumpsrv   r   r}   rw   r#  r   )r   r;  r<  r   Z
merge_filefr   writerr   Ztoken_indexr   r$   r$   r(   save_vocabulary  s>      (

 (zLukeTokenizer.save_vocabulary)Nr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rG   rF   rH   rI   rJ   F)N)NF)N)F)NNNNNTFNNNr   FNNNNFFFFT)NNNNN)NNNNNTFNNNr   NNNNFFFFTF)TNNNNNT)N);__name__
__module____qualname____doc__rG  Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesr   r   propertyr   r   r   r   r   r   r   r   r0  r   r   r   r   r   r   r   r   'ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRINGr   r   EntitySpanInputEntityInputrr   r   r   r   r   r   r  r!  r   r   r   r   r   r*   r   r   r   r   r   r  r.   r2  rL  __classcell__r$   r$   r   r(   r:      s  _                  t
+  
    
   

                      
Ul     
 .Q                     


 o       
 $ r:   )4rP  r   rt   rC  collections.abcr   	functoolsr   typingr   r   r   r   r   numpyr+  regexr   Ztokenization_utilsr
   Ztokenization_utils_baser   r   r   r   r   r   r   r   r   r   utilsr   r   r   r   Z
get_loggerrM  r"  r0  Z
EntitySpanrU  rr   EntityrV  rG  rQ  rR  rT  r3   r9   r:   r$   r$   r$   r(   <module>   sL   0
L
