


import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length



def 							UpperCamelCase_( lowerCamelCase_					)       ->		int:
    _lowercase			:				List[str] 						=						int(lowerCamelCase_					)
    _lowercase						,							_lowercase						,							_lowercase			:				Optional[Any] 						=						t // 3600, (t // 60) % 60, t % 60
    return F'''{h}:{m:02d}:{s:02d}''' if h != 0 else F'''{m:02d}:{s:02d}'''



def 							UpperCamelCase_( lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_=300					)       ->		Dict:
    # docstyle-ignore
    return F'''
    <div>
      {prefix}
      <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
      {label}
    </div>
    '''



def 							UpperCamelCase_( lowerCamelCase_					)       ->		Any:
    _lowercase			:				int 						=						'<table border="1" class="dataframe">\n'
    html_code += """  <thead>\n <tr style="text-align: left;">\n"""
    for i in items[0]:
        html_code += F'''      <th>{i}</th>\n'''
    html_code += "    </tr>\n  </thead>\n  <tbody>\n"
    for line in items[1:]:
        html_code += "    <tr>\n"
        for elt in line:
            _lowercase			:				Any 						=						F'''{elt:.6f}''' if isinstance(lowerCamelCase_				,					lowerCamelCase_					) else str(lowerCamelCase_					)
            html_code += F'''      <td>{elt}</td>\n'''
        html_code += "    </tr>\n"
    html_code += "  </tbody>\n</table><p>"
    return html_code






class _lowerCamelCase:
       lowercase_					:      str       					=     5
       lowercase_					:      str       					=     0.2
       def __init__(   self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = True, lowerCamelCase = None, lowerCamelCase = 3_00, )			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						total
           _lowercase			:				Optional[int] 						=						'' if prefix is None else prefix
           _lowercase			:				Tuple 						=						leave
           _lowercase			:				str 						=						parent
           _lowercase			:				str 						=						width
           _lowercase			:				List[Any] 						=						None
           _lowercase			:				List[str] 						=						None
           _lowercase			:				Tuple 						=						None
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase = False, lowerCamelCase = None)			->  Dict:




           """simple docstring"""

           _lowercase			:				Any 						=						value
           if comment is not None:
               _lowercase			:				Union[str, Any] 						=						comment
           if self.last_value is None:
               _lowercase			:				Dict 						=						time.time()
               _lowercase			:				Tuple 						=						value
               _lowercase			:				str 						=						None
               _lowercase			:				Optional[int] 						=						self.warmup
               _lowercase			:				Optional[Any] 						=						1
               self.update_bar(lowerCamelCase)
           elif value <= self.last_value and not force_update:
               return
           elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
               if self.first_calls > 0:
                   self.first_calls -= 1
               _lowercase			:				List[str] 						=						time.time()
               _lowercase			:				Tuple 						=						current_time - self.start_time
               # We could have value = self.start_value if the update is called twixe with the same start value.
               if value > self.start_value:
                   _lowercase			:				Dict 						=						self.elapsed_time / (value - self.start_value)
               else:
                   _lowercase			:				int 						=						None
               if value >= self.total:
                   _lowercase			:				Dict 						=						self.total
                   _lowercase			:				List[str] 						=						None
                   if not self.leave:
                       self.close()
               elif self.average_time_per_item is not None:
                   _lowercase			:				Optional[int] 						=						self.average_time_per_item * (self.total - value)
               self.update_bar(lowerCamelCase)
               _lowercase			:				int 						=						value
               _lowercase			:				Tuple 						=						current_time
               if self.average_time_per_item is None:
                   _lowercase			:				str 						=						1
               else:
                   _lowercase			:				int 						=						max(int(self.update_every / self.average_time_per_item), 1)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase=None)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						' ' * (len(str(self.total)) - len(str(lowerCamelCase))) + str(lowerCamelCase)
           if self.elapsed_time is None:
               _lowercase			:				int 						=						F'''[{spaced_value}/{self.total} : < :'''
           elif self.predicted_remaining is None:
               _lowercase			:				Union[str, Any] 						=						F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time)}'''
           else:
               _lowercase			:				Union[str, Any] 						=						(
                   F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <'''
                   F''' {format_time(self.predicted_remaining)}'''
               )
               self.label += F''', {1/self.average_time_per_item:.2f} it/s'''
           self.label += "]" if self.comment is None or len(self.comment) == 0 else F''', {self.comment}]'''
           self.display()
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Any 						=						html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
           if self.parent is not None:
               # If this is a child bar, the parent will take care of the display.
               self.parent.display()
               return
           if self.output is None:
               _lowercase			:				Optional[Any] 						=						disp.display(disp.HTML(self.html_code), display_id=lowerCamelCase)
           else:
               self.output.update(disp.HTML(self.html_code))




       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           if self.parent is None and self.output is not None:
               self.output.update(disp.HTML(''))






