






'''simple docstring'''





import unittest

from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_detectrona,
    require_pytesseract,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image

 from transformers.image_utils import load_image
else:


 class 						_a       :






   """simple docstring"""





   @staticmethod
   def    _UpperCAmelCase     (     *_UpperCAmelCase		,		**_UpperCAmelCase )			-> Union[str, Any]:
      pass






 def     _snake_case    (__lowercase):
    return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
snake_case__      :	Any       	=      (
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)


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






  """simple docstring"""





  A_						=   MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING




  @require_pytesseract
  @require_vision
  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Union[str, Any]:
     UpperCamelCase_									=     pipeline(
         'document-question-answering'		,		model=__UpperCamelCase		,		tokenizer=__UpperCamelCase		,		image_processor=__UpperCamelCase )

     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     list(zip(*apply_tesseract(load_image(__UpperCamelCase )		,		__UpperCamelCase		,		'' ) ) )
     UpperCamelCase_									=     'What is the placebo?'
     UpperCamelCase_									=     [
         {
             'image': load_image(__UpperCamelCase ),
             'question': question,
         },
         {
             'image': image,
             'question': question,
         },
         {
             'image': image,
             'question': question,
             'word_boxes': word_boxes,
         },
     ]
     return dqa_pipeline, examples




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[Any]:
     UpperCamelCase_									=     dqa_pipeline(__UpperCamelCase		,		top_k=2 )
     self.assertEqual(
         __UpperCamelCase		,		[
             [
                 {'score': ANY(__UpperCamelCase ), 'answer': ANY(__UpperCamelCase ), 'start': ANY(__UpperCamelCase ), 'end': ANY(__UpperCamelCase )},
                 {'score': ANY(__UpperCamelCase ), 'answer': ANY(__UpperCamelCase ), 'start': ANY(__UpperCamelCase ), 'end': ANY(__UpperCamelCase )},
             ]
         ]
         * 3		,		)




  @require_torch
  @require_detectrona
  @require_pytesseract
  def    _UpperCAmelCase     (     self )			-> Tuple:
     UpperCamelCase_									=     pipeline('document-question-answering'		,		model='hf-internal-testing/tiny-random-layoutlmv2' )
     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     'How many cats are there?'

     UpperCamelCase_									=     [
         {'score': 0.0_0_0_1, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39},
         {'score': 0.0_0_0_1, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40},
     ]
     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(nested_simplify(__UpperCamelCase		,		decimals=4 )		,		__UpperCamelCase )

     UpperCamelCase_									=     dqa_pipeline({'image': image, 'question': question}		,		top_k=2 )
     self.assertEqual(nested_simplify(__UpperCamelCase		,		decimals=4 )		,		__UpperCamelCase )

     # This image does not detect ANY text in it, meaning layoutlmv2 should fail.
     # Empty answer probably
     UpperCamelCase_									=     './tests/fixtures/tests_samples/COCO/000000039769.png'
     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(__UpperCamelCase		,		[] )

     # We can optionnally pass directly the words and bounding boxes
     UpperCamelCase_									=     './tests/fixtures/tests_samples/COCO/000000039769.png'
     UpperCamelCase_									=     []
     UpperCamelCase_									=     []
     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		words=__UpperCamelCase		,		boxes=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(__UpperCamelCase		,		[] )




  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def    _UpperCAmelCase     (     self )			-> List[str]:
     UpperCamelCase_									=     pipeline(
         'document-question-answering'		,		model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'		,		revision='9977165'		,		)
     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     'What is the invoice number?'

     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.9_9_4_4, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.0_0_0_9, 'answer': 'us-001', 'start': 16, 'end': 16},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline({'image': image, 'question': question}		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.9_9_4_4, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.0_0_0_9, 'answer': 'us-001', 'start': 16, 'end': 16},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline(
         [{'image': image, 'question': question}, {'image': image, 'question': question}]		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             [
                 {'score': 0.9_9_4_4, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_0_0_9, 'answer': 'us-001', 'start': 16, 'end': 16},
             ],
         ]
         * 2		,		)




  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     pipeline(
         'document-question-answering'		,		model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'		,		revision='9977165'		,		max_seq_len=50		,		)
     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     'What is the invoice number?'

     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.9_9_7_4, 'answer': '1110212019', 'start': 23, 'end': 23},
             {'score': 0.9_9_4_8, 'answer': 'us-001', 'start': 16, 'end': 16},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline({'image': image, 'question': question}		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.9_9_7_4, 'answer': '1110212019', 'start': 23, 'end': 23},
             {'score': 0.9_9_4_8, 'answer': 'us-001', 'start': 16, 'end': 16},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline(
         [{'image': image, 'question': question}, {'image': image, 'question': question}]		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             [
                 {'score': 0.9_9_7_4, 'answer': '1110212019', 'start': 23, 'end': 23},
                 {'score': 0.9_9_4_8, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]
         ]
         * 2		,		)




  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     AutoTokenizer.from_pretrained(
         'impira/layoutlm-document-qa'		,		revision='3dc6de3'		,		add_prefix_space=__UpperCamelCase )
     UpperCamelCase_									=     pipeline(
         'document-question-answering'		,		model='impira/layoutlm-document-qa'		,		tokenizer=__UpperCamelCase		,		revision='3dc6de3'		,		)
     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     'What is the invoice number?'

     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline({'image': image, 'question': question}		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline(
         [{'image': image, 'question': question}, {'image': image, 'question': question}]		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             [
                 {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
             ]
         ]
         * 2		,		)

     UpperCamelCase_									=     list(zip(*apply_tesseract(load_image(__UpperCamelCase )		,		__UpperCamelCase		,		'' ) ) )

     # This model should also work if `image` is set to None
     UpperCamelCase_									=     dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.4_2_5_1, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.0_8_1_9, 'answer': '1110212019', 'start': 23, 'end': 23},
         ]		,		)




  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     AutoTokenizer.from_pretrained(
         'impira/layoutlm-document-qa'		,		revision='3dc6de3'		,		add_prefix_space=__UpperCamelCase )
     UpperCamelCase_									=     pipeline(
         'document-question-answering'		,		model='impira/layoutlm-document-qa'		,		tokenizer=__UpperCamelCase		,		revision='3dc6de3'		,		max_seq_len=50		,		)
     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     'What is the invoice number?'

     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.9_9_9_9, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.9_9_9_8, 'answer': 'us-001', 'start': 16, 'end': 16},
         ]		,		)

     UpperCamelCase_									=     dqa_pipeline(
         [{'image': image, 'question': question}, {'image': image, 'question': question}]		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             [
                 {'score': 0.9_9_9_9, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.9_9_9_8, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]
         ]
         * 2		,		)

     UpperCamelCase_									=     list(zip(*apply_tesseract(load_image(__UpperCamelCase )		,		__UpperCamelCase		,		'' ) ) )

     # This model should also work if `image` is set to None
     UpperCamelCase_									=     dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}		,		top_k=2 )
     self.assertEqual(
         nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[
             {'score': 0.9_9_9_9, 'answer': 'us-001', 'start': 16, 'end': 16},
             {'score': 0.9_9_9_8, 'answer': 'us-001', 'start': 16, 'end': 16},
         ]		,		)




  @slow
  @require_torch
  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     pipeline(
         'document-question-answering'		,		model='naver-clova-ix/donut-base-finetuned-docvqa'		,		tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' )		,		feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa'		,		)

     UpperCamelCase_									=     INVOICE_URL
     UpperCamelCase_									=     'What is the invoice number?'
     UpperCamelCase_									=     dqa_pipeline(image=__UpperCamelCase		,		question=__UpperCamelCase		,		top_k=2 )
     self.assertEqual(nested_simplify(__UpperCamelCase		,		decimals=4 )		,		[{'answer': 'us-001'}] )




  @require_tf
  @unittest.skip('Document question answering not implemented in TF' )
  def    _UpperCAmelCase     (     self )			-> Any:
     pass













