






'''simple docstring'''



from typing import Optional, Tuple, Union

import torch
from einops import rearrange, reduce

from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel
from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput


SCREAMING_SNAKE_CASE						=	8


def 							lowercase_				(    __A :       Optional[Any]					,      __A :       Tuple=BITS			)       ->      Optional[Any]:



 """simple docstring"""




 lowercase					:   Any				  =x.device

 lowercase					:   List[str]				  =(x * 2_5_5).int().clamp(0					,      2_5_5			)

 lowercase					:   int				  =2 ** torch.arange(bits - 1					,      -1					,      -1					,      device=_lowerCAmelCase			)
 lowercase					:   Union[str, Any]				  =rearrange(_lowerCAmelCase					,      '''d -> d 1 1'''			)
 lowercase					:   Any				  =rearrange(_lowerCAmelCase					,      '''b c h w -> b c 1 h w'''			)

 lowercase					:   Any				  =((x & mask) != 0).float()
 lowercase					:   Union[str, Any]				  =rearrange(_lowerCAmelCase					,      '''b c d h w -> b (c d) h w'''			)
 lowercase					:   Optional[int]				  =bits * 2 - 1
 return bits


def 							lowercase_				(    __A :       int					,      __A :       int=BITS			)       ->      int:



 """simple docstring"""




 lowercase					:   Dict				  =x.device

 lowercase					:   str				  =(x > 0).int()
 lowercase					:   Optional[Any]				  =2 ** torch.arange(bits - 1					,      -1					,      -1					,      device=_lowerCAmelCase					,      dtype=torch.intaa			)

 lowercase					:   Union[str, Any]				  =rearrange(_lowerCAmelCase					,      '''d -> d 1 1'''			)
 lowercase					:   Tuple				  =rearrange(_lowerCAmelCase					,      '''b (c d) h w -> b c d h w'''					,      d=8			)
 lowercase					:   List[Any]				  =reduce(x * mask					,      '''b c d h w -> b c h w'''					,      '''sum'''			)
 return (dec / 2_5_5).clamp(0.0					,      1.0			)