class _lowerCamelCase(		_a  ):
       def __init__(   self, lowerCamelCase, lowerCamelCase=None)			->  int:




           """simple docstring"""

           super().__init__(lowerCamelCase)
           _lowercase			:				Optional[Any] 						=						None if column_names is None else [column_names]
           _lowercase			:				Any 						=						None
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Any 						=						html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
           if self.inner_table is not None:
               self.html_code += text_to_html_table(self.inner_table)
           if self.child_bar is not None:
               self.html_code += self.child_bar.html_code
           if self.output is None:
               _lowercase			:				Dict 						=						disp.display(disp.HTML(self.html_code), display_id=lowerCamelCase)
           else:
               self.output.update(disp.HTML(self.html_code))
       def      UpperCamelCase	(   self, lowerCamelCase)			->  Dict:




           """simple docstring"""

           if self.inner_table is None:
               _lowercase			:				Dict 						=						[list(values.keys()), list(values.values())]
           else:
               _lowercase			:				Tuple 						=						self.inner_table[0]
               if len(self.inner_table) == 1:
                   # We give a chance to update the column names at the first iteration
                   for key in values.keys():
                       if key not in columns:
                           columns.append(lowerCamelCase)
                   _lowercase			:				str 						=						columns
               self.inner_table.append([values[c] for c in columns])
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase=None, lowerCamelCase=3_00)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				List[str] 						=						NotebookProgressBar(lowerCamelCase, prefix=lowerCamelCase, parent=self, width=lowerCamelCase)
           return self.child_bar




       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						None
           self.display()






class _lowerCamelCase(		_a  ):
       def __init__(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						None
           _lowercase			:				Dict 						=						None
           _lowercase			:				Dict 						=						False
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase)			->  Dict:




           """simple docstring"""

           _lowercase			:				Dict 						=						'Epoch' if args.evaluation_strategy == IntervalStrategy.EPOCH else 'Step'
           _lowercase			:				Dict 						=						0
           _lowercase			:				Tuple 						=						0
           _lowercase			:				int 						=						[self.first_column] + ['Training Loss']
           if args.evaluation_strategy != IntervalStrategy.NO:
               column_names.append('Validation Loss')
           _lowercase			:				Union[str, Any] 						=						NotebookTrainingTracker(state.max_steps, lowerCamelCase)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				Any 						=						int(state.epoch) if int(state.epoch) == state.epoch else F'''{state.epoch:.2f}'''
           self.training_tracker.update(
               state.global_step + 1, comment=F'''Epoch {epoch}/{state.num_train_epochs}''', force_update=self._force_next_update, )
           _lowercase			:				str 						=						False
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase)			->  Any:




           """simple docstring"""

           if not has_length(lowerCamelCase):
               return
           if self.prediction_bar is None:
               if self.training_tracker is not None:
                   _lowercase			:				Optional[int] 						=						self.training_tracker.add_child(len(lowerCamelCase))
               else:
                   _lowercase			:				Optional[int] 						=						NotebookProgressBar(len(lowerCamelCase))
               self.prediction_bar.update(1)
           else:
               self.prediction_bar.update(self.prediction_bar.value + 1)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase)			->  Optional[int]:




           """simple docstring"""

           if self.prediction_bar is not None:
               self.prediction_bar.close()
           _lowercase			:				Any 						=						None
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase)			->  List[Any]:




           """simple docstring"""

           if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
               _lowercase			:				Dict 						=						{'Training Loss': logs['loss']}
               # First column is necessarily Step sine we're not in epoch eval strategy
               _lowercase			:				List[Any] 						=						state.global_step
               self.training_tracker.write_line(lowerCamelCase)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase)			->  List[str]:




           """simple docstring"""

           if self.training_tracker is not None:
               _lowercase			:				Tuple 						=						{'Training Loss': 'No log', 'Validation Loss': 'No log'}
               for log in reversed(state.log_history):
                   if "loss" in log:
                       _lowercase			:				int 						=						log['loss']
                       break

               if self.first_column == "Epoch":
                   _lowercase			:				Union[str, Any] 						=						int(state.epoch)
               else:
                   _lowercase			:				Optional[Any] 						=						state.global_step
               _lowercase			:				str 						=						'eval'
               for k in metrics:
                   if k.endswith('_loss'):
                       _lowercase			:				str 						=						re.sub(R'\_loss$', '', lowerCamelCase)
               _lowercase			:				Tuple 						=						metrics.pop('total_flos', lowerCamelCase)
               _lowercase			:				List[str] 						=						metrics.pop('epoch', lowerCamelCase)
               _lowercase			:				List[Any] 						=						metrics.pop(F'''{metric_key_prefix}_runtime''', lowerCamelCase)
               _lowercase			:				Dict 						=						metrics.pop(F'''{metric_key_prefix}_samples_per_second''', lowerCamelCase)
               _lowercase			:				Tuple 						=						metrics.pop(F'''{metric_key_prefix}_steps_per_second''', lowerCamelCase)
               _lowercase			:				List[str] 						=						metrics.pop(F'''{metric_key_prefix}_jit_compilation_time''', lowerCamelCase)
               for k, v in metrics.items():
                   if k == F'''{metric_key_prefix}_loss''':
                       _lowercase			:				Union[str, Any] 						=						v
                   else:
                       _lowercase			:				Optional[Any] 						=						k.split('_')
                       _lowercase			:				Optional[int] 						=						' '.join([part.capitalize() for part in splits[1:]])
                       _lowercase			:				Tuple 						=						v
               self.training_tracker.write_line(lowerCamelCase)
               self.training_tracker.remove_child()
               _lowercase			:				str 						=						None
               # Evaluation takes a long time so we should force the next update.
               _lowercase			:				Optional[Any] 						=						True




       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase)			->  Union[str, Any]:




           """simple docstring"""

           self.training_tracker.update(
               state.global_step, comment=F'''Epoch {int(state.epoch)}/{state.num_train_epochs}''', force_update=lowerCamelCase)
           _lowercase			:				Any 						=						None




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_fast import BertTokenizerFast
from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer


