U
    4Af[                     @   s
  d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
m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 ddlmZmZmZmZ dd	lmZ e rddlZe e!Z"d
ddZ#G dd deZ$dZ%e dd Z&dd Z'G dd dZ(G dd deZ)dS )zTokenization classes for TAPEX.    N)	lru_cache)DictListOptionalTupleUnion   )ExplicitEnumPaddingStrategy
TensorTypeadd_end_docstringsis_pandas_available)
AddedTokenPreTrainedTokenizer)ENCODE_KWARGS_DOCSTRINGBatchEncoding	TextInputTruncationStrategy)loggingz
vocab.jsonz
merges.txt)
vocab_filemerges_filec                   @   s   e Zd ZdZdZdS )TapexTruncationStrategyz}
    Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
    Zdrop_rows_to_fitN)__name__
__module____qualname____doc__DROP_ROWS_TO_FIT r   r   [/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/deprecated/tapex/tokenization_tapex.pyr   (   s   r   a  
            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`, [`TapexTruncationStrategy`] or [`~tokenization_utils_base.TruncationStrategy`],
                   *optional*, defaults to `False`):

                Activates and controls truncation. Accepts the following values:

                - `'drop_rows_to_fit'`: 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
                  row by row, removing rows from the table.
                - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
                  to the maximum acceptable input length for the model if that argument is not provided. This will
                  truncate token by token, removing a token from the longest sequence in the pair if a pair of
                  sequences (or a batch of pairs) is provided.
                - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
                  maximum acceptable input length for the model if that argument is not provided. This will only
                  truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
                  maximum acceptable input length for the model if that argument is not provided. This will only
                  truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
                - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
                  greater than the model maximum admissible input size).
            max_length (`int`, *optional*):
                Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
                `None`, this will use the predefined model maximum length if a maximum length is required by one of the
                truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
                truncation/padding to a maximum length will be deactivated.
            stride (`int`, *optional*, defaults to 0):
                If set to a number along with `max_length`, the overflowing tokens returned when
                `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
                returned to provide some overlap between truncated and overflowing sequences. The value of this
                argument defines the number of overlapping tokens.
            pad_to_multiple_of (`int`, *optional*):
                If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
                the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
            return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
c                  C   s   t ttdtdd t ttdtdd  t ttdtdd  } | dd }d	}td
D ],}|| krf| | |d
|  |d7 }qfdd |D }tt| |S )a3  
    Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
    characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
    of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
    you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
    vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
    !~      ¡   ¬   ®   ÿNr      c                 S   s   g | ]}t |qS r   )chr).0nr   r   r   
<listcomp>y   s     z$bytes_to_unicode.<locals>.<listcomp>)listrangeordappenddictzip)bscsr)   br   r   r   bytes_to_unicodef   s    
L

r4   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    r:   c                   @   s<   e Zd ZdZedddZedddZeedd	d
Z	dS )IndexedRowTableLinearizezQ
    FORMAT: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
    )table_contentc                 C   sd   d|krd|kst | j| |d d }t|d D ]"\}}|| j||d dd 7 }q8| S )zs
        Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
        headerrows r!   )	row_index)AssertionErrorZPROMPT_MESSAGEprocess_header	enumerateprocess_rowstrip)selfr<   Z	table_strirow_exampler   r   r   process_table   s
    z&IndexedRowTableLinearize.process_table)headersc                 C   s   dd | S )z}
        Given a list of headers, TableLinearize aims at converting it into a flatten sequence with special symbols.
        zcol :  | )join)rF   rJ   r   r   r   rB      s    z'IndexedRowTableLinearize.process_header)rowr@   c                 C   sX   d}g }|D ](}t |tr*|t| q|| q|d|7 }dt| d | S )zq
        Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
         rK   zrow z : )
