U
    9%e                    @   s:  d Z ddlZddlZddlZddlZddl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mZmZ ddlmZmZmZmZ eeZdd	iZdd
ddiZ dddZ!ddiddidZ"dZ#dZ$dd Z%dd Z&e'(dd e)ej*D Z+dd Z,G dd deZ-G dd de.Z/G dd de.Z0dS ) z"Tokenization class for LayoutLMv2.    N)DictListOptionalTupleUnion   )PreTrainedTokenizer_is_control_is_punctuation_is_whitespace)BatchEncodingEncodedInputPreTokenizedInput	TextInputTextInputPairTruncationStrategy)PaddingStrategy
TensorTypeadd_end_docstringslogging
vocab_filez	vocab.txtzOhttps://huggingface.co/microsoft/layoutlmv2-base-uncased/resolve/main/vocab.txtzPhttps://huggingface.co/microsoft/layoutlmv2-large-uncased/resolve/main/vocab.txt)z!microsoft/layoutlmv2-base-uncasedz"microsoft/layoutlmv2-large-uncased   do_lower_caseTaU  
            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.
a  
            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              	   C   sR   t  }t| ddd}| }W 5 Q R X t|D ]\}}|d}|||< q2|S )z*Loads a vocabulary file into a dictionary.rutf-8encoding
)collectionsOrderedDictopen	readlines	enumeraterstrip)r   vocabreadertokensindextoken r)   u/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
load_vocab   s    

r+   c                 C   s   |   } | sg S |  }|S )z@Runs basic whitespace cleaning and splitting on a piece of text.)stripsplit)textr&   r)   r)   r*   whitespace_tokenize   s
    r/   c                 c   s&   | ]}t t|d r|V  qdS )PN)unicodedatacategorychr
startswith).0ir)   r)   r*   	<genexpr>   s      r7   c                 C   sz   g }g }t tt| D ]D\}}| | |d kr| ||t|  |kr|| || q|rr|d |d fS dS d S )Nr   )Nr   )r"   rangelenappend)Zmylistpatternmatchesindicesidxr6   r)   r)   r*   	subfinder   s    (
r?   c                       s  e Zd ZdZeZeZeZ	e
Z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ddddfeeee  d fddZedd Zedd Zdd Zdd Zdd Zdd Zdd ZdGee eee  ee ddd ZdHee eee  eee d" fd#d$ZdIee eee  ee dd%d&ZdJeee ee d'd(d)Zee e!dKe"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!dLe"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(d-d.d/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(d0d1d2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(d3d4d5Z/ee dMe"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*d6d7Z0ee e!dNe"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*d8d9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!dOe"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?Z3dPe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 dA	dBdCZ4de%j,ddfe"e5ee6f e(f ee e%ee ee e7dDdEdFZ8  Z9S )QLayoutLMv2Tokenizera  
    Construct a LayoutLMv2 tokenizer. Based on WordPiece. [`LayoutLMv2Tokenizer`] 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.

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

    TNz[UNK]z[SEP]z[PAD]z[CLS]z[MASK]r   i  ir   )model_max_lengthadditional_special_tokensc                    s   t j|std| dt|| _tdd | j D | _	|| _
