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

							@staticmethod
							def    lowercase__      (	*__UpperCamelCase					:     Any   ,					**__UpperCamelCase					:     List[str]   ):
														pass



		def      __lowerCAmelCase						(							UpperCAmelCase__				:      int       )  ->    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.
lowercase        =  (
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)





@is_pipeline_test
@require_torch
@require_vision
class       __A(				unittest.TestCase       ):
					SCREAMING_SNAKE_CASE			    =    MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING

					@require_pytesseract
					@require_vision
					def    lowercase__      (	self					:     Optional[int]   ,					__UpperCamelCase					:     List[str]   ,					__UpperCamelCase					:     str   ,					__UpperCamelCase					:     List[str]   ):
												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    lowercase__      (	self					:     Union[str, Any]   ,					__UpperCamelCase					:     Any   ,					__UpperCamelCase					:     Any   ):
												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    lowercase__      (	self					:     int   ):
												lowerCamelCase_							  =					pipeline("""document-question-answering"""   ,					model="""hf-internal-testing/tiny-random-layoutlmv2"""   )
												lowerCamelCase_							  =					INVOICE_URL
												lowerCamelCase_							  =					"""How many cats are there?"""

												lowerCamelCase_							  =					[
												    {"""score""": 0.0001, """answer""": """oy 2312/2019""", """start""": 3_8, """end""": 3_9},
												    {"""score""": 0.0001, """answer""": """oy 2312/2019 DUE""", """start""": 3_8, """end""": 4_0},
												]
												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    lowercase__      (	self					:     Union[str, Any]   ):
												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.9944, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.0009, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												    ]   ,					)

												lowerCamelCase_							  =					dqa_pipeline({"""image""": image, """question""": question}   ,					top_k=2   )
												self.assertEqual(
												    nested_simplify(__UpperCamelCase   ,					decimals=4   )   ,					[
												        {"""score""": 0.9944, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.0009, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												    ]   ,					)

												lowerCamelCase_							  =					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""": 1_6, """end""": 1_6},
												            {"""score""": 0.0009, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        ],
												    ]
												    * 2   ,					)

					@slow
					@require_torch
					@require_detectrona
					@require_pytesseract
					def    lowercase__      (	self					:     str   ):
												lowerCamelCase_							  =					pipeline(
												    """document-question-answering"""   ,					model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""   ,					revision="""9977165"""   ,					max_seq_len=5_0   ,					)
												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.9974, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
												        {"""score""": 0.9948, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												    ]   ,					)

												lowerCamelCase_							  =					dqa_pipeline({"""image""": image, """question""": question}   ,					top_k=2   )
												self.assertEqual(
												    nested_simplify(__UpperCamelCase   ,					decimals=4   )   ,					[
												        {"""score""": 0.9974, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
												        {"""score""": 0.9948, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												    ]   ,					)

												lowerCamelCase_							  =					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""": 2_3, """end""": 2_3},
												            {"""score""": 0.9948, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        ]
												    ]
												    * 2   ,					)

					@slow
					@require_torch
					@require_pytesseract
					@require_vision
					def    lowercase__      (	self					:     List[Any]   ):
												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.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
												    ]   ,					)

												lowerCamelCase_							  =					dqa_pipeline({"""image""": image, """question""": question}   ,					top_k=2   )
												self.assertEqual(
												    nested_simplify(__UpperCamelCase   ,					decimals=4   )   ,					[
												        {"""score""": 0.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
												    ]   ,					)

												lowerCamelCase_							  =					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""": 1_6, """end""": 1_6},
												            {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
												        ]
												    ]
												    * 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.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3},
												    ]   ,					)

					@slow
					@require_torch
					@require_pytesseract
					@require_vision
					def    lowercase__      (	self					:     Union[str, Any]   ):
												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=5_0   ,					)
												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.9999, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.9998, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												    ]   ,					)

												lowerCamelCase_							  =					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""": 1_6, """end""": 1_6},
												            {"""score""": 0.9998, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        ]
												    ]
												    * 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.9999, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												        {"""score""": 0.9998, """answer""": """us-001""", """start""": 1_6, """end""": 1_6},
												    ]   ,					)

					@slow
					@require_torch
					def    lowercase__      (	self					:     List[str]   ):
												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    lowercase__      (	self					:     int   ):
												pass