isinstanceintr.   strrL   )rF   rM   r@   Zrow_strZrow_cell_values
cell_valuer   r   r   rD      s    
z$IndexedRowTableLinearize.process_rowN)
r   r   r   r   r   rI   r   rB   rP   rD   r   r   r   r   r;      s   r;   c                       s  e Zd ZdZeZddgZdc f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dgddZedd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zdhee
e ee d(d)d*Zeeedied,ed, f e
eeee f  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$djed,ed, f e
eeee f  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-d0d1Z%eeedked,ed, f e
ee  ee eeeee f eeef e
e	 e
e	 e
eee"f  e
e e
e eeeeee#d2d3d4Z&ddde j'e!j(dd+dddddddddfed,ed, f 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#d5d6d7Z)eeeddde j'e!j(dd+ddddddddfed,ed, f e
eeee f  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#d8d9d:Z*eedld,e
e e
e eeeee f eeee!e+f e
e	 e
eee"f  ee	 d;	d<d=Z,eeedmd,e
e e
e eeeee f eeef e
e	 e
e	 e
eee"f  e
e e
e eeeee#d>d?d@Z-ddde j'e!j(dd+dddddddddfd,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#d5dAdBZ.dne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#dCdDdEZ/doee eeeee f eeef e
e	 e
e	 e
eee"f  e
e e
e eeeeee#dFdGdHZ0de j'e!j(dd+dddddddddfee ee e!e
e	 e	e
e	 e
eee"f  e
e e
e eeeeee#dIdJdKZ1dpeeeeee f eeee!e+f e
e	 e
eee"f  ee	 dLdMdNZ2dqeeeeee f eeef e
e	 e
e	 e
eee"f  e
e e
e eeeee#dOdPdQZ3de j'e!j(dd+dddddddddfeee e!e
e	 e	e
e	 e
eee"f  e
e e
e eeeeee#dIdRdSZ4deee!e+f dfdTdUZ5e6eedVdWdXZ7dYdZ Z8dre6ee
eeee f  dVd[d\Z9dse6ed]d^d_Z:e6eee;d`dadbZ<  Z=S )tTapexTokenizera  
    Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).

    This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences
    to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:

    sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...

    The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table
    will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated
    for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to
    the tokenizer for instance to prepare them for the model.

    Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.

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

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        do_lower_case (`bool`, *optional*, defaults to `True`):
            Whether or not to lowercase the input when tokenizing.
        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. (BART tokenizer detect beginning of words by the preceding space).
        max_cell_length (`int`, *optional*, defaults to 15):
            Maximum number of characters per cell when linearizing a table. If this number is exceeded, truncation
            takes place.
    	input_idsZattention_maskTreplace<s></s><unk><pad><mask>F   c                    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| || _t | _d S )NF)lstriprstripTutf-8encodingc                 S   s   i | ]\}}||qS r   r   r(   kvr   r   r   
<dictcomp>  s      z+TapexTokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r   r   ra   r   r   r   rd     s      
r!   c                 S   s   g | ]}t | qS r   )tuplesplit)r(   merger   r   r   r*     s     z+TapexTokenizer.__init__.<locals>.<listcomp>zJ's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+)r   r   do_lower_caseerrors	bos_token	eos_token	unk_token	sep_token	cls_token	pad_token
mask_tokenadd_prefix_spacemax_cell_length)rO   rQ   r   openjsonloadencoderitemsdecoderrk   r4   byte_encoderbyte_decoderreadrh   r/   r0   r,   len	bpe_rankscachers   rj   recompilepatsuper__init__rt   r;   table_linearize)rF   r   r   rj   rk   rl   rm   ro   rp   rn   rq   rr   rs   rt   kwargsZvocab_handleZmerges_handleZ
bpe_merges	__class__r   r   r      sP     zTapexTokenizer.__init__N)token_ids_0token_ids_1returnc                 C   sD   |dkr| j g| | jg S | j g}| jg}|| | | | | S )a  
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A TAPEX 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)rF   r   r   clssepr   r   r    build_inputs_with_special_tokens>  s
    z/TapexTokenizer.build_inputs_with_special_tokens)r   r   already_has_special_tokensr   c                    sh   |rt  j||ddS |dkr8dgdgt|  dg S dgdgt|  ddg dgt|  dg S )a  
        Args:
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.
        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        T)r   r   r   Nr!   r   )r   get_special_tokens_maskr~   )rF   r   r   r   r   r   r   r   U  s      z&TapexTokenizer.get_special_tokens_maskc                 C   sP   | j g}| jg}|dkr.t|| | dg S t|| | | | | dg S )a  
        Args:
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
        make use of token type ids, therefore a list of zeros is returned.
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
        Returns:
            `List[int]`: List of zeros.
        Nr   )r   r   r~   )rF   r   r   r   r   r   r   r   $create_token_type_ids_from_sequencesn  s
    z3TapexTokenizer.create_token_type_ids_from_sequencesc                 K   s>   | d| j}|s|r6t|dkr6|d  s6d| }||fS )Nrs   r   r?   )poprs   r~   isspace)rF   textZis_split_into_wordsr   rs   r   r   r   prepare_for_tokenization  s     z'TapexTokenizer.prepare_for_tokenizationc                 C   s
   t | jS N)r~   rx   rF   r   r   r   
vocab_size  s    zTapexTokenizer.vocab_sizec                 C   s   t | jf| jS r   )r/   rx   Zadded_tokens_encoderr   r   r   r   	get_vocab  s    zTapexTokenizer.get_vocabc           
         sd  | j kr j | S t|}t|}|s,|S t| fddd}| jkrNqL|\}}g }d}|t|k r"z|||}	W n, tk
r   |||d   Y q"Y nX ||||	  |	}|| |kr
|t|d k r
||d  |kr
|	||  |d7 }q^|	||  |d7 }q^t|}|}t|dkrBqLq,t|}q,d
|}| j |< |S )Nc                    s    j | tdS )Ninf)r   getfloat)pairr   r   r   <lambda>      z$TapexTokenizer.bpe.<locals>.<lambda>keyr   r!      r?   )r   rg   r:   minr   r~   index
ValueErrorextendr.   rL   )
rF   tokenr7   r8   ZbigramfirstsecondZnew_wordrG   jr   r   r   bpe  sB    


2




zTapexTokenizer.bpec                    sZ   g }t  j|D ]B}d fdd|dD }|dd  |dD  q|S )zTokenize a string.rN   c                 3   s   | ]} j | V  qd S r   )r{   )r(   r3   r   r   r   	<genexpr>  s    z+TapexTokenizer._tokenize.<locals>.<genexpr>r^   c                 s   s   | ]
}|V  qd S r   r   )r(   Z	bpe_tokenr   r   r   r     s     r?   )r   findallr   rL   encoder   r   rh   )rF   r   
bpe_tokensr   r   r   r   	_tokenize  s    "zTapexTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)rx   r   rn   )rF   r   r   r   r   _convert_token_to_id  s    z#TapexTokenizer._convert_token_to_idc                 C   s   | j |S )z=Converts an index (integer) in a token (str) using the vocab.)rz   r   )rF   r   r   r   r   _convert_id_to_token  s    z#TapexTokenizer._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.rN   c                    s   g | ]} j | qS r   )r|   )r(   cr   r   r   r*     s     z;TapexTokenizer.convert_tokens_to_string.<locals>.<listcomp>r^   )rk   )rL   	bytearraydecoderk   )rF   tokensr   r   r   r   convert_tokens_to_string  s    
"z'TapexTokenizer.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||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-rN   r   r   wr^   r_   r   TF)indent	sort_keysensure_asciire   r   z#version: 0.2
c                 S   s   | d S )Nr!   r   )kvr   r   r   r     r   z0TapexTokenizer.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errorrL   VOCAB_FILES_NAMESru   writerv   dumpsrx   sortedr   ry   warning)
rF   r   r   r   Z
merge_filefr   writerr   Ztoken_indexr   r   r   save_vocabulary  s2      (

zTapexTokenizer.save_vocabularyr   zpd.DataFrame)tablequeryanswer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k	r<| j f |||||||||	|
|||||||d|S |dk	rt| jf |||||||	|
|||||||d|S tddS )aY  
        Main method to tokenize and prepare for the model one or several table-sequence pair(s).

        Args:
            table (`pd.DataFrame`, `List[pd.DataFrame]`):
                Table(s) containing tabular data.
            query (`str` or `List[str]`, *optional*):
                Sentence or batch of sentences related to one or more table(s) to be encoded. Note that the number of
                sentences must match the number of tables.
            answer (`str` or `List[str]`, *optional*):
                Optionally, the corresponding answer to the questions as supervision.
        N)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   z4You need to provide either a `table` or an `answer`.)source_call_functarget_call_funcr   )rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __call__  sV    #zTapexTokenizer.__call__c                 K   s   d}d}t |tjrd}n"t |ttfr<t |d tjr<d}|d ksNt |trTd}n,t |ttfrt|dks|t |d trd}|std|stdt |ttfpt |ttf}|r| jf ||||||||	|
|||||||d|S | j	f ||||||||	|
|||||||d|S d S )NFTr   zdtable input must of type `pd.DataFrame` (single example), `List[pd.DataFrame]` (batch of examples). zRquery input must of type `str` (single example), `List[str]` (batch of examples). )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )
rO   pd	DataFramer+   rg   rQ   r~   r   batch_encode_plusencode_plus)rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zvalid_tableZvalid_query
is_batchedr   r   r   r   =  sv    zTapexTokenizer.source_call_func)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sV   | j f |||||d|\}}}}| jf |||||||||	|
||||||d|S )z}
        <Tip warning={true}>

        This method is deprecated, `__call__` should be used instead.

        </Tip>
        r   r   r   r   r   )r   r   r   r   padding_strategytruncation_strategyr   r   r   r   r   r   r   r   r   r   )"_get_padding_truncation_strategies_batch_encode_plus)rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s:    	z TapexTokenizer.batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   s   |rt dt|tjr4t|ttfr4|gt| }t|ttfrZt|trZ|gt| }| 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   )
NotImplementedErrorrO   r   r   r+   rg   r~   rQ   _batch_prepare_for_modelr   )rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   batch_outputsr   r   r   r     s6    z!TapexTokenizer._batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 C   s   i }|dkrdgt | }t|||D ]\}}}| j|||||d}| jrR| }| |}| j| ||tj	j
|j
||dd||||dd|d}| D ]&\}}||krg ||< || | qq&| j||j
||	|d}t||
d}|S )z
        This method 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.
        Nr   r   Fidsr   r   r   r   r   r   r   r   r   r   r   r   prepend_batch_axisr   r   r   r   r   Ztensor_type)r~   r0   prepare_table_queryrj   lowertokenizeprepare_for_modelconvert_tokens_to_idsr
   
DO_NOT_PADvaluery   r.   padr   )rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z_tableZ_queryZ_answerr   r   outputsr   r   r   r   r   r     sX        
z'TapexTokenizer._batch_prepare_for_model)	r   r   r   r   r   r   r   r   r   c	              
   K   s*   | j |f|||||||d|	}
|
d S )a6  
        Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
        attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
        your processing on your own, otherwise refer to `__call__`.
        )r   r   r   r   r   r   r   rT   )r   )rF   r   r   r   r   r   r   r   r   r   Zencoded_inputsr   r   r   r   O  s    	zTapexTokenizer.encode)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sT   | j f |||||d|\}}}}| jf |||||||||	|
|||||d|S )Nr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   _encode_plus)rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   o  s8    	zTapexTokenizer.encode_plusc                 K   sj   |rt d| j|||||d}| jr.| }| |}| j| |||j|j|||	|
d||||||dS )N  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/2674r   Tr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   rj   r   r   r   r   r   )rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s>        
zTapexTokenizer._encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sr   t |ttf}|r@| jf ||||||||	|
|||||d|S | jf ||||||||	|
|||||d|S dS )z
        The method tokenizes and prepares the answer label for the model.

        Args:
            answer (`str` or `List[str]`):
                Corresponding answer supervision to the queries for training the model.
        )r   r   r   r   r   r   r   r   r   r   r   r   r   r   N)rO   r+   rg   target_batch_encode_plustarget_encode_plus)rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     sL    zTapexTokenizer.target_call_func)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sR   | j f |||||d|\}}}}| jf |||||||||	|
||||d|S )z
        Prepare answer strings for the model.

        Args:
            answer `List[str]`:
                Corresponding answer supervision to the queries for training the model.
        r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   _target_batch_encode_plus)rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    s6    	z'TapexTokenizer.target_batch_encode_plus)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   s   i }|D ]}| j r| }| |}| j| ||tjj|j||d d|	|||d d|d}| D ]&\}}||krxg ||< || 	| q`q| j
