


import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


A			:						List[Any]        =  logging.getLogger(__name__)






def 					UpperCamelCase   (      __magic_name__	:				Optional[Any]       ,       __magic_name__	:				Optional[Any]	)  ->    Optional[Any]:
		"""simple docstring"""




		if os.path.exists(__magic_name__	):
				if os.path.exists(os.path.join(__magic_name__       ,       """config.json"""	)	) and os.path.isfile(
				    os.path.join(__magic_name__       ,       """config.json"""	)	):
						os.remove(os.path.join(__magic_name__       ,       """config.json"""	)	)
				if os.path.exists(os.path.join(__magic_name__       ,       """pytorch_model.bin"""	)	) and os.path.isfile(
				    os.path.join(__magic_name__       ,       """pytorch_model.bin"""	)	):
						os.remove(os.path.join(__magic_name__       ,       """pytorch_model.bin"""	)	)
		else:
				os.makedirs(__magic_name__	)
		model.save_pretrained(__magic_name__	)






def 					UpperCamelCase   (      __magic_name__	:				int       ,       __magic_name__	:				int=False	)  ->    Optional[int]:
		"""simple docstring"""




		lowercase__	     =						2
		if unlogit:
				lowercase__	     =						torch.pow(__magic_name__       ,       __magic_name__	)
		lowercase__	     =						p * torch.log(__magic_name__	)
		lowercase__	     =						0
		return -plogp.sum(dim=-1	)






def 					UpperCamelCase   (      __magic_name__	:				Any	)  ->    Optional[int]:
		"""simple docstring"""




		logger.info("""lv, h >\t""" + """\t""".join(f'''{x + 1}''' for x in range(len(__magic_name__	)	)	)	)
		for row in range(len(__magic_name__	)	):
				if tensor.dtype != torch.long:
						logger.info(f'''layer {row + 1}:\t''' + """\t""".join(f'''{x:.5f}''' for x in tensor[row].cpu().data	)	)
				else:
						logger.info(f'''layer {row + 1}:\t''' + """\t""".join(f'''{x:d}''' for x in tensor[row].cpu().data	)	)






