





import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel





class      lowercase__    :







  def __init__(	self    ,						_lowercase    ,						_lowercase=13    ,						_lowercase=7    ,						_lowercase=True    ,						_lowercase=True    ,						_lowercase=False    ,						_lowercase=True    ,						_lowercase=99    ,						_lowercase=32    ,						_lowercase=5    ,						_lowercase=4    ,						_lowercase=37    ,						_lowercase="gelu"    ,						_lowercase=0.1    ,						_lowercase=0.1    ,						_lowercase=512    ,						_lowercase=16    ,						_lowercase=2    ,						_lowercase=0.02    ,						_lowercase=3    ,						_lowercase=4    ,						_lowercase=None    ,						):
       lowerCAmelCase_					:       Dict    =		parent
       lowerCAmelCase_					:       Optional[int]    =		batch_size
       lowerCAmelCase_					:       Tuple    =		seq_length
       lowerCAmelCase_					:       Any    =		is_training
       lowerCAmelCase_					:       Dict    =		use_input_mask
       lowerCAmelCase_					:       Dict    =		use_token_type_ids
       lowerCAmelCase_					:       str    =		use_labels
       lowerCAmelCase_					:       int    =		vocab_size
       lowerCAmelCase_					:       Dict    =		hidden_size
       lowerCAmelCase_					:       str    =		num_hidden_layers
       lowerCAmelCase_					:       str    =		num_attention_heads
       lowerCAmelCase_					:       str    =		intermediate_size
       lowerCAmelCase_					:       Optional[int]    =		hidden_act
       lowerCAmelCase_					:       List[Any]    =		hidden_dropout_prob
       lowerCAmelCase_					:       Optional[Any]    =		attention_probs_dropout_prob
       lowerCAmelCase_					:       Any    =		max_position_embeddings
       lowerCAmelCase_					:       Dict    =		type_vocab_size
       lowerCAmelCase_					:       List[str]    =		type_sequence_label_size
       lowerCAmelCase_					:       Tuple    =		initializer_range
       lowerCAmelCase_					:       Union[str, Any]    =		num_labels
       lowerCAmelCase_					:       Tuple    =		num_choices
       lowerCAmelCase_					:       str    =		scope







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[Any]    =		ids_tensor([self.batch_size, self.seq_length]    ,						self.vocab_size						)

       lowerCAmelCase_					:       List[Any]    =		None
       if self.use_input_mask:
            lowerCAmelCase_					:       Dict    =		random_attention_mask([self.batch_size, self.seq_length]						)

       lowerCAmelCase_					:       Optional[Any]    =		None
       if self.use_token_type_ids:
            lowerCAmelCase_					:       Any    =		ids_tensor([self.batch_size, self.seq_length]    ,						self.type_vocab_size						)

       lowerCAmelCase_					:       Tuple    =		None
       lowerCAmelCase_					:       Any    =		None
       lowerCAmelCase_					:       Dict    =		None
       if self.use_labels:
            lowerCAmelCase_					:       Any    =		ids_tensor([self.batch_size]    ,						self.type_sequence_label_size						)
            lowerCAmelCase_					:       Union[str, Any]    =		ids_tensor([self.batch_size, self.seq_length]    ,						self.num_labels						)
            lowerCAmelCase_					:       Any    =		ids_tensor([self.batch_size]    ,						self.num_choices						)

       lowerCAmelCase_					:       Optional[int]    =		self.get_config()

       return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







  def 	UpperCAmelCase__		(	self						):
       return OpenLlamaConfig(
           vocab_size=self.vocab_size    ,						hidden_size=self.hidden_size    ,						num_hidden_layers=self.num_hidden_layers    ,						num_attention_heads=self.num_attention_heads    ,						intermediate_size=self.intermediate_size    ,						hidden_act=self.hidden_act    ,						hidden_dropout_prob=self.hidden_dropout_prob    ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,						max_position_embeddings=self.max_position_embeddings    ,						type_vocab_size=self.type_vocab_size    ,						is_decoder=A_    ,						initializer_range=self.initializer_range    ,						use_stable_embedding=A_    ,						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       List[str]    =		OpenLlamaModel(config=A_						)
       model.to(A_						)
       model.eval()
       lowerCAmelCase_					:       Tuple    =		model(A_    ,						attention_mask=A_						)
       lowerCAmelCase_					:       Optional[int]    =		model(A_						)
       self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						):
       lowerCAmelCase_					:       Optional[Any]    =		True
       lowerCAmelCase_					:       Optional[Any]    =		OpenLlamaModel(A_						)
       model.to(A_						)
       model.eval()
       lowerCAmelCase_					:       Dict    =		model(
           A_    ,						attention_mask=A_    ,						encoder_hidden_states=A_    ,						encoder_attention_mask=A_    ,						)
       lowerCAmelCase_					:       Optional[int]    =		model(
           A_    ,						attention_mask=A_    ,						encoder_hidden_states=A_    ,						)
       lowerCAmelCase_					:       str    =		model(A_    ,						attention_mask=A_						)
       self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						):
       lowerCAmelCase_					:       Dict    =		OpenLlamaForCausalLM(config=A_						)
       model.to(A_						)
       model.eval()
       lowerCAmelCase_					:       List[Any]    =		model(A_    ,						attention_mask=A_    ,						labels=A_						)
       self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length, self.vocab_size)						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						_lowercase    ,						):
       lowerCAmelCase_					:       int    =		True
       lowerCAmelCase_					:       Dict    =		True
       lowerCAmelCase_					:       int    =		OpenLlamaForCausalLM(config=A_						)
       model.to(A_						)
       model.eval()

       # first forward pass
       lowerCAmelCase_					:       List[str]    =		model(
           A_    ,						attention_mask=A_    ,						encoder_hidden_states=A_    ,						encoder_attention_mask=A_    ,						use_cache=A_    ,						)
       lowerCAmelCase_					:       Union[str, Any]    =		outputs.past_key_values

       # create hypothetical multiple next token and extent to next_input_ids
       lowerCAmelCase_					:       List[Any]    =		ids_tensor((self.batch_size, 3)    ,						config.vocab_size						)
       lowerCAmelCase_					:       Tuple    =		ids_tensor((self.batch_size, 3)    ,						vocab_size=2						)

       # append to next input_ids and
       lowerCAmelCase_					:       Tuple    =		torch.cat([input_ids, next_tokens]    ,						dim=-1						)
       lowerCAmelCase_					:       List[Any]    =		torch.cat([input_mask, next_mask]    ,						dim=-1						)

       lowerCAmelCase_					:       str    =		model(
           A_    ,						attention_mask=A_    ,						encoder_hidden_states=A_    ,						encoder_attention_mask=A_    ,						output_hidden_states=A_    ,						)["""hidden_states"""][0]
       lowerCAmelCase_					:       Union[str, Any]    =		model(
           A_    ,						attention_mask=A_    ,						encoder_hidden_states=A_    ,						encoder_attention_mask=A_    ,						past_key_values=A_    ,						output_hidden_states=A_    ,						)["""hidden_states"""][0]

       # select random slice
       lowerCAmelCase_					:       Dict    =		ids_tensor((1,)    ,						output_from_past.shape[-1]						).item()
       lowerCAmelCase_					:       Any    =		output_from_no_past[:, -3:, random_slice_idx].detach()
       lowerCAmelCase_					:       List[Any]    =		output_from_past[:, :, random_slice_idx].detach()

       self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]						)

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(A_    ,						A_    ,						atol=1e-3						)						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[Any]    =		self.prepare_config_and_inputs()
       (
           (
           lowerCAmelCase_						
       )   ,  (
           lowerCAmelCase_						
       )   ,  (
           lowerCAmelCase_						
       )   ,  (
           lowerCAmelCase_						
       )   ,  (
           lowerCAmelCase_						
       )   ,  (
           lowerCAmelCase_						
       )   ,  (
           lowerCAmelCase_						
       )   ,  						
       )					:       Any    =		config_and_inputs
       lowerCAmelCase_					:       Dict    =		{"""input_ids""": input_ids, """attention_mask""": input_mask}
       return config, inputs_dict





