Ë
    S^(h]?  ã                   óz  — 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 d	d
lmZmZmZ  ej&                  e«      ZdddœZ G d„ de«      Z G d„ de«      Z ej2                  dg d¢«      Z ej2                  dg d¢«      ZdZ ee«       G d„ d«      «       Z e
e«       G d„ dee«      «       Zg d¢Zy)zTokenization classes for DPR.é    N)ÚListÚOptionalÚUnioné   )ÚBatchEncoding)Ú
TensorTypeÚadd_end_docstringsÚadd_start_docstringsÚloggingé   )ÚBertTokenizerFasté   )ÚDPRContextEncoderTokenizerÚDPRQuestionEncoderTokenizerÚDPRReaderTokenizerz	vocab.txtztokenizer.json)Ú
vocab_fileÚtokenizer_filec                   ó   — e Zd ZdZeZeZy)ÚDPRContextEncoderTokenizerFastal  
    Construct a "fast" DPRContextEncoder tokenizer (backed by HuggingFace's *tokenizers* library).

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

    Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚVOCAB_FILES_NAMESÚvocab_files_namesr   Úslow_tokenizer_class© ó    úk/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/dpr/tokenization_dpr_fast.pyr   r      s   „ ñð *ÐØ5Ñr   r   c                   ó   — e Zd ZdZeZeZy)ÚDPRQuestionEncoderTokenizerFastao  
    Constructs a "fast" DPRQuestionEncoder tokenizer (backed by HuggingFace's *tokenizers* library).

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

    Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
    N)r   r   r   r   r   r   r   r   r   r   r   r!   r!   -   s   „ ñð *ÐØ6Ñ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)

    Return:
        `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                   óè   ‡ — 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 )ÚCustomDPRReaderTokenizerMixinÚtitlesÚtextsÚpaddingÚ
truncationÚ
max_lengthÚreturn_tensorsÚreturn_attention_maskÚreturnc	           
      ó  •— |€|€t        ‰| �  |f|||||dœ|	¤ŽS |�|€|€|n|}
t        ‰| �  ||
f|||||dœ|	¤ŽS t        |t        «      s|n|g}t        |t        «      s|n|g}t	        |«      }t        |t        «      s|n|g|z  }t	        |«      t	        |«      k(  s J dt	        |«      › dt	        |«      › d�«       ‚t         ‰| �  ||dd¬«      d   }t         ‰| �  |ddd¬«      d   }dt        ||«      D ��cg c]  \  }}|�
|r||z   d | n||z   ‘Œ c}}i}|durFg }|d   D ]7  }|j                  |D �cg c]  }t        || j                  k7  «      ‘Œ c}«       Œ9 ||d	<   | j                  ||||¬
«      S c c}}w c c}w )N)r2   r3   r4   r5   r6   z2There should be as many titles than texts but got z titles and z texts.F)r2   r3   Ú	input_ids)Úadd_special_tokensr2   r3   Úattention_mask)r2   r4   r5   )
ÚsuperÚ__call__Ú
isinstanceÚstrÚlenÚzipÚappendÚintÚpad_token_idÚpad)ÚselfÚ	questionsr0   r1   r2   r3   r4   r5   r6   ÚkwargsÚ	text_pairÚ
n_passagesÚencoded_question_and_titlesÚencoded_textsÚencoded_question_and_titleÚencoded_textÚencoded_inputsr;   r9   Úinput_idÚ	__class__s                       €r   r=   z&CustomDPRReaderTokenizerMixin.__call__‡   s)  ø€ ð ˆ>˜e˜mÜ‘7Ñ#ØðàØ%Ø%Ø-Ø&;ñð ñð ð ˆ^˜u˜}Ø"' -™°UˆIÜ‘7Ñ#ØØð	ð  Ø%Ø%Ø-Ø&;ñ	ð ñ	ð 	ô  *¨&´#Ô6‘¸V¸HˆÜ'¨¬sÔ3‘¸%¸ˆÜ˜“[ˆ
Ü%/°	¼3Ô%?‘IÀiÀ[ÐS]ÑE]ˆ	Ü�6‹{œc %›jÒ(ð 	
Ø@ÄÀVÃÀÈ\ÔZ]Ð^cÓZdÐYeÐelÐmó	
Ð(ô ',¡gÑ&6°yÀ&ÐRWÐdiÐ&6Ó&jÐkvÑ&wÐ#Ü™Ñ(¨À5ÐRWÐdiÐ(ÓjÐkvÑwˆàô ADÐD_ÐanÓ@o÷	ñ =Ð.°ð Ð)©jð ,¨lÑ:¸K¸ZÑHà/°,Ñ>ñ?óð
ˆð !¨Ñ-ØˆNØ+¨KÑ8ò f�	Ø×%Ñ%ÐZcÖ&dÈh¤s¨8°t×7HÑ7HÑ+HÕ'IÒ&dÕeðfà/=ˆNÐ+Ñ,Ø�x‰x˜°ÀJÐ_mˆxÓnÐnùóùò 'es   Ã=E<Ä:F
Úreader_inputÚreader_outputÚ	num_spansÚmax_answer_lengthÚnum_spans_per_passagec                 óv  — |d   }|dd \  }}}	t        |	«      }
t        t        |
«      d|	j                  ¬«      }g }|D ]ô  }t	        ||   «      }|j                  | j                  d«      dz   }|d   | j                  k(  r|j                  | j                  «      }nt        |«      }| j                  ||   || ||   || ||¬	«      }|D ]V  \  }}||z  }||z  }|j                  t        ||   |   ||   |   z   |	|   |||| j                  |||dz    «      ¬
«      «       ŒX t        |«      |k\  sŒô n |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
        ```r9   Nr   T)ÚreverseÚkeyr   r   éÿÿÿÿ)r+   r,   rU   Ú	top_spansr#   )r@   ÚsortedÚrangeÚ__getitem__ÚlistÚindexÚsep_token_idrD   Ú_get_best_spansrB   r"   Údecode)rF   rR   rS   rT   rU   rV   r9   r+   r,   r-   rJ   Ú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 ! Ñ-ˆ	Ø5BÀ2ÀAÐ5FÑ2ˆ�jÐ"2ÜÐ)Ó*ˆ
