'''simple docstring'''

from typing import Any, Dict, List, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import DistributedSampler, RandomSampler

from transformers import PreTrainedModel, Trainer, logging
from transformers.integrations import is_fairscale_available
from transformers.models.fsmt.configuration_fsmt import FSMTConfig
from transformers.optimization import (
    Adafactor,
    AdamW,
    get_constant_schedule,
    get_constant_schedule_with_warmup,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.trainer_pt_utils import get_tpu_sampler
from transformers.training_args import ParallelMode
from transformers.utils import is_torch_tpu_available


if is_fairscale_available():
 from fairscale.optim import OSS


A_     :						int    							=logging.get_logger(__name__)

A_     :						List[Any]    							={
    '''linear''': get_linear_schedule_with_warmup,
    '''cosine''': get_cosine_schedule_with_warmup,
    '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
    '''polynomial''': get_polynomial_decay_schedule_with_warmup,
    '''constant''': get_constant_schedule,
    '''constant_w_warmup''': get_constant_schedule_with_warmup,
}


class     __UpperCAmelCase       ( __a		):





  def __init__(	self    ,     _lowerCamelCase=None    ,     _lowerCamelCase=None    ,     *_lowerCamelCase    ,     **_lowerCamelCase ):
     super().__init__(*_lowerCamelCase    ,     **_lowerCamelCase )

     if config is None:
        assert isinstance(self.model    ,     _lowerCamelCase ), (
            "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is"
            F''' {self.model.__class__}'''
        )
        lowerCAmelCase_			=      self.model.config
     else:
        lowerCAmelCase_			=      config

     lowerCAmelCase_			=      data_args
     lowerCAmelCase_			=      self.config.tgt_vocab_size if isinstance(self.config    ,     _lowerCamelCase ) else self.config.vocab_size

     if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss):
        assert self.config.pad_token_id is not None, (
            "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss"
            " calculation or doing label smoothing."
        )

     if self.config.pad_token_id is None and self.config.eos_token_id is not None:
        logger.warning(
            F'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for'''
            ''' padding..''' )

     if self.args.label_smoothing == 0:
        lowerCAmelCase_			=      torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id )
     else:
        # dynamically import label_smoothed_nll_loss
        from utils import label_smoothed_nll_loss

        lowerCAmelCase_			=      label_smoothed_nll_loss





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase ):
     if self.optimizer is None:
        lowerCAmelCase_			=      ['''bias''', '''LayerNorm.weight''']
        lowerCAmelCase_			=      [
            {
                '''params''': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )],
                '''weight_decay''': self.args.weight_decay,
            },
            {
                '''params''': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )],
                '''weight_decay''': 0.0,
            },
        ]
        lowerCAmelCase_			=      Adafactor if self.args.adafactor else AdamW
        if self.args.adafactor:
           lowerCAmelCase_			=      Adafactor
           lowerCAmelCase_			=      {'''scale_parameter''': False, '''relative_step''': False}
        else:
           lowerCAmelCase_			=      AdamW
           lowerCAmelCase_			=      {
               '''betas''': (self.args.adam_betaa, self.args.adam_betaa),
               '''eps''': self.args.adam_epsilon,
           }
        lowerCAmelCase_			=      self.args.learning_rate
        if self.sharded_ddp:
           lowerCAmelCase_			=      OSS(
               params=_lowerCamelCase    ,     optim=_lowerCamelCase    ,     **_lowerCamelCase    ,     )
        else:
           lowerCAmelCase_			=      optimizer_cls(_lowerCamelCase    ,     **_lowerCamelCase )

     if self.lr_scheduler is None:
        lowerCAmelCase_			=      self._get_lr_scheduler(_lowerCamelCase )
     else:  # ignoring --lr_scheduler
        logger.warning('''scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.''' )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      arg_to_scheduler[self.args.lr_scheduler]
     if self.args.lr_scheduler == "constant":
        lowerCAmelCase_			=      schedule_func(self.optimizer )
     elif self.args.lr_scheduler == "constant_w_warmup":
        lowerCAmelCase_			=      schedule_func(self.optimizer    ,     num_warmup_steps=self.args.warmup_steps )
     else:
        lowerCAmelCase_			=      schedule_func(
            self.optimizer    ,     num_warmup_steps=self.args.warmup_steps    ,     num_training_steps=_lowerCamelCase )
     return scheduler





  def 						UpperCAmelCase_	(	self ):
     if isinstance(self.train_dataset    ,     torch.utils.data.IterableDataset ):
        return None
     elif is_torch_tpu_available():
        return get_tpu_sampler(self.train_dataset )
     else:
        if self.args.sortish_sampler:
           self.train_dataset.make_sortish_sampler(
               self.args.per_device_train_batch_size    ,     distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED)    ,     )

        return (
            RandomSampler(self.train_dataset )
            if self.args.local_rank == -1
            else DistributedSampler(self.train_dataset )
        )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     if self.args.label_smoothing == 0:
        if self.data_args is not None and self.data_args.ignore_pad_token_for_loss:
           # force training to ignore pad token
           lowerCAmelCase_			=      model(**_lowerCamelCase    ,     use_cache=_lowerCamelCase )[0]
           lowerCAmelCase_			=      self.loss_fn(logits.view(-1    ,     logits.shape[-1] )    ,     labels.view(-1 ) )
        else:
           # compute usual loss via models
           lowerCAmelCase_	,lowerCAmelCase_			=      model(**_lowerCamelCase    ,     labels=_lowerCamelCase    ,     use_cache=_lowerCamelCase )[:2]
     else:
        # compute label smoothed loss
        lowerCAmelCase_			=      model(**_lowerCamelCase    ,     use_cache=_lowerCamelCase )[0]
        lowerCAmelCase_			=      torch.nn.functional.log_softmax(_lowerCamelCase    ,     dim=-1 )
        lowerCAmelCase_	,lowerCAmelCase_			=      self.loss_fn(_lowerCamelCase    ,     _lowerCamelCase    ,     self.args.label_smoothing    ,     ignore_index=self.config.pad_token_id )
     return loss, logits





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      inputs.pop('''labels''' )
     lowerCAmelCase_	,lowerCAmelCase_			=      self._compute_loss(_lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase )
     return loss





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase = None    ,     ):
     lowerCAmelCase_			=      self._prepare_inputs(_lowerCamelCase )

     lowerCAmelCase_			=      {
         '''max_length''': self.data_args.val_max_target_length
         if self.data_args is not None
         else self.config.max_length,
         '''num_beams''': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams,
     }

     if self.args.predict_with_generate and not self.args.prediction_loss_only:
        lowerCAmelCase_			=      self.model.generate(
            inputs['''input_ids''']    ,     attention_mask=inputs['''attention_mask''']    ,     **_lowerCamelCase    ,     )
        # in case the batch is shorter than max length, the output should be padded
        if generated_tokens.shape[-1] < gen_kwargs["max_length"]:
           lowerCAmelCase_			=      self._pad_tensors_to_max_len(_lowerCamelCase    ,     gen_kwargs['''max_length'''] )

     lowerCAmelCase_			=      inputs.pop('''labels''' )
     with torch.no_grad():
        # compute loss on predict data
        lowerCAmelCase_	,lowerCAmelCase_			=      self._compute_loss(_lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase )

     lowerCAmelCase_			=      loss.mean().detach()
     if self.args.prediction_loss_only:
        return (loss, None, None)

     lowerCAmelCase_			=      generated_tokens if self.args.predict_with_generate else logits

     if labels.shape[-1] < gen_kwargs["max_length"]:
        lowerCAmelCase_			=      self._pad_tensors_to_max_len(_lowerCamelCase    ,     gen_kwargs['''max_length'''] )

     return (loss, logits, labels)







  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     # If PAD token is not defined at least EOS token has to be defined
     lowerCAmelCase_			=      self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id

     if pad_token_id is None:
        raise ValueError(
            '''Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be'''
            F''' padded to `max_length`={max_length}''' )

     lowerCAmelCase_			=      pad_token_id * torch.ones(
         (tensor.shape[0], max_length)    ,     dtype=tensor.dtype    ,     device=tensor.device )
     lowerCAmelCase_			=      tensor
     return padded_tensor






'''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_	(	*_lowerCamelCase    ,     **_lowerCamelCase ):
      pass






 def snake_case_      (					__snake_case  :							int)			->					Union[str, 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.
A_     :						Any    							=(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


@is_pipeline_test
@require_torch
@require_vision
class     __UpperCAmelCase       ( unittest.TestCase		):
  __A :				Union[str, Any]											= MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING





  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model=_lowerCamelCase    ,     tokenizer=_lowerCamelCase    ,     image_processor=_lowerCamelCase )

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





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      dqa_pipeline(_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         _lowerCamelCase    ,     [
             [
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
             ]
         ]
         * 3    ,     )





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

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

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

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

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





  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ],
         ]
         * 2    ,     )





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

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
                 {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ]
         ]
         * 2    ,     )





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

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             ]
         ]
         * 2    ,     )

     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )





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

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ]
         ]
         * 2    ,     )

     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )

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





  @slow
  @require_torch
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      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'''    ,     )

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







  @require_tf
  @unittest.skip('''Document question answering not implemented in TF''' )
  def 						UpperCAmelCase_	(	self ):
     pass





