U
    9%et                    @   s   d 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
 ddlZddlmZmZmZ ddlmZmZ ddlmZmZmZmZmZmZmZ dd	lmZ eeZ d
dddZ!dddddddZ"dddZ#dZ$e dd Z%dd Z&G dd deZ'dS )z Tokenization class for MarkupLM.    N)	lru_cache)DictListOptionalTupleUnion   )PaddingStrategy
TensorTypeadd_end_docstrings)
AddedTokenPreTrainedTokenizer)ENCODE_KWARGS_DOCSTRINGBatchEncodingEncodedInputPreTokenizedInput	TextInputTextInputPairTruncationStrategy)loggingz
vocab.jsonz
merges.txtztokenizer.json)
vocab_filemerges_fileZtokenizer_filezFhttps://huggingface.co/microsoft/markuplm-base/resolve/main/vocab.jsonzGhttps://huggingface.co/microsoft/markuplm-large/resolve/main/vocab.json)zmicrosoft/markuplm-basezmicrosoft/markuplm-largezFhttps://huggingface.co/microsoft/markuplm-base/resolve/main/merges.txtzGhttps://huggingface.co/microsoft/markuplm-large/resolve/main/merges.txt)r   r   i   aT  
            add_special_tokens (`bool`, *optional*, defaults to `True`):
                Whether or not to encode the sequences with the special tokens relative to their model.
            padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
                Activates and controls padding. Accepts the following values:

                - `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).
            truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
                Activates and controls truncation. Accepts the following values:

                - `True` or `'longest_first'`: Truncate 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. This will
                  truncate token by token, removing a token from the longest sequence in the pair if a pair of
                  sequences (or a batch of pairs) is provided.
                - `'only_first'`: Truncate 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. This will only
                  truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `'only_second'`: Truncate 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. This will only
                  truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
                  greater than the model maximum admissible input size).
            max_length (`int`, *optional*):
                Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
                `None`, this will use the predefined model maximum length if a maximum length is required by one of the
                truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
                truncation/padding to a maximum length will be deactivated.
            stride (`int`, *optional*, defaults to 0):
                If set to a number along with `max_length`, the overflowing tokens returned when
                `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
                returned to provide some overlap between truncated and overflowing sequences. The value of this
                argument defines the number of overlapping tokens.
            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_tensors (`str` or [`~file_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.
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 )a3  
    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    q/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/markuplm/tokenization_markuplm.py
<listcomp>   s     z$bytes_to_unicode.<locals>.<listcomp>)listrangeordappenddictzip)bscsr#   br    r    r$   bytes_to_unicodem   s    
L

r/   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    r5   c                       s  e Zd ZdZeZeZeZ	dR fdd	Z
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dSeee ee d!d"d#ZdTd$d%ZdUee eee  ee d&d'd(ZdVee eee  ee d)d*d+ZdWee eee  ee d,d-d.ZdXee eee  eee d/ fd0d1ZdYee eee  ee d&d2d3Z e!e"e#dZe$e%e&ee% ee& f ee$e&ee& f  e$eee  eeee   f ee$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)f  ee ee eeeeee*d5d6d7Z+e!e"e#d[e$ee% ee, ee& f eeeeee    ee$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)f  ee ee eeeeee*d8d9d:Z-d d d de'j.e(j/d d4d d d d dddddfe$ee% ee, ee& f 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*d;d<d=Z0e!e"e#d d d de'j.e(j/d d4d 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*d>d?d@Z1e!e"d\e$e%e&f ee& eeee   eee  ee$eee'f e$eee(f ee eee ee$ee)f  ee ee eeeeeee d5dAdBZ2e!e"e#d]e$e%e&f ee& eeee   eee  ee$eee'f e$eee(f ee eee ee$ee)f  ee ee eeeeee*d5dCdDZ3d d d de'j.e(j/d d4d d d d dddddfe$e%e&f 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*dEdFdGZ4e!e"e#d^e$e%e&f ee& eeee   eee  ee$eee'f e$eee(f ee eee ee$ee)f  ee ee eeeeeee*dHdIdJZ5d_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 f dLdMdNZ6d e'j.d d fe$e7ee8f e*f ee e'ee ee e9dOdPdQZ:  Z;S )`MarkupLMTokenizera
  
    Construct a MarkupLM tokenizer. Based on byte-level Byte-Pair-Encoding (BPE). [`MarkupLMTokenizer`] can be used to
    turn HTML strings into to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and
    `xpath_tags_seq`. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods.
    Users should refer to this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        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. (RoBERTa tokenizer detect beginning of words by the preceding space).
    replace<s></s><unk><pad><mask>F2       Tc                    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| j| _| jd
 | _| jg| j | _| jg| j | _ t! j"f |||||||	|||
|||||||d| || _#|| _$d S )NF)lstriprstripTutf-8encodingc                 S   s   i | ]\}}||qS r    r    r"   kvr    r    r$   
<dictcomp>   s      z.MarkupLMTokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r    r    rF   r    r    r$   rI      s      
r   c                 S   s   g | ]}t | qS r    )tuplesplit)r"   merger    r    r$   r%      s     z.MarkupLMTokenizer.__init__.<locals>.<listcomp>zJ's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+)r   r   	tags_dicterrors	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenadd_prefix_space	max_depth	max_width	pad_widthpad_token_labelonly_label_first_subword)%
isinstancestrr   openjsonloadencoderrO   itemsdecoderrP   r/   byte_encoderbyte_decoderreadrM   r*   r+   r'   len	bpe_rankscacherX   recompilepatrY   rZ   r[   
unk_tag_id
pad_tag_idpad_xpath_tags_seqpad_xpath_subs_seqsuper__init__r\   r]   )selfr   r   rO   rP   rQ   rR   rT   rU   rS   rV   rW   rX   rY   rZ   r[   r\   r]   kwargsZvocab_handleZmerges_handleZ
bpe_merges	__class__r    r$   rt      sf     zMarkupLMTokenizer.__init__c           	      C   s   g }g }| d}|D ]p}| s$q|  d}|d }t|dkrJdnt|d dd }|| j|| j |t| j	| q|d| j
 }|d| j
 }|| jg| j
