U
    ,-eE                     @   s   d 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
 ddlZddlmZmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZ d	d
lmZmZmZm Z  e!e"Z#dZ$G dd deZ%dS )z* Tokenization classes for LayoutXLM model.    N)copyfile)AnyDictListOptionalTupleUnion   )
AddedTokenPreTrainedTokenizer)BatchEncodingEncodedInputPreTokenizedInput	TextInputTextInputPairTruncationStrategy)PaddingStrategy
TensorTypeadd_end_docstringslogging   )&PRETRAINED_POSITIONAL_EMBEDDINGS_SIZESPRETRAINED_VOCAB_FILES_MAPSPIECE_UNDERLINEVOCAB_FILES_NAMESa  
            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.
            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)

            - **bbox** -- List of bounding boxes to be fed to a model.

            - **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)

            - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
            - **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                       s  e Zd ZdZeZeZeZ	ddgZ
dddddddd	d	d	d	gd
d
d
d
gd	d	d	d	gdddfeeeef  dd fddZdd Zdd ZdDee eee  ee dddZdEee eee  eee d fddZdFee eee  ee dddZedd Zd d! Zeee d"d#d$Zd%d& Zd'd( Zd)d* ZdGeee ee d+d,d-Z e!e"dHe#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)d.d/d0Z*dddde&j+e'j,dd	d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)d1d2d3Z.e!e"dddde&j+e'j,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)d4d5d6Z/dddde&j+e'j,dd	d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)d7d8d9Z0e!e"dIe#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)d:d;d<Z1dJe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 d>	d?d@Z2de&j+ddfe#eee3f e)f ee e&ee ee e4dAdBdCZ5  Z6S )KLayoutXLMTokenizeraP  
    Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
    [SentencePiece](https://github.com/google/sentencepiece).

    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.
        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.
        cls_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
            The bounding box to use for the special [CLS] token.
        sep_token_box (`List[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
            The bounding box to use for the special [SEP] token.
        pad_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
            The bounding box to use for the special [PAD] token.
        pad_token_label (`int`, *optional*, defaults to -100):
            The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
            CrossEntropyLoss.
        only_label_first_subword (`bool`, *optional*, defaults to `True`):
            Whether or not to only label the first subword, in case word labels are provided.
        additional_special_tokens (`List[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
            Additional special tokens used by the tokenizer.
        sp_model_kwargs (`dict`, *optional*):
            Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
            SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
            to set:

            - `enable_sampling`: Enable subword regularization.
            - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.

              - `nbest_size = {0,1}`: No sampling is performed.
              - `nbest_size > 1`: samples from the nbest_size results.
              - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
                using forward-filtering-and-backward-sampling algorithm.

            - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
              BPE-dropout.

    Attributes:
        sp_model (`SentencePieceProcessor`):
            The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
    	input_idsattention_mask<s></s><unk><pad><mask>r   i  iTN)sp_model_kwargsreturnc                    s   t |trt|dddn|}|d kr(i n|| _tjf | j| _| jt| || _ddddd| _	d| _
t| j| j
 | j	d	< d
d | j	 D | _|	| _|
| _|| _|| _|| _t jf ||||||||	|
|||| jd| d S )NTF)lstriprstripr      r   r	   )r   r!   r   r    r"   c                 S   s   i | ]\}}||qS  r(   ).0kvr(   r(   u/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/layoutxlm/tokenization_layoutxlm.py
<dictcomp>  s      z/LayoutXLMTokenizer.__init__.<locals>.<dictcomp>)	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokencls_token_boxsep_token_boxpad_token_boxpad_token_labelonly_label_first_subwordr#   )
isinstancestrr
   r#   spmSentencePieceProcessorsp_modelLoad
vocab_filefairseq_tokens_to_idsfairseq_offsetlenitemsfairseq_ids_to_tokensr5   r6   r7   r8   r9   super__init__)selfr@   r.   r/   r1   r2   r0   r3   r4   r5   r6   r7   r8   r9   r#   kwargs	__class__r(   r,   rG      s>    	zLayoutXLMTokenizer.__init__c                 C   s$   | j  }d |d< | j |d< |S )Nr>   sp_model_proto)__dict__copyr>   serialized_model_proto)rH   stater(   r(   r,   __getstate__,  s    
zLayoutXLMTokenizer.__getstate__c                 C   s8   || _ t| dsi | _tjf | j| _| j| j d S )Nr#   )rM   hasattrr#   r<   r=   r>   ZLoadFromSerializedProtorL   )rH   dr(   r(   r,   __setstate__2  s
    
zLayoutXLMTokenizer.__setstate__)token_ids_0token_ids_1r$   c                 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. An XLM-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)rH   rU   rV   clssepr(   r(   r,    build_inputs_with_special_tokens<  s
    z3LayoutXLMTokenizer.build_inputs_with_special_tokensF)rU   rV   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)rU   rV   r\   Nr'   r   )rF   get_special_tokens_maskrC   )rH   rU   rV   r\   rJ   r(   r,   r]   V  s      z*LayoutXLMTokenizer.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. XLM-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   )rX   rW   rC   )rH   rU   rV   rZ   rY   r(   r(   r,   $create_token_type_ids_from_sequencesr  s
    z7LayoutXLMTokenizer.create_token_type_ids_from_sequencesc                 C   s   t | j| j d S )Nr'   )rC   r>   rB   rH   r(   r(   r,   