@require_torch
class      lowercase__    (							_SCREAMING_SNAKE_CASE     ,					_SCREAMING_SNAKE_CASE     ,					_SCREAMING_SNAKE_CASE     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  (
      (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
  )
  __UpperCamelCase	     =  (OpenLlamaForCausalLM,) if is_torch_available() else ()
  __UpperCamelCase	     =  (
      {
          "feature-extraction": OpenLlamaModel,
          "text-classification": OpenLlamaForSequenceClassification,
          "text-generation": OpenLlamaForCausalLM,
          "zero-shot": OpenLlamaForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Dict    =		OpenLlamaModelTester(self						)
       lowerCAmelCase_					:       Tuple    =		ConfigTester(self    ,						config_class=A_    ,						hidden_size=37						)







  def 	UpperCAmelCase__		(	self						):
       self.config_tester.run_common_tests()







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Dict    =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Dict    =		self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
            lowerCAmelCase_					:       Optional[Any]    =		type
            self.model_tester.create_and_check_model(*A_						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_   ,  lowerCAmelCase_					:       Optional[int]    =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_					:       Dict    =		3
       lowerCAmelCase_					:       Optional[Any]    =		input_dict["""input_ids"""]
       lowerCAmelCase_					:       List[str]    =		input_ids.ne(1						).to(A_						)
       lowerCAmelCase_					:       Tuple    =		ids_tensor([self.model_tester.batch_size]    ,						self.model_tester.type_sequence_label_size						)
       lowerCAmelCase_					:       str    =		OpenLlamaForSequenceClassification(A_						)
       model.to(A_						)
       model.eval()
       lowerCAmelCase_					:       Tuple    =		model(A_    ,						attention_mask=A_    ,						labels=A_						)
       self.assertEqual(result.logits.shape    ,						(self.model_tester.batch_size, self.model_tester.num_labels)						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_   ,  lowerCAmelCase_					:       Any    =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_					:       Tuple    =		3
       lowerCAmelCase_					:       int    =		"""single_label_classification"""
       lowerCAmelCase_					:       List[Any]    =		input_dict["""input_ids"""]
       lowerCAmelCase_					:       int    =		input_ids.ne(1						).to(A_						)
       lowerCAmelCase_					:       Optional[int]    =		ids_tensor([self.model_tester.batch_size]    ,						self.model_tester.type_sequence_label_size						)
       lowerCAmelCase_					:       int    =		OpenLlamaForSequenceClassification(A_						)
       model.to(A_						)
       model.eval()
       lowerCAmelCase_					:       Optional[Any]    =		model(A_    ,						attention_mask=A_    ,						labels=A_						)
       self.assertEqual(result.logits.shape    ,						(self.model_tester.batch_size, self.model_tester.num_labels)						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_   ,  lowerCAmelCase_					:       Any    =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_					:       str    =		3
       lowerCAmelCase_					:       int    =		"""multi_label_classification"""
       lowerCAmelCase_					:       Union[str, Any]    =		input_dict["""input_ids"""]
       lowerCAmelCase_					:       Dict    =		input_ids.ne(1						).to(A_						)
       lowerCAmelCase_					:       int    =		ids_tensor(
           [self.model_tester.batch_size, config.num_labels]    ,						self.model_tester.type_sequence_label_size						).to(torch.float						)
       lowerCAmelCase_					:       Any    =		OpenLlamaForSequenceClassification(A_						)
       model.to(A_						)
       model.eval()
       lowerCAmelCase_					:       Optional[Any]    =		model(A_    ,						attention_mask=A_    ,						labels=A_						)
       self.assertEqual(result.logits.shape    ,						(self.model_tester.batch_size, self.model_tester.num_labels)						)







  @unittest.skip("""Open-Llama buffers include complex numbers, which breaks this test"""						)
  def 	UpperCAmelCase__		(	self						):
       pass







  @parameterized.expand([("""linear""",), ("""dynamic""",)]						)
  def 	UpperCAmelCase__		(	self    ,						_lowercase						):
       lowerCAmelCase_   ,  lowerCAmelCase_					:       Union[str, Any]    =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_					:       str    =		ids_tensor([1, 10]    ,						config.vocab_size						)
       lowerCAmelCase_					:       Any    =		ids_tensor([1, int(config.max_position_embeddings * 1.5						)]    ,						config.vocab_size						)

       set_seed(42						)  # Fixed seed at init time so the two models get the same random weights
       lowerCAmelCase_					:       Optional[int]    =		OpenLlamaModel(A_						)
       original_model.to(A_						)
       original_model.eval()
       lowerCAmelCase_					:       Union[str, Any]    =		original_model(A_						).last_hidden_state
       lowerCAmelCase_					:       Tuple    =		original_model(A_						).last_hidden_state

       set_seed(42						)  # Fixed seed at init time so the two models get the same random weights
       lowerCAmelCase_					:       Optional[int]    =		{"""type""": scaling_type, """factor""": 10.0}
       lowerCAmelCase_					:       Union[str, Any]    =		OpenLlamaModel(A_						)
       scaled_model.to(A_						)
       scaled_model.eval()
       lowerCAmelCase_					:       Union[str, Any]    =		scaled_model(A_						).last_hidden_state
       lowerCAmelCase_					:       Tuple    =		scaled_model(A_						).last_hidden_state

       # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
       # maximum sequence length, so the outputs for the short input should match.
       if scaling_type == "dynamic":
            self.assertTrue(torch.allclose(A_    ,						A_    ,						atol=1e-5						)						)
       else:
            self.assertFalse(torch.allclose(A_    ,						A_    ,						atol=1e-5						)						)

       # The output should be different for long inputs
       self.assertFalse(torch.allclose(A_    ,						A_    ,						atol=1e-5						)						)












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







        @staticmethod
        def 	UpperCAmelCase__		(	*_lowercase    ,						**_lowercase						):
             pass






      def 							_lowerCAmelCase (  _a   :					List[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.
UpperCAmelCase_					:   Optional[Any] 							=						(
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)





@is_pipeline_test
@require_torch
@require_vision
class      lowercase__    (							unittest.TestCase  ):
  __UpperCamelCase	     =  MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING







  @require_pytesseract
  @require_vision
  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Optional[int]    =		pipeline(
           """document-question-answering"""    ,						model=_lowercase    ,						tokenizer=_lowercase    ,						image_processor=_lowercase						)

       lowerCAmelCase_					:       List[str]    =		INVOICE_URL
       lowerCAmelCase_					:       str    =		list(zip(*apply_tesseract(load_image(_lowercase						)    ,						_lowercase    ,						""""""						)						)						)
       lowerCAmelCase_					:       int    =		"""What is the placebo?"""
       lowerCAmelCase_					:       str    =		[
           {
               """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    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       List[str]    =		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						):
       lowerCAmelCase_					:       Tuple    =		pipeline("""document-question-answering"""    ,						model="""hf-internal-testing/tiny-random-layoutlmv2"""						)
       lowerCAmelCase_					:       str    =		INVOICE_URL
       lowerCAmelCase_					:       int    =		"""How many cats are there?"""

       lowerCAmelCase_					:       List[Any]    =		[
           {"""score""": 0.0001, """answer""": """oy 2312/2019""", """start""": 38, """end""": 39},
           {"""score""": 0.0001, """answer""": """oy 2312/2019 DUE""", """start""": 38, """end""": 40},
       ]
       lowerCAmelCase_					:       Optional[Any]    =		dqa_pipeline(image=_lowercase    ,						question=_lowercase    ,						top_k=2						)
       self.assertEqual(nested_simplify(_lowercase    ,						decimals=4						)    ,						_lowercase						)

       lowerCAmelCase_					:       Any    =		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
       lowerCAmelCase_					:       List[Any]    =		"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
       lowerCAmelCase_					:       Any    =		dqa_pipeline(image=_lowercase    ,						question=_lowercase    ,						top_k=2						)
       self.assertEqual(_lowercase    ,						[]						)

       # We can optionnally pass directly the words and bounding boxes
       lowerCAmelCase_					:       int    =		"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
       lowerCAmelCase_					:       int    =		[]
       lowerCAmelCase_					:       List[Any]    =		[]
       lowerCAmelCase_					:       List[Any]    =		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						):
       lowerCAmelCase_					:       Optional[Any]    =		pipeline(
           """document-question-answering"""    ,						model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""    ,						revision="""9977165"""    ,						)
       lowerCAmelCase_					:       Dict    =		INVOICE_URL
       lowerCAmelCase_					:       int    =		"""What is the invoice number?"""

       lowerCAmelCase_					:       Union[str, Any]    =		dqa_pipeline(image=_lowercase    ,						question=_lowercase    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.9944, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.0009, """answer""": """us-001""", """start""": 16, """end""": 16},
           ]    ,						)

       lowerCAmelCase_					:       List[Any]    =		dqa_pipeline({"""image""": image, """question""": question}    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.9944, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.0009, """answer""": """us-001""", """start""": 16, """end""": 16},
           ]    ,						)

       lowerCAmelCase_					:       List[str]    =		dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               [
                   {"""score""": 0.9944, """answer""": """us-001""", """start""": 16, """end""": 16},
                   {"""score""": 0.0009, """answer""": """us-001""", """start""": 16, """end""": 16},
               ],
           ]
           * 2    ,						)







  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[int]    =		pipeline(
           """document-question-answering"""    ,						model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""    ,						revision="""9977165"""    ,						max_seq_len=50    ,						)
       lowerCAmelCase_					:       List[str]    =		INVOICE_URL
       lowerCAmelCase_					:       Optional[int]    =		"""What is the invoice number?"""

       lowerCAmelCase_					:       List[Any]    =		dqa_pipeline(image=_lowercase    ,						question=_lowercase    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.9974, """answer""": """1110212019""", """start""": 23, """end""": 23},
               {"""score""": 0.9948, """answer""": """us-001""", """start""": 16, """end""": 16},
           ]    ,						)

       lowerCAmelCase_					:       Optional[Any]    =		dqa_pipeline({"""image""": image, """question""": question}    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.9974, """answer""": """1110212019""", """start""": 23, """end""": 23},
               {"""score""": 0.9948, """answer""": """us-001""", """start""": 16, """end""": 16},
           ]    ,						)

       lowerCAmelCase_					:       List[Any]    =		dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               [
                   {"""score""": 0.9974, """answer""": """1110212019""", """start""": 23, """end""": 23},
                   {"""score""": 0.9948, """answer""": """us-001""", """start""": 16, """end""": 16},
               ]
           ]
           * 2    ,						)







  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       int    =		AutoTokenizer.from_pretrained(
           """impira/layoutlm-document-qa"""    ,						revision="""3dc6de3"""    ,						add_prefix_space=_lowercase						)
       lowerCAmelCase_					:       Any    =		pipeline(
           """document-question-answering"""    ,						model="""impira/layoutlm-document-qa"""    ,						tokenizer=_lowercase    ,						revision="""3dc6de3"""    ,						)
       lowerCAmelCase_					:       int    =		INVOICE_URL
       lowerCAmelCase_					:       Union[str, Any]    =		"""What is the invoice number?"""

       lowerCAmelCase_					:       Optional[Any]    =		dqa_pipeline(image=_lowercase    ,						question=_lowercase    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
           ]    ,						)

       lowerCAmelCase_					:       int    =		dqa_pipeline({"""image""": image, """question""": question}    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
           ]    ,						)

       lowerCAmelCase_					:       Union[str, Any]    =		dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               [
                   {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
                   {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
               ]
           ]
           * 2    ,						)

       lowerCAmelCase_					:       int    =		list(zip(*apply_tesseract(load_image(_lowercase						)    ,						_lowercase    ,						""""""						)						)						)

       # This model should also work if `image` is set to None
       lowerCAmelCase_					:       List[Any]    =		dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.4251, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.0819, """answer""": """1110212019""", """start""": 23, """end""": 23},
           ]    ,						)







  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       int    =		AutoTokenizer.from_pretrained(
           """impira/layoutlm-document-qa"""    ,						revision="""3dc6de3"""    ,						add_prefix_space=_lowercase						)
       lowerCAmelCase_					:       Optional[Any]    =		pipeline(
           """document-question-answering"""    ,						model="""impira/layoutlm-document-qa"""    ,						tokenizer=_lowercase    ,						revision="""3dc6de3"""    ,						max_seq_len=50    ,						)
       lowerCAmelCase_					:       Tuple    =		INVOICE_URL
       lowerCAmelCase_					:       Tuple    =		"""What is the invoice number?"""

       lowerCAmelCase_					:       Optional[int]    =		dqa_pipeline(image=_lowercase    ,						question=_lowercase    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.9999, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.9998, """answer""": """us-001""", """start""": 16, """end""": 16},
           ]    ,						)

       lowerCAmelCase_					:       int    =		dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               [
                   {"""score""": 0.9999, """answer""": """us-001""", """start""": 16, """end""": 16},
                   {"""score""": 0.9998, """answer""": """us-001""", """start""": 16, """end""": 16},
               ]
           ]
           * 2    ,						)

       lowerCAmelCase_					:       Union[str, Any]    =		list(zip(*apply_tesseract(load_image(_lowercase						)    ,						_lowercase    ,						""""""						)						)						)

       # This model should also work if `image` is set to None
       lowerCAmelCase_					:       List[str]    =		dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}    ,						top_k=2						)
       self.assertEqual(
           nested_simplify(_lowercase    ,						decimals=4						)    ,						[
               {"""score""": 0.9999, """answer""": """us-001""", """start""": 16, """end""": 16},
               {"""score""": 0.9998, """answer""": """us-001""", """start""": 16, """end""": 16},
           ]    ,						)







  @slow
  @require_torch
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       int    =		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_					:       Union[str, Any]    =		INVOICE_URL
       lowerCAmelCase_					:       int    =		"""What is the invoice number?"""
       lowerCAmelCase_					:       str    =		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						):
       pass
