





'''simple docstring'''

from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
  import tensorflow as tf

  from ..tf_utils import stable_softmax


if is_torch_available():
  import torch


__lowerCAmelCase				:      int						      =logging.get_logger(__name__)






@add_end_docstrings(
    UpperCamelCase__     ,			r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """     ,			)
class   UpperCAmelCase      (			UpperCamelCase__							):
 def 	UpperCAmelCase_				(							self :Union[str, Any]		,			lowercase_ :GenericTensor				)->				np.ndarray:
     if self.framework == "tf":
         A__							=     tf.where(input_ids == self.tokenizer.mask_token_id				).numpy()
     elif self.framework == "pt":
         A__							=     torch.nonzero(input_ids == self.tokenizer.mask_token_id		,			as_tuple=lowercase_				)
     else:
         raise ValueError("Unsupported framework"				)
     return masked_index
 def 	UpperCAmelCase_				(							self :List[str]		,			lowercase_ :GenericTensor				)->				np.ndarray:
     A__							=     self.get_masked_index(lowercase_				)
     A__							=     np.prod(masked_index.shape				)
     if numel < 1:
         raise PipelineException(
             "fill-mask"		,			self.model.base_model_prefix		,			F"No mask_token ({self.tokenizer.mask_token}) found on the input"		,			)
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :GenericTensor				)->				Any:
     if isinstance(lowercase_		,			lowercase_				):
         for model_input in model_inputs:
             self._ensure_exactly_one_mask_token(model_input["input_ids"][0]				)
     else:
         for input_ids in model_inputs["input_ids"]:
             self._ensure_exactly_one_mask_token(lowercase_				)
 def 	UpperCAmelCase_				(							self :Optional[Any]		,			lowercase_ :Any		,			lowercase_ :Dict=None		,			**lowercase_ :Dict				)->				Dict[str, GenericTensor]:
     if return_tensors is None:
         A__							=     self.framework
     A__							=     self.tokenizer(lowercase_		,			return_tensors=lowercase_				)
     self.ensure_exactly_one_mask_token(lowercase_				)
     return model_inputs
 def 	UpperCAmelCase_				(							self :Any		,			lowercase_ :Tuple				)->				Any:
     A__							=     self.model(**lowercase_				)
     A__							=     model_inputs["input_ids"]
     return model_outputs
 def 	UpperCAmelCase_				(							self :Optional[Any]		,			lowercase_ :Optional[Any]		,			lowercase_ :Union[str, Any]=5		,			lowercase_ :str=None				)->				int:
     # Cap top_k if there are targets
     if target_ids is not None and target_ids.shape[0] < top_k:
         A__							=     target_ids.shape[0]
     A__							=     model_outputs["input_ids"][0]
     A__							=     model_outputs["logits"]

     if self.framework == "tf":
         A__							=     tf.where(input_ids == self.tokenizer.mask_token_id				).numpy()[:, 0]

         A__							=     outputs.numpy()

         A__							=     outputs[0, masked_index, :]
         A__							=     stable_softmax(lowercase_		,			axis=-1				)
         if target_ids is not None:
             A__							=     tf.gather_nd(tf.squeeze(lowercase_		,			0				)		,			target_ids.reshape(-1		,			1				)				)
             A__							=     tf.expand_dims(lowercase_		,			0				)

         A__							=     tf.math.top_k(lowercase_		,			k=lowercase_				)
         A__,      A__							=     topk.values.numpy(), topk.indices.numpy()
     else:
         A__							=     torch.nonzero(input_ids == self.tokenizer.mask_token_id		,			as_tuple=lowercase_				).squeeze(-1				)
         # Fill mask pipeline supports only one ${mask_token} per sample

         A__							=     outputs[0, masked_index, :]
         A__							=     logits.softmax(dim=-1				)
         if target_ids is not None:
             A__							=     probs[..., target_ids]

         A__,      A__							=     probs.topk(lowercase_				)

     A__							=     []
     A__							=     values.shape[0] == 1
     for i, (_values, _predictions) in enumerate(zip(values.tolist()		,			predictions.tolist()				)				):
         A__							=     []
         for v, p in zip(_values		,			_predictions				):
             # Copy is important since we're going to modify this array in place
             A__							=     input_ids.numpy().copy()
             if target_ids is not None:
                 A__							=     target_ids[p].tolist()

             A__							=     p
             # Filter padding out:
             A__							=     tokens[np.where(tokens != self.tokenizer.pad_token_id				)]
             # Originally we skip special tokens to give readable output.
             # For multi masks though, the other [MASK] would be removed otherwise
             # making the output look odd, so we add them back
             A__							=     self.tokenizer.decode(lowercase_		,			skip_special_tokens=lowercase_				)
             A__							=     {"score": v, "token": p, "token_str": self.tokenizer.decode([p]				), "sequence": sequence}
             row.append(lowercase_				)
         result.append(lowercase_				)
     if single_mask:
         return result[0]
     return result
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :List[Any]		,			lowercase_ :Tuple=None				)->				Optional[Any]:
     if isinstance(lowercase_		,			lowercase_				):
         A__							=     [targets]
     try:
         A__							=     self.tokenizer.get_vocab()
     except Exception:
         A__							=     {}
     A__							=     []
     for target in targets:
         A__							=     vocab.get(lowercase_		,			lowercase_				)
         if id_ is None:
             A__							=     self.tokenizer(
                 lowercase_		,			add_special_tokens=lowercase_		,			return_attention_mask=lowercase_		,			return_token_type_ids=lowercase_		,			max_length=1		,			truncation=lowercase_		,			)["input_ids"]
             if len(lowercase_				) == 0:
                 logger.warning(
                     F"The specified target token `{target}` does not exist in the model vocabulary. "
                     "We cannot replace it with anything meaningful, ignoring it"				)
                 continue
             A__							=     input_ids[0]
             # XXX: If users encounter this pass
             # it becomes pretty slow, so let's make sure
             # The warning enables them to fix the input to
             # get faster performance.
             logger.warning(
                 F"The specified target token `{target}` does not exist in the model vocabulary. "
                 F"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_				)}`."				)
         target_ids.append(id_				)
     A__							=     list(set(lowercase_				)				)
     if len(lowercase_				) == 0:
         raise ValueError("At least one target must be provided when passed."				)
     A__							=     np.array(lowercase_				)
     return target_ids
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :Any=None		,			lowercase_ :List[Any]=None				)->				List[Any]:
     A__							=     {}

     if targets is not None:
         A__							=     self.get_target_ids(lowercase_		,			lowercase_				)
         A__							=     target_ids

     if top_k is not None:
         A__							=     top_k

     if self.tokenizer.mask_token_id is None:
         raise PipelineException(
             "fill-mask"		,			self.model.base_model_prefix		,			"The tokenizer does not define a `mask_token`."				)
     return {}, {}, postprocess_params



 def __call__(							self :Tuple		,			lowercase_ :List[Any]		,			*lowercase_ :Any		,			**lowercase_ :int				)->				Union[str, Any]:
     A__							=     super().__call__(lowercase_		,			**lowercase_				)
     if isinstance(lowercase_		,			lowercase_				) and len(lowercase_				) == 1:
         return outputs[0]
     return outputs










'''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   UpperCAmelCase      :
   @staticmethod
   def 	UpperCAmelCase_				(							*lowercase_ :Optional[Any]		,			**lowercase_ :List[Any]				)->				Optional[int]:
       pass





  def 		UpperCamelCase							(				_lowerCamelCase   :   List[Any]			):
      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.
__lowerCAmelCase				:      int						      =(
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)






@is_pipeline_test
@require_torch
@require_vision
class   UpperCAmelCase      (			unittest.TestCase							):
 __lowercase  						=							MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
 @require_pytesseract
 @require_vision
 def 	UpperCAmelCase_				(							self :int		,			lowercase_ :Optional[Any]		,			lowercase_ :Optional[Any]		,			lowercase_ :Dict				)->				int:
     A__							=     pipeline(
         "document-question-answering"		,			model=lowercase_		,			tokenizer=lowercase_		,			image_processor=lowercase_				)

     A__							=     INVOICE_URL
     A__							=     list(zip(*apply_tesseract(load_image(lowercase_				)		,			lowercase_		,			""				)				)				)
     A__							=     "What is the placebo?"
     A__							=     [
         {
             "image": load_image(lowercase_				),
             "question": question,
         },
         {
             "image": image,
             "question": question,
         },
         {
             "image": image,
             "question": question,
             "word_boxes": word_boxes,
         },
     ]
     return dqa_pipeline, examples
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :List[Any]		,			lowercase_ :List[str]				)->				List[str]:
     A__							=     dqa_pipeline(lowercase_		,			top_k=2				)
     self.assertEqual(
         lowercase_		,			[
             [
                 {"score": ANY(lowercase_				), "answer": ANY(lowercase_				), "start": ANY(lowercase_				), "end": ANY(lowercase_				)},
                 {"score": ANY(lowercase_				), "answer": ANY(lowercase_				), "start": ANY(lowercase_				), "end": ANY(lowercase_				)},
             ]
         ]
         * 3		,			)
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 	UpperCAmelCase_				(							self :Dict				)->				Optional[Any]:
     A__							=     pipeline("document-question-answering"		,			model="hf-internal-testing/tiny-random-layoutlmv2"				)
     A__							=     INVOICE_URL
     A__							=     "How many cats are there?"

     A__							=     [
         {"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},
     ]
     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(nested_simplify(lowercase_		,			decimals=4				)		,			lowercase_				)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(nested_simplify(lowercase_		,			decimals=4				)		,			lowercase_				)

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

     # We can optionnally pass directly the words and bounding boxes
     A__							=     "./tests/fixtures/tests_samples/COCO/000000039769.png"
     A__							=     []
     A__							=     []
     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			words=lowercase_		,			boxes=lowercase_		,			top_k=2				)
     self.assertEqual(lowercase_		,			[]				)
 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 	UpperCAmelCase_				(							self :Optional[Any]				)->				Tuple:
     A__							=     pipeline(
         "document-question-answering"		,			model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"		,			revision="9977165"		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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 :Tuple				)->				Optional[Any]:
     A__							=     pipeline(
         "document-question-answering"		,			model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"		,			revision="9977165"		,			max_seq_len=50		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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 :List[Any]				)->				Any:
     A__							=     AutoTokenizer.from_pretrained(
         "impira/layoutlm-document-qa"		,			revision="3dc6de3"		,			add_prefix_space=lowercase_				)
     A__							=     pipeline(
         "document-question-answering"		,			model="impira/layoutlm-document-qa"		,			tokenizer=lowercase_		,			revision="3dc6de3"		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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		,			)

     A__							=     list(zip(*apply_tesseract(load_image(lowercase_				)		,			lowercase_		,			""				)				)				)

     # This model should also work if `image` is set to None
     A__							=     dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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 :Optional[int]				)->				Union[str, Any]:
     A__							=     AutoTokenizer.from_pretrained(
         "impira/layoutlm-document-qa"		,			revision="3dc6de3"		,			add_prefix_space=lowercase_				)
     A__							=     pipeline(
         "document-question-answering"		,			model="impira/layoutlm-document-qa"		,			tokenizer=lowercase_		,			revision="3dc6de3"		,			max_seq_len=50		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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		,			)

     A__							=     list(zip(*apply_tesseract(load_image(lowercase_				)		,			lowercase_		,			""				)				)				)

     # This model should also work if `image` is set to None
     A__							=     dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			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 :Optional[int]				)->				Tuple:
     A__							=     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"		,			)

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



 @require_tf
 @unittest.skip("Document question answering not implemented in TF"				)
 def 	UpperCAmelCase_				(							self :Optional[Any]				)->				List[str]:
     pass