t|  7 }|| jg| j
t|  7 }||fS )z
        Given the xpath expression of one particular node (like "/html/body/div/li[1]/div/span[2]"), return a list of
        tag IDs and corresponding subscripts, taking into account max depth.
        /[r   r   NrK   )rM   stripri   intr)   rO   getro   minrZ   rY   rp   r[   )	ru   xpathxpath_tags_listxpath_subs_listZxpath_unitsunitZ	name_subsZtag_namesubr    r    r$   get_xpath_seq  s     
$zMarkupLMTokenizer.get_xpath_seqc                 C   s
   t | jS N)ri   rc   ru   r    r    r$   
vocab_size7  s    zMarkupLMTokenizer.vocab_sizec                 C   s   | j  }|| j |S r   )rc   copyupdateZadded_tokens_encoder)ru   Zvocabr    r    r$   	get_vocab;  s    
zMarkupLMTokenizer.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)rj   r}   floatpairr   r    r$   <lambda>J      z'MarkupLMTokenizer.bpe.<locals>.<lambda>keyr   r       )rk   rL   r5   r~   rj   ri   index
ValueErrorextendr)   join)
ru   tokenr2   r3   ZbigramfirstsecondZnew_wordijr    r   r$   bpe@  sB    


2




zMarkupLMTokenizer.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   )rf   )r"   r.   r   r    r$   	<genexpr>n  s    z.MarkupLMTokenizer._tokenize.<locals>.<genexpr>rC   c                 s   s   | ]
}|V  qd S r   r    )r"   Z	bpe_tokenr    r    r$   r   q  s     r   )rl   findallrn   r   encoder   r   rM   )ru   text
bpe_tokensr   r    r   r$   	_tokenizej  s    "zMarkupLMTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)rc   r}   rS   )ru   r   r    r    r$   _convert_token_to_idt  s    z&MarkupLMTokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)re   r}   )ru   r   r    r    r$   _convert_id_to_tokenx  s    z&MarkupLMTokenizer._convert_id_to_tokenc                    s:   t d d|}t fdd|D jd jd}|S )z:Converts a sequence of tokens (string) in a single string.z_MarkupLM now does not support generative tasks, decoding is experimental and subject to change.r   c                    s   g | ]} j | qS r    )rg   )r"   cr   r    r$   r%     s     z>MarkupLMTokenizer.convert_tokens_to_string.<locals>.<listcomp>rC   )rP   )loggerwarningr   	bytearraydecoderP   )ru   tokensr   r    r   r$   convert_tokens_to_string|  s    
"z*MarkupLMTokenizer.convert_tokens_to_stringN)save_directoryfilename_prefixreturnc           
   	   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 ||fS )NzVocabulary path (z) should be a directory-r   r   r   wrC   rD   r   TF)indent	sort_keysensure_asciirJ   r   z#version: 0.2
