

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


       @staticmethod
       def 						_lowerCamelCase   ( *_UpperCamelCase			,				**_UpperCamelCase  ):





          """simple docstring"""





          pass







    def 					_A		(	snake_case     )			->	Dict:
       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.
_snake_case     =  (
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


@is_pipeline_test
@require_torch
@require_vision
class    a__  (							unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE    :     Union[str, Any]	       =							MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING


   @require_pytesseract
   @require_vision
   def 						_lowerCamelCase   ( self			,				_UpperCamelCase			,				_UpperCamelCase			,				_UpperCamelCase  ):





      """simple docstring"""





      _lowercase			:      Tuple			     =   pipeline(
          "document-question-answering"			,				model=lowerCAmelCase__			,				tokenizer=lowerCAmelCase__			,				image_processor=lowerCAmelCase__  )

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


   def 						_lowerCamelCase   ( self			,				_UpperCamelCase			,				_UpperCamelCase  ):





      """simple docstring"""





      _lowercase			:      Tuple			     =   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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





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

      _lowercase			:      Tuple			     =   [
          {"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},
      ]
      _lowercase			:      Optional[int]			     =   dqa_pipeline(image=lowerCAmelCase__			,				question=lowerCAmelCase__			,				top_k=2  )
      self.assertEqual(nested_simplify(lowerCAmelCase__			,				decimals=4  )			,				lowerCAmelCase__  )

      _lowercase			:      Optional[int]			     =   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
      _lowercase			:      List[Any]			     =   "./tests/fixtures/tests_samples/COCO/000000039769.png"
      _lowercase			:      Any			     =   dqa_pipeline(image=lowerCAmelCase__			,				question=lowerCAmelCase__			,				top_k=2  )
      self.assertEqual(lowerCAmelCase__			,				[]  )

      # We can optionnally pass directly the words and bounding boxes
      _lowercase			:      Optional[int]			     =   "./tests/fixtures/tests_samples/COCO/000000039769.png"
      _lowercase			:      Tuple			     =   []
      _lowercase			:      Optional[int]			     =   []
      _lowercase			:      List[str]			     =   dqa_pipeline(image=lowerCAmelCase__			,				question=lowerCAmelCase__			,				words=lowerCAmelCase__			,				boxes=lowerCAmelCase__			,				top_k=2  )
      self.assertEqual(lowerCAmelCase__			,				[]  )


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





      """simple docstring"""





      _lowercase			:      int			     =   pipeline(
          "document-question-answering"			,				model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"			,				revision="9977165"			,				)
      _lowercase			:      List[str]			     =   INVOICE_URL
      _lowercase			:      List[Any]			     =   "What is the invoice number?"

      _lowercase			:      int			     =   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},
          ]			,				)

      _lowercase			:      str			     =   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},
          ]			,				)

      _lowercase			:      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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      _lowercase			:      List[str]			     =   pipeline(
          "document-question-answering"			,				model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"			,				revision="9977165"			,				max_seq_len=50			,				)
      _lowercase			:      Optional[Any]			     =   INVOICE_URL
      _lowercase			:      Tuple			     =   "What is the invoice number?"

      _lowercase			:      List[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},
          ]			,				)

      _lowercase			:      str			     =   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},
          ]			,				)

      _lowercase			:      Tuple			     =   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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      _lowercase			:      Optional[int]			     =   AutoTokenizer.from_pretrained(
          "impira/layoutlm-document-qa"			,				revision="3dc6de3"			,				add_prefix_space=lowerCAmelCase__  )
      _lowercase			:      int			     =   pipeline(
          "document-question-answering"			,				model="impira/layoutlm-document-qa"			,				tokenizer=lowerCAmelCase__			,				revision="3dc6de3"			,				)
      _lowercase			:      List[Any]			     =   INVOICE_URL
      _lowercase			:      Tuple			     =   "What is the invoice number?"

      _lowercase			:      List[str]			     =   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},
          ]			,				)

      _lowercase			:      Dict			     =   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},
          ]			,				)

      _lowercase			:      List[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			,				)

      _lowercase			:      Dict			     =   list(zip(*apply_tesseract(load_image(lowerCAmelCase__  )			,				lowerCAmelCase__			,				""  )  )  )

      # This model should also work if `image` is set to None
      _lowercase			:      Optional[Any]			     =   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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





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

      _lowercase			:      List[Any]			     =   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},
          ]			,				)

      _lowercase			:      List[str]			     =   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			,				)

      _lowercase			:      List[Any]			     =   list(zip(*apply_tesseract(load_image(lowerCAmelCase__  )			,				lowerCAmelCase__			,				""  )  )  )

      # This model should also work if `image` is set to None
      _lowercase			:      Any			     =   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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      _lowercase			:      Tuple			     =   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			:      Optional[Any]			     =   INVOICE_URL
      _lowercase			:      Tuple			     =   "What is the invoice number?"
      _lowercase			:      List[Any]			     =   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 						_lowerCamelCase   ( self  ):





      """simple docstring"""





      pass













"""simple docstring"""




from typing import Dict, List, Optional, Tuple, Union

import torch

from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