__lowerCAmelCase     :	Optional[Any]       			=  logging.get_logger(__name__)

__lowerCAmelCase     :	List[str]       			=  {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

__lowerCAmelCase     :	int       			=  {
    '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'
        ),
    },
}
__lowerCAmelCase     :	Any       			=  {
    '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'
        ),
    },
}
__lowerCAmelCase     :	List[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'
        ),
    },
}

__lowerCAmelCase     :	Any       			=  {
    'facebook/dpr-ctx_encoder-single-nq-base': 512,
    'facebook/dpr-ctx_encoder-multiset-base': 512,
}
__lowerCAmelCase     :	Optional[int]       			=  {
    'facebook/dpr-question_encoder-single-nq-base': 512,
    'facebook/dpr-question_encoder-multiset-base': 512,
}
__lowerCAmelCase     :	Optional[int]       			=  {
    'facebook/dpr-reader-single-nq-base': 512,
    'facebook/dpr-reader-multiset-base': 512,
}


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




class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						VOCAB_FILES_NAMES
  a__       			=						CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
  a__       			=						CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a__       			=						CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
  a__       			=						DPRContextEncoderTokenizer







class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						VOCAB_FILES_NAMES
  a__       			=						QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
  a__       			=						QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a__       			=						QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
  a__       			=						DPRQuestionEncoderTokenizer







__lowerCAmelCase     :	Optional[int]       			=  collections.namedtuple(
    'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text']
)

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


__lowerCAmelCase     :	str       			=  R'\n    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n    with the format:\n\n    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n    Args:\n        questions (`str` or `List[str]`):\n            The questions to be encoded. You can specify one question for many passages. In this case, the question\n            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n            `titles` or `texts`.\n        titles (`str` or `List[str]`):\n            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n        texts (`str` or `List[str]`):\n            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n            Activates and controls padding. Accepts the following values:\n\n            - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n              if provided).\n            - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided.\n            - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n              lengths).\n        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n            Activates and controls truncation. Accepts the following values:\n\n            - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n              the maximum acceptable input length for the model if that argument is not provided. This will truncate\n              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n              of pairs) is provided.\n            - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the first\n              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n              acceptable input length for the model if that argument is not provided. This will only truncate the\n              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n            - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n              greater than the model maximum admissible input size).\n        max_length (`int`, *optional*):\n                Controls the maximum length to use by one of the truncation/padding parameters.\n\n                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n                is required by one of the truncation/padding parameters. If the model has no specific maximum input\n                length (like XLNet) truncation/padding to a maximum length will be deactivated.\n        return_tensors (`str` or [`~utils.TensorType`], *optional*):\n                If set, will return tensors instead of list of python integers. Acceptable values are:\n\n                - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n                - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n                - `\'np\'`: Return Numpy `np.ndarray` objects.\n        return_attention_mask (`bool`, *optional*):\n            Whether or not to return the attention mask. If not set, will return the attention mask according to the\n            specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n            [What are attention masks?](../glossary#attention-mask)\n\n    Return:\n        `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n        - `input_ids`: List of token ids to be fed to a model.\n        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n    '




