
"""simple docstring"""







from abc import ABC, abstractmethod
from typing import List, Optional




class  A__       (	_lowerCamelCase):

		def __init__(      self ):
			# test for the above condition
			self.test()

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Optional[int]									=      0
			__lowerCAmelCase			:						List[Any]									=      False
			while not completed:
				if counter == 1:
					self.reset()
				__lowerCAmelCase			:						str									=      self.advance()
				if not self.does_advance(_SCREAMING_SNAKE_CASE ):
					raise Exception(
					    'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' )

				__lowerCAmelCase			,   __lowerCAmelCase			,   __lowerCAmelCase			:						int									=      self.update(_SCREAMING_SNAKE_CASE )
				counter += 1

				if counter > 1_00_00:
					raise Exception('update() does not fulfill the constraint.' )

			if self.remaining() != 0:
				raise Exception('Custom Constraint is not defined correctly.' )

		@abstractmethod
		def 							__lowerCamelCase							(      self ):
			raise NotImplementedError(
			    f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )

		@abstractmethod
		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			raise NotImplementedError(
			    f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )

		@abstractmethod
		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			raise NotImplementedError(
			    f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )

		@abstractmethod
		def 							__lowerCamelCase							(      self ):
			raise NotImplementedError(
			    f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )

		@abstractmethod
		def 							__lowerCamelCase							(      self ):
			raise NotImplementedError(
			    f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )







		@abstractmethod
		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE=False ):
			raise NotImplementedError(
			    f"{self.__class__} is an abstract class. Only classes inheriting this class can be called." )




class  A__       (	_lowerCamelCase):

		def __init__(      self       ,		_SCREAMING_SNAKE_CASE ):
			super(_SCREAMING_SNAKE_CASE       ,		self ).__init__()

			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ) or len(_SCREAMING_SNAKE_CASE ) == 0:
				raise ValueError(f"`token_ids` has to be a non-empty list, but is {token_ids}." )
			if any((not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ) or token_id < 0) for token_id in token_ids ):
				raise ValueError(f"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}." )

			__lowerCAmelCase			:						List[Any]									=      token_ids

			__lowerCAmelCase			:						List[Any]									=      len(self.token_ids )
			__lowerCAmelCase			:						Optional[Any]									=      -1  # the index of the currently fulfilled step
			__lowerCAmelCase			:						Optional[int]									=      False

		def 							__lowerCamelCase							(      self ):
			if self.completed:
				return None
			return self.token_ids[self.fulfilled_idx + 1]

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(_SCREAMING_SNAKE_CASE )}" )

			if self.completed:
				return False

			return token_id == self.token_ids[self.fulfilled_idx + 1]

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(_SCREAMING_SNAKE_CASE )}" )

			__lowerCAmelCase			:						str									=      False
			__lowerCAmelCase			:						Union[str, Any]									=      False
			__lowerCAmelCase			:						Tuple									=      False

			if self.does_advance(_SCREAMING_SNAKE_CASE ):
				self.fulfilled_idx += 1
				__lowerCAmelCase			:						Tuple									=      True
				if self.fulfilled_idx == (self.seqlen - 1):
					__lowerCAmelCase			:						Dict									=      True
				__lowerCAmelCase			:						Tuple									=      completed
			else:
				# failed to make progress.
				__lowerCAmelCase			:						Any									=      True
				self.reset()
			return stepped, completed, reset

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Union[str, Any]									=      False
			__lowerCAmelCase			:						Tuple									=      0

		def 							__lowerCamelCase							(      self ):
			return self.seqlen - (self.fulfilled_idx + 1)







		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE=False ):
			__lowerCAmelCase			:						Optional[Any]									=      PhrasalConstraint(self.token_ids )

			if stateful:
				__lowerCAmelCase			:						int									=      self.seqlen
				__lowerCAmelCase			:						List[Any]									=      self.fulfilled_idx
				__lowerCAmelCase			:						List[Any]									=      self.completed

			return new_constraint