def 							lowercase_				(    self :       Optional[int]					,      __A :       Dict					,      __A :       str					,      __A :       Optional[Any]					,      __A :       List[Any] = 0.0					,      __A :       List[str] = True					,      __A :       str=None					,      __A :       Dict = True					,      )       ->      Union[DDIMSchedulerOutput, Tuple]:



 """simple docstring"""




 if self.num_inference_steps is None:
  raise ValueError(
      '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler'''			)

 # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
 # Ideally, read DDIM paper in-detail understanding

 # Notation (<variable name> -> <name in paper>
 # - pred_noise_t -> e_theta(x_t, t)
 # - pred_original_sample -> f_theta(x_t, t) or x_0
 # - std_dev_t -> sigma_t
 # - eta -> η
 # - pred_sample_direction -> "direction pointing to x_t"
 # - pred_prev_sample -> "x_t-1"

 # 1. get previous step value (=t-1)
 lowercase					:   List[Any]				  =timestep - self.config.num_train_timesteps // self.num_inference_steps

 # 2. compute alphas, betas
 lowercase					:   List[str]				  =self.alphas_cumprod[timestep]
 lowercase					:   str				  =self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod

 lowercase					:   Optional[Any]				  =1 - alpha_prod_t

 # 3. compute predicted original sample from predicted noise also called
 # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
 lowercase					:   Any				  =(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5

 # 4. Clip "predicted x_0"
 lowercase					:   List[str]				  =self.bit_scale
 if self.config.clip_sample:
  lowercase					:   Any				  =torch.clamp(_lowerCAmelCase					,      -scale					,      _lowerCAmelCase			)

 # 5. compute variance: "sigma_t(η)" -> see formula (16)
 # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
 lowercase					:   int				  =self._get_variance(_lowerCAmelCase					,      _lowerCAmelCase			)
 lowercase					:   Union[str, Any]				  =eta * variance ** 0.5

 if use_clipped_model_output:
  # the model_output is always re-derived from the clipped x_0 in Glide
  lowercase					:   Tuple				  =(sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5

 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
 lowercase					:   Union[str, Any]				  =(1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output

 # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
 lowercase					:   Tuple				  =alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction

 if eta > 0:
  # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
  lowercase					:   Any				  =model_output.device if torch.is_tensor(_lowerCAmelCase			) else "cpu"
  lowercase					:   Optional[Any]				  =torch.randn(model_output.shape					,      dtype=model_output.dtype					,      generator=_lowerCAmelCase			).to(_lowerCAmelCase			)
  lowercase					:   List[str]				  =self._get_variance(_lowerCAmelCase					,      _lowerCAmelCase			) ** 0.5 * eta * noise

  lowercase					:   str				  =prev_sample + variance

 if not return_dict:
  return (prev_sample,)

 return DDIMSchedulerOutput(prev_sample=_lowerCAmelCase					,      pred_original_sample=_lowerCAmelCase			)


def 							lowercase_				(    self :       Dict					,      __A :       Optional[int]					,      __A :       List[Any]					,      __A :       str					,      __A :       Optional[Any]="epsilon"					,      __A :       Optional[Any]=None					,      __A :       Optional[int] = True					,      )       ->      Union[DDPMSchedulerOutput, Tuple]:



 """simple docstring"""




 lowercase					:   Tuple				  =timestep

 if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
  lowercase					:   List[Any]				  =torch.split(_lowerCAmelCase					,      sample.shape[1]					,      dim=1			)
 else:
  lowercase					:   Any				  =None

 # 1. compute alphas, betas
 lowercase					:   Union[str, Any]				  =self.alphas_cumprod[t]
 lowercase					:   Optional[Any]				  =self.alphas_cumprod[t - 1] if t > 0 else self.one
 lowercase					:   List[Any]				  =1 - alpha_prod_t
 lowercase					:   Any				  =1 - alpha_prod_t_prev

 # 2. compute predicted original sample from predicted noise also called
 # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
 if prediction_type == "epsilon":
  lowercase					:   Any				  =(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
 elif prediction_type == "sample":
  lowercase					:   Optional[Any]				  =model_output
 else:
  raise ValueError(F'Unsupported prediction_type {prediction_type}.'			)

 # 3. Clip "predicted x_0"
 lowercase					:   Any				  =self.bit_scale
 if self.config.clip_sample:
  lowercase					:   int				  =torch.clamp(_lowerCAmelCase					,      -scale					,      _lowerCAmelCase			)

 # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
 # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
 lowercase					:   Any				  =(alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t
 lowercase					:   List[Any]				  =self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t

 # 5. Compute predicted previous sample µ_t
 # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
 lowercase					:   List[str]				  =pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample

 # 6. Add noise
 lowercase					:   Optional[Any]				  =0
 if t > 0:
  lowercase					:   Any				  =torch.randn(
      model_output.size()					,      dtype=model_output.dtype					,      layout=model_output.layout					,      generator=_lowerCAmelCase			).to(model_output.device			)
  lowercase					:   str				  =(self._get_variance(_lowerCAmelCase					,      predicted_variance=_lowerCAmelCase			) ** 0.5) * noise

 lowercase					:   str				  =pred_prev_sample + variance

 if not return_dict:
  return (pred_prev_sample,)

 return DDPMSchedulerOutput(prev_sample=_lowerCAmelCase					,      pred_original_sample=_lowerCAmelCase			)





class UpperCAmelCase_					(    __snake_case				):




      """simple docstring"""




      def __init__( self			:		List[str]     ,      UpperCAmelCase			:		Tuple     ,      UpperCAmelCase			:		Union[str, Any]     ,      UpperCAmelCase			:		Tuple = 1.0     ,      )  ->  Any:


       '''simple docstring'''

       super().__init__()
       lowercase					:   Optional[int]				  =bit_scale
       lowercase					:   int				  =(
           ddim_bit_scheduler_step if isinstance(A_     ,      A_		) else ddpm_bit_scheduler_step
       )

       self.register_modules(unet=A_     ,      scheduler=A_		)






      @torch.no_grad()
      def __call__( self			:		int     ,      UpperCAmelCase			:		Optional[Any] = 256     ,      UpperCAmelCase			:		Any = 256     ,      UpperCAmelCase			:		str = 50     ,      UpperCAmelCase			:		List[Any] = None     ,      UpperCAmelCase			:		Dict = 1     ,      UpperCAmelCase			:		int = "pil"     ,      UpperCAmelCase			:		List[str] = True     ,      **UpperCAmelCase			:		Any     ,      )  ->  Union[str, Any]:


       '''simple docstring'''

       lowercase					:   str				  =torch.randn(
           (batch_size, self.unet.config.in_channels, height, width)     ,      generator=A_     ,      )
       lowercase					:   str				  =decimal_to_bits(A_		) * self.bit_scale
       lowercase					:   List[str]				  =latents.to(self.device		)

       self.scheduler.set_timesteps(A_		)

       for t in self.progress_bar(self.scheduler.timesteps		):
        # predict the noise residual
        lowercase					:   int				  =self.unet(A_     ,      A_		).sample

        # compute the previous noisy sample x_t -> x_t-1
        lowercase					:   Tuple				  =self.scheduler.step(A_     ,      A_     ,      A_		).prev_sample

       lowercase					:   Any				  =bits_to_decimal(A_		)

       if output_type == "pil":
        lowercase					:   Any				  =self.numpy_to_pil(A_		)

       if not return_dict:
        return (image,)

       return ImagePipelineOutput(images=A_		)











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




            """simple docstring"""




            @staticmethod
            def 				A__      ( *UpperCAmelCase			:		Union[str, Any]     ,      **UpperCAmelCase			:		Optional[int]		)  ->  Any:


             '''simple docstring'''

             pass





      def 							lowercase_				(    __A :       Union[str, Any]			)       ->      List[Any]:



       """simple docstring"""




       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.
SCREAMING_SNAKE_CASE						=	(
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)
@is_pipeline_test
@require_torch
@require_vision
class UpperCAmelCase_					(    unittest.TestCase				):




      """simple docstring"""




      UpperCamelCase_								=			MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING






      @require_pytesseract
      @require_vision
      def 				A__      ( self			:		Union[str, Any]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		List[str]		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   Dict				  =pipeline(
           '''document-question-answering'''     ,      model=UpperCAmelCase     ,      tokenizer=UpperCAmelCase     ,      image_processor=UpperCAmelCase		)

       lowercase					:   Optional[Any]				  =INVOICE_URL
       lowercase					:   Any				  =list(zip(*apply_tesseract(load_image(UpperCAmelCase		)     ,      UpperCAmelCase     ,      ''''''		)		)		)
       lowercase					:   Dict				  ='''What is the placebo?'''
       lowercase					:   Optional[Any]				  =[
           {
               '''image''': load_image(UpperCAmelCase		),
               '''question''': question,
           },
           {
               '''image''': image,
               '''question''': question,
           },
           {
               '''image''': image,
               '''question''': question,
               '''word_boxes''': word_boxes,
           },
       ]
       return dqa_pipeline, examples






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		int		)  ->  Optional[int]:


       '''simple docstring'''

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






      @require_torch
      @require_detectrona
      @require_pytesseract
      def 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Dict				  =pipeline('''document-question-answering'''     ,      model='''hf-internal-testing/tiny-random-layoutlmv2'''		)
       lowercase					:   Union[str, Any]				  =INVOICE_URL
       lowercase					:   Tuple				  ='''How many cats are there?'''

       lowercase					:   Optional[int]				  =[
           {'''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},
       ]
       lowercase					:   Optional[Any]				  =dqa_pipeline(image=UpperCAmelCase     ,      question=UpperCAmelCase     ,      top_k=2		)
       self.assertEqual(nested_simplify(UpperCAmelCase     ,      decimals=4		)     ,      UpperCAmelCase		)

       lowercase					:   List[str]				  =dqa_pipeline({'''image''': image, '''question''': question}     ,      top_k=2		)
       self.assertEqual(nested_simplify(UpperCAmelCase     ,      decimals=4		)     ,      UpperCAmelCase		)

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

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






      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Union[str, Any]				  =pipeline(
           '''document-question-answering'''     ,      model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''     ,      revision='''9977165'''     ,      )
       lowercase					:   Dict				  =INVOICE_URL
       lowercase					:   str				  ='''What is the invoice number?'''

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

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

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






      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def 				A__      ( self			:		Dict		)  ->  List[str]:


       '''simple docstring'''

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

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

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

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






      @slow
      @require_torch
      @require_pytesseract
      @require_vision
      def 				A__      ( self			:		str		)  ->  Dict:


       '''simple docstring'''

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

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

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

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

       lowercase					:   Tuple				  =list(zip(*apply_tesseract(load_image(UpperCAmelCase		)     ,      UpperCAmelCase     ,      ''''''		)		)		)

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






      @slow
      @require_torch
      @require_pytesseract
      @require_vision
      def 				A__      ( self			:		Dict		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Dict				  =AutoTokenizer.from_pretrained(
           '''impira/layoutlm-document-qa'''     ,      revision='''3dc6de3'''     ,      add_prefix_space=UpperCAmelCase		)
       lowercase					:   List[Any]				  =pipeline(
           '''document-question-answering'''     ,      model='''impira/layoutlm-document-qa'''     ,      tokenizer=UpperCAmelCase     ,      revision='''3dc6de3'''     ,      max_seq_len=50     ,      )
       lowercase					:   str				  =INVOICE_URL
       lowercase					:   int				  ='''What is the invoice number?'''

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

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

       lowercase					:   List[str]				  =list(zip(*apply_tesseract(load_image(UpperCAmelCase		)     ,      UpperCAmelCase     ,      ''''''		)		)		)

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






      @slow
      @require_torch
      def 				A__      ( self			:		List[Any]		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   str				  =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'''     ,      )

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






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


       '''simple docstring'''

       pass



