
    gm=                        d Z ddlZddlmZmZmZ ddlmZ ddlm	Z	m
Z
mZmZ ddlmZ  ej        e          Zd	d
dZ G d de          Z G d de          Z ej        dg d          Z ej        dg d          ZdZ ee           G d d                      Z e
e           G d dee                      ZdS )zTokenization classes for DPR.    N)ListOptionalUnion   )BatchEncoding)
TensorTypeadd_end_docstringsadd_start_docstringslogging   )BertTokenizerz	vocab.txtztokenizer.json)
vocab_filetokenizer_filec                       e Zd ZdZeZdS )DPRContextEncoderTokenizera*  
    Construct a DPRContextEncoder tokenizer.

    [`DPRContextEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
    splitting and wordpiece.

    Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
    N__name__
__module____qualname____doc__VOCAB_FILES_NAMESvocab_files_names     d/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/dpr/tokenization_dpr.pyr   r      "          *r   r   c                       e Zd ZdZeZdS )DPRQuestionEncoderTokenizera-  
    Constructs a DPRQuestionEncoder tokenizer.

    [`DPRQuestionEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
    splitting and wordpiece.

    Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
    Nr   r   r   r   r   r   +   r   r   r   DPRSpanPrediction
span_scorerelevance_scoredoc_idstart_index	end_indextextDPRReaderOutput)start_logits
end_logitsrelevance_logitsa  
    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
    with the format:

    ```
    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
    ```

    Args:
        questions (`str` or `List[str]`):
            The questions to be encoded. You can specify one question for many passages. In this case, the question
            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
            `titles` or `texts`.
        titles (`str` or `List[str]`):
            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
        texts (`str` or `List[str]`):
            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
        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.
        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.
        return_attention_mask (`bool`, *optional*):
            Whether or not to return the attention mask. If not set, 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)

    Returns:
        `Dict[str, List[List[int]]]`: A dictionary with the following keys:

        - `input_ids`: List of token ids to be fed to a model.
        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.
    c                   0    e Zd Z	 	 	 	 	 	 	 ddee         dee         deeef         deeef         dee         deeeef                  d	ee         d
e	f fdZ
	 	 	 dde	dedededed
ee         fdZdee         dee         deded
ee         f
dZ xZS )CustomDPRReaderTokenizerMixinNFtitlestextspadding
truncation
max_lengthreturn_tensorsreturn_attention_maskreturnc	           	          |"|  t                      j        |f|||d|	S ||'||n|}
 t                      j        ||