|r^t||||d| _t| jt|d| _|
| _|| _|| _|| _|| _t jf ||||||||	|
||||||||d| d S )Nz&Can't find a vocabulary file at path 'z'. To load the vocabulary from a Google pretrained model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`c                 S   s   g | ]\}}||fqS r)   r)   )r5   tokidsr)   r)   r*   
<listcomp>   s     z0LayoutLMv2Tokenizer.__init__.<locals>.<listcomp>)r   never_splittokenize_chinese_charsstrip_accents)r$   	unk_token)r   do_basic_tokenizerF   rI   	sep_token	pad_token	cls_token
mask_tokencls_token_boxsep_token_boxpad_token_boxpad_token_labelonly_label_first_subwordrG   rH   rA   rB   )ospathisfile
ValueErrorr+   r$   r   r   itemsids_to_tokensrJ   BasicTokenizerbasic_tokenizerWordpieceTokenizerstrwordpiece_tokenizerrO   rP   rQ   rR   rS   super__init__)selfr   r   rJ   rF   rI   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rG   rH   rA   rB   kwargs	__class__r)   r*   r`      sR    

zLayoutLMv2Tokenizer.__init__c                 C   s   | j jS N)r[   r   ra   r)   r)   r*   r   #  s    z!LayoutLMv2Tokenizer.do_lower_casec                 C   s
   t | jS re   )r9   r$   rf   r)   r)   r*   
vocab_size'  s    zLayoutLMv2Tokenizer.vocab_sizec                 C   s   t | jf| jS re   )dictr$   Zadded_tokens_encoderrf   r)   r)   r*   	get_vocab+  s    zLayoutLMv2Tokenizer.get_vocabc                 C   s\   g }| j rL| jj|| jdD ],}|| jjkr8|| q|| j|7 }qn| j|}|S )N)rF   )rJ   r[   tokenizeZall_special_tokensrF   r:   r^   )ra   r.   split_tokensr(   r)   r)   r*   	_tokenize.  s    zLayoutLMv2Tokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r$   getrI   )ra   r(   r)   r)   r*   _convert_token_to_id;  s    z(LayoutLMv2Tokenizer._convert_token_to_idc                 C   s   | j || jS )z=Converts an index (integer) in a token (str) using the vocab.)rY   rm   rI   )ra   r'   r)   r)   r*   _convert_id_to_token?  s    z(LayoutLMv2Tokenizer._convert_id_to_tokenc                 C   s   d |dd }|S )z:Converts a sequence of tokens (string) in a single string. z ## )joinreplacer,   )ra   r&   Z
out_stringr)   r)   r*   convert_tokens_to_stringC  s    z,LayoutLMv2Tokenizer.convert_tokens_to_string)token_ids_0token_ids_1returnc                 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 BERT sequence has the following format:

        - single sequence: `[CLS] X [SEP]`
        - pair of sequences: `[CLS] A [SEP] B [SEP]`

        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)ra   ru   rv   clssepr)   r)   r*    build_inputs_with_special_tokensH  s
    z4LayoutLMv2Tokenizer.build_inputs_with_special_tokensF)ru   rv   already_has_special_tokensrw   c                    sf   |rt  j||ddS |dk	rLdgdgt|  dg dgt|  dg S 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}   N   r   )r_   get_special_tokens_maskr9   )ra   ru   rv   r}   rc   r)   r*   r   a  s      .z+LayoutLMv2Tokenizer.get_special_tokens_maskc                 C   sV   | j g}| jg}|dkr.t|| | dg S t|| | dg t|| dg  S )a  
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
        pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second
        sequence | If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

        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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        Nr   r~   )ry   rx   r9   )ra   ru   rv   r{   rz   r)   r)   r*   $create_token_type_ids_from_sequences}  s
    z8LayoutLMv2Tokenizer.create_token_type_ids_from_sequences)save_directoryfilename_prefixrw   c              	   C   s   d}t j|r4t j||r$|d ndtd  }n|r@|d nd| }t|dddZ}t| j dd	 d
D ]<\}}||krt	
d| d |}||d  |d7 }qnW 5 Q R X |fS )Nr   -rq   r   wr   r   c                 S   s   | d S )Nr~   r)   )kvr)   r)   r*   <lambda>      z5LayoutLMv2Tokenizer.save_vocabulary.<locals>.<lambda>)keyzSaving vocabulary to z\: vocabulary indices are not consecutive. Please check that the vocabulary is not corrupted!r   r~   )rT   rU   isdirrr   VOCAB_FILES_NAMESr    sortedr$   rX   loggerwarningwrite)ra   r   r   r'   r   writerr(   Ztoken_indexr)   r)   r*   save_vocabulary  s"     
z#LayoutLMv2Tokenizer.save_vocabulary)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verboserw   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)
isinstancer]   listtupler9   )tr)   r)   r*   _is_valid_text_input  s    
"z:LayoutLMv2Tokenizer.__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   )	rW   r   r   r   r9   zipboolbatch_encode_plusencode_plus)ra   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   Z
is_batchedwordsZwords_exampleboxes_exampler   r   r)   r)   r*   __call__  s    *$zLayoutLMv2Tokenizer.__call__)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   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)ra   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   r)   r)   r*   r   =  s>    	z%LayoutLMv2Tokenizer.batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   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   )ra   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   batch_outputsr)   r)   r*   r   x  s0    z&LayoutLMv2Tokenizer._batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   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)
r"   r   prepare_for_modelr   
DO_NOT_PADvaluerX   r:   padr   )ra   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r>   ZexampleZbatch_text_or_text_pairr   outputsr   r   r)   r)   r*   r     sH    z,LayoutLMv2Tokenizer._batch_prepare_for_modelc                 K   s>   | j f |||||||||	|
||||||||d|}|d S )Nr   	input_ids)r   )ra   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   encoded_inputsr)   r)   r*   encode  s.    zLayoutLMv2Tokenizer.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)ra   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   r)   r)   r*   r   %  s>    $	zLayoutLMv2Tokenizer.encode_plus)r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   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   )ra   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r)   r)   r*   r   h  s0    z LayoutLMv2Tokenizer._encode_plus)r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   c           -   
      s8   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< |r> | |!}* | |!}+ jg|  jg }|r"| jg }|rv jg|  jg }n8|"rL| |! n| }*dgt|  |"rpd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. 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)   )rQ   )r5   _rf   r)   r*   rE     s     z9LayoutLMv2Tokenizer.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   )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_idsattention_maskoverflowing_tokensoverflowing_token_boxesoverflowing_labelsZnum_truncated_tokensr   bboxspecial_tokens_maskr   )r   r   r   r   length)r   r   )r   r   r9   rj   extendrS   rR   r8   Zconvert_tokens_to_idsr   LONGEST_FIRSTrW   r   Znum_special_tokens_to_addDO_NOT_TRUNCATEtruncate_sequencesmodel_input_namesr|   r   rO   rP   r   Z&_eventual_warn_about_too_long_sequencer   r   r   r   r   )-ra   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   r&   Zpair_tokenstoken_boxesr   r   wordboxZword_tokenslabelrD   r   r   Zlen_idsZlen_pair_idsZ	total_lenr   r   r   r   sequencer   r   r)   rf   r*   r     s    ,	




"








&  z%LayoutLMv2Tokenizer.prepare_for_modellongest_first)	rD   r   r   r   r   r   r   r   rw   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.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   r9   minr   errorr   r   r8   ZONLY_SECOND)ra   rD   r   r   r   r   r   r   r   r   r   r   Z
window_len	error_msgr   r)   r)   r*   r   o  sp    5


z&LayoutLMv2Tokenizer.truncate_sequences)r   r   r   r   r   rw   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LONGESTr9   r   Zpadding_sideZpad_token_type_idrQ   rR   Zpad_token_idrW   r]   )	ra   r   r   r   r   r   Zrequired_inputZneeds_to_be_padded
differencer)   r)   r*   _pad  sR     









zLayoutLMv2Tokenizer._pad)N)NF)N)N)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_sizesPRETRAINED_INIT_CONFIGURATIONZpretrained_init_configurationintr   r   r]   r`   propertyr   rg   ri   rl   rn   ro   rt   r|   r   r   r   r   r   r   "LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING2LAYOUTLMV2_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   rh   r   __classcell__r)   r)   rc   r*   r@      s.  



