





import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


snake_case_				=			logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()






def lowerCamelCase__    (							snake_case_	:  Optional[int]       )      ->				Any:
   if "token" in model_name_or_path:
      return "rag_token"
   if "sequence" in model_name_or_path:
      return "rag_sequence"
   if "bart" in model_name_or_path:
      return "bart"
   return None






def lowerCamelCase__    (							snake_case_	:  Optional[int]       ,      snake_case_	:  Tuple       ,      snake_case_	:  Any       )      ->				str:
   return max(metric_fn(snake_case_       ,      snake_case_       ) for gt in ground_truths       )






def lowerCamelCase__    (							snake_case_	:  Tuple       ,      snake_case_	:  str       ,      snake_case_	:  Dict       )      ->				int:
   __snake_case							       =   [line.strip() for line in open(snake_case_       ,      '''r'''       ).readlines()]
   __snake_case							       =   []

   if args.gold_data_mode == "qa":
      __snake_case							       =   pd.read_csv(snake_case_       ,      sep='''\t'''       ,      header=snake_case_       )
      for answer_list in data[1]:
         __snake_case							       =   ast.literal_eval(snake_case_       )
         answers.append(snake_case_       )
   else:
      __snake_case							       =   [line.strip() for line in open(snake_case_       ,      '''r'''       ).readlines()]
      __snake_case							       =   [[reference] for reference in references]

   __snake_case							       =   __snake_case							       =   __snake_case							       =   0
   for prediction, ground_truths in zip(snake_case_       ,      snake_case_       ):
      total += 1
      em += metric_max_over_ground_truths(snake_case_       ,      snake_case_       ,      snake_case_       )
      fa += metric_max_over_ground_truths(snake_case_       ,      snake_case_       ,      snake_case_       )

   __snake_case							       =   100.0 * em / total
   __snake_case							       =   100.0 * fa / total

   logger.info(f"""F1: {fa:.2f}"""       )
   logger.info(f"""EM: {em:.2f}"""       )






def lowerCamelCase__    (							snake_case_	:  Any       ,      snake_case_	:  Tuple       ,      snake_case_	:  Dict       )      ->				int:
   __snake_case							       =   args.k
   __snake_case							       =   [line.strip() for line in open(snake_case_       ,      '''r'''       ).readlines()]
   __snake_case							       =   [line.strip() for line in open(snake_case_       ,      '''r'''       ).readlines()]

   __snake_case							       =   __snake_case							       =   0
   for hypo, reference in zip(snake_case_       ,      snake_case_       ):
      __snake_case							       =   set(hypo.split('''\t'''       )[:k]       )
      __snake_case							       =   set(reference.split('''\t'''       )       )
      total += 1
      em += len(hypo_provenance & ref_provenance       ) / k

   __snake_case							       =   100.0 * em / total
   logger.info(f"""Precision@{k}: {em: .2f}"""       )






def lowerCamelCase__    (							snake_case_	:  Optional[Any]       ,      snake_case_	:  Union[str, Any]       ,      snake_case_	:  List[str]       )      ->				Optional[Any]:
   def strip_title(snake_case_	:  Dict       ):
      if title.startswith('''"'''       ):
         __snake_case							       =   title[1:]
      if title.endswith('''"'''       ):
         __snake_case							       =   title[:-1]
      return title

   __snake_case							       =   rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
       snake_case_       ,      return_tensors='''pt'''       ,      padding=snake_case_       ,      truncation=snake_case_       ,      )['''input_ids'''].to(args.device       )

   __snake_case							       =   rag_model.rag.question_encoder(snake_case_       )
   __snake_case							       =   question_enc_outputs[0]

   __snake_case							       =   rag_model.retriever(
       snake_case_       ,      question_enc_pool_output.cpu().detach().to(torch.floataa       ).numpy()       ,      prefix=rag_model.rag.generator.config.prefix       ,      n_docs=rag_model.config.n_docs       ,      return_tensors='''pt'''       ,      )
   __snake_case							       =   rag_model.retriever.index.get_doc_dicts(result.doc_ids       )
   __snake_case							       =   []
   for docs in all_docs:
      __snake_case							       =   [strip_title(snake_case_       ) for title in docs['''title''']]
      provenance_strings.append('''\t'''.join(snake_case_       )       )
   return provenance_strings