import hashlib
import unittest

from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image
else:





		class       __A:

							@staticmethod
							def    lowercase__      (	*__UpperCamelCase					:     str   ,					**__UpperCamelCase					:     Dict   ):
														pass



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Image       )  ->    str:
							lowerCamelCase_							  =					hashlib.mda(image.tobytes()       )
							return m.hexdigest()





@is_pipeline_test
@require_vision
@require_timm
@require_torch
class       __A(				unittest.TestCase       ):
					SCREAMING_SNAKE_CASE			    =    MODEL_FOR_DEPTH_ESTIMATION_MAPPING

					def    lowercase__      (	self					:     Union[str, Any]   ,					__UpperCamelCase					:     int   ,					__UpperCamelCase					:     Optional[int]   ,					__UpperCamelCase					:     int   ):
												lowerCamelCase_							  =					DepthEstimationPipeline(model=__UpperCamelCase   ,					image_processor=__UpperCamelCase   )
												return depth_estimator, [
												    "./tests/fixtures/tests_samples/COCO/000000039769.png",
												    "./tests/fixtures/tests_samples/COCO/000000039769.png",
												]

					def    lowercase__      (	self					:     Any   ,					__UpperCamelCase					:     List[str]   ,					__UpperCamelCase					:     Union[str, Any]   ):
												lowerCamelCase_							  =					depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
												self.assertEqual({"""predicted_depth""": ANY(torch.Tensor   ), """depth""": ANY(Image.Image   )}   ,					__UpperCamelCase   )
												import datasets

												lowerCamelCase_							  =					datasets.load_dataset("""hf-internal-testing/fixtures_image_utils"""   ,					"""image"""   ,					split="""test"""   )
												lowerCamelCase_							  =					depth_estimator(
												    [
												        Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   ),
												        """http://images.cocodataset.org/val2017/000000039769.jpg""",
												        # RGBA
												        dataset[0]["""file"""],
												        # LA
												        dataset[1]["""file"""],
												        # L
												        dataset[2]["""file"""],
												    ]   )
												self.assertEqual(
												    [
												        {"""predicted_depth""": ANY(torch.Tensor   ), """depth""": ANY(Image.Image   )},
												        {"""predicted_depth""": ANY(torch.Tensor   ), """depth""": ANY(Image.Image   )},
												        {"""predicted_depth""": ANY(torch.Tensor   ), """depth""": ANY(Image.Image   )},
												        {"""predicted_depth""": ANY(torch.Tensor   ), """depth""": ANY(Image.Image   )},
												        {"""predicted_depth""": ANY(torch.Tensor   ), """depth""": ANY(Image.Image   )},
												    ]   ,					__UpperCamelCase   ,					)

					@require_tf
					@unittest.skip("""Depth estimation is not implemented in TF"""   )
					def    lowercase__      (	self					:     Optional[int]   ):
												pass

					@slow
					@require_torch
					def    lowercase__      (	self					:     List[Any]   ):
												lowerCamelCase_							  =					"""Intel/dpt-large"""
												lowerCamelCase_							  =					pipeline("""depth-estimation"""   ,					model=__UpperCamelCase   )
												lowerCamelCase_							  =					depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg"""   )
												lowerCamelCase_							  =					hashimage(outputs["""depth"""]   )

												# This seems flaky.
												# self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
												self.assertEqual(nested_simplify(outputs["""predicted_depth"""].max().item()   )   ,					29.304   )
												self.assertEqual(nested_simplify(outputs["""predicted_depth"""].min().item()   )   ,					2.662   )



					@require_torch
					def    lowercase__      (	self					:     Dict   ):
												# This is highly irregular to have no small tests.
												self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT"""   )