||j|||
d}t||d}t|S )NFr   r   r   )rj   r   r   r   r   r
   r   r   ry   r.   r   r   )rF   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  P  sF    
z(TapexTokenizer._target_batch_encode_plus)r   r   r   r   r   r   r   c           	   	   K   s&   | j f ||||||d|}|d S )a  
        Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
        which are necessary for the model to work correctly. Use this method if you want to build your processing on
        your own, otherwise refer to `__call__`.

        Args:
            answer `str`:
                Corresponding answer supervision to the queries for training the model
        )r   r   r   r   r   r   rT   )r  )	rF   r   r   r   r   r   r   r   Zencoded_outputsr   r   r   target_encode  s    
zTapexTokenizer.target_encode)r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                 K   sP   | j f |||||d|\}}}}| jf |||||||||	|
|||d|S )z
        Prepare a answer string for the model.

        Args:
            answer `str`:
                Corresponding answer supervision to the queries for training the model.
        r   )r   r   r   r   r   r   r   r   r   r   r   r   r   )r   _target_encode_plus)rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    s4    	z!TapexTokenizer.target_encode_plusc                 K   sZ   |rt d|}| jr| }| |}| j| |||j|j||||d|
|	||||dS )Nr  Tr  )r   rj   r   r   r   r   r   )rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    s2    
z"TapexTokenizer._target_encode_plusc           
      C   s   |j s\t|jdd | D d}| ||| |tjkrN| j||||d | j	|}nd}|dkr~t