c                 S   s   | d S )Nr   r    )kvr    r    r$   r     r   z3MarkupLMTokenizer.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   )ospathisdirr   errorr   VOCAB_FILES_NAMESr`   writera   dumpsrc   sortedrj   rd   r   )
ru   r   r   r   Z
merge_filefr   writerr   Ztoken_indexr    r    r$   save_vocabulary  s2      (

z!MarkupLMTokenizer.save_vocabularyc                 K   s>   | d| j}|s|r6t|dkr6|d  s6d| }||fS )NrX   r   r   )poprX   ri   isspace)ru   r   Zis_split_into_wordsrv   rX   r    r    r$   prepare_for_tokenization  s     z*MarkupLMTokenizer.prepare_for_tokenization)token_ids_0token_ids_1r   c                 C   s@   |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 RoBERTa 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)ru   r   r   clssepr    r    r$    build_inputs_with_special_tokens  s
    z2MarkupLMTokenizer.build_inputs_with_special_tokens)xpath_tags_0xpath_tags_1r   c                 C   s4   | j g}t|dkr || | S || | | | S Nr   )rq   ri   )ru   r   r   padr    r    r$   $build_xpath_tags_with_special_tokens  s    z6MarkupLMTokenizer.build_xpath_tags_with_special_tokens)xpath_subs_0xpath_subs_1r   c                 C   s4   | j g}t|dkr || | S || | | | S r   )rr   ri   )ru   r   r   r   r    r    r$   $build_xpath_subs_with_special_tokens  s    z6MarkupLMTokenizer.build_xpath_subs_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  
        Args:
        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.
            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   )rs   get_special_tokens_maskri   )ru   r   r   r   rw   r    r$   r     s      z)MarkupLMTokenizer.get_special_tokens_maskc                 C   sL   | 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. RoBERTa 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   ri   )ru   r   r   r   r   r    r    r$   $create_token_type_ids_from_sequences  s
    z6MarkupLMTokenizer.create_token_type_ids_from_sequencesr   )r   	text_pairxpathsnode_labelsadd_special_tokenspadding
truncation
max_lengthstride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  dd }|dk	r8||s t dt|ttfsNt dnt|ttfsNt d|dk	rft|ttf}n$t|ttfo|ot|d ttf}|dkr|n|}|dk	std|rt|t|kstdt||D ] \}}t|t|kstd	qnt|t|kstd	|r|dk	rNt|t|krNt d
t| dt| d|dk	rftt||n|}t|dk	}| 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 with node-level xpaths and optional labels.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
                (nodes of a single example or questions of a batch of examples) or a list of list of strings (batch of
                nodes).
            text_pair (`List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
                (pretokenized string).
            xpaths (`List[List[int]]`, `List[List[List[int]]]`):
                Node-level xpaths.
            node_labels (`List[int]`, `List[List[int]]`, *optional*):
                Node-level integer labels (for token classification tasks).
        c                 S   s   t | trdS t | ttfrxt| dkr,dS t | d tr>dS t | d ttfrrt| d dkppt | d d tS dS ndS d S )NTr   F)r^   r_   r&   rL   ri   )tr    r    r$   _is_valid_text_input*  s    