B

  
    
   
                                   A7F                 

.                 

E

4                  

 W      



 r@   c                   @   sN   e Zd ZdZdddZdddZdd	 Zdd
dZdd Zdd Z	dd Z
dS )rZ   a  
    Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).

    Args:
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        never_split (`Iterable`, *optional*):
            Collection of tokens which will never be split during tokenization. Only has an effect when
            `do_basic_tokenize=True`
        tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
            Whether or not to tokenize Chinese characters.

            This should likely be deactivated for Japanese (see this
            [issue](https://github.com/huggingface/transformers/issues/328)).
        strip_accents (`bool`, *optional*):
            Whether or not to strip all accents. If this option is not specified, then it will be determined by the
            value for `lowercase` (as in the original BERT).
        do_split_on_punc (`bool`, *optional*, defaults to `True`):
            In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
            the full context of the words, such as contractions.
    TNc                 C   s2   |d krg }|| _ t|| _|| _|| _|| _d S re   )r   setrF   rG   rH   do_split_on_punc)ra   r   rF   rG   rH   r   r)   r)   r*   r`   Y  s    
zBasicTokenizer.__init__c                 C   s   |r| j t|n| j }| |}| jr4| |}td|}t|}g }|D ]R}||kr| j	r|
 }| jdk	r| |}n| jr| |}|| || qPtd|}|S )aj  
        Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.

        Args:
            never_split (`List[str]`, *optional*)
                Kept for backward compatibility purposes. Now implemented directly at the base class level (see
                [`PreTrainedTokenizer.tokenize`]) List of token not to split.
        NFCFrp   )rF   unionr   _clean_textrG   _tokenize_chinese_charsr1   	normalizer/   r   lowerrH   _run_strip_accentsr   _run_split_on_puncrr   )ra   r.   rF   Zunicode_normalized_textZorig_tokensrk   r(   output_tokensr)   r)   r*   rj   i  s$    




zBasicTokenizer.tokenizec                 C   sB   t d|}g }|D ]"}t |}|dkr,q|| qd|S )z$Strips accents from a piece of text.ZNFDZMnrq   )r1   r   r2   r:   rr   )ra   r.   outputcharcatr)   r)   r*   r     s    
z!BasicTokenizer._run_strip_accentsc                 C   s   | j r|dk	r||kr|gS t|}d}d}g }|t|k r|| }t|r^||g d}n |rl|g  d}|d | |d7 }q0dd |D S )	z&Splits punctuation on a piece of text.Nr   TFr   r~   c                 S   s   g | ]}d  |qS )rq   )rr   )r5   xr)   r)   r*   rE     s     z5BasicTokenizer._run_split_on_punc.<locals>.<listcomp>)r   r   r9   r
   r:   )ra   r.   rF   charsr6   Zstart_new_wordr   r   r)   r)   r*   r     s"    

z!BasicTokenizer._run_split_on_puncc                 C   sT   g }|D ]@}t |}| |r>|d || |d q|| qd|S )z)Adds whitespace around any CJK character.rp   rq   )ord_is_chinese_charr:   rr   ra   r.   r   r   cpr)   r)   r*   r     s    


z&BasicTokenizer._tokenize_chinese_charsc                 C   s   |dkr|dks|dkr |dks|dkr0|dks|dkr@|dks|d	krP|d
ks|dkr`|dks|dkrp|dks|dkr|dkrdS dS )z6Checks whether CP is the codepoint of a CJK character.i N  i  i 4  iM  i   iߦ i  i? i@ i i  i i   i  i  i TFr)   )ra   r  r)   r)   r*   r    sD    
zBasicTokenizer._is_chinese_charc                 C   sX   g }|D ]D}t |}|dks|dkst|r.qt|rB|d q|| qd|S )zBPerforms invalid character removal and whitespace cleanup on text.r   i  rp   rq   )r  r	   r   r:   rr   r  r)   r)   r*   r     s    zBasicTokenizer._clean_text)TNTNT)N)N)r   r   r   r   r`   rj   r   r   r   r  r   r)   r)   r)   r*   rZ   B  s        

&
rZ   c                   @   s"   e Zd ZdZdddZdd ZdS )	r\   zRuns WordPiece tokenization.d   c                 C   s   || _ || _|| _d S re   )r$   rI   max_input_chars_per_word)ra   r$   rI   r  r)   r)   r*   r`     s    zWordpieceTokenizer.__init__c                 C   s   g }t |D ]}t|}t|| jkr4|| j qd}d}g }|t|k rt|}d}	||k rd||| }
|dkrd|
 }
|
| jkr|
}	q|d8 }qX|	dkrd}q||	 |}q@|r|| j q|| q|S )a  
        Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
        tokenization using the given vocabulary.

        For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.

        Args:
            text: A single token or whitespace separated tokens. This should have
                already been passed through *BasicTokenizer*.

        Returns:
            A list of wordpiece tokens.
        Fr   Nrq   z##r~   T)	r/   r   r9   r  r:   rI   rr   r$   r   )ra   r.   r   r(   r  Zis_badstartZ
sub_tokensendZ
cur_substrsubstrr)   r)   r*   rj     s:    


zWordpieceTokenizer.tokenizeN)r  )r   r   r   r   r`   rj   r)   r)   r)   r*   r\     s   
r\   )1r   r   rT   sysr1   typingr   r   r   r   r   Ztokenization_utilsr   r	   r
   r   Ztokenization_utils_baser   r   r   r   r   r   utilsr   r   r   r   Z
get_loggerr   r   r   r   r   r   r   r   r+   r/   rh   fromkeysr8   
maxunicodetabler?   r@   objectrZ   r\   r)   r)   r)   r*   <module>   sN    
1:	        | #