import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer


snake_case__      :	List[str]       	=      logging.get_logger(__name__)

snake_case__      :	Optional[int]       	=      {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

snake_case__      :	Optional[Any]       	=      {
    """vocab_file""": {
        """google/realm-cc-news-pretrained-embedder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt"""
        ),
        """google/realm-cc-news-pretrained-encoder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt"""
        ),
        """google/realm-cc-news-pretrained-scorer""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt"""
        ),
        """google/realm-cc-news-pretrained-openqa""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt"""
        ),
        """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""",
        """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""",
        """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""",
        """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""",
    },
    """tokenizer_file""": {
        """google/realm-cc-news-pretrained-embedder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont"""
        ),
        """google/realm-cc-news-pretrained-encoder""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json"""
        ),
        """google/realm-cc-news-pretrained-scorer""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json"""
        ),
        """google/realm-cc-news-pretrained-openqa""": (
            """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-nq-openqa""": (
            """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-nq-reader""": (
            """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-wq-openqa""": (
            """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json"""
        ),
        """google/realm-orqa-wq-reader""": (
            """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json"""
        ),
    },
}

snake_case__      :	List[str]       	=      {
    """google/realm-cc-news-pretrained-embedder""": 5_1_2,
    """google/realm-cc-news-pretrained-encoder""": 5_1_2,
    """google/realm-cc-news-pretrained-scorer""": 5_1_2,
    """google/realm-cc-news-pretrained-openqa""": 5_1_2,
    """google/realm-orqa-nq-openqa""": 5_1_2,
    """google/realm-orqa-nq-reader""": 5_1_2,
    """google/realm-orqa-wq-openqa""": 5_1_2,
    """google/realm-orqa-wq-reader""": 5_1_2,
}

snake_case__      :	Tuple       	=      {
    """google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True},
    """google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True},
    """google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True},
    """google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True},
    """google/realm-orqa-nq-openqa""": {"""do_lower_case""": True},
    """google/realm-orqa-nq-reader""": {"""do_lower_case""": True},
    """google/realm-orqa-wq-openqa""": {"""do_lower_case""": True},
    """google/realm-orqa-wq-reader""": {"""do_lower_case""": True},
}


