



"""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    SCREAMING_SNAKE_CASE__						:

       @staticmethod
       def 			SCREAMING_SNAKE_CASE  (     *_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)						->   Tuple:





        '''simple docstring'''




        pass

    def    _snake_case		(		UpperCamelCase		:	List[str]		):
     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    SCREAMING_SNAKE_CASE__						(      unittest.TestCase				):
   __lowerCAmelCase						:     Dict		=		MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING

   @require_pytesseract
   @require_vision
   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   List[str]:





    '''simple docstring'''




    UpperCAmelCase			:      Dict			=			pipeline(
        """document-question-answering"""   ,  model=UpperCamelCase__   ,  tokenizer=UpperCamelCase__   ,  image_processor=UpperCamelCase__		)

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

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			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 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




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

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

    UpperCAmelCase			:      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
    UpperCAmelCase			:      int			=			'''./tests/fixtures/tests_samples/COCO/000000039769.png'''
    UpperCAmelCase			:      Dict			=			dqa_pipeline(image=UpperCamelCase__   ,  question=UpperCamelCase__   ,  top_k=2		)
    self.assertEqual(UpperCamelCase__   ,  []		)

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

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





    '''simple docstring'''




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

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

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

    UpperCAmelCase			:      List[str]			=			dqa_pipeline(
        [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]   ,  top_k=2		)
    self.assertEqual(
        nested_simplify(UpperCamelCase__   ,  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 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




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

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

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

    UpperCAmelCase			:      Optional[int]			=			dqa_pipeline(
        [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]   ,  top_k=2		)
    self.assertEqual(
        nested_simplify(UpperCamelCase__   ,  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 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''simple docstring'''




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

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

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

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

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

    # This model should also work if `image` is set to None
    UpperCAmelCase			:      Tuple			=			dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}   ,  top_k=2		)
    self.assertEqual(
        nested_simplify(UpperCamelCase__   ,  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 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




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

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

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

    UpperCAmelCase			:      int			=			list(zip(*apply_tesseract(load_image(UpperCamelCase__		)   ,  UpperCamelCase__   ,  """"""		)		)		)

    # This model should also work if `image` is set to None
    UpperCAmelCase			:      int			=			dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}   ,  top_k=2		)
    self.assertEqual(
        nested_simplify(UpperCamelCase__   ,  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 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Any			=			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			:      Dict			=			INVOICE_URL
    UpperCAmelCase			:      Optional[Any]			=			'''What is the invoice number?'''
    UpperCAmelCase			:      Optional[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 			SCREAMING_SNAKE_CASE  (     self		)						->   List[str]:





    '''simple docstring'''




    pass





"""simple docstring"""
from __future__ import annotations

from decimal import Decimal

from numpy import array

def    _snake_case		(		UpperCamelCase		:	list[list[float]]		):
 UpperCAmelCase			:      str			=			Decimal

 # Check if the provided matrix has 2 rows and 2 columns
 # since this implementation only works for 2x2 matrices
 if len(UpperCamelCase		) == 2 and len(matrix[0]		) == 2 and len(matrix[1]		) == 2:
  # Calculate the determinant of the matrix
  UpperCAmelCase			:      Optional[int]			=			float(
      d(matrix[0][0]		) * d(matrix[1][1]		) - d(matrix[1][0]		) * d(matrix[0][1]		)		)
  if determinant == 0:
   raise ValueError("""This matrix has no inverse."""		)

  # Creates a copy of the matrix with swapped positions of the elements
  UpperCAmelCase			:      Optional[Any]			=			[[0.0, 0.0], [0.0, 0.0]]
  UpperCAmelCase			,	UpperCAmelCase			:      Any			=			matrix[1][1], matrix[0][0]
  UpperCAmelCase			,	UpperCAmelCase			:      Union[str, Any]			=			-matrix[1][0], -matrix[0][1]

  # Calculate the inverse of the matrix
  return [
      [(float(d(UpperCamelCase		)		) / determinant) or 0.0 for n in row] for row in swapped_matrix
  ]
 elif (
     len(UpperCamelCase		) == 3
     and len(matrix[0]		) == 3
     and len(matrix[1]		) == 3
     and len(matrix[2]		) == 3
 ):
  # Calculate the determinant of the matrix using Sarrus rule
  UpperCAmelCase			:      str			=			float(
      (
          (d(matrix[0][0]		) * d(matrix[1][1]		) * d(matrix[2][2]		))
          + (d(matrix[0][1]		) * d(matrix[1][2]		) * d(matrix[2][0]		))
          + (d(matrix[0][2]		) * d(matrix[1][0]		) * d(matrix[2][1]		))
      )
      - (
          (d(matrix[0][2]		) * d(matrix[1][1]		) * d(matrix[2][0]		))
          + (d(matrix[0][1]		) * d(matrix[1][0]		) * d(matrix[2][2]		))
          + (d(matrix[0][0]		) * d(matrix[1][2]		) * d(matrix[2][1]		))
      )		)
  if determinant == 0:
   raise ValueError("""This matrix has no inverse."""		)

  # Creating cofactor matrix
  UpperCAmelCase			:      Optional[int]			=			[
      [d(0.0		), d(0.0		), d(0.0		)],
      [d(0.0		), d(0.0		), d(0.0		)],
      [d(0.0		), d(0.0		), d(0.0		)],
  ]
  UpperCAmelCase			:      str			=			(d(matrix[1][1]		) * d(matrix[2][2]		)) - (
      d(matrix[1][2]		) * d(matrix[2][1]		)
  )
  UpperCAmelCase			:      List[str]			=			-(
      (d(matrix[1][0]		) * d(matrix[2][2]		)) - (d(matrix[1][2]		) * d(matrix[2][0]		))
  )
  UpperCAmelCase			:      Optional[int]			=			(d(matrix[1][0]		) * d(matrix[2][1]		)) - (
      d(matrix[1][1]		) * d(matrix[2][0]		)
  )
  UpperCAmelCase			:      Optional[int]			=			-(
      (d(matrix[0][1]		) * d(matrix[2][2]		)) - (d(matrix[0][2]		) * d(matrix[2][1]		))
  )
  UpperCAmelCase			:      str			=			(d(matrix[0][0]		) * d(matrix[2][2]		)) - (
      d(matrix[0][2]		) * d(matrix[2][0]		)
  )
  UpperCAmelCase			:      Union[str, Any]			=			-(
      (d(matrix[0][0]		) * d(matrix[2][1]		)) - (d(matrix[0][1]		) * d(matrix[2][0]		))
  )
  UpperCAmelCase			:      Dict			=			(d(matrix[0][1]		) * d(matrix[1][2]		)) - (
      d(matrix[0][2]		) * d(matrix[1][1]		)
  )
  UpperCAmelCase			:      Optional[Any]			=			-(
      (d(matrix[0][0]		) * d(matrix[1][2]		)) - (d(matrix[0][2]		) * d(matrix[1][0]		))
  )
  UpperCAmelCase			:      str			=			(d(matrix[0][0]		) * d(matrix[1][1]		)) - (
      d(matrix[0][1]		) * d(matrix[1][0]		)
  )

  # Transpose the cofactor matrix (Adjoint matrix)
  UpperCAmelCase			:      str			=			array(UpperCamelCase		)
  for i in range(3		):
   for j in range(3		):
    UpperCAmelCase			:      Any			=			cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
  UpperCAmelCase			:      Tuple			=			array(UpperCamelCase		)
  for i in range(3		):
   for j in range(3		):
    inverse_matrix[i][j] /= d(UpperCamelCase		)

        # Calculate the inverse of the matrix
  return [[float(d(UpperCamelCase		)		) or 0.0 for n in row] for row in inverse_matrix]
 raise ValueError("""Please provide a matrix of size 2x2 or 3x3."""		)