def 					UpperCamelCase   (      __magic_name__	:				Any       ,       __magic_name__	:				Any       ,       __magic_name__	:				str       ,       __magic_name__	:				Union[str, Any]=True       ,       __magic_name__	:				Optional[int]=True       ,       __magic_name__	:				List[Any]=None       ,       __magic_name__	:				int=False	)  ->    int:
		"""simple docstring"""




		lowercase__     ,      lowercase__	     =						model.config.num_hidden_layers, model.config.num_attention_heads
		lowercase__	     =						torch.zeros(__magic_name__       ,       __magic_name__	).to(args.device	)
		lowercase__	     =						torch.zeros(__magic_name__       ,       __magic_name__	).to(args.device	)

		if head_mask is None:
				lowercase__	     =						torch.ones(__magic_name__       ,       __magic_name__	).to(args.device	)

		head_mask.requires_grad_(requires_grad=__magic_name__	)
		# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
		if actually_pruned:
				lowercase__	     =						None

		lowercase__	     =						0.0
		lowercase__	     =						0.0
		for step, inputs in enumerate(tqdm(__magic_name__       ,       desc="""Iteration"""       ,       disable=args.local_rank not in [-1, 0]	)	):
				lowercase__	     =						tuple(t.to(args.device	) for t in inputs	)
				((lowercase__)     ,      )	     =						inputs

				# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
				lowercase__	     =						model(__magic_name__       ,       labels=__magic_name__       ,       head_mask=__magic_name__	)
				#  (loss), lm_logits, presents, (all hidden_states), (attentions)
				lowercase__     ,      lowercase__     ,      lowercase__	     =						(
				    outputs[0],
				    outputs[1],
				    outputs[-1],
				)  # Loss and logits are the first, attention the last
				loss.backward()  # Backpropagate to populate the gradients in the head mask
				total_loss += loss.detach().cpu().numpy()
				if compute_entropy:
						for layer, attn in enumerate(__magic_name__	):
								lowercase__	     =						entropy(attn.detach()       ,       __magic_name__	)
								attn_entropy[layer] += masked_entropy.sum(-1	).sum(0	).sum(0	).detach()

				if compute_importance:
						head_importance += head_mask.grad.abs().detach()
				tot_tokens += torch.ones_like(__magic_name__	).float().detach().sum().data

		# Normalize
		attn_entropy /= tot_tokens
		head_importance /= tot_tokens
		# Layerwise importance normalization
		if not args.dont_normalize_importance_by_layer:
				lowercase__	     =						2
				lowercase__	     =						torch.pow(torch.pow(__magic_name__       ,       __magic_name__	).sum(-1	)       ,       1 / exponent	)
				head_importance /= norm_by_layer.unsqueeze(-1	) + 1E-2_0

		if not args.dont_normalize_global_importance:
				lowercase__	     =						(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

		# Print matrices
		if compute_entropy:
				logger.info("""Attention entropies"""	)
				print_ad_tensor(__magic_name__	)
		if compute_importance:
				logger.info("""Head importance scores"""	)
				print_ad_tensor(__magic_name__	)
		logger.info("""Head ranked by importance scores"""	)
		lowercase__	     =						torch.zeros(head_importance.numel()       ,       dtype=torch.long       ,       device=args.device	)
		lowercase__	     =						torch.arange(
		    head_importance.numel()       ,       device=args.device	)
		lowercase__	     =						head_ranks.view_as(__magic_name__	)
		print_ad_tensor(__magic_name__	)
		return attn_entropy, head_importance, total_loss






def 					UpperCamelCase   (      __magic_name__	:				Optional[int]       ,       __magic_name__	:				Tuple       ,       __magic_name__	:				Union[str, Any]	)  ->    int:
		"""simple docstring"""




		lowercase__     ,      lowercase__     ,      lowercase__	     =						compute_heads_importance(__magic_name__       ,       __magic_name__       ,       __magic_name__       ,       compute_entropy=__magic_name__	)
		lowercase__	     =						1 / loss  # instead of downsteam score use the LM loss
		logger.info("""Pruning: original score: %f, threshold: %f"""       ,       __magic_name__       ,       original_score * args.masking_threshold	)

		lowercase__	     =						torch.ones_like(__magic_name__	)
		lowercase__	     =						max(1       ,       int(new_head_mask.numel() * args.masking_amount	)	)

		lowercase__	     =						original_score
		while current_score >= original_score * args.masking_threshold:
				lowercase__	     =						new_head_mask.clone().detach()  # save current head mask
				# heads from least important to most - keep only not-masked heads
				lowercase__	     =						float("""Inf"""	)
				lowercase__	     =						head_importance.view(-1	).sort()[1]

				if len(__magic_name__	) <= num_to_mask:
						print("""BREAK BY num_to_mask"""	)
						break

				# mask heads
				lowercase__	     =						current_heads_to_mask[:num_to_mask]
				logger.info("""Heads to mask: %s"""       ,       str(current_heads_to_mask.tolist()	)	)
				lowercase__	     =						new_head_mask.view(-1	)
				lowercase__	     =						0.0
				lowercase__	     =						new_head_mask.view_as(__magic_name__	)
				lowercase__	     =						new_head_mask.clone().detach()
				print_ad_tensor(__magic_name__	)

				# Compute metric and head importance again
				lowercase__     ,      lowercase__     ,      lowercase__	     =						compute_heads_importance(
				    __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       compute_entropy=__magic_name__       ,       head_mask=__magic_name__	)
				lowercase__	     =						1 / loss
				logger.info(
				    """Masking: current score: %f, remaining heads %d (%.1f percents)"""       ,       __magic_name__       ,       new_head_mask.sum()       ,       new_head_mask.sum() / new_head_mask.numel() * 100       ,       )

		logger.info("""Final head mask"""	)
		print_ad_tensor(__magic_name__	)
		np.save(os.path.join(args.output_dir       ,       """head_mask.npy"""	)       ,       head_mask.detach().cpu().numpy()	)

		return head_mask






def 					UpperCamelCase   (      __magic_name__	:				int       ,       __magic_name__	:				str       ,       __magic_name__	:				Any       ,       __magic_name__	:				Optional[int]	)  ->    Tuple:
		"""simple docstring"""




		lowercase__	     =						datetime.now()
		lowercase__     ,      lowercase__     ,      lowercase__	     =						compute_heads_importance(
		    __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       compute_entropy=__magic_name__       ,       compute_importance=__magic_name__       ,       head_mask=__magic_name__	)
		lowercase__	     =						1 / loss
		lowercase__	     =						datetime.now() - before_time

		lowercase__	     =						sum(p.numel() for p in model.parameters()	)
		lowercase__	     =						{
		    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__magic_name__	)	)
		}

		for k, v in heads_to_prune.items():
				if isinstance(__magic_name__       ,       __magic_name__	):
						lowercase__	     =						[
						    v,
						]

		assert sum(len(__magic_name__	) for h in heads_to_prune.values()	) == (1 - head_mask.long()).sum().item()
		model.prune_heads(__magic_name__	)
		lowercase__	     =						sum(p.numel() for p in model.parameters()	)

		lowercase__	     =						datetime.now()
		lowercase__     ,      lowercase__     ,      lowercase__	     =						compute_heads_importance(
		    __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       compute_entropy=__magic_name__       ,       compute_importance=__magic_name__       ,       head_mask=__magic_name__       ,       actually_pruned=__magic_name__       ,       )

		lowercase__	     =						1 / loss
		lowercase__	     =						datetime.now() - before_time

		logger.info(
		    """Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)"""       ,       __magic_name__       ,       __magic_name__       ,       pruned_num_params / original_num_params * 100       ,       )
		logger.info("""Pruning: score with masking: %f score with pruning: %f"""       ,       __magic_name__       ,       __magic_name__	)
		logger.info("""Pruning: speed ratio (original timing / new timing): %f percents"""       ,       original_time / new_time * 100	)
		save_model(__magic_name__       ,       args.output_dir	)