vocab_size  s    zLayoutXLMTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r(   )Zconvert_ids_to_tokens)r)   ir_   r(   r,   r-     s      z0LayoutXLMTokenizer.get_vocab.<locals>.<dictcomp>)ranger`   updateZadded_tokens_encoder)rH   Zvocabr(   r_   r,   	get_vocab  s    zLayoutXLMTokenizer.get_vocab)textr$   c                 C   s   | j j|tdS )N)Zout_type)r>   encoder;   )rH   re   r(   r(   r,   	_tokenize  s    zLayoutXLMTokenizer._tokenizec                 C   s4   || j kr| j | S | j|}|r.|| j S | jS )z0Converts a token (str) in an id using the vocab.)rA   r>   Z	PieceToIdrB   Zunk_token_id)rH   tokenZspm_idr(   r(   r,   _convert_token_to_id  s    

z'LayoutXLMTokenizer._convert_token_to_idc                 C   s&   || j kr| j | S | j|| j S )z=Converts an index (integer) in a token (str) using the vocab.)rE   r>   Z	IdToPiecerB   )rH   indexr(   r(   r,   _convert_id_to_token  s    

z'LayoutXLMTokenizer._convert_id_to_tokenc                 C   s   d |td }|S )zIConverts a sequence of tokens (strings for sub-words) in a single string.  )joinreplacer   strip)rH   tokensZ
out_stringr(   r(   r,   convert_tokens_to_string  s    z+LayoutXLMTokenizer.convert_tokens_to_string)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| jt j|krzt j	| jrzt
| j| n8t j	| jst|d}| j }|| W 5 Q R X |fS )NzVocabulary path (z) should be a directory-rl   r@   wb)ospathisdirloggererrorrn   r   abspathr@   isfiler   openr>   rO   write)rH   rs   rt   Zout_vocab_filefiZcontent_spiece_modelr(   r(   r,   save_vocabulary  s     (
z"LayoutXLMTokenizer.save_vocabulary)re   	text_pairboxesword_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rt d|rt|t|krt d	t||D ] \}}t|t|krt d
qnt|t|kr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 )a3  
        Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
        sequences with word-level normalized bounding boxes 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
                (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
                words).
            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).
            boxes (`List[List[int]]`, `List[List[List[int]]]`):
                Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
            word_labels (`List[int]`, `List[List[int]]`, *optional*):
                Word-level integer labels (for token classification tasks such as FUNSD, CORD).
        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;   listtuplerC   )tr(   r(   r,   _is_valid_text_input  s    
"z9LayoutXLMTokenizer.__call__.<locals>._is_valid_text_inputNzStext input must of type `str` (single example) or `List[str]` (batch of examples). ztwords must of type `List[str]` (single pretokenized example), or `List[List[str]]` (batch of pretokenized examples).ztWords must of type `List[str]` (single pretokenized example), or `List[List[str]]` (batch of pretokenized examples).r   z-You must provide corresponding bounding boxesz@You must provide words and boxes for an equal amount of examplesz:You must provide as many words as there are bounding boxesz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   )re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )	
ValueErrorr:   r   r   rC   zipboolZbatch_encode_plusZencode_plus)rH   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rI   r   Z
is_batchedwordsZwords_exampleboxes_exampler   r   r(   r(   r,   __call__  s    *$zLayoutXLMTokenizer.__call__)r   r   r   r   r   padding_strategytruncation_strategyr   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   )rH   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rI   batch_outputsr(   r(   r,   _batch_encode_plusQ  s0    z%LayoutXLMTokenizer._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   appendpadr   )rH   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   outputskeyr   r(   r(   r,   r     sH    z+LayoutXLMTokenizer._batch_prepare_for_model)re   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)re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   )rH   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rI   r(   r(   r,   _encode_plus  s0    zLayoutXLMTokenizer._encode_plus)re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   c           -   
      s   j f ||||
|d|\}}}}g }g }g }g }g }|dkr$|dkrt||D ]>\}}t|dk rjqT |}|| ||gt|  qTnt|||D ]~\}}}t|dk rq |}|| ||gt|   jr||g jgt|d    q||gt|  qn| |} fddtt|D  jg }t||D ]D\}}t|dk rtqZ |}|| ||gt|  qZ 	|} |r 	|nd}!t
|!dk	}"t| }#|"rt|!nd}$|#|$ |r j|"dnd }%g }&g }'g }(|tjkrX|rX|%|krX j| ||!|||%| ||	d\} }}!}}}&}'}(|rl|sltd	|dkrd
 jk}|dkrd jk}i })|r|&|)d< |'|)d< |(|)d< |%| |)d< |r" | |!}* | |!}+ jg|  jg }|r| jg }|rZ jg|  jg }n8|"r0| |! n| }*dgt|  |"rTdgt|! ng  }+|*|)d< || |)d< |r||+|)d
< |r|r | |!|)d< ndgt|* |)d< |r||)d<  |)d || |tjks|r j|)||j|
|d})|r
t|)d |)d< t|)||d},|,S )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.

        Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
        token-level `labels`. The word label is used for the first token of the word, 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 (words of a single example) or a
                list of list of strings (words of a batch of examples).
        )r   r   r   r   r   Nr'   c                    s   g | ]
} j qS r(   )r7   )r)   _r_   r(   r,   
<listcomp>W  s     z8LayoutXLMTokenizer.prepare_for_model.<locals>.<listcomp>r   )pair)pair_idspair_token_boxes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_idsr   overflowing_tokensoverflowing_token_boxesoverflowing_labelsZnum_truncated_tokensr   bboxspecial_tokens_maskr   )r   r   r   r   length)r   r   )Z"_get_padding_truncation_strategiesr   rC   tokenizeextendr9   r8   rb   r6   Zconvert_tokens_to_idsr   Znum_special_tokens_to_addr   DO_NOT_TRUNCATEtruncate_sequencesr   model_input_namesr[   r^   r5   r]   Z&_eventual_warn_about_too_long_sequencer   r   r   r   r   )-rH   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rI   r   r   rq   Zpair_tokenstoken_boxesr   r   wordboxZword_tokenslabelidsr   r   Zlen_idsZlen_pair_idsZ	total_lenr   r   r   encoded_inputssequencer   r   r(   r_   r,   r     s    *	




"
"







&  z$LayoutXLMTokenizer.prepare_for_modellongest_first)	r   r   r   r   r   r   r   r   r$   c	              	   C   s  |dkr|||||g g g fS t |ts.t|}g }	g }
g }|tjkrLt|D ]}|dksjt|t|kr|	stt||d }nd}|	|| d  |
|| d  ||| d  |dd }|dd }|dd }qN|	stt||d }nd}|	|| d  |
|| d  |dd }|dd }qNn8|tjkrt||krtt||| }|| d }	|| d }
|| d }|d|  }|d|  }|d|  }n"t	d| dt| d| d n|tj
kr|dk	rt||krbtt||| }|| d }	|| d }
|d|  }|d|  }n"t	d| d	t| d| d
 ||||||	|
|fS )aG  
        Truncates a sequence pair in-place following the strategy.

        Args:
            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.
            token_boxes (`List[List[int]]`):
                Bounding boxes 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_token_boxes (`List[List[int]]`, *optional*):
                Bounding boxes of the second sequence.
            labels (`List[int]`, *optional*):
                Labels of the first sequence (for token classification tasks).
            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.
        r   Nr'   zWe need to remove z; to truncate the input but the first sequence has a length z1. Please select another truncation strategy than z0, for instance 'longest_first' or 'only_second'.z< to truncate the input but the second sequence has a length z/, for instance 'longest_first' or 'only_first'.)r:   r   ZLONGEST_FIRSTrb   rC   minr   Z
ONLY_FIRSTrz   r{   ZONLY_SECOND)rH   r   r   r   r   r   r   r   r   r   r   r   r   Z
window_lenr(   r(   r,   r     sr    4
z%LayoutXLMTokenizer.truncate_sequences)r   r   r   r   r   r$   c           	      C   sJ  |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< |rF|t| }| jdkrj|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rN|d	 dg|  |d	< || j	g|  || j d < n| jd
kr4|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dg| |d	  |d	< | j	g| | || j 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.
            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   leftzInvalid padding strategy:)r   r   ZLONGESTrC   r   Zpadding_sideZpad_token_type_idr7   r8   Zpad_token_idr   r;   )	rH   r   r   r   r   r   Zrequired_inputZneeds_to_be_padded
differencer(   r(   r,   _padF  sR     









zLayoutXLMTokenizer._pad)N)NF)N)N)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFTF)NNNr   r   r   )7__name__
__module____qualname____doc__r   Zvocab_files_namesr   Zpretrained_vocab_files_mapr   Zmax_model_input_sizesr   r   r   r;   r   rG   rQ   rT   r   intr[   r   r]   r^   propertyr`   rd   rg   ri   rk   rr   r   r   r   !LAYOUTXLM_ENCODE_KWARGS_DOCSTRINGr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   dictr   __classcell__r(   r(   rJ   r,   r      s2  O


B  
    
   

	                  7I

4                  

 J      



 r   )&r   rw   shutilr   typingr   r   r   r   r   r   Zsentencepiecer<   Ztokenization_utilsr
   r   Ztokenization_utils_baser   r   r   r   r   r   utilsr   r   r   r   Z$xlm_roberta.tokenization_xlm_robertar   r   r   r   Z
get_loggerr   rz   r   r   r(   r(   r(   r,   <module>   s     
h