U
    9%e                    @   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 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 eeZd	d
dZdddddddZ dddZ!dZ"dZ#e dd Z$dd Z%G dd deZ&dS )znTokenization class for LayoutLMv3. Same as LayoutLMv2, but RoBERTa-like BPE tokenization instead of WordPiece.    N)	lru_cache)DictListOptionalTupleUnion   )
AddedTokenPreTrainedTokenizer)BatchEncodingEncodedInputPreTokenizedInput	TextInputTextInputPairTruncationStrategy)PaddingStrategy
TensorTypeadd_end_docstringsloggingz
vocab.jsonz
merges.txt)
vocab_filemerges_filezDhttps://huggingface.co/microsoft/layoutlmv3-base/raw/main/vocab.jsonzEhttps://huggingface.co/microsoft/layoutlmv3-large/raw/main/vocab.json)zmicrosoft/layoutlmv3-basezmicrosoft/layoutlmv3-largezDhttps://huggingface.co/microsoft/layoutlmv3-base/raw/main/merges.txtzEhttps://huggingface.co/microsoft/layoutlmv3-large/raw/main/merges.txti   aU  
            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.
aJ  
            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 [`~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 [`~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 )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   u/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/layoutlmv3/tokenization_layoutlmv3.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

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    r4   c                       s  e Zd ZdZeZeZeZ	dddgZ
ddddddd	d
dddddgddddgddddgddf 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dJeee ee dd d!ZdKee eee  ee d"d#d$ZdLee eee  eee d& fd'd(ZdMee eee  ee d"d)d*ZdNd+d,Zee e!dOe"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.d/Z)ee e!dPe"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(d0d1d2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(d3d4d5Z.e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(d6d7d8Z/ee dQe"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-d9d:Z0ee e!dRe"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(d-d;d<Z1d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(d=d>d?Z2ee e!dSe"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@dAdBZ3dTe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 dD	dEdFZ4de%j,ddfe"e5ee6f e(f ee e%ee ee e7dGdHdIZ8  Z9S )ULayoutLMv3Tokenizera,  
    Construct a LayoutLMv3 tokenizer. Based on [`RoBERTatokenizer`] (Byte Pair Encoding or BPE).
    [`LayoutLMv3Tokenizer`] can be used to turn words, word-level bounding boxes and optional word labels to
    token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`, and optional `labels` (for token
    classification).

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    this superclass for more information regarding those methods.

    [`LayoutLMv3Tokenizer`] runs end-to-end tokenization: punctuation splitting and wordpiece. It also turns the
    word-level bounding boxes into token-level bounding boxes.

    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).
        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 `[0, 0, 0, 0]`):
            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.
    	input_idsattention_maskbboxreplacez<s>z</s>z<unk>z<pad>z<mask>Tr   ic                    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f |||||||	|
||||||d| d S )NF)lstriprstripTutf-8encodingc                 S   s   i | ]\}}||qS r   r   r!   kvr   r   r#   
<dictcomp>4  s      z0LayoutLMv3Tokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r   r   r?   r   r   r#   rB   7  s      
r   c                 S   s   g | ]}t | qS r   )tuplesplit)r!   merger   r   r#   r$   :  s     z0LayoutLMv3Tokenizer.__init__.<locals>.<listcomp>zJ's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+)errors	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenadd_prefix_spacecls_token_boxsep_token_boxpad_token_boxpad_token_labelonly_label_first_subword) 
isinstancestrr	   openjsonloadencoderitemsdecoderrH   r.   byte_encoderbyte_decoderreadrF   r)   r*   r&   len	bpe_rankscacherP   recompilepatrQ   rR   rS   rT   rU   super__init__)selfr   r   rH   rI   rJ   rL   rM   rK   rN   rO   rP   rQ   rR   rS   rT   rU   kwargsZvocab_handleZmerges_handleZ
bpe_merges	__class__r   r#   rh     sV     zLayoutLMv3Tokenizer.__init__c                 C   s
   t | jS N)ra   r[   ri   r   r   r#   
vocab_size[  s    zLayoutLMv3Tokenizer.vocab_sizec                 C   s   t | j }|| j |S rm   )r)   r[   copyupdateadded_tokens_encoder)ri   Zvocabr   r   r#   	get_vocaba  s    zLayoutLMv3Tokenizer.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)rb   getfloatpairrn   r   r#   <lambda>q      z)LayoutLMv3Tokenizer.bpe.<locals>.<lambda>keyr   r       )rc   rE   r4   minrb   ra   index
ValueErrorextendr(   join)
ri   tokenr1   r2   ZbigramfirstsecondZnew_wordijr   rn   r#   bpeg  sB    


2




zLayoutLMv3Tokenizer.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 rm   )r^   )r!   r-   rn   r   r#   	<genexpr>  s    z0LayoutLMv3Tokenizer._tokenize.<locals>.<genexpr>r<   c                 s   s   | ]
}|V  qd S rm   r   )r!   Z	bpe_tokenr   r   r#   r     s     r~   )rd   findallrf   r   encoder   r   rF   )ri   text
bpe_tokensr   r   rn   r#   	_tokenize  s    "zLayoutLMv3Tokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r[   ru   rK   )ri   r   r   r   r#   _convert_token_to_id  s    z(LayoutLMv3Tokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)r]   ru   )ri   r   r   r   r#   _convert_id_to_token  s    z(LayoutLMv3Tokenizer._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   )r_   )r!   crn   r   r#   r$     s     z@LayoutLMv3Tokenizer.convert_tokens_to_string.<locals>.<listcomp>r<   )rH   )r   	bytearraydecoderH   )ri   tokensr   r   rn   r#   convert_tokens_to_string  s    
"z,LayoutLMv3Tokenizer.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   wr<   r=   r}   TF)indent	sort_keysensure_asciirC   r   z#version: 0.2
c                 S   s   | d S )Nr   r   )kvr   r   r#   ry     rz   z5LayoutLMv3Tokenizer.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isdirloggererrorr   VOCAB_FILES_NAMESrX   writerY   dumpsr[   sortedrb   r\   warning)
ri   r   r   r   Z
merge_filefr   writerr   Ztoken_indexr   r   r#   save_vocabulary  s2      (

z#LayoutLMv3Tokenizer.save_vocabulary)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. 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)ri   r   r   clssepr   r   r#    build_inputs_with_special_tokens  s
    z4LayoutLMv3Tokenizer.build_inputs_with_special_tokensF)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   )rg   get_special_tokens_maskra   )ri   r   r   r   rk   r   r#   r     s      z+LayoutLMv3Tokenizer.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. 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   ra   )ri   r   r   r   r   r   r   r#   $create_token_type_ids_from_sequences  s
    z8LayoutLMv3Tokenizer.create_token_type_ids_from_sequencesc                    sZ   | d| j}|s|rRt dkrR d  sRt fdd| jD dkrRd    |fS )NrP   r   c                    s   g | ]}  |qS r   )
startswith)r!   Zno_split_tokenr   r   r#   r$      s     z@LayoutLMv3Tokenizer.prepare_for_tokenization.<locals>.<listcomp>r~   )poprP   ra   isspacesumrr   )ri   r   Zis_split_into_wordsrj   rP   r   r   r#   prepare_for_tokenization  s    

z,LayoutLMv3Tokenizer.prepare_for_tokenization)r   	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)rV   rW   r%   rE   ra   )tr   r   r#   _is_valid_text_inputP  s    
"z:LayoutLMv3Tokenizer.__call__.<locals>._is_valid_text_inputNzStext input must of type `str` (single example) or `List[str]` (batch of examples). zwWords must be 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   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )	r   rV   r%   rE   ra   r*   boolbatch_encode_plusencode_plus)ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   Z
is_batchedwordsZwords_exampleboxes_exampler   r   r   r   r#   __call__%  s    +$zLayoutLMv3Tokenizer.__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)ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   r   r   r   r#   r     s>    	z%LayoutLMv3Tokenizer.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   )ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   batch_outputsr   r   r#   r     s0    z&LayoutLMv3Tokenizer._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valuer\   r(   padr   )ri   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,LayoutLMv3Tokenizer._batch_prepare_for_modelc                 K   s>   | j f |||||||||	|
||||||||d|}|d S )Nr   r6   )r   )ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   encoded_inputsr   r   r#   r   w  s.    zLayoutLMv3Tokenizer.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 (words of a single example) or a
                list of list of strings (words 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)ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   r   r   r   r#   r     s>    %	zLayoutLMv3Tokenizer.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   )ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   r   r#   r     s0    z LayoutLMv3Tokenizer._encode_plus)r   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|  qnt |} fddtt|D }t||D ]D\}}t|dk rlqR |}|| ||gt|  qR |} |r |nd}!|r|t	j
kr|!dk	rtdt|!dk	}"t| }#|"rt|!nd}$|#|$ |r j|"dnd }%g }&g }'g }(|t	jkrt|rt|%|krt j| ||!|||%| ||	d	\} }}!}}}&}'}(|r|std
|dkrd jk}|dkrd jk}i })|r|&|)d< |'|)d< |(|)d< |%| |)d< |rX | |!}* | |!}+ jg|  jg }|r* jg|  jg }|"r8|| n|}|r jg|  jg }nJ|"rf| |! n| }*dgt|  |"rdgt|! ng  }+|"r|| n|}|*|)d< ||)d< |r|+|)d< |r|rވ | |!|)d< ndgt|* |)d< |r||)d<  |)d || |tjks"|r8 j|)||j|
|d})|rNt|)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. 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.

        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   Nr   c                    s   g | ]
} j qS r   )rS   )r!   _rn   r   r#   r$   v  s     z9LayoutLMv3Tokenizer.prepare_for_model.<locals>.<listcomp>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   rw   )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_idsr7   overflowing_tokensoverflowing_token_boxesoverflowing_labelsZnum_truncated_tokensr6   r8   special_tokens_maskr   )r   r   r   r   length)r   r   )r   r*   ra   tokenizer   rU   rT   r&   Zconvert_tokens_to_idsr   LONGEST_FIRSTr   r   Znum_special_tokens_to_addDO_NOT_TRUNCATEtruncate_sequencesmodel_input_namesr   r   rQ   rR   r   Z&_eventual_warn_about_too_long_sequencer   r   r   r   r   )-ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   r   r   r   Zpair_tokenstoken_boxesr   r   r1   boxZword_tokenslabelidsr   rx   Zlen_idsZlen_pair_idsZ	total_lenr   r   r   r   sequencer   r   r   rn   r#   r      s   ,	




"








&  z%LayoutLMv3Tokenizer.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sZ|tjkr|dkrt||krtt||| }|| d }	|| d }
|| d }|d|  }|d|  }|d|  }n:d| dt| d}|tjkr|d| d }t| n |tjkrtdtjj	 d	 t
|D ]`}|dksVt|t|kr||dd
 }|dd
 }|dd
 }n|dd
 }|dd
 }q6n|tjkr,|dk	r,t||kr
