



import collections
from typing import List, Optional, Union

from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer


__snake_case						:Optional[int]						=					logging.get_logger(__name__)

__snake_case						:Optional[Any]						=					{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

__snake_case						:List[Any]						=					{
    '''vocab_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
__snake_case						:Optional[int]						=					{
    '''vocab_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
__snake_case						:Optional[Any]						=					{
    '''vocab_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}

__snake_case						:List[Any]						=					{
    '''facebook/dpr-ctx_encoder-single-nq-base''': 512,
    '''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
__snake_case						:str						=					{
    '''facebook/dpr-question_encoder-single-nq-base''': 512,
    '''facebook/dpr-question_encoder-multiset-base''': 512,
}
__snake_case						:str						=					{
    '''facebook/dpr-reader-single-nq-base''': 512,
    '''facebook/dpr-reader-multiset-base''': 512,
}


__snake_case						:Union[str, Any]						=					{
    '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
__snake_case						:List[str]						=					{
    '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
__snake_case						:List[str]						=					{
    '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}

class    _A	(     __UpperCAmelCase   ):
       UpperCamelCase__  :   Optional[Any]						 =						VOCAB_FILES_NAMES
       UpperCamelCase__  :   Any						 =						CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       UpperCamelCase__  :   Any						 =						CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       UpperCamelCase__  :   Tuple						 =						CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION


class    _A	(     __UpperCAmelCase   ):
       UpperCamelCase__  :   int						 =						VOCAB_FILES_NAMES
       UpperCamelCase__  :   List[str]						 =						QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       UpperCamelCase__  :   Any						 =						QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       UpperCamelCase__  :   Tuple						 =						QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION


__snake_case						:Tuple						=					collections.namedtuple(
    '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text''']
)

__snake_case						:Union[str, Any]						=					collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])


__snake_case						:Optional[int]						=					r'''
    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.
    '''

@add_start_docstrings(__UpperCAmelCase   )
class    _A	:



       def __call__(		self							:					int					,		__SCREAMING_SNAKE_CASE							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					Optional[str] = None					,		__SCREAMING_SNAKE_CASE							:					Optional[str] = None					,		__SCREAMING_SNAKE_CASE							:					Union[bool, str] = False					,		__SCREAMING_SNAKE_CASE							:					Union[bool, str] = False					,		__SCREAMING_SNAKE_CASE							:					Optional[int] = None					,		__SCREAMING_SNAKE_CASE							:					Optional[Union[str, TensorType]] = None					,		__SCREAMING_SNAKE_CASE							:					Optional[bool] = None					,		**__SCREAMING_SNAKE_CASE							:					Union[str, Any]					,		):


           '''simple docstring'''

           if titles is None and texts is None:
               return super().__call__(
                   __SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		truncation=__SCREAMING_SNAKE_CASE					,		max_length=__SCREAMING_SNAKE_CASE					,		return_tensors=__SCREAMING_SNAKE_CASE					,		return_attention_mask=__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		)
           elif titles is None or texts is None:
               __a							=    titles if texts is None else texts
               return super().__call__(
                   __SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		truncation=__SCREAMING_SNAKE_CASE					,		max_length=__SCREAMING_SNAKE_CASE					,		return_tensors=__SCREAMING_SNAKE_CASE					,		return_attention_mask=__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		)
           __a							=    titles if not isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE) else [titles]
           __a							=    texts if not isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE) else [texts]
           __a							=    len(__SCREAMING_SNAKE_CASE)
           __a							=    questions if not isinstance(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE) else [questions] * n_passages
           if len(__SCREAMING_SNAKE_CASE) != len(__SCREAMING_SNAKE_CASE):
               raise ValueError(
                   F'There should be as many titles than texts but got {len(__SCREAMING_SNAKE_CASE)} titles and {len(__SCREAMING_SNAKE_CASE)} texts.')
           __a							=    super().__call__(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		truncation=__SCREAMING_SNAKE_CASE)['''input_ids''']
           __a							=    super().__call__(__SCREAMING_SNAKE_CASE					,		add_special_tokens=__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		truncation=__SCREAMING_SNAKE_CASE)['''input_ids''']
           __a							=    {
               '''input_ids''': [
                   (encoded_question_and_title + encoded_text)[:max_length]
                   if max_length is not None and truncation
                   else encoded_question_and_title + encoded_text
                   for encoded_question_and_title, encoded_text in zip(__SCREAMING_SNAKE_CASE					,		__SCREAMING_SNAKE_CASE)
               ]
           }
           if return_attention_mask is not False:
               __a							=    []
               for input_ids in encoded_inputs["input_ids"]:
                   attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
               __a							=    attention_mask
           return self.pad(__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		max_length=__SCREAMING_SNAKE_CASE					,		return_tensors=__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					str					,		__SCREAMING_SNAKE_CASE							:					BatchEncoding					,		__SCREAMING_SNAKE_CASE							:					DPRReaderOutput					,		__SCREAMING_SNAKE_CASE							:					int = 16					,		__SCREAMING_SNAKE_CASE							:					int = 64					,		__SCREAMING_SNAKE_CASE							:					int = 4					,		):


           '''simple docstring'''

           __a							=    reader_input['''input_ids''']
           __a	,       __a	,       __a							=    reader_output[:3]
           __a							=    len(__SCREAMING_SNAKE_CASE)
           __a							=    sorted(range(__SCREAMING_SNAKE_CASE)					,		reverse=__SCREAMING_SNAKE_CASE					,		key=relevance_logits.__getitem__)
           __a							=    []
           for doc_id in sorted_docs:
               __a							=    list(input_ids[doc_id])
               # assuming question & title information is at the beginning of the sequence
               __a							=    sequence_ids.index(self.sep_token_id					,		2) + 1  # second sep id
               if sequence_ids[-1] == self.pad_token_id:
                   __a							=    sequence_ids.index(self.pad_token_id)
               else:
                   __a							=    len(__SCREAMING_SNAKE_CASE)

               __a							=    self._get_best_spans(
                   start_logits=start_logits[doc_id][passage_offset:sequence_len]					,		end_logits=end_logits[doc_id][passage_offset:sequence_len]					,		max_answer_length=__SCREAMING_SNAKE_CASE					,		top_spans=__SCREAMING_SNAKE_CASE					,		)
               for start_index, end_index in best_spans:
                   start_index += passage_offset
                   end_index += passage_offset
                   nbest_spans_predictions.append(
                       DPRSpanPrediction(
                           span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index]					,		relevance_score=relevance_logits[doc_id]					,		doc_id=__SCREAMING_SNAKE_CASE					,		start_index=__SCREAMING_SNAKE_CASE					,		end_index=__SCREAMING_SNAKE_CASE					,		text=self.decode(sequence_ids[start_index : end_index + 1])					,		))
               if len(__SCREAMING_SNAKE_CASE) >= num_spans:
                   break
           return nbest_spans_predictions[:num_spans]





       def 		_lowerCamelCase      (		self							:					int					,		__SCREAMING_SNAKE_CASE							:					List[int]					,		__SCREAMING_SNAKE_CASE							:					List[int]					,		__SCREAMING_SNAKE_CASE							:					int					,		__SCREAMING_SNAKE_CASE							:					int					,		):


           '''simple docstring'''

           __a							=    []
           for start_index, start_score in enumerate(__SCREAMING_SNAKE_CASE):
               for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
                   scores.append(((start_index, start_index + answer_length), start_score + end_score))
           __a							=    sorted(__SCREAMING_SNAKE_CASE					,		key=lambda __SCREAMING_SNAKE_CASE: x[1]					,		reverse=__SCREAMING_SNAKE_CASE)
           __a							=    []
           for (start_index, end_index), score in scores:
               if start_index > end_index:
                   raise ValueError(F'Wrong span indices: [{start_index}:{end_index}]')
               __a							=    end_index - start_index + 1
               if length > max_answer_length:
                   raise ValueError(F'Span is too long: {length} > {max_answer_length}')
               if any(
                   start_index <= prev_start_index <= prev_end_index <= end_index
                   or prev_start_index <= start_index <= end_index <= prev_end_index
                   for (prev_start_index, prev_end_index) in chosen_span_intervals):
                   continue
               chosen_span_intervals.append((start_index, end_index))

               if len(__SCREAMING_SNAKE_CASE) == top_spans:
                   break
           return chosen_span_intervals