"z8MarkupLMTokenizer.__call__.<locals>._is_valid_text_inputNzStext input must of type `str` (single example) or `List[str]` (batch of examples). zwNodes must be of type `List[str]` (single pretokenized example), or `List[List[str]]` (batch of pretokenized examples).r   z%You must provide corresponding xpathszAYou must provide nodes and xpaths for an equal amount of examplesz2You must provide as many nodes as there are xpathszbatch length of `text`: z- does not match batch length of `text_pair`: .)batch_text_or_text_pairsis_pairr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )
r   r^   r&   rL   AssertionErrorri   r+   boolbatch_encode_plusencode_plus)ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   Z
is_batchedZnodesZnodes_examplexpaths_exampler   r   r    r    r$   __call__   s    *$zMarkupLMTokenizer.__call__)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sZ   | j f ||||
|d|\}}}}| jf |||||||||	|
||||||||d|S )Nr   r   r   r   r   )r   r   r   r   r   padding_strategytruncation_strategyr   r   r   r   r   r   r   r   r   r   r   )"_get_padding_truncation_strategies_batch_encode_plus)ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   r   r    r    r$   r     s>    	z#MarkupLMTokenizer.batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   s@   |rt d| 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   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )NotImplementedError_batch_prepare_for_modelr   )ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   batch_outputsr    r    r$   r     s0    z$MarkupLMTokenizer._batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 C   s   i }t t||D ]\}}|\}}| j|r2|d n||r@|d nd||dk	rT|| nd|tjj|j||	dd||||dd|d}| D ]&\}}||krg ||< || | qq| 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
        r   r   NF)r   r   r   r   r   r   r   r   r   r   r   r   r   prepend_batch_axisr   )r   r   r   r   )tensor_type)
	enumerater+   prepare_for_modelr	   
DO_NOT_PADvaluerd   r)   r   r   )ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   idxZexampleZbatch_text_or_text_pairr   outputsr   r  r    r    r$   r     sH    z*MarkupLMTokenizer._batch_prepare_for_modelc                 K   s>   | j f |||||||||	|
||||||||d|}|d S )Nr   	input_ids)r   )ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   encoded_inputsr    r    r$   r   J  s.    zMarkupLMTokenizer.encodec                 K   sZ   | j f ||||
|d|\}}}}| jf |||||||||	|
||||||||d|S )aj  
        Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
        `__call__` should be used instead.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
            text_pair (`List[str]` or `List[int]`, *optional*):
                Optional second sequence to be encoded. This can be a list of strings (nodes of a single example) or a
                list of list of strings (nodes of a batch of examples).
        r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   _encode_plus)ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   r   r    r    r$   r   y  s>    $	zMarkupLMTokenizer.encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   s>   |rt 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/2674T)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r  )ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r    r    r$   r    s0    zMarkupLMTokenizer._encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c           4         s   j f ||||