def 					UpperCamelCase   (      )  ->    Any:
		"""simple docstring"""




		lowercase__	     =						argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    """--data_dir"""       ,       default=__magic_name__       ,       type=__magic_name__       ,       required=__magic_name__       ,       help="""The input data dir. Should contain the .tsv files (or other data files) for the task."""       ,       )
		parser.add_argument(
		    """--model_name_or_path"""       ,       default=__magic_name__       ,       type=__magic_name__       ,       required=__magic_name__       ,       help="""Path to pretrained model or model identifier from huggingface.co/models"""       ,       )
		parser.add_argument(
		    """--output_dir"""       ,       default=__magic_name__       ,       type=__magic_name__       ,       required=__magic_name__       ,       help="""The output directory where the model predictions and checkpoints will be written."""       ,       )

		# Other parameters
		parser.add_argument(
		    """--config_name"""       ,       default=""""""       ,       type=__magic_name__       ,       help="""Pretrained config name or path if not the same as model_name_or_path"""       ,       )
		parser.add_argument(
		    """--tokenizer_name"""       ,       default=""""""       ,       type=__magic_name__       ,       help="""Pretrained tokenizer name or path if not the same as model_name_or_path"""       ,       )
		parser.add_argument(
		    """--cache_dir"""       ,       default=__magic_name__       ,       type=__magic_name__       ,       help="""Where do you want to store the pre-trained models downloaded from s3"""       ,       )
		parser.add_argument(
		    """--data_subset"""       ,       type=__magic_name__       ,       default=-1       ,       help="""If > 0: limit the data to a subset of data_subset instances."""	)
		parser.add_argument(
		    """--overwrite_output_dir"""       ,       action="""store_true"""       ,       help="""Whether to overwrite data in output directory"""	)
		parser.add_argument(
		    """--overwrite_cache"""       ,       action="""store_true"""       ,       help="""Overwrite the cached training and evaluation sets"""	)

		parser.add_argument(
		    """--dont_normalize_importance_by_layer"""       ,       action="""store_true"""       ,       help="""Don't normalize importance score by layers"""	)
		parser.add_argument(
		    """--dont_normalize_global_importance"""       ,       action="""store_true"""       ,       help="""Don't normalize all importance scores between 0 and 1"""       ,       )

		parser.add_argument(
		    """--try_masking"""       ,       action="""store_true"""       ,       help="""Whether to try to mask head until a threshold of accuracy."""	)
		parser.add_argument(
		    """--masking_threshold"""       ,       default=0.9       ,       type=__magic_name__       ,       help="""masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."""       ,       )
		parser.add_argument(
		    """--masking_amount"""       ,       default=0.1       ,       type=__magic_name__       ,       help="""Amount to heads to masking at each masking step."""	)
		parser.add_argument("""--metric_name"""       ,       default="""acc"""       ,       type=__magic_name__       ,       help="""Metric to use for head masking."""	)

		parser.add_argument(
		    """--max_seq_length"""       ,       default=128       ,       type=__magic_name__       ,       help=(
		        """The maximum total input sequence length after WordPiece tokenization. \n"""
		        """Sequences longer than this will be truncated, sequences shorter padded."""
		    )       ,       )
		parser.add_argument("""--batch_size"""       ,       default=1       ,       type=__magic_name__       ,       help="""Batch size."""	)

		parser.add_argument("""--seed"""       ,       type=__magic_name__       ,       default=42	)
		parser.add_argument("""--local_rank"""       ,       type=__magic_name__       ,       default=-1       ,       help="""local_rank for distributed training on gpus"""	)
		parser.add_argument("""--no_cuda"""       ,       action="""store_true"""       ,       help="""Whether not to use CUDA when available"""	)
		parser.add_argument("""--server_ip"""       ,       type=__magic_name__       ,       default=""""""       ,       help="""Can be used for distant debugging."""	)
		parser.add_argument("""--server_port"""       ,       type=__magic_name__       ,       default=""""""       ,       help="""Can be used for distant debugging."""	)
		lowercase__	     =						parser.parse_args()

		if args.server_ip and args.server_port:
				# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
				import ptvsd

				print("""Waiting for debugger attach"""	)
				ptvsd.enable_attach(address=(args.server_ip, args.server_port)       ,       redirect_output=__magic_name__	)
				ptvsd.wait_for_attach()

		# Setup devices and distributed training
		if args.local_rank == -1 or args.no_cuda:
				lowercase__	     =						torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""	)
				lowercase__	     =						0 if args.no_cuda else torch.cuda.device_count()
		else:
				torch.cuda.set_device(args.local_rank	)
				lowercase__	     =						torch.device("""cuda"""       ,       args.local_rank	)
				lowercase__	     =						1
				torch.distributed.init_process_group(backend="""nccl"""	)  # Initializes the distributed backend

		# Setup logging
		logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN	)
		logger.info("""device: {} n_gpu: {}, distributed: {}""".format(args.device       ,       args.n_gpu       ,       bool(args.local_rank != -1	)	)	)

		lowercase__	     =						GPTaLMHeadModel.from_pretrained(args.model_name_or_path	)

		# Distributed and parallel training
		model.to(args.device	)
		if args.local_rank != -1:
				lowercase__	     =						nn.parallel.DistributedDataParallel(
				    __magic_name__       ,       device_ids=[args.local_rank]       ,       output_device=args.local_rank       ,       find_unused_parameters=__magic_name__	)
		elif args.n_gpu > 1:
				lowercase__	     =						nn.DataParallel(__magic_name__	)

		# Print/save training arguments
		os.makedirs(args.output_dir       ,       exist_ok=__magic_name__	)
		torch.save(__magic_name__       ,       os.path.join(args.output_dir       ,       """run_args.bin"""	)	)
		logger.info("""Training/evaluation parameters %s"""       ,       __magic_name__	)

		# Prepare dataset
		lowercase__	     =						np.concatenate(
		    [
		        np.loadtxt(args.data_dir       ,       dtype=np.intaa	),
		    ]	)
		lowercase__	     =						(torch.from_numpy(__magic_name__	),)
		lowercase__	     =						TensorDataset(*__magic_name__	)
		lowercase__	     =						RandomSampler(__magic_name__	)
		lowercase__	     =						DataLoader(__magic_name__       ,       sampler=__magic_name__       ,       batch_size=args.batch_size	)

		# Compute head entropy and importance score
		compute_heads_importance(__magic_name__       ,       __magic_name__       ,       __magic_name__	)

		# Try head masking (set heads to zero until the score goes under a threshole)
		# and head pruning (remove masked heads and see the effect on the network)
		if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
				lowercase__	     =						mask_heads(__magic_name__       ,       __magic_name__       ,       __magic_name__	)
				prune_heads(__magic_name__       ,       __magic_name__       ,       __magic_name__       ,       __magic_name__	)


if __name__ == "__main__":
	main()








'''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