ÜœU :Ó.¸ÐBR×B^ÑB^Ô_ˆØ9;ÐØ!ò 	ˆFÜ 	¨&Ñ 1Ó2ˆLà)×/Ñ/°×0AÑ0AÀ1ÓEÈÑIˆNØ˜BÑ 4×#4Ñ#4Ò4Ø+×1Ñ1°$×2CÑ2CÓD‘ä" <Ó0�à×-Ñ-Ø)¨&Ñ1°.ÀÐNØ% fÑ-¨n¸\ÐJØ"3Ø/ð	 .ó ˆJð +5ò Ñ&�˜YØ˜~Ñ-�Ø˜^Ñ+�	Ø'×.Ñ.Ü%Ø#/°Ñ#7¸Ñ#DÀzÐRXÑGYÐZcÑGdÑ#dØ(8¸Ñ(@Ø%Ø$/Ø"+Ø!Ÿ[™[¨°kÀIÐPQÁMÐ)RÓSôõ	ðô Ð*Ó+¨yÓ8Ùð;	ð< ' z¨	Ð2Ð2r   r+   r,   r[   c                 ó¦  ‡‡— g }t        |«      D ]9  \  Š}t        |‰‰|z    «      D ]   \  }}|j                  ‰‰|z   f||z   f«       Œ" Œ; t        |d„ d¬«      }g }	|D ]o  \  \  ŠŠ}
‰‰k  sJ d‰› d‰› d�«       ‚‰‰z
  dz   }||k  sJ d|› d	|› �«       ‚t        ˆˆfd