|d|\}}}}g }g }g }g }g }g }g }|dkrp|dkrt||D ]`\}}t|dk rrq\ |} ||   |\}!}"||!gt|   ||"gt|   q\nt|||D ]\}}}#t|dk rq̈ |} ||   |\}!}"||!gt|   ||"gt|    jrX||#g jgt| d    q||#gt|   qn |} fddtt|D } fddtt|D }t||D ]f\}}t|dk rҐq |} ||   |\}!}"||!gt|   ||"gt|   q 	|}$|r: 	|nd}%|rb|t
jkrb|%dk	rbtdt|%dk	}&t|$}'|&rt|%nd}(|'|( |r j|&d	nd })g }*g }+g },g }-|t
jkr
|r
|)|kr
 j|$|||%||||)| ||	d

\}$}}}%}}}}*}+},}-|r|std|dkr2d jk}|dkrFd jk}i }.|r||*|.d< |+|.d< |,|.d< |-|.d< |)| |.d< |rΈ |$|%}/ |$|%}0 ||}1 ||}2|r* jg|  jg }n\|&r|$|% n|$}/dgt|$ |&r dgt|% ng  }0|&r|| n|}1|&r&|| n|}2|/|.d< |1|.d< |2|.d< |rP|0|.d< |r|rn |$|%|.d< ndgt|/ |.d< |r||.d<  |.d || |tjks|rȈ j|.||j|
|d}.|rt|.d |.d< t|.||d}3|3S )a  
        Prepares a sequence or a pair of sequences 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 *text_pair* 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.

        Node-level `xpaths` are turned into token-level `xpath_tags_seq` and `xpath_subs_seq`. If provided, node-level
        `node_labels` are turned into token-level `labels`. The node label is used for the first token of the node,
        while remaining tokens are labeled with -100, such that they will be ignored by the loss function.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
            text_pair (`List[str]` or `List[int]`, *optional*):
                Optional second sequence to be encoded. This can be a list of strings (nodes of a single example) or a
                list of list of strings (nodes of a batch of examples).
        r   Nr   c                    s   g | ]
} j qS r    )rq   r"   _r   r    r$   r%   L  s     z7MarkupLMTokenizer.prepare_for_model.<locals>.<listcomp>c                    s   g | ]
} j qS r    )rr   r  r   r    r$   r%   M  s     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`.r   r   )	xpath_tags_seqxpath_subs_seqpair_idspair_xpath_tags_seqpair_xpath_subs_seqlabelsnum_tokens_to_remover   r   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.token_type_idsattention_maskoverflowing_tokensoverflowing_xpath_tags_seqoverflowing_xpath_subs_seqoverflowing_labelsZnum_truncated_tokensr  r
  r  special_tokens_maskr  )r   r   r   r   length)r   r   )r   r+   ri   tokenizer   r   r]   r\   r'   Zconvert_tokens_to_idsr   LONGEST_FIRSTr   r   Znum_special_tokens_to_addDO_NOT_TRUNCATEtruncate_sequencesmodel_input_namesr   r   r   r   r   Z&_eventual_warn_about_too_long_sequencer	   r  r   r  r   )4ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   r   r   Zpair_tokensr
  r  r  r  r  r2   r   Zword_tokensr   r   labelidsr  r   Zlen_idsZlen_pair_idsZ	total_lenr  r  r  r  r  sequencer  Zxpath_tags_idsZxpath_subs_idsr   r    r   r$   r     s$   ,	




"







&  z#MarkupLMTokenizer.prepare_for_modellongest_first)r  r
  r  r  r  r  r  r  r   r   r   c                 C   s  |dkr||||||g g g f	S t |	ts0t|	}	g }g }g }g }|	tjks`|	tjkr"|dkr"t||krtt||
| }|| d }|| d }|| d }|d|  }|d|  }|d|  }|d|  }n<d| dt| d}|	tjkr|d|	 d }t| nT|	tjkrtdtjj	 d	 t
|D ]x}|dkslt|t|kr|dd
 }|dd
 }|dd
 }|dd
 }n$|dd
 }|dd
 }|dd
 }qLn|	tjkrv|dk	rvt||krTtt||
| }|| d }|| d }|| d }|d|  }|d|  }|d|  }n"td| dt| d|	 d |||||||||||fS )aE  
        Args:
        Truncates a sequence pair in-place following the strategy.
            ids (`List[int]`):
                Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
                `convert_tokens_to_ids` methods.
            xpath_tags_seq (`List[List[int]]`):
                XPath tag IDs of the first sequence.
            xpath_subs_seq (`List[List[int]]`):
                XPath sub IDs of the first sequence.
            pair_ids (`List[int]`, *optional*):
                Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
                and `convert_tokens_to_ids` methods.
            pair_xpath_tags_seq (`List[List[int]]`, *optional*):
                XPath tag IDs of the second sequence.
            pair_xpath_subs_seq (`List[List[int]]`, *optional*):
                XPath sub IDs of the second sequence.
            num_tokens_to_remove (`int`, *optional*, defaults to 0):
                Number of tokens to remove using the truncation strategy.
            truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to
            `False`):
                The strategy to follow for truncation. Can be:
                - `'longest_first'`: Truncate 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. This will truncate
                  token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
                  batch of pairs) is provided.
                - `'only_first'`: Truncate 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. This will only
                  truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `'only_second'`: Truncate 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. This will only
                  truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
                  than the model maximum admissible input size).
            stride (`int`, *optional*, defaults to 0):
                If set to a positive number, the overflowing tokens returned will contain some tokens from the main
                sequence returned. The value of this argument defines the number of additional tokens.
        Returns:
            `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
            overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
            of sequences (or a batch of pairs) is provided.
        r   NzWe need to remove z; to truncate the input but the first sequence has a length z. z/Please select another truncation strategy than z0, for instance 'longest_first' or 'only_second'.zmBe aware, overflowing tokens are not returned for the setting you have chosen, i.e. sequence pairs with the 'zg' truncation strategy. So the returned list will always be empty even if some tokens have been removed.rK   z< to truncate the input but the second sequence has a length z1. Please select another truncation strategy than z/, for instance 'longest_first' or 'only_first'.)r^   r   Z