def lowerCamelCase__    (							snake_case_	:  Optional[Any]       ,      snake_case_	:  Union[str, Any]       ,      snake_case_	:  Optional[int]       )      ->				str:
   with torch.no_grad():
      __snake_case							       =   rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
          snake_case_       ,      return_tensors='''pt'''       ,      padding=snake_case_       ,      truncation=snake_case_       )

      __snake_case							       =   inputs_dict.input_ids.to(args.device       )
      __snake_case							       =   inputs_dict.attention_mask.to(args.device       )
      __snake_case							       =   rag_model.generate(  # rag_model overwrites generate
          snake_case_       ,      attention_mask=snake_case_       ,      num_beams=args.num_beams       ,      min_length=args.min_length       ,      max_length=args.max_length       ,      early_stopping=snake_case_       ,      num_return_sequences=1       ,      bad_words_ids=[[0, 0]]       ,      )
      __snake_case							       =   rag_model.retriever.generator_tokenizer.batch_decode(snake_case_       ,      skip_special_tokens=snake_case_       )

      if args.print_predictions:
         for q, a in zip(snake_case_       ,      snake_case_       ):
            logger.info('''Q: {} - A: {}'''.format(snake_case_       ,      snake_case_       )       )

      return answers






def lowerCamelCase__    (							)      ->				List[Any]:
   __snake_case							       =   argparse.ArgumentParser()
   parser.add_argument(
       '''--model_type'''       ,      choices=['''rag_sequence''', '''rag_token''', '''bart''']       ,      type=snake_case_       ,      help=(
           '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the'''
           ''' model_name_or_path'''
       )       ,      )
   parser.add_argument(
       '''--index_name'''       ,      default=snake_case_       ,      choices=['''exact''', '''compressed''', '''legacy''']       ,      type=snake_case_       ,      help='''RAG model retriever type'''       ,      )
   parser.add_argument(
       '''--index_path'''       ,      default=snake_case_       ,      type=snake_case_       ,      help='''Path to the retrieval index'''       ,      )
   parser.add_argument('''--n_docs'''       ,      default=5       ,      type=snake_case_       ,      help='''Number of retrieved docs'''       )
   parser.add_argument(
       '''--model_name_or_path'''       ,      default=snake_case_       ,      type=snake_case_       ,      required=snake_case_       ,      help='''Path to pretrained checkpoints or model identifier from huggingface.co/models'''       ,      )
   parser.add_argument(
       '''--eval_mode'''       ,      choices=['''e2e''', '''retrieval''']       ,      default='''e2e'''       ,      type=snake_case_       ,      help=(
           '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates'''
           ''' precision@k.'''
       )       ,      )
   parser.add_argument('''--k'''       ,      default=1       ,      type=snake_case_       ,      help='''k for the precision@k calculation'''       )
   parser.add_argument(
       '''--evaluation_set'''       ,      default=snake_case_       ,      type=snake_case_       ,      required=snake_case_       ,      help='''Path to a file containing evaluation samples'''       ,      )
   parser.add_argument(
       '''--gold_data_path'''       ,      default=snake_case_       ,      type=snake_case_       ,      required=snake_case_       ,      help='''Path to a tab-separated file with gold samples'''       ,      )
   parser.add_argument(
       '''--gold_data_mode'''       ,      default='''qa'''       ,      type=snake_case_       ,      choices=['''qa''', '''ans''']       ,      help=(
           '''Format of the gold data file'''
           '''qa - a single line in the following format: question [tab] answer_list'''
           '''ans - a single line of the gold file contains the expected answer string'''
       )       ,      )
   parser.add_argument(
       '''--predictions_path'''       ,      type=snake_case_       ,      default='''predictions.txt'''       ,      help='''Name of the predictions file, to be stored in the checkpoints directory'''       ,      )
   parser.add_argument(
       '''--eval_all_checkpoints'''       ,      action='''store_true'''       ,      help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number'''       ,      )
   parser.add_argument(
       '''--eval_batch_size'''       ,      default=8       ,      type=snake_case_       ,      help='''Batch size per GPU/CPU for evaluation.'''       ,      )
   parser.add_argument(
       '''--recalculate'''       ,      help='''Recalculate predictions even if the prediction file exists'''       ,      action='''store_true'''       ,      )
   parser.add_argument(
       '''--num_beams'''       ,      default=4       ,      type=snake_case_       ,      help='''Number of beams to be used when generating answers'''       ,      )
   parser.add_argument('''--min_length'''       ,      default=1       ,      type=snake_case_       ,      help='''Min length of the generated answers'''       )
   parser.add_argument('''--max_length'''       ,      default=50       ,      type=snake_case_       ,      help='''Max length of the generated answers'''       )

   parser.add_argument(
       '''--print_predictions'''       ,      action='''store_true'''       ,      help='''If True, prints predictions while evaluating.'''       ,      )
   parser.add_argument(
       '''--print_docs'''       ,      action='''store_true'''       ,      help='''If True, prints docs retried while generating.'''       ,      )
   __snake_case							       =   parser.parse_args()
   __snake_case							       =   torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''       )
   return args






def lowerCamelCase__    (							snake_case_	:  int       )      ->				str:
   __snake_case							       =   {}
   if args.model_type is None:
      __snake_case							       =   infer_model_type(args.model_name_or_path       )
      assert args.model_type is not None
   if args.model_type.startswith('''rag'''       ):
      __snake_case							       =   RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration
      __snake_case							       =   args.n_docs
      if args.index_name is not None:
         __snake_case							       =   args.index_name
      if args.index_path is not None:
         __snake_case							       =   args.index_path
   else:
      __snake_case							       =   BartForConditionalGeneration

   __snake_case							       =   (
       [f.path for f in os.scandir(args.model_name_or_path       ) if f.is_dir()]
       if args.eval_all_checkpoints
       else [args.model_name_or_path]
   )

   logger.info('''Evaluate the following checkpoints: %s'''       ,      snake_case_       )

   __snake_case							       =   get_scores if args.eval_mode == '''e2e''' else get_precision_at_k
   __snake_case							       =   evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval

   for checkpoint in checkpoints:
      if os.path.exists(args.predictions_path       ) and (not args.recalculate):
         logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path       )       )
         score_fn(snake_case_       ,      args.predictions_path       ,      args.gold_data_path       )
         continue

      logger.info('''***** Running evaluation for {} *****'''.format(snake_case_       )       )
      logger.info('''  Batch size = %d'''       ,      args.eval_batch_size       )
      logger.info('''  Predictions will be stored under {}'''.format(args.predictions_path       )       )

      if args.model_type.startswith('''rag'''       ):
         __snake_case							       =   RagRetriever.from_pretrained(snake_case_       ,      **snake_case_       )
         __snake_case							       =   model_class.from_pretrained(snake_case_       ,      retriever=snake_case_       ,      **snake_case_       )
         model.retriever.init_retrieval()
      else:
         __snake_case							       =   model_class.from_pretrained(snake_case_       ,      **snake_case_       )
      model.to(args.device       )

      with open(args.evaluation_set       ,      '''r'''       ) as eval_file, open(args.predictions_path       ,      '''w'''       ) as preds_file:
         __snake_case							       =   []
         for line in tqdm(snake_case_       ):
            questions.append(line.strip()       )
            if len(snake_case_       ) == args.eval_batch_size:
               __snake_case							       =   evaluate_batch_fn(snake_case_       ,      snake_case_       ,      snake_case_       )
               preds_file.write('''\n'''.join(snake_case_       ) + '''\n'''       )
               preds_file.flush()
               __snake_case							       =   []
         if len(snake_case_       ) > 0:
            __snake_case							       =   evaluate_batch_fn(snake_case_       ,      snake_case_       ,      snake_case_       )
            preds_file.write('''\n'''.join(snake_case_       )       )
            preds_file.flush()

         score_fn(snake_case_       ,      args.predictions_path       ,      args.gold_data_path       )


if __name__ == "__main__":
    snake_case_				=			get_args()
    main(args)








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 		SCREAMING_SNAKE_CASE__				:


          @staticmethod
          def    a (*a__       :      List[str]				,			**a__       :      List[str]      ):





             """simple docstring"""



             pass






    def lowerCamelCase__    (							snake_case_	:  int       )      ->				Optional[int]:
       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_				=			(
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)

@is_pipeline_test
@require_torch
@require_vision
class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):
      A_						:				Optional[Any]							=    MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING


      @require_pytesseract
      @require_vision
      def    a (self       :      List[Any]				,			a__       :      Tuple				,			a__       :      Union[str, Any]				,			a__       :      Any      ):





         """simple docstring"""



         __snake_case							       =   pipeline(
             '''document-question-answering'''				,			model=a__				,			tokenizer=a__				,			image_processor=a__      )

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


      def    a (self       :      Union[str, Any]				,			a__       :      Optional[int]				,			a__       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   dqa_pipeline(a__				,			top_k=2      )
         self.assertEqual(
             a__				,			[
                 [
                     {'''score''': ANY(a__      ), '''answer''': ANY(a__      ), '''start''': ANY(a__      ), '''end''': ANY(a__      )},
                     {'''score''': ANY(a__      ), '''answer''': ANY(a__      ), '''start''': ANY(a__      ), '''end''': ANY(a__      )},
                 ]
             ]
             * 3				,			)


      @require_torch
      @require_detectrona
      @require_pytesseract
      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   pipeline('''document-question-answering'''				,			model='''hf-internal-testing/tiny-random-layoutlmv2'''      )
         __snake_case							       =   INVOICE_URL
         __snake_case							       =   '''How many cats are there?'''

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

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

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

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


      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def    a (self       :      str      ):





         """simple docstring"""



         __snake_case							       =   pipeline(
             '''document-question-answering'''				,			model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''				,			revision='''9977165'''				,			)
         __snake_case							       =   INVOICE_URL
         __snake_case							       =   '''What is the invoice number?'''

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

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

         __snake_case							       =   dqa_pipeline(
             [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]				,			top_k=2      )
         self.assertEqual(
             nested_simplify(a__				,			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    a (self       :      List[Any]      ):





         """simple docstring"""



         __snake_case							       =   pipeline(
             '''document-question-answering'''				,			model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''				,			revision='''9977165'''				,			max_seq_len=50				,			)
         __snake_case							       =   INVOICE_URL
         __snake_case							       =   '''What is the invoice number?'''

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

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

         __snake_case							       =   dqa_pipeline(
             [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]				,			top_k=2      )
         self.assertEqual(
             nested_simplify(a__				,			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    a (self       :      Tuple      ):





         """simple docstring"""



         __snake_case							       =   AutoTokenizer.from_pretrained(
             '''impira/layoutlm-document-qa'''				,			revision='''3dc6de3'''				,			add_prefix_space=a__      )
         __snake_case							       =   pipeline(
             '''document-question-answering'''				,			model='''impira/layoutlm-document-qa'''				,			tokenizer=a__				,			revision='''3dc6de3'''				,			)
         __snake_case							       =   INVOICE_URL
         __snake_case							       =   '''What is the invoice number?'''

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

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

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

         __snake_case							       =   list(zip(*apply_tesseract(load_image(a__      )				,			a__				,			''''''      )      )      )

         # This model should also work if `image` is set to None
         __snake_case							       =   dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}				,			top_k=2      )
         self.assertEqual(
             nested_simplify(a__				,			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    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   AutoTokenizer.from_pretrained(
             '''impira/layoutlm-document-qa'''				,			revision='''3dc6de3'''				,			add_prefix_space=a__      )
         __snake_case							       =   pipeline(
             '''document-question-answering'''				,			model='''impira/layoutlm-document-qa'''				,			tokenizer=a__				,			revision='''3dc6de3'''				,			max_seq_len=50				,			)
         __snake_case							       =   INVOICE_URL
         __snake_case							       =   '''What is the invoice number?'''

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

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

         __snake_case							       =   list(zip(*apply_tesseract(load_image(a__      )				,			a__				,			''''''      )      )      )

         # This model should also work if `image` is set to None
         __snake_case							       =   dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}				,			top_k=2      )
         self.assertEqual(
             nested_simplify(a__				,			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    a (self       :      Tuple      ):





         """simple docstring"""



         __snake_case							       =   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'''				,			)

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


      @require_tf
      @unittest.skip('''Document question answering not implemented in TF'''      )
      def    a (self       :      List[str]      ):





         """simple docstring"""



         pass

