





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


A	     =					logging.get_logger(__name__)

A	     =					{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

A	     =					{
    '''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'''
        ),
    },
}
A	     =					{
    '''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'''
        ),
    },
}
A	     =					{
    '''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'''
        ),
    },
}

A	     =					{
    '''facebook/dpr-ctx_encoder-single-nq-base''': 512,
    '''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
A	     =					{
    '''facebook/dpr-question_encoder-single-nq-base''': 512,
    '''facebook/dpr-question_encoder-multiset-base''': 512,
}
A	     =					{
    '''facebook/dpr-reader-single-nq-base''': 512,
    '''facebook/dpr-reader-multiset-base''': 512,
}


A	     =					{
    '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
A	     =					{
    '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
A	     =					{
    '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}




class 			__lowercase     (     a_							):







					'''simple docstring'''




					__lowerCAmelCase					=					VOCAB_FILES_NAMES
					__lowerCAmelCase					=					CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
					__lowerCAmelCase					=					CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					__lowerCAmelCase					=					CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION






class 			__lowercase     (     a_							):







					'''simple docstring'''




					__lowerCAmelCase					=					VOCAB_FILES_NAMES
					__lowerCAmelCase					=					QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
					__lowerCAmelCase					=					QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					__lowerCAmelCase					=					QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION






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

A	     =					collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])


A	     =					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(a_							)
class 			__lowercase     :







					'''simple docstring'''




					def __call__(  self		,     _UpperCAmelCase		,     _UpperCAmelCase = None		,     _UpperCAmelCase = None		,     _UpperCAmelCase = False		,     _UpperCAmelCase = False		,     _UpperCAmelCase = None		,     _UpperCAmelCase = None		,     _UpperCAmelCase = None		,     **_UpperCAmelCase		,     ):

									if titles is None and texts is None:
													return super().__call__(
													    lowercase_		,     padding=lowercase_		,     truncation=lowercase_		,     max_length=lowercase_		,     return_tensors=lowercase_		,     return_attention_mask=lowercase_		,     **lowercase_		,     )
									elif titles is None or texts is None:
													__a	:  List[str]         =					titles if texts is None else texts
													return super().__call__(
													    lowercase_		,     lowercase_		,     padding=lowercase_		,     truncation=lowercase_		,     max_length=lowercase_		,     return_tensors=lowercase_		,     return_attention_mask=lowercase_		,     **lowercase_		,     )
									__a	:  List[str]         =					titles if not isinstance(lowercase_		,     lowercase_       ) else [titles]
									__a	:  int         =					texts if not isinstance(lowercase_		,     lowercase_       ) else [texts]
									__a	:  List[str]         =					len(lowercase_       )
									__a	:  Optional[Any]         =					questions if not isinstance(lowercase_		,     lowercase_       ) else [questions] * n_passages
									if len(lowercase_       ) != len(lowercase_       ):
													raise ValueError(
													    f"""There should be as many titles than texts but got {len(lowercase_       )} titles and {len(lowercase_       )} texts."""       )
									__a	:  Tuple         =					super().__call__(lowercase_		,     lowercase_		,     padding=lowercase_		,     truncation=lowercase_       )['''input_ids''']
									__a	:  List[Any]         =					super().__call__(lowercase_		,     add_special_tokens=lowercase_		,     padding=lowercase_		,     truncation=lowercase_       )['''input_ids''']
									__a	:  Optional[Any]         =					{
									    '''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(lowercase_		,     lowercase_       )
									    ]
									}
									if return_attention_mask is not False:
													__a	:  Any         =					[]
													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	:  str         =					attention_mask
									return self.pad(lowercase_		,     padding=lowercase_		,     max_length=lowercase_		,     return_tensors=lowercase_       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase = 16		,     _UpperCAmelCase = 64		,     _UpperCAmelCase = 4		,     ):
									__a	:  int         =					reader_input['''input_ids''']
									__a    ,  __a    ,  __a	:  str         =					reader_output[:3]
									__a	:  Optional[int]         =					len(lowercase_       )
									__a	:  Optional[Any]         =					sorted(range(lowercase_       )		,     reverse=lowercase_		,     key=relevance_logits.__getitem__       )
									__a	:  Dict         =					[]
									for doc_id in sorted_docs:
													__a	:  int         =					list(input_ids[doc_id]       )
													# assuming question & title information is at the beginning of the sequence
													__a	:  List[str]         =					sequence_ids.index(self.sep_token_id		,     2       ) + 1  # second sep id
													if sequence_ids[-1] == self.pad_token_id:
																	__a	:  int         =					sequence_ids.index(self.pad_token_id       )
													else:
																	__a	:  Dict         =					len(lowercase_       )

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







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     ):
									__a	:  Union[str, Any]         =					[]
									for start_index, start_score in enumerate(lowercase_       ):
													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	:  Tuple         =					sorted(lowercase_		,     key=lambda _UpperCAmelCase       : x[1]		,     reverse=lowercase_       )
									__a	:  Dict         =					[]
									for (start_index, end_index), score in scores:
													if start_index > end_index:
																	raise ValueError(f"""Wrong span indices: [{start_index}:{end_index}]"""       )
													__a	:  List[Any]         =					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(lowercase_       ) == top_spans:
																	break
									return chosen_span_intervals






@add_end_docstrings(a_							)
class 			__lowercase     (     a_				, a_							):







					'''simple docstring'''




					__lowerCAmelCase					=					VOCAB_FILES_NAMES
					__lowerCAmelCase					=					READER_PRETRAINED_VOCAB_FILES_MAP
					__lowerCAmelCase					=					READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					__lowerCAmelCase					=					READER_PRETRAINED_INIT_CONFIGURATION
					__lowerCAmelCase					=					['''input_ids''', '''attention_mask''']