class  A__       :

		def __init__(      self       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE=True ):
			__lowerCAmelCase			:						str									=      max([len(_SCREAMING_SNAKE_CASE ) for one in nested_token_ids] )

			__lowerCAmelCase			:						str									=      {}
			for token_ids in nested_token_ids:
				__lowerCAmelCase			:						List[Any]									=      root
				for tidx, token_id in enumerate(_SCREAMING_SNAKE_CASE ):
					if token_id not in level:
						__lowerCAmelCase			:						Union[str, Any]									=      {}

					__lowerCAmelCase			:						Dict									=      level[token_id]

			if no_subsets and self.has_subsets(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				raise ValueError(
				    'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
				    f" {nested_token_ids}." )

			__lowerCAmelCase			:						List[str]									=      root

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						Optional[int]									=      self.trie

			for current_token in current_seq:
				__lowerCAmelCase			:						int									=      start[current_token]

			__lowerCAmelCase			:						Any									=      list(start.keys() )

			return next_tokens

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						Tuple									=      self.next_tokens(_SCREAMING_SNAKE_CASE )

			return len(_SCREAMING_SNAKE_CASE ) == 0

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						Optional[Any]									=      list(root.values() )
			if len(_SCREAMING_SNAKE_CASE ) == 0:
				return 1
			else:
				return sum([self.count_leaves(_SCREAMING_SNAKE_CASE ) for nn in next_nodes] )







		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						List[Any]									=      self.count_leaves(_SCREAMING_SNAKE_CASE )
			return len(_SCREAMING_SNAKE_CASE ) != leaf_count




class  A__       (	_lowerCamelCase):

		def __init__(      self       ,		_SCREAMING_SNAKE_CASE ):
			super(_SCREAMING_SNAKE_CASE       ,		self ).__init__()

			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ) or len(_SCREAMING_SNAKE_CASE ) == 0:
				raise ValueError(f"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}." )
			if any(not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ) for token_ids in nested_token_ids ):
				raise ValueError(f"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}." )
			if any(
			    any((not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ) or token_id < 0) for token_id in token_ids )
			    for token_ids in nested_token_ids ):
				raise ValueError(
				    f"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}." )

			__lowerCAmelCase			:						int									=      DisjunctiveTrie(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Union[str, Any]									=      nested_token_ids

			__lowerCAmelCase			:						Any									=      self.trie.max_height
			__lowerCAmelCase			:						Union[str, Any]									=      []
			__lowerCAmelCase			:						Tuple									=      False

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Tuple									=      self.trie.next_tokens(self.current_seq )

			if len(_SCREAMING_SNAKE_CASE ) == 0:
				return None
			else:
				return token_list

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(_SCREAMING_SNAKE_CASE )}" )

			__lowerCAmelCase			:						List[str]									=      self.trie.next_tokens(self.current_seq )

			return token_id in next_tokens

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(_SCREAMING_SNAKE_CASE )}" )

			__lowerCAmelCase			:						Tuple									=      False
			__lowerCAmelCase			:						List[str]									=      False
			__lowerCAmelCase			:						List[str]									=      False

			if self.does_advance(_SCREAMING_SNAKE_CASE ):
				self.current_seq.append(_SCREAMING_SNAKE_CASE )
				__lowerCAmelCase			:						str									=      True
			else:
				__lowerCAmelCase			:						Optional[int]									=      True
				self.reset()

			__lowerCAmelCase			:						Dict									=      self.trie.reached_leaf(self.current_seq )
			__lowerCAmelCase			:						Union[str, Any]									=      completed

			return stepped, completed, reset

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						List[Any]									=      False
			__lowerCAmelCase			:						List[str]									=      []

		def 							__lowerCamelCase							(      self ):
			if self.completed:
				# since this can be completed without reaching max height
				return 0
			else:
				return self.seqlen - len(self.current_seq )







		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE=False ):
			__lowerCAmelCase			:						Any									=      DisjunctiveConstraint(self.token_ids )

			if stateful:
				__lowerCAmelCase			:						Optional[Any]									=      self.seqlen
				__lowerCAmelCase			:						int									=      self.current_seq
				__lowerCAmelCase			:						Union[str, Any]									=      self.completed

			return new_constraint