dd| d  |dkrt
d	 |r|rd
nd}|r|| | n|}	|	S )z
        This method can be used to linearize a table and add a corresponding query.

        Optionally, it also handles truncation of the table (cells).

        An answer can be provided for more precise truncation.
        c                 S   s   g | ]\}}t |jqS r   )r+   values)r(   rG   rM   r   r   r   r*   %  s     z6TapexTokenizer.prepare_table_query.<locals>.<listcomp>)r=   r>   )r   rN   zUYou provide an empty table, or all cells contain much tokens (e.g., >= 1024 tokens). z@Please carefully check the corresponding table with the query : .z7You provide nothing to query with respect to the table.r?   )emptyr+   columnsZiterrowstruncate_table_cellsr   r   truncate_table_rowsr   rI   r   r   )
rF   r   r   r   r   r   r<   Zlinear_table	separatorZjoint_inputr   r   r   r     s$    


z"TapexTokenizer.prepare_table_query)r<   questionr   c           
      C   s|   i }|d D ]8}t |D ]*\}}| |}|d k	r|||< |||< qq|d k	rxt |D ] \}}	|	| krV||	 ||< qVd S )Nr>   )rC   truncate_cellkeys)
rF   r<   r  r   Zcell_mappingrM   rG   cellr  Zcaser   r   r   r  @  s    
z#TapexTokenizer.truncate_table_cellsc                 C   sf   t |tst |tr|S | dkr^| |}t|| jkrX|d | j }| |}|S d S n|S d S )NrN   )rO   rP   r   rE   r   r~   rt   r   )rF   rR   Z
try_tokensZretain_tokensZretain_cell_valuer   r   r   r  P  s    