@add_start_docstrings(_A	)
class 			UpperCAmelCase_     :


  '''simple docstring'''







  def __call__(					self     :					Tuple     ,				UpperCamelCase__     :					List[str]     ,				UpperCamelCase__     :					Optional[str] = None     ,				UpperCamelCase__     :					Optional[str] = None     ,				UpperCamelCase__     :					Union[bool, str] = False     ,				UpperCamelCase__     :					Union[bool, str] = False     ,				UpperCamelCase__     :					Optional[int] = None     ,				UpperCamelCase__     :					Optional[Union[str, TensorType]] = None     ,				UpperCamelCase__     :					Optional[bool] = None     ,				**UpperCamelCase__     :					List[str]     ,				)     ->      BatchEncoding:







    """simple docstring"""






    if titles is None and texts is None:
      return super().__call__(
          UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__     ,				max_length=UpperCamelCase__     ,				return_tensors=UpperCamelCase__     ,				return_attention_mask=UpperCamelCase__     ,				**UpperCamelCase__     ,				)
    elif titles is None or texts is None:
      __magic_name__								=			titles if texts is None else texts
      return super().__call__(
          UpperCamelCase__     ,				UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__     ,				max_length=UpperCamelCase__     ,				return_tensors=UpperCamelCase__     ,				return_attention_mask=UpperCamelCase__     ,				**UpperCamelCase__     ,				)
    __magic_name__								=			titles if not isinstance(UpperCamelCase__     ,				UpperCamelCase__       ) else [titles]
    __magic_name__								=			texts if not isinstance(UpperCamelCase__     ,				UpperCamelCase__       ) else [texts]
    __magic_name__								=			len(UpperCamelCase__       )
    __magic_name__								=			questions if not isinstance(UpperCamelCase__     ,				UpperCamelCase__       ) else [questions] * n_passages
    assert len(UpperCamelCase__       ) == len(
        UpperCamelCase__       ), F'''There should be as many titles than texts but got {len(UpperCamelCase__       )} titles and {len(UpperCamelCase__       )} texts.'''
    __magic_name__								=			super().__call__(UpperCamelCase__     ,				UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__       )["""input_ids"""]
    __magic_name__								=			super().__call__(UpperCamelCase__     ,				add_special_tokens=UpperCamelCase__     ,				padding=UpperCamelCase__     ,				truncation=UpperCamelCase__       )["""input_ids"""]
    __magic_name__								=			{
        """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(UpperCamelCase__     ,				UpperCamelCase__       )
        ]
    }
    if return_attention_mask is not False:
      __magic_name__								=			[]
      for input_ids in encoded_inputs["input_ids"]:
        attention_mask.append([int(input_id != self.pad_token_id       ) for input_id in input_ids]       )
      __magic_name__								=			attention_mask
    return self.pad(UpperCamelCase__     ,				padding=UpperCamelCase__     ,				max_length=UpperCamelCase__     ,				return_tensors=UpperCamelCase__       )
  def 				_lowercase				(					self     :					List[Any]     ,				UpperCamelCase__     :					BatchEncoding     ,				UpperCamelCase__     :					DPRReaderOutput     ,				UpperCamelCase__     :					int = 16     ,				UpperCamelCase__     :					int = 64     ,				UpperCamelCase__     :					int = 4     ,				)     ->      List[DPRSpanPrediction]:







    """simple docstring"""






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

      __magic_name__								=			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=UpperCamelCase__     ,				top_spans=UpperCamelCase__     ,				)
      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=UpperCamelCase__     ,				start_index=UpperCamelCase__     ,				end_index=UpperCamelCase__     ,				text=self.decode(sequence_ids[start_index : end_index + 1]       )     ,				)       )
      if len(UpperCamelCase__       ) >= num_spans:
        break
    return nbest_spans_predictions[:num_spans]





  def 				_lowercase				(					self     :					Optional[int]     ,				UpperCamelCase__     :					List[int]     ,				UpperCamelCase__     :					List[int]     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int     ,				)     ->      List[DPRSpanPrediction]:







    """simple docstring"""






    __magic_name__								=			[]
    for start_index, start_score in enumerate(UpperCamelCase__       ):
      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)       )
    __magic_name__								=			sorted(UpperCamelCase__     ,				key=lambda UpperCamelCase__       : x[1]     ,				reverse=UpperCamelCase__       )
    __magic_name__								=			[]
    for (start_index, end_index), score in scores:
      assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]'''
      __magic_name__								=			end_index - start_index + 1
      assert length <= max_answer_length, 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(UpperCamelCase__       ) == top_spans:
        break
    return chosen_span_intervals







@add_end_docstrings(_A	)
class 			UpperCAmelCase_     (					_A    ,			_A	):


  '''simple docstring'''







  a__       			=						VOCAB_FILES_NAMES
  a__       			=						READER_PRETRAINED_VOCAB_FILES_MAP
  a__       			=						READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a__       			=						READER_PRETRAINED_INIT_CONFIGURATION
  a__       			=						["""input_ids""", """attention_mask"""]
  a__       			=						DPRReaderTokenizer