class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   VOCAB_FILES_NAMES
  A_						=   PRETRAINED_VOCAB_FILES_MAP
  A_						=   PRETRAINED_INIT_CONFIGURATION
  A_						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  A_						=   RealmTokenizer




  def __init__(     self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=True		,		_UpperCAmelCase="[UNK]"		,		_UpperCAmelCase="[SEP]"		,		_UpperCAmelCase="[PAD]"		,		_UpperCAmelCase="[CLS]"		,		_UpperCAmelCase="[MASK]"		,		_UpperCAmelCase=True		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)			-> Optional[Any]:
     super().__init__(
         _UpperCAmelCase		,		tokenizer_file=_UpperCAmelCase		,		do_lower_case=_UpperCAmelCase		,		unk_token=_UpperCAmelCase		,		sep_token=_UpperCAmelCase		,		pad_token=_UpperCAmelCase		,		cls_token=_UpperCAmelCase		,		mask_token=_UpperCAmelCase		,		tokenize_chinese_chars=_UpperCAmelCase		,		strip_accents=_UpperCAmelCase		,		**_UpperCAmelCase		,		)

     UpperCamelCase_									=     json.loads(self.backend_tokenizer.normalizer.__getstate__() )
     if (
         normalizer_state.get('lowercase'		,		_UpperCAmelCase ) != do_lower_case
         or normalizer_state.get('strip_accents'		,		_UpperCAmelCase ) != strip_accents
         or normalizer_state.get('handle_chinese_chars'		,		_UpperCAmelCase ) != tokenize_chinese_chars
     ):
        UpperCamelCase_									=     getattr(_UpperCAmelCase		,		normalizer_state.pop('type' ) )
        UpperCamelCase_									=     do_lower_case
        UpperCamelCase_									=     strip_accents
        UpperCamelCase_									=     tokenize_chinese_chars
        UpperCamelCase_									=     normalizer_class(**_UpperCAmelCase )

     UpperCamelCase_									=     do_lower_case




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		**_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     PaddingStrategy.MAX_LENGTH

     UpperCamelCase_									=     text
     UpperCamelCase_									=     kwargs.pop('text_pair'		,		_UpperCAmelCase )
     UpperCamelCase_									=     kwargs.pop('return_tensors'		,		_UpperCAmelCase )

     UpperCamelCase_									=     {
         'input_ids': [],
         'attention_mask': [],
         'token_type_ids': [],
     }

     for idx, candidate_text in enumerate(_UpperCAmelCase ):
        if batch_text_pair is not None:
           UpperCamelCase_									=     batch_text_pair[idx]
        else:
           UpperCamelCase_									=     None

        UpperCamelCase_									=     super().__call__(_UpperCAmelCase		,		_UpperCAmelCase		,		return_tensors=_UpperCAmelCase		,		**_UpperCAmelCase )

        UpperCamelCase_									=     encoded_candidates.get('input_ids' )
        UpperCamelCase_									=     encoded_candidates.get('attention_mask' )
        UpperCamelCase_									=     encoded_candidates.get('token_type_ids' )

        if encoded_input_ids is not None:
           output_data["input_ids"].append(_UpperCAmelCase )
        if encoded_attention_mask is not None:
           output_data["attention_mask"].append(_UpperCAmelCase )
        if encoded_token_type_ids is not None:
           output_data["token_type_ids"].append(_UpperCAmelCase )

     UpperCamelCase_									=     {key: item for key, item in output_data.items() if len(_UpperCAmelCase ) != 0}

     return BatchEncoding(_UpperCAmelCase		,		tensor_type=_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase=None )			-> Union[str, Any]:
     UpperCamelCase_									=     [self.cls_token_id] + token_ids_a + [self.sep_token_id]

     if token_ids_a:
        output += token_ids_a + [self.sep_token_id]

     return output




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> List[int]:
     UpperCamelCase_									=     [self.sep_token_id]
     UpperCamelCase_									=     [self.cls_token_id]
     if token_ids_a is None:
        return len(cls + token_ids_a + sep ) * [0]
     return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase = None )			-> Tuple[str]:
     UpperCamelCase_									=     self._tokenizer.model.save(_UpperCAmelCase		,		name=_UpperCAmelCase )
     return tuple(_UpperCAmelCase )