class  A__       :

		def __init__(      self       ,		_SCREAMING_SNAKE_CASE ):
			__lowerCAmelCase			:						List[str]									=      constraints

			# max # of steps required to fulfill a given constraint
			__lowerCAmelCase			:						Dict									=      max([c.seqlen for c in constraints] )
			__lowerCAmelCase			:						Optional[Any]									=      len(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						int									=      False

			self.init_state()

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Tuple									=      []
			__lowerCAmelCase			:						Tuple									=      None
			__lowerCAmelCase			:						Any									=      [constraint.copy(stateful=_SCREAMING_SNAKE_CASE ) for constraint in self.constraints]

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Any									=      0
			if self.inprogress_constraint:
				# extra points for having a constraint mid-fulfilled
				add += self.max_seqlen - self.inprogress_constraint.remaining()

			return (len(self.complete_constraints ) * self.max_seqlen) + add

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						int									=      []
			if self.inprogress_constraint is None:
				for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
					__lowerCAmelCase			:						Union[str, Any]									=      constraint.advance()
					if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
						token_list.append(_SCREAMING_SNAKE_CASE )
					elif isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
						token_list.extend(_SCREAMING_SNAKE_CASE )
			else:
				__lowerCAmelCase			:						int									=      self.inprogress_constraint.advance()
				if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
					token_list.append(_SCREAMING_SNAKE_CASE )
				elif isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
					token_list.extend(_SCREAMING_SNAKE_CASE )

			if len(_SCREAMING_SNAKE_CASE ) == 0:
				return None
			else:
				return token_list

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			self.init_state()

			if token_ids is not None:
				for token in token_ids:
					# completes or steps **one** constraint
					__lowerCAmelCase			,   __lowerCAmelCase			:						Optional[int]									=      self.add(_SCREAMING_SNAKE_CASE )

					# the entire list of constraints are fulfilled
					if self.completed:
						break

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			if not isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				raise ValueError(f"`token_id` should be an `int`, but is `{token_id}`." )

			__lowerCAmelCase			,   __lowerCAmelCase			:						List[str]									=      False, False

			if self.completed:
				__lowerCAmelCase			:						Dict									=      True
				__lowerCAmelCase			:						Optional[int]									=      False
				return complete, stepped

			if self.inprogress_constraint is not None:
				# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
				# job, simply update the state

				__lowerCAmelCase			,   __lowerCAmelCase			,   __lowerCAmelCase			:						Tuple									=      self.inprogress_constraint.update(_SCREAMING_SNAKE_CASE )
				if reset:
					# 1. If the next token breaks the progress, then we must restart.
					#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

					#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
					#     constraint, not the full list of constraints.

					self.pending_constraints.append(self.inprogress_constraint.copy(stateful=_SCREAMING_SNAKE_CASE ) )
					__lowerCAmelCase			:						List[str]									=      None

				if complete:
					# 2. If the next token completes the constraint, move it to completed list, set
					#     inprogress to None. If there are no pending constraints either, then this full list of constraints
					#     is complete.

					self.complete_constraints.append(self.inprogress_constraint )
					__lowerCAmelCase			:						Dict									=      None

					if len(self.pending_constraints ) == 0:
						# we're done!
						__lowerCAmelCase			:						Optional[int]									=      True

			else:
				# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
				# of constraints?

				for cidx, pending_constraint in enumerate(self.pending_constraints ):
					if pending_constraint.does_advance(_SCREAMING_SNAKE_CASE ):
						__lowerCAmelCase			,   __lowerCAmelCase			,   __lowerCAmelCase			:						Any									=      pending_constraint.update(_SCREAMING_SNAKE_CASE )

						if not stepped:
							raise Exception(
							    '`constraint.update(token_id)` is not yielding incremental progress, '
							    'even though `constraint.does_advance(token_id)` is true.' )

						if complete:
							self.complete_constraints.append(_SCREAMING_SNAKE_CASE )
							__lowerCAmelCase			:						Optional[Any]									=      None

						if not complete and stepped:
							__lowerCAmelCase			:						Any									=      pending_constraint

						if complete or stepped:
							# If we made any progress at all, then it's at least not a "pending constraint".

							__lowerCAmelCase			:						str									=      (
							    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
							)

							if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None:
								# If there's no longer any pending after this and no inprogress either, then we must be
								# complete.

								__lowerCAmelCase			:						Optional[Any]									=      True

							break  # prevent accidentally stepping through multiple constraints with just one token.

			return complete, stepped







		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE=True ):
			__lowerCAmelCase			:						Union[str, Any]									=      ConstraintListState(self.constraints )  # we actually never though self.constraints objects
			# throughout this process. So it's at initialization state.

			if stateful:
				__lowerCAmelCase			:						Tuple									=      [
				    constraint.copy(stateful=_SCREAMING_SNAKE_CASE ) for constraint in self.complete_constraints
				]
				if self.inprogress_constraint is not None:
					__lowerCAmelCase			:						List[Any]									=      self.inprogress_constraint.copy(stateful=_SCREAMING_SNAKE_CASE )
				__lowerCAmelCase			:						List[str]									=      [constraint.copy() for constraint in self.pending_constraints]

			return new_state



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





       """simple docstring"""




       @staticmethod
       def   snake_case		(    *UpperCamelCase			,  **UpperCamelCase     ):







        """simple docstring"""
        pass





     def __snake_case					(      UpperCAmelCase_						:						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.
a_  :				Dict						= (
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)





@is_pipeline_test
@require_torch
@require_vision
class      snake_case    (    unittest.TestCase			):





  """simple docstring"""




  _lowerCamelCase		    =  MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING






  @require_pytesseract
  @require_vision
  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  pipeline(
       "document-question-answering"			,  model=UpperCamelCase			,  tokenizer=UpperCamelCase			,  image_processor=UpperCamelCase     )

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






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  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   snake_case		(    self     ):







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

   lowerCamelCase_      =  [
       {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39},
       {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
   ]
   lowerCamelCase_      =  dqa_pipeline(image=UpperCamelCase			,  question=UpperCamelCase			,  top_k=2     )
   self.assertEqual(nested_simplify(UpperCamelCase			,  decimals=4     )			,  UpperCamelCase     )

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

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






  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def   snake_case		(    self     ):







   """simple docstring"""
   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=UpperCamelCase			,  question=UpperCamelCase			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
       ]			,  )

   lowerCamelCase_      =  dqa_pipeline({"image": image, "question": question}			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.0_009, "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(UpperCamelCase			,  decimals=4     )			,  [
           [
               {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
               {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
           ],
       ]
       * 2			,  )






  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def   snake_case		(    self     ):







   """simple docstring"""
   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=UpperCamelCase			,  question=UpperCamelCase			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
           {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
       ]			,  )

   lowerCamelCase_      =  dqa_pipeline({"image": image, "question": question}			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
           {"score": 0.9_948, "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(UpperCamelCase			,  decimals=4     )			,  [
           [
               {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
               {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
           ]
       ]
       * 2			,  )






  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  AutoTokenizer.from_pretrained(
       "impira/layoutlm-document-qa"			,  revision="3dc6de3"			,  add_prefix_space=UpperCamelCase     )
   lowerCamelCase_      =  pipeline(
       "document-question-answering"			,  model="impira/layoutlm-document-qa"			,  tokenizer=UpperCamelCase			,  revision="3dc6de3"			,  )
   lowerCamelCase_      =  INVOICE_URL
   lowerCamelCase_      =  "What is the invoice number?"

   lowerCamelCase_      =  dqa_pipeline(image=UpperCamelCase			,  question=UpperCamelCase			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
       ]			,  )

   lowerCamelCase_      =  dqa_pipeline({"image": image, "question": question}			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
       ]			,  )

   lowerCamelCase_      =  dqa_pipeline(
       [{"image": image, "question": question}, {"image": image, "question": question}]			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           [
               {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
               {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
           ]
       ]
       * 2			,  )

   lowerCamelCase_      =  list(zip(*apply_tesseract(load_image(UpperCamelCase     )			,  UpperCamelCase			,  ""     )     )     )

   # 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(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
       ]			,  )






  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  AutoTokenizer.from_pretrained(
       "impira/layoutlm-document-qa"			,  revision="3dc6de3"			,  add_prefix_space=UpperCamelCase     )
   lowerCamelCase_      =  pipeline(
       "document-question-answering"			,  model="impira/layoutlm-document-qa"			,  tokenizer=UpperCamelCase			,  revision="3dc6de3"			,  max_seq_len=50			,  )
   lowerCamelCase_      =  INVOICE_URL
   lowerCamelCase_      =  "What is the invoice number?"

   lowerCamelCase_      =  dqa_pipeline(image=UpperCamelCase			,  question=UpperCamelCase			,  top_k=2     )
   self.assertEqual(
       nested_simplify(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.9_998, "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(UpperCamelCase			,  decimals=4     )			,  [
           [
               {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
               {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
           ]
       ]
       * 2			,  )

   lowerCamelCase_      =  list(zip(*apply_tesseract(load_image(UpperCamelCase     )			,  UpperCamelCase			,  ""     )     )     )

   # 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(UpperCamelCase			,  decimals=4     )			,  [
           {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
           {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
       ]			,  )






  @slow
  @require_torch
  def   snake_case		(    self     ):







   """simple docstring"""
   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=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   snake_case		(    self     ):







   """simple docstring"""
   pass