"""simple docstring"""






import hashlib
import unittest
from typing import Dict

import numpy as np

from transformers import (
    MODEL_FOR_MASK_GENERATION_MAPPING,
    TF_MODEL_FOR_MASK_GENERATION_MAPPING,
    is_vision_available,
    pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)


if is_vision_available():
		from PIL import Image
else:




		class 			__lowercase     :







							'''simple docstring'''




							@staticmethod
							def 	_lowerCamelCase						(  *_UpperCAmelCase		,     **_UpperCAmelCase       ):
											pass

def       __A (     a_  :Image)						->						str:
				__a	:  List[str]         =					hashlib.mda(image.tobytes())
				return m.hexdigest()[:10]

def       __A (     a_  :Image)						->						Dict:
				__a	:  Any         =					np.array(a_)
				__a	:  Tuple         =					npimg.shape
				return {"hash": hashimage(a_), "shape": shape}






@is_pipeline_test
@require_vision
@require_torch
class 			__lowercase     (     unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase					=					dict(
					    (list(MODEL_FOR_MASK_GENERATION_MAPPING.items()							) if MODEL_FOR_MASK_GENERATION_MAPPING else [])							)
					__lowerCAmelCase					=					dict(
					    (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items()							) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else [])							)







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									__a	:  List[str]         =					MaskGenerationPipeline(model=_UpperCAmelCase		,     image_processor=_UpperCAmelCase       )
									return image_segmenter, [
									    "./tests/fixtures/tests_samples/COCO/000000039769.png",
									    "./tests/fixtures/tests_samples/COCO/000000039769.png",
									]







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase       ):
									pass







					@require_tf
					@unittest.skip('''Image segmentation not implemented in TF'''       )
					def 	_lowerCamelCase						(  self       ):
									pass







					@slow
					@require_torch
					def 	_lowerCamelCase						(  self       ):
									__a	:  Dict         =					pipeline('''mask-generation'''		,     model='''facebook/sam-vit-huge'''       )

									__a	:  Optional[Any]         =					image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg'''		,     points_per_batch=256       )

									# Shortening by hashing
									__a	:  Optional[int]         =					[]
									for i, o in enumerate(outputs['''masks''']       ):
													new_outupt += [{"mask": mask_to_test_readable(_UpperCAmelCase       ), "scores": outputs["scores"][i]}]

									# fmt: off
									self.assertEqual(
									    nested_simplify(_UpperCAmelCase		,     decimals=4       )		,     [
									        {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_4_4_4},
									        {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_2_1},
									        {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_1_6_7},
									        {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_1_3_2},
									        {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_0_5_3},
									        {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (480, 640)}, '''scores''': 0.9_9_6_7},
									        {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (480, 640)}, '''scores''': 0.9_9_3},
									        {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (480, 640)}, '''scores''': 0.9_9_0_9},
									        {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (480, 640)}, '''scores''': 0.9_8_7_9},
									        {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (480, 640)}, '''scores''': 0.9_8_3_4},
									        {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (480, 640)}, '''scores''': 0.9_7_1_6},
									        {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (480, 640)}, '''scores''': 0.9_6_1_2},
									        {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (480, 640)}, '''scores''': 0.9_5_9_9},
									        {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (480, 640)}, '''scores''': 0.9_5_5_2},
									        {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (480, 640)}, '''scores''': 0.9_5_3_2},
									        {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (480, 640)}, '''scores''': 0.9_5_1_6},
									        {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (480, 640)}, '''scores''': 0.9_4_9_9},
									        {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (480, 640)}, '''scores''': 0.9_4_8_3},
									        {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (480, 640)}, '''scores''': 0.9_4_6_4},
									        {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (480, 640)}, '''scores''': 0.9_4_3},
									        {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (480, 640)}, '''scores''': 0.9_4_3},
									        {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (480, 640)}, '''scores''': 0.9_4_0_8},
									        {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (480, 640)}, '''scores''': 0.9_3_3_5},
									        {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (480, 640)}, '''scores''': 0.9_3_2_6},
									        {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (480, 640)}, '''scores''': 0.9_2_6_2},
									        {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (480, 640)}, '''scores''': 0.8_9_9_9},
									        {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (480, 640)}, '''scores''': 0.8_9_8_6},
									        {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (480, 640)}, '''scores''': 0.8_9_8_4},
									        {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (480, 640)}, '''scores''': 0.8_8_7_3},
									        {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (480, 640)}, '''scores''': 0.8_8_7_1}
									    ]		,     )
									# fmt: on







					@require_torch
					@slow
					def 	_lowerCamelCase						(  self       ):
									__a	:  Dict         =					'''facebook/sam-vit-huge'''
									__a	:  Tuple         =					pipeline('''mask-generation'''		,     model=_UpperCAmelCase       )

									__a	:  List[Any]         =					image_segmenter(
									    '''http://images.cocodataset.org/val2017/000000039769.jpg'''		,     pred_iou_thresh=1		,     points_per_batch=256       )

									# Shortening by hashing
									__a	:  Optional[int]         =					[]
									for i, o in enumerate(outputs['''masks''']       ):
													new_outupt += [{"mask": mask_to_test_readable(_UpperCAmelCase       ), "scores": outputs["scores"][i]}]

									self.assertEqual(
									    nested_simplify(_UpperCAmelCase		,     decimals=4       )		,     [
									        {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (480, 640)}, '''scores''': 1.0_4_4_4},
									        {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (480, 640)}, '''scores''': 1.0_2_1_0},
									        {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (480, 640)}, '''scores''': 1.0_1_6_7},
									        {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (480, 640)}, '''scores''': 1.0_1_3_2},
									        {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (480, 640)}, '''scores''': 1.0_0_5_3},
									    ]		,     )