zTapexTokenizer.truncate_cellc                 C   s   |  |||\}}| |||| d}t|d D ]D\}}	| j|	|d }
t| |
}||krf qx||8 }|d7 }q2|d |d= dS )a  
        Args:
        table_content:
            {"header": xxx, "rows": xxx, "id" (Optionally): xxx}

        question:
            natural language sentence

        answer:
            if for training, is the supervision; otherwise will be empty
        r   r>   r!   N)estimate_delete_ratiodelete_unrelated_rowsrC   r   rD   r~   r   )rF   r<   r  r   r   delete_ratioremain_token_lenZmaximum_keep_rowsindrH   value_stringvalue_token_lenr   r   r   r  _  s    
z"TapexTokenizer.truncate_table_rows)r<   r  c                 C   s   d|ksd|krt d| j|dd}| j|d }| j|dd}t|t| }|| }d}	t|d D ]\}
}|	| j|dd	 7 }	qlt| |	}||k rd
|fS d||  |fS d S )Nr=   r>   z?The table content should contain both 'header' and 'rows' keys.T)r   FrN   d   r?   g        g      ?)r   r   r   rB   r~   rC   rD   )rF   r<   r  r   Zquestion_tokensZheader_stringZheader_tokensZused_token_lenr  r  _rH   r  r   r   r   r  |  s    z$TapexTokenizer.estimate_delete_ratio)r<   r  r   r  c              	      sx  g }g  |dkst |dkr$t }ndd |D }|dk	rH||  t|dd}t |d }t|d D ]f\}	}
dd |
D }t ||@ dkrt ||@ dkr||	 qt |	d	 |	d
 |	|	d
 |	d	 g qt fdd|D }tt |t	t |d | }t