f|||d|	S t          |t                    s|n|g}t          |t                    s|n|g}t	          |          }t          |t                    s|n|g|z  }t	          |          t	          |          k    r0t          dt	          |           dt	          |           d          t                                          ||dd          d         }t                                          |ddd          d         }dfd	t          ||          D             i}|dur3g }|d         D ]#}|                     fd
|D                        $||d<                        |||          S )N)r/   r0   r1   r2   r3   z2There should be as many titles than texts but got z titles and z texts.F)r/   r0   	input_ids)add_special_tokensr/   r0   c                 B    g | ]\  }}r||z   d          n||z   S Nr   ).0encoded_question_and_titleencoded_textr1   r0   s      r   
<listcomp>z:CustomDPRReaderTokenizerMixin.__call__.<locals>.<listcomp>   sV        =. )j) ,l:KZKHH/,>  r   c                 @    g | ]}t          |j        k              S r   )intpad_token_id)r:   input_idselfs     r   r=   z:CustomDPRReaderTokenizerMixin.__call__.<locals>.<listcomp>   s)    &d&d&dhs8t7H+H'I'I&d&d&dr   attention_mask)r/   r1   r2   )	super__call__
isinstancestrlen
ValueErrorzipappendpad)rB   	questionsr-   r.   r/   r0   r1   r2   r3   kwargs	text_pair
n_passagesencoded_question_and_titlesencoded_textsencoded_inputsrC   r6   	__class__s   `    ``          r   rE   z&CustomDPRReaderTokenizerMixin.__call__   ss    >em#577#%%-&;     ^u}"'-UI#577#	  %%-&;	 	 	 	 	  *&#66DVH's33@%[[
%/	3%?%?]IIi[S]E]	v;;#e**$$qS[[qq^abg^h^hqqq   ',gg&6&6y&RWdi&6&j&jkv&w#((5RWdi(jjkvw      ADD_an@o@o	  
 !--N+K8 f f	%%&d&d&d&dZc&d&d&deeee/=N+,xxJ_mxnnnr      @      reader_inputreader_output	num_spansmax_answer_lengthnum_spans_per_passagec                    |d         }|dd         \  }}}	t          |	          }
t          t          |
          d|	j                  }g }|D ]4}t	          ||                   }|                    | j        d          dz   }|d         | j        k    r|                    | j                  }nt          |          }|                     ||         ||         ||         ||         ||	          }|D ]v\  }}||z  }||z  }|	                    t          ||         |         ||         |         z   |	|         ||||                     |||dz                      
                     wt          |          |k    r n6|d|         S )a_  
        Get the span predictions for the extractive Q&A model.

        Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
        *DPRReaderOutput* is a *Tuple* with:

            - **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
              spans in the same passage. It corresponds to the sum of the start and end logits of the span.
            - **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
              compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
            - **doc_id**: `int` the id of the passage. - **start_index**: `int` the start index of the span
              (inclusive). - **end_index**: `int` the end index of the span (inclusive).

        Examples:

        ```python
        >>> from transformers import DPRReader, DPRReaderTokenizer

        >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
        >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
        >>> encoded_inputs = tokenizer(
        ...     questions=["What is love ?"],
        ...     titles=["Haddaway"],
        ...     texts=["'What Is Love' is a song recorded by the artist Haddaway"],
        ...     return_tensors="pt",
        ... )
        >>> outputs = model(**encoded_inputs)
        >>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
        >>> print(predicted_spans[0].text)  # best span
        a song
        ```r6   Nr   T)reversekeyr      )r(   r)   r[   	top_spansr    )rH   sortedrange__getitem__listindexsep_token_idr@   _get_best_spansrK   r   decode)rB   rX   rY   rZ   r[   r\   r6   r(   r)   r*   rP   sorted_docsnbest_spans_predictionsr#   sequence_idspassage_offsetsequence_len
best_spansr$   r%   s                       r   decode_best_spansz/CustomDPRReaderTokenizerMixin.decode_best_spans   s   N !-	5B2A25F2j"2)**
U:..BRB^___9;! 	 	F	& 122L)//0A1EEINB4#444+11$2CDD"<00--)&1.2MN%f-n\.IJ"3/	 .  J +5  &Y~-^+	'..%#/#7#DzRXGYZcGd#d(8(@%$/"+![[kIPQM6Q)RSS  	 	 	 	 *++y88 9&z	z22r   r(   r)   rb   c                    g }t          |          D ]D\  }t          ||z                      D ]$\  }}|                    |z   f||z   f           %Et          |d d          }g }	|D ]\  \  }
k    rt          d d d          z
  dz   }||k    rt          d| d	|           t	          fd
|	D                       rd|	                    f           t          |	          |k    r n|	S )z
        Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
        `span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
        c                     | d         S )Nr`   r   )xs    r   <lambda>z?CustomDPRReaderTokenizerMixin._get_best_spans.<locals>.<lambda>  s
    ad r   T)r_   r^   zWrong span indices: [:]r`   zSpan is too long: z > c              3   z   K   | ]5\  }}|cxk    o|cxk    ok    nc p|cxk    ocxk    o|k    nc V  6d S r9   r   )r:   prev_start_indexprev_end_indexr%   r$   s      r   	<genexpr>z@CustomDPRReaderTokenizerMixin._get_best_spans.<locals>.<genexpr>$  s         7%~ /NNNN>NNNNYNNNN R#{QQQQiQQQQ>QQQQ     r   )	enumeraterK   rc   rI   anyrH   )rB   r(   r)   r[   rb   scoresstart_scoreanswer_length	end_scorechosen_span_intervalsscorelengthr%   r$   s               @@r   ri   z-CustomDPRReaderTokenizerMixin._get_best_spans  s    (1,(?(? 	e 	e$K,5j{]nOnAn6o,p,p e e(y[=-HI;YbKbcddddeNNDAAA "/5 	 	+$[)eY&& !S!S!Sy!S!S!STTT,q0F))) !Tf!T!TAR!T!TUUU      ;P     
 !((+y)ABBB())Y66 7$$r   )NNFFNNN)rU   rV   rW   )r   r   r   r   rG   r   boolr?   r   r   rE   r'   r   r   rq   ri   __classcell__)rT   s   @r   r,   r,      s       
 !%#$)',$(;?049o 9o 9o }	9o
 tSy!9o $)$9o SM9o !sJ!789o  (~9o 
9o 9o 9o 9o 9o 9o~ !#%&J3 J3#J3 'J3 	J3
 J3  #J3 
	 J3 J3 J3 J3X!%3i!% I!% 	!%
 !% 
	 !% !% !% !% !% !% !% !%r   r,   c                       e Zd ZdZeZddgZdS )DPRReaderTokenizera  
    Construct a DPRReader tokenizer.

    [`DPRReaderTokenizer`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
    splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts that are
    combined to be fed to the [`DPRReader`] model.

    Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
    r6   rC   N)r   r   r   r   r   r   model_input_namesr   r   r   r   r   1  s.          *$&67r   r   )r   collectionstypingr   r   r   tokenization_utils_baser   utilsr   r	   r
   r   bert.tokenization_bertr   
get_loggerr   loggerr   r   r   
namedtupler   r'   CUSTOM_DPR_READER_DOCSTRINGr,   r   r   r   r   <module>r      s   $ #     ( ( ( ( ( ( ( ( ( ( 4 4 4 4 4 4 R R R R R R R R R R R R 2 2 2 2 2 2 
	H	%	%#.BRSS 
* 
* 
* 
* 
* 
* 
* 
*
* 
* 
* 
* 
*- 
* 
* 
* +K*hhh   )+():<n<n<nooB J 122i% i% i% i% i% i% i% 32i%X /008 8 8 8 86 8 8 108 8 8r   