class        __UpperCamelCase				(						a__						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = None      ,					)	-> int:
								super().__init__()
								self.register_modules(transformer=lowerCAmelCase__      ,					vae=lowerCAmelCase__      ,					scheduler=lowerCAmelCase__      )

								# create a imagenet -> id dictionary for easier use
								a      :		str	=				{}
								if idalabel is not None:
									for key, value in idalabel.items():
										for label in value.split(","      ):
											a      :		int	=				int(lowerCAmelCase__      )
									a      :		Any	=				dict(sorted(self.labels.items()      )      )






							def     __a   (   self      ,					lowerCAmelCase__      )	-> List[int]:

								if not isinstance(lowerCAmelCase__      ,					lowerCAmelCase__      ):
									a      :		Optional[Any]	=				list(lowerCAmelCase__      )

								for l in label:
									if l not in self.labels:
										raise ValueError(
										    f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}."""      )

								return [self.labels[l] for l in label]






							@torch.no_grad()
							def __call__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 4.0      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = 50      ,					lowerCAmelCase__ = "pil"      ,					lowerCAmelCase__ = True      ,					)	-> Union[ImagePipelineOutput, Tuple]:
								a      :		Dict	=				len(lowerCAmelCase__      )
								a      :		Tuple	=				self.transformer.config.sample_size
								a      :		Tuple	=				self.transformer.config.in_channels

								a      :		Optional[int]	=				randn_tensor(
								    shape=(batch_size, latent_channels, latent_size, latent_size)      ,					generator=lowerCAmelCase__      ,					device=self.device      ,					dtype=self.transformer.dtype      ,					)
								a      :		Tuple	=				torch.cat([latents] * 2      ) if guidance_scale > 1 else latents

								a      :		List[str]	=				torch.tensor(lowerCAmelCase__      ,					device=self.device      ).reshape(-1      )
								a      :		str	=				torch.tensor([1000] * batch_size      ,					device=self.device      )
								a      :		Dict	=				torch.cat([class_labels, class_null]      ,					0      ) if guidance_scale > 1 else class_labels

								# set step values
								self.scheduler.set_timesteps(lowerCAmelCase__      )

								for t in self.progress_bar(self.scheduler.timesteps      ):
									if guidance_scale > 1:
										a      :		Any	=				latent_model_input[: len(lowerCAmelCase__      ) // 2]
										a      :		Tuple	=				torch.cat([half, half]      ,					dim=0      )
									a      :		List[str]	=				self.scheduler.scale_model_input(lowerCAmelCase__      ,					lowerCAmelCase__      )

									a      :		Dict	=				t
									if not torch.is_tensor(lowerCAmelCase__      ):
										# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
										# This would be a good case for the `match` statement (Python 3.10+)
										a      :		Optional[int]	=				latent_model_input.device.type == "mps"
										if isinstance(lowerCAmelCase__      ,					lowerCAmelCase__      ):
											a      :		Union[str, Any]	=				torch.floataa if is_mps else torch.floataa
										else:
											a      :		str	=				torch.intaa if is_mps else torch.intaa
										a      :		List[str]	=				torch.tensor([timesteps]      ,					dtype=lowerCAmelCase__      ,					device=latent_model_input.device      )
									elif len(timesteps.shape      ) == 0:
										a      :		List[Any]	=				timesteps[None].to(latent_model_input.device      )
									# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
									a      :		Dict	=				timesteps.expand(latent_model_input.shape[0]      )
									# predict noise model_output
									a      :		Union[str, Any]	=				self.transformer(
									    lowerCAmelCase__      ,					timestep=lowerCAmelCase__      ,					class_labels=lowerCAmelCase__      ).sample

									# perform guidance
									if guidance_scale > 1:
										a,       a      :		Any	=				noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
										a,       a      :		Union[str, Any]	=				torch.split(lowerCAmelCase__      ,					len(lowerCAmelCase__      ) // 2      ,					dim=0      )

										a      :		Dict	=				uncond_eps + guidance_scale * (cond_eps - uncond_eps)
										a      :		Optional[int]	=				torch.cat([half_eps, half_eps]      ,					dim=0      )

										a      :		Optional[int]	=				torch.cat([eps, rest]      ,					dim=1      )

									# learned sigma
									if self.transformer.config.out_channels // 2 == latent_channels:
										a,       a      :		str	=				torch.split(lowerCAmelCase__      ,					lowerCAmelCase__      ,					dim=1      )
									else:
										a      :		Any	=				noise_pred

									# compute previous image: x_t -> x_t-1
									a      :		Optional[int]	=				self.scheduler.step(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ).prev_sample

								if guidance_scale > 1:
									a,       a      :		Tuple	=				latent_model_input.chunk(2      ,					dim=0      )
								else:
									a      :		Tuple	=				latent_model_input

								a      :		Optional[Any]	=				1 / self.vae.config.scaling_factor * latents
								a      :		Any	=				self.vae.decode(lowerCAmelCase__      ).sample

								a      :		Tuple	=				(samples / 2 + 0.5).clamp(0      ,					1      )

								# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
								a      :		Optional[Any]	=				samples.cpu().permute(0      ,					2      ,					3      ,					1      ).float().numpy()

								if output_type == "pil":
									a      :		int	=				self.numpy_to_pil(lowerCAmelCase__      )

								if not return_dict:
									return (samples,)

								return ImagePipelineOutput(images=lowerCAmelCase__      )


