






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  _lowerCamelCase						(						__lowerCamelCase       ) ->			Tuple:

           '''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__		:							Tuple 				=				(
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)







@is_pipeline_test
@require_torch
@require_vision
class 				UpperCAmelCase_  (		unittest.TestCase		):
     __lowerCamelCase      				=  MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING




     @require_pytesseract
     @require_vision
     def   __UpperCAmelCase  (				self	,						_lowerCAmelCase	,						_lowerCAmelCase	,						_lowerCAmelCase		):
          UpperCAmelCase__      :  Optional[Any]				      =			pipeline(
              """document-question-answering"""	,						model=_lowerCAmelCase	,						tokenizer=_lowerCAmelCase	,						image_processor=_lowerCAmelCase		)

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

          UpperCAmelCase__      :  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},
          ]
          UpperCAmelCase__      :  List[Any]				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						_lowerCAmelCase		)

          UpperCAmelCase__      :  Optional[Any]				      =			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
          UpperCAmelCase__      :  Union[str, Any]				      =			"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
          UpperCAmelCase__      :  Tuple				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(_lowerCAmelCase	,						[]		)

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

          UpperCAmelCase__      :  str				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

          UpperCAmelCase__      :  Union[str, Any]				      =			dqa_pipeline({"""image""": image, """question""": question}	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

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




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

          UpperCAmelCase__      :  Union[str, Any]				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

          UpperCAmelCase__      :  Dict				      =			dqa_pipeline({"""image""": image, """question""": question}	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

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




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

          UpperCAmelCase__      :  Dict				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

          UpperCAmelCase__      :  Any				      =			dqa_pipeline({"""image""": image, """question""": question}	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

          UpperCAmelCase__      :  Optional[Any]				      =			dqa_pipeline(
              [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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	,						)

          UpperCAmelCase__      :  Dict				      =			list(zip(*apply_tesseract(load_image(_lowerCAmelCase		)	,						_lowerCAmelCase	,						""""""		)		)		)

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




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

          UpperCAmelCase__      :  int				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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},
              ]	,						)

          UpperCAmelCase__      :  Any				      =			dqa_pipeline(
              [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]	,						top_k=2		)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						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	,						)

          UpperCAmelCase__      :  List[Any]				      =			list(zip(*apply_tesseract(load_image(_lowerCAmelCase		)	,						_lowerCAmelCase	,						""""""		)		)		)

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




     @slow
     @require_torch
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[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"""	,						)

          UpperCAmelCase__      :  List[Any]				      =			INVOICE_URL
          UpperCAmelCase__      :  Optional[int]				      =			"""What is the invoice number?"""
          UpperCAmelCase__      :  List[str]				      =			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












import argparse
import json
import os

from tensorflow.core.protobuf.saved_model_pba import SavedModel


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
__UpperCamelCase   :			Tuple          = "."

# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model)
__UpperCamelCase   :			List[str]          = [
    "Assert",
    "AssignVariableOp",
    "EmptyTensorList",
    "MergeV2Checkpoints",
    "ReadVariableOp",
    "ResourceGather",
    "RestoreV2",
    "SaveV2",
    "ShardedFilename",
    "StatefulPartitionedCall",
    "StaticRegexFullMatch",
    "VarHandleOp",
]





def 						__A						(      __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase       ) ->			Union[str, Any]:
	a									=				SavedModel()
	a									=				[]

	with open(os.path.join(__lowerCamelCase				,     """utils"""				,     """tf_ops"""				,     """onnx.json"""       )       ) as f:
		a									=				json.load(__lowerCamelCase       )["""opsets"""]

	for i in range(1				,     opset + 1       ):
		onnx_ops.extend(onnx_opsets[str(__lowerCamelCase       )]       )

	with open(__lowerCamelCase				,     """rb"""       ) as f:
		saved_model.ParseFromString(f.read()       )

	a									=				set()

	# Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs)
	for meta_graph in saved_model.meta_graphs:
		# Add operations in the graph definition
		model_op_names.update(node.op for node in meta_graph.graph_def.node       )

		# Go through the functions in the graph definition
		for func in meta_graph.graph_def.library.function:
			# Add operations in each function
			model_op_names.update(node.op for node in func.node_def       )

    # Convert to list, sorted if you want
	a									=				sorted(__lowerCamelCase       )
	a									=				[]

	for op in model_op_names:
		if op not in onnx_ops and op not in INTERNAL_OPS:
			incompatible_ops.append(__lowerCamelCase       )

	if strict and len(__lowerCamelCase       ) > 0:
		raise Exception(f'Found the following incompatible ops for the opset {opset}:\n' + incompatible_ops       )
	elif len(__lowerCamelCase       ) > 0:
		print(f'Found the following incompatible ops for the opset {opset}:'       )
		print(*__lowerCamelCase				,     sep="""\n"""       )
	else:
		print(f'The saved model {saved_model_path} can properly be converted with ONNX.'       )


if __name__ == "__main__":
		__UpperCamelCase   :			Optional[Any]          = argparse.ArgumentParser()
		parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).")
		parser.add_argument(
		    "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested."
		)
		parser.add_argument(
		    "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model."
		)
		parser.add_argument(
		    "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)"
		)
		__UpperCamelCase   :			str          = parser.parse_args()

		if args.framework == "onnx":
				onnx_compliancy(args.saved_model_path, args.strict, args.opset)