j||d}tt|D ]}	|	|kr&|d |	= q&d|krtt |dkrttdt ||d  dS )zC
        The argument answer is used only during training.
        Nr   c                 S   s   h | ]}|  qS r   )r   )r(   Zans_exr   r   r   	<setcomp>  s     z7TapexTokenizer.delete_unrelated_rows.<locals>.<setcomp>z?!.,r?   r>   c                 S   s   h | ]}t | qS r   )rQ   r   )r(   r  r   r   r   r    s     r   r!   c                    s   g | ]}| kr|qS r   r   )r(   _row_idxZrelated_indicesr   r   r*     s     z8TapexTokenizer.delete_unrelated_rows.<locals>.<listcomp>)rb   idzDelete {:.2f} rows in table {})r~   r5   updaterh   rE   rC   r.   r   r   rP   randomchoicesreversedr,   r   r   format)rF   r<   r  r   r  Ztruncated_unrelated_indicesZ
answer_setZquestion_setZrow_max_lenr  rM   Z	lower_rowZ
drop_itemsZdrop_row_indicesr   r  r   r    s0     &

z$TapexTokenizer.delete_unrelated_rows)TrU   rV   rW   rW   rV   rX   rY   rZ   Fr[   )N)NF)N)F)N)NNNTFNNr   NNNNFFFFT)NNTFNNr   NNNNFFFFT)NNTFNNNNNNFFFFT)NNTFNNN)NNTFNNNNNNFFFT)TFNNr   NNNNFFFFT)TFNNNNNNFFFFT)TFNNN)TFNNNNNNFFFT)NN)N)>r   r   r   r   r   Zvocab_files_namesZmodel_input_namesr   r   rP   r   r   boolr   r   r   propertyr   r   r   r   r   r   r   rQ   r   r   r   r   -TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRINGr   r   r
   r   r   r   r   r   r   r   ZDO_NOT_TRUNCATEr   r   r   r   r   r   r   r  r  r  r  r  r   r   r  r  r  r  r   r  __classcell__r   r   r   r   rS      s  G           C  
    
   


*
                 P                W               

<

:F                     
3=              D             
8?     "            
6:
,     rS   )*r   rv   r   r!  	functoolsr   typingr   r   r   r   r   regexr   Z
file_utilsr	   r
   r   r   r   Ztokenization_utilsr   r   Ztokenization_utils_baser   r   r   r   utilsr   Zpandasr   Z
get_loggerr   r   r   r   r'  r4   r:   r;   rS   r   r   r   r   <module>   s*   

6
'