@add_end_docstrings(__UpperCAmelCase   )
class    _A	(     __UpperCAmelCase				,__UpperCAmelCase   ):
       UpperCamelCase__  :   str						 =						VOCAB_FILES_NAMES
       UpperCamelCase__  :   Optional[Any]						 =						READER_PRETRAINED_VOCAB_FILES_MAP
       UpperCamelCase__  :   Dict						 =						READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       UpperCamelCase__  :   Optional[Any]						 =						READER_PRETRAINED_INIT_CONFIGURATION
       UpperCamelCase__  :   Union[str, Any]						 =						['''input_ids''', '''attention_mask''']










import os
import warnings
from typing import List, Optional

from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig


__snake_case						:int						=					logging.get_logger(__name__)

class    _A	:



       def __init__(		self							:					Any					,		__SCREAMING_SNAKE_CASE							:					Any					,		__SCREAMING_SNAKE_CASE							:					Optional[int]):


           '''simple docstring'''

           __a							=    question_encoder
           __a							=    generator
           __a							=    self.question_encoder



       def 		_lowerCamelCase      (		self							:					List[str]					,		__SCREAMING_SNAKE_CASE							:					Optional[int]):


           '''simple docstring'''

           if os.path.isfile(__SCREAMING_SNAKE_CASE):
               raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file')
           os.makedirs(__SCREAMING_SNAKE_CASE					,		exist_ok=__SCREAMING_SNAKE_CASE)
           __a							=    os.path.join(__SCREAMING_SNAKE_CASE					,		'''question_encoder_tokenizer''')
           __a							=    os.path.join(__SCREAMING_SNAKE_CASE					,		'''generator_tokenizer''')
           self.question_encoder.save_pretrained(__SCREAMING_SNAKE_CASE)
           self.generator.save_pretrained(__SCREAMING_SNAKE_CASE)



       @classmethod
       def 		_lowerCamelCase      (		cls							:					List[Any]					,		__SCREAMING_SNAKE_CASE							:					Any					,		**__SCREAMING_SNAKE_CASE							:					Optional[int]):


           '''simple docstring'''

           from ..auto.tokenization_auto import AutoTokenizer

           __a							=    kwargs.pop('''config'''					,		__SCREAMING_SNAKE_CASE)

           if config is None:
               __a							=    RagConfig.from_pretrained(__SCREAMING_SNAKE_CASE)

           __a							=    AutoTokenizer.from_pretrained(
               __SCREAMING_SNAKE_CASE					,		config=config.question_encoder					,		subfolder='''question_encoder_tokenizer''')
           __a							=    AutoTokenizer.from_pretrained(
               __SCREAMING_SNAKE_CASE					,		config=config.generator					,		subfolder='''generator_tokenizer''')
           return cls(question_encoder=__SCREAMING_SNAKE_CASE					,		generator=__SCREAMING_SNAKE_CASE)



       def __call__(		self							:					Dict					,		*__SCREAMING_SNAKE_CASE							:					List[Any]					,		**__SCREAMING_SNAKE_CASE							:					List[Any]):


           '''simple docstring'''

           return self.current_tokenizer(*__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					Optional[Any]					,		*__SCREAMING_SNAKE_CASE							:					Dict					,		**__SCREAMING_SNAKE_CASE							:					Any):


           '''simple docstring'''

           return self.generator.batch_decode(*__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					Optional[int]					,		*__SCREAMING_SNAKE_CASE							:					List[str]					,		**__SCREAMING_SNAKE_CASE							:					List[str]):


           '''simple docstring'''

           return self.generator.decode(*__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase      (		self							:					int):


           '''simple docstring'''

           __a							=    self.question_encoder



       def 		_lowerCamelCase      (		self							:					List[str]):


           '''simple docstring'''

           __a							=    self.generator





       def 		_lowerCamelCase      (		self							:					List[str]					,		__SCREAMING_SNAKE_CASE							:					List[str]					,		__SCREAMING_SNAKE_CASE							:					Optional[List[str]] = None					,		__SCREAMING_SNAKE_CASE							:					Optional[int] = None					,		__SCREAMING_SNAKE_CASE							:					Optional[int] = None					,		__SCREAMING_SNAKE_CASE							:					str = "longest"					,		__SCREAMING_SNAKE_CASE							:					str = None					,		__SCREAMING_SNAKE_CASE							:					bool = True					,		**__SCREAMING_SNAKE_CASE							:					List[str]					,		):


           '''simple docstring'''

           warnings.warn(
               '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '''
               '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '''
               '''context manager to prepare your targets. See the documentation of your specific tokenizer for more '''
               '''details'''					,		__SCREAMING_SNAKE_CASE					,		)
           if max_length is None:
               __a							=    self.current_tokenizer.model_max_length
           __a							=    self(
               __SCREAMING_SNAKE_CASE					,		add_special_tokens=__SCREAMING_SNAKE_CASE					,		return_tensors=__SCREAMING_SNAKE_CASE					,		max_length=__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		truncation=__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		)
           if tgt_texts is None:
               return model_inputs
           # Process tgt_texts
           if max_target_length is None:
               __a							=    self.current_tokenizer.model_max_length
           __a							=    self(
               text_target=__SCREAMING_SNAKE_CASE					,		add_special_tokens=__SCREAMING_SNAKE_CASE					,		return_tensors=__SCREAMING_SNAKE_CASE					,		padding=__SCREAMING_SNAKE_CASE					,		max_length=__SCREAMING_SNAKE_CASE					,		truncation=__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		)
           __a							=    labels['''input_ids''']
           return model_inputs