ONLY_FIRSTr  ri   r~   r   r   r   r  r'   ZONLY_SECOND)ru   r  r
  r  r  r  r  r  r  r   r   r  r  r  r  Z
window_len	error_msgr	  r    r    r$   r    s    7

z$MarkupLMTokenizer.truncate_sequences)r  r   r   r   r   r   c           	      C   s  |dkrd| j k}|| j d  }|tjkr2t|}|dk	r^|dk	r^|| dkr^|| d | }|tjkort||k}|rd|krdgt| |d< |r|t| }| jdkr|r|d dg|  |d< d|kr|d | jg|  |d< d|kr|d | jg|  |d< d|kr.|d | jg|  |d< d	|krP|d	 | j	g|  |d	< d
|krp|d
 dg|  |d
< || j
g|  || j d < n| jdkrx|rdg| |d  |d< d|kr| jg| |d  |d< d|kr| jg| |d  |d< d|kr| jg| |d  |d< d	|kr<| j	g| |d	  |d	< d
|kr\dg| |d
  |d
< | j
g| | || j d < ntdt| j |S )a<  
        Args:
        Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
            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.
            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)
        Nr  r   r   rightr  r
  r  r  r  leftzInvalid padding strategy:)r  r	   ZLONGESTri   r  Zpadding_sideZpad_token_type_idrq   rr   r\   Zpad_token_idr   r_   )	ru   r  r   r   r   r   Zrequired_inputZneeds_to_be_padded
differencer    r    r$   _pad]  sf    













zMarkupLMTokenizer._pad)r7   r8   r9   r9   r8   r:   r;   r<   Fr=   r>   r?   r@   T)N)F)N)N)N)NF)N)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFTF)NNNNr   r!  r   )<__name__
__module____qualname____doc__r   Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_map&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESZmax_model_input_sizesrt   r   propertyr   r   r   r   r   r   r   r_   r   r   r   r   r   r|   r   r   r   r   r   r   r   r   0MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRINGr   r   r   r	   r   r
   r   r   r   r   r  r  r   r   r   r   r  r   r  r   r   r*   r&  __classcell__r    r    rw   r$   r6      s@  6              R
*
	
  
  
	  
	    
   
                                   A7F                 

.                 

E

4                  

 j       




 r6   )(r*  ra   r   	functoolsr   typingr   r   r   r   r   regexrl   Z
file_utilsr	   r
   r   Ztokenization_utilsr   r   Ztokenization_utils_baser   r   r   r   r   r   r   utilsr   Z
get_loggerr'  r   r   r+  r,  r.  r/   r5   r6   r    r    r    r$   <module>   s4   $	
1