tt||| }|| d }	|| d }
|d|  }|d|  }n"td| dt| d| d ||||||	|
|fS )a  
        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. 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.rD   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'.)rV   r   Z
ONLY_FIRSTr   ra   r   r   r   r   r   r&   ZONLY_SECOND)ri   r  r   r   r   r   r   r   r   r   r   r   Z
window_len	error_msgr   r   r   r#   r     sp    5


z&LayoutLMv3Tokenizer.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)
        Nr7   r   r   rightr   r8   r   r   leftzInvalid padding strategy:)r   r   ZLONGESTra   r   Zpadding_sideZpad_token_type_idrS   rT   Zpad_token_idr   rW   )	ri   r   r   r   r   r   Zrequired_inputZneeds_to_be_padded
differencer   r   r#   _padt  sR     









zLayoutLMv3Tokenizer._pad)N)N)NF)N)F)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFT)NNNTFNNr   NNNNFFFFTF)NNNr   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_sizesr   rh   propertyro   rs   r   r   r   r   r   rW   r   r   r   r   intr   r   r   r   r   r   "LAYOUTLMV3_ENCODE_KWARGS_DOCSTRING2LAYOUTLMV3_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   rk   r#   r5      s"  F



G
+  
    
   

                  	                 B7F                 

.                 

F

4                  

 Z      



 r5   )'r  rY   r   	functoolsr   typingr   r   r   r   r   regexrd   Ztokenization_utilsr	   r
   Ztokenization_utils_baser   r   r   r   r   r   utilsr   r   r   r   Z
get_loggerr	  r   r   r  r  r  r  r.   r4   r5   r   r   r   r#   <module>   s8    
21
