


"""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  lowerCamelCase__    :
             @staticmethod
             def SCREAMING_SNAKE_CASE_						(		*A_						:						int   ,							**A_						:						Optional[int]				):






              '''simple docstring'''


              pass






       def lowerCAmelCase_   (					UpperCamelCase__						:			Optional[Any]			):






        """simple docstring"""







        return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
UpperCAmelCase__					=(
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)





@is_pipeline_test
@require_torch
@require_vision
class  lowerCamelCase__    (		unittest.TestCase     ):
      a			:  Optional[int]           =		MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
      @require_pytesseract
      @require_vision
      def SCREAMING_SNAKE_CASE_						(		self						:						Any   ,							A_						:						Union[str, Any]   ,							A_						:						Optional[Any]   ,							A_						:						Union[str, Any]				):






       '''simple docstring'''


       __lowercase						=						pipeline(
           """document-question-answering"""   ,							model=A_   ,							tokenizer=A_   ,							image_processor=A_				)

       __lowercase						=						INVOICE_URL
       __lowercase						=						list(zip(*apply_tesseract(load_image(A_				)   ,							A_   ,							""""""				)				)				)
       __lowercase						=						"""What is the placebo?"""
       __lowercase						=						[
           {
               """image""": load_image(A_				),
               """question""": question,
           },
           {
               """image""": image,
               """question""": question,
           },
           {
               """image""": image,
               """question""": question,
               """word_boxes""": word_boxes,
           },
       ]
       return dqa_pipeline, examples
      def SCREAMING_SNAKE_CASE_						(		self						:						Any   ,							A_						:						Tuple   ,							A_						:						List[Any]				):






       '''simple docstring'''


       __lowercase						=						dqa_pipeline(A_   ,							top_k=2				)
       self.assertEqual(
           A_   ,							[
               [
                   {"""score""": ANY(A_				), """answer""": ANY(A_				), """start""": ANY(A_				), """end""": ANY(A_				)},
                   {"""score""": ANY(A_				), """answer""": ANY(A_				), """start""": ANY(A_				), """end""": ANY(A_				)},
               ]
           ]
           * 3   ,							)
      @require_torch
      @require_detectrona
      @require_pytesseract
      def SCREAMING_SNAKE_CASE_						(		self						:						int				):






       '''simple docstring'''


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

       __lowercase						=						[
           {"""score""": 0.00_01, """answer""": """oy 2312/2019""", """start""": 3_8, """end""": 3_9},
           {"""score""": 0.00_01, """answer""": """oy 2312/2019 DUE""", """start""": 3_8, """end""": 4_0},
       ]
       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							top_k=2				)
       self.assertEqual(nested_simplify(A_   ,							decimals=4				)   ,							A_				)

       __lowercase						=						dqa_pipeline({"""image""": image, """question""": question}   ,							top_k=2				)
       self.assertEqual(nested_simplify(A_   ,							decimals=4				)   ,							A_				)

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

       # We can optionnally pass directly the words and bounding boxes
       __lowercase						=						"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
       __lowercase						=						[]
       __lowercase						=						[]
       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							words=A_   ,							boxes=A_   ,							top_k=2				)
       self.assertEqual(A_   ,							[]				)
      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict				):






       '''simple docstring'''


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

       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.99_44, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.00_09, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
           ]   ,							)

       __lowercase						=						dqa_pipeline({"""image""": image, """question""": question}   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.99_44, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.00_09, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
           ]   ,							)

       __lowercase						=						dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               [
                   {"""score""": 0.99_44, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
                   {"""score""": 0.00_09, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               ],
           ]
           * 2   ,							)
      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def SCREAMING_SNAKE_CASE_						(		self						:						str				):






       '''simple docstring'''


       __lowercase						=						pipeline(
           """document-question-answering"""   ,							model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""   ,							revision="""9977165"""   ,							max_seq_len=5_0   ,							)
       __lowercase						=						INVOICE_URL
       __lowercase						=						"""What is the invoice number?"""

       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.99_74, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
               {"""score""": 0.99_48, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
           ]   ,							)

       __lowercase						=						dqa_pipeline({"""image""": image, """question""": question}   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.99_74, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
               {"""score""": 0.99_48, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
           ]   ,							)

       __lowercase						=						dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               [
                   {"""score""": 0.99_74, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
                   {"""score""": 0.99_48, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               ]
           ]
           * 2   ,							)
      @slow
      @require_torch
      @require_pytesseract
      @require_vision
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]				):






       '''simple docstring'''


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

       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.42_51, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
           ]   ,							)

       __lowercase						=						dqa_pipeline({"""image""": image, """question""": question}   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.42_51, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
           ]   ,							)

       __lowercase						=						dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               [
                   {"""score""": 0.42_51, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
                   {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
               ]
           ]
           * 2   ,							)

       __lowercase						=						list(zip(*apply_tesseract(load_image(A_				)   ,							A_   ,							""""""				)				)				)

       # This model should also work if `image` is set to None
       __lowercase						=						dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.42_51, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
           ]   ,							)
      @slow
      @require_torch
      @require_pytesseract
      @require_vision
      def SCREAMING_SNAKE_CASE_						(		self						:						int				):






       '''simple docstring'''


       __lowercase						=						AutoTokenizer.from_pretrained(
           """impira/layoutlm-document-qa"""   ,							revision="""3dc6de3"""   ,							add_prefix_space=A_				)
       __lowercase						=						pipeline(
           """document-question-answering"""   ,							model="""impira/layoutlm-document-qa"""   ,							tokenizer=A_   ,							revision="""3dc6de3"""   ,							max_seq_len=5_0   ,							)
       __lowercase						=						INVOICE_URL
       __lowercase						=						"""What is the invoice number?"""

       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.99_99, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.99_98, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
           ]   ,							)

       __lowercase						=						dqa_pipeline(
           [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               [
                   {"""score""": 0.99_99, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
                   {"""score""": 0.99_98, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               ]
           ]
           * 2   ,							)

       __lowercase						=						list(zip(*apply_tesseract(load_image(A_				)   ,							A_   ,							""""""				)				)				)

       # This model should also work if `image` is set to None
       __lowercase						=						dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}   ,							top_k=2				)
       self.assertEqual(
           nested_simplify(A_   ,							decimals=4				)   ,							[
               {"""score""": 0.99_99, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
               {"""score""": 0.99_98, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
           ]   ,							)
      @slow
      @require_torch
      def SCREAMING_SNAKE_CASE_						(		self						:						int				):






       '''simple docstring'''


       __lowercase						=						pipeline(
           """document-question-answering"""   ,							model="""naver-clova-ix/donut-base-finetuned-docvqa"""   ,							tokenizer=AutoTokenizer.from_pretrained("""naver-clova-ix/donut-base-finetuned-docvqa"""				)   ,							feature_extractor="""naver-clova-ix/donut-base-finetuned-docvqa"""   ,							)

       __lowercase						=						INVOICE_URL
       __lowercase						=						"""What is the invoice number?"""
       __lowercase						=						dqa_pipeline(image=A_   ,							question=A_   ,							top_k=2				)
       self.assertEqual(nested_simplify(A_   ,							decimals=4				)   ,							[{"""answer""": """us-001"""}]				)






      @require_tf
      @unittest.skip("""Document question answering not implemented in TF"""				)
      def SCREAMING_SNAKE_CASE_						(		self						:						int				):






       '''simple docstring'''


       pass




"""simple docstring"""

def lowerCAmelCase_   (					UpperCamelCase__						:			list					, UpperCamelCase__						:			int					, UpperCamelCase__						:			int = 0					, UpperCamelCase__						:			int = 0			):






 """simple docstring"""







 __lowercase						=						right or len(UpperCamelCase__			) - 1
 if left > right:
  return -1
 elif list_data[left] == key:
  return left
 elif list_data[right] == key:
  return right
 else:
  return search(UpperCamelCase__					, UpperCamelCase__					, left + 1					, right - 1			)


if __name__ == "__main__":
       import doctest

       doctest.testmod()