„|	D «       «      rŒL|	j                  ‰‰f«       t	        |	«      |k(  sŒn |	S  |	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)rY   rX   zWrong span indices: [ú:ú]r   zSpan is too long: z > c              3   óˆ   •K  — | ]9  \  }}‰|cxk  xr |cxk  xr ‰k  nc xs |‰cxk  xr ‰cxk  xr |k  nc –— Œ; y ­w)Nr   )Ú.0Úprev_start_indexÚprev_end_indexr(   r'   s      €€r   ú	<genexpr>z@CustomDPRReaderTokenizerMixin._get_best_spans.<locals>.<genexpr>"  sN   øè ø€ ò ñ 7Ð% ~ð Ð/ÖN°>ÖNÀYÔNò RØ# {ÖQ°iÖQÀ>ÔQóRñùs   ƒ?A)Ú	enumeraterB   r\   Úanyr@   )rF   r+   r,   rU   r[   ÚscoresÚstart_scoreÚanswer_lengthÚ	end_scoreÚchosen_span_intervalsÚscoreÚlengthr(   r'   s               @@r   rb   z-CustomDPRReaderTokenizerMixin._get_best_spans  sF  ù€ ð ˆÜ(1°,Ó(?ò 	eÑ$ˆK˜Ü,5°jÀÈ{Ð]nÑOnÐ6oÓ,pò eÑ(�˜yØ—‘ ¨[¸=Ñ-HÐIÈ;ÐYbÑKbÐcÕdñeð	eô ˜¡N¸DÔAˆØ "ÐØ/5ò 	Ñ+Ñ$ˆ[˜) eØ )Ò+Ð_Ð/DÀ[ÀMÐQRÐS\ÐR]Ð]^Ð-_Ó_Ð+Ø Ñ,¨qÑ0ˆFØÐ.Ò.ÐcÐ2DÀVÀHÈCÐPaÐObÐ0cÓcÐ.Üô ð ;Pôô ð
 Ø!×(Ñ(¨+°yÐ)AÔBäÐ(Ó)¨YÓ6ØØ$Ð$ð	ð %Ð$r   )NNFFNNN)é   é@   é   )r   r   r   r   r?   r   ÚboolrC   r   r   r=   r*   r   r"   rj   rb   Ú__classcell__)rQ   s   @r   r/   r/   …   sD  ø„ ð
 !%Ø#Ø$)Ø',Ø$(Ø;?Ø04ñ8oð ˜‘ð8oð ˜‰}ð	8oð
 �t˜S�yÑ!ð8oð ˜$ ˜)Ñ$ð8oð ˜S‘Mð8oð !  s¨J Ñ!7Ñ8ð8oð  (¨™~ð8oð 
õ8oð| Ø!#Ø%&ñJ3à#ðJ3ð 'ðJ3ð ð	J3ð
 ðJ3ð  #ðJ3ð 
ÐÑ	 óJ3ðX%à˜3‘ið%ð ˜‘Ið%ð ð	%ð
 ð%ð 
ÐÑ	 ÷%r   r/   c                   ó    — e Zd ZdZeZddgZeZy)ÚDPRReaderTokenizerFastað  
    Constructs a "fast" DPRReader tokenizer (backed by HuggingFace's *tokenizers* library).

    [`DPRReaderTokenizerFast`] is almost identical to [`BertTokenizerFast`] 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 [`BertTokenizerFast`] for usage examples and documentation concerning parameters.

    r9   r;   N)	r   r   r   r   r   r   Úmodel_input_namesr   r   r   r   r   r…   r…   /  s!   „ ñ	ð *ÐØ$Ð&6Ð7ÐØ-Ñr   r…   )r   r!   r…   ) r   ÚcollectionsÚtypingr   r   r   Útokenization_utils_baser   Úutilsr   r	   r
   r   Úbert.tokenization_bert_fastr   Útokenization_dprr   r   r   Ú
get_loggerr   Úloggerr   r   r!   Ú
namedtupler"   r*   ÚCUSTOM_DPR_READER_DOCSTRINGr/   r…   Ú__all__r   r   r   ú<module>r’      sì   ðñ $ã ß (Ñ (å 4ß RÓ RÝ ;ß iÑ ið 
ˆ×	Ñ	˜HÓ	%€à#.ÐBRÑSÐ ô6Ð%6ô 6ô7Ð&7ô 7ð +�K×*Ñ*ØÒhóÐ ð )�+×(Ñ(Ð):Ò<nÓo€ð@Ð ñF Ð1Ó2÷f%ð f%ó 3ðf%ñR Ð/Ó0ô.Ð:Ð<Mó .ó 1ð.ò" j�r   