





"""simple docstring"""




from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


a						: Any     	=			logging.get_logger(__name__)

# General docstring
a						: Optional[Any]     	=			'''RegNetConfig'''

# Base docstring
a						: str     	=			'''facebook/regnet-y-040'''
a						: Optional[Any]     	=			[1, 1088, 7, 7]

# Image classification docstring
a						: Tuple     	=			'''facebook/regnet-y-040'''
a						: Dict     	=			'''tabby, tabby cat'''

a						: int     	=			[
    '''facebook/regnet-y-040''',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 3      ,					lowerCAmelCase__ = 1      ,					lowerCAmelCase__ = 1      ,					lowerCAmelCase__ = "relu"      ,					)	-> Optional[Any]:
								super().__init__()
								a      :		Optional[Any]	=				nn.Convad(
								    lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=lowerCAmelCase__      ,					stride=lowerCAmelCase__      ,					padding=kernel_size // 2      ,					groups=lowerCAmelCase__      ,					bias=lowerCAmelCase__      ,					)
								a      :		int	=				nn.BatchNormad(lowerCAmelCase__      )
								a      :		List[str]	=				ACTaFN[activation] if activation is not None else nn.Identity()






							def     __a   (   self      ,					lowerCAmelCase__      )	-> int:
								a      :		List[str]	=				self.convolution(lowerCAmelCase__      )
								a      :		Any	=				self.normalization(lowerCAmelCase__      )
								a      :		Optional[Any]	=				self.activation(lowerCAmelCase__      )
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      )	-> int:
								super().__init__()
								a      :		Union[str, Any]	=				RegNetConvLayer(
								    config.num_channels      ,					config.embedding_size      ,					kernel_size=3      ,					stride=2      ,					activation=config.hidden_act      )
								a      :		List[str]	=				config.num_channels






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Tuple:
								a      :		Union[str, Any]	=				pixel_values.shape[1]
								if num_channels != self.num_channels:
									raise ValueError(
									    "Make sure that the channel dimension of the pixel values match with the one set in the configuration."      )
								a      :		Any	=				self.embedder(lowerCAmelCase__      )
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 2      )	-> List[Any]:
								super().__init__()
								a      :		List[Any]	=				nn.Convad(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      ,					stride=lowerCAmelCase__      ,					bias=lowerCAmelCase__      )
								a      :		Union[str, Any]	=				nn.BatchNormad(lowerCAmelCase__      )






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Tensor:
								a      :		List[Any]	=				self.convolution(lowerCAmelCase__      )
								a      :		List[Any]	=				self.normalization(lowerCAmelCase__      )
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Optional[int]:
								super().__init__()

								a      :		int	=				nn.AdaptiveAvgPoolad((1, 1)      )
								a      :		Dict	=				nn.Sequential(
								    nn.Convad(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      )      ,					nn.ReLU()      ,					nn.Convad(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      )      ,					nn.Sigmoid()      ,					)






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Union[str, Any]:
								# b c h w -> b c 1 1
								a      :		int	=				self.pooler(lowerCAmelCase__      )
								a      :		Optional[Any]	=				self.attention(lowerCAmelCase__      )
								a      :		Any	=				hidden_state * attention
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 1      )	-> List[str]:
								super().__init__()
								a      :		str	=				in_channels != out_channels or stride != 1
								a      :		str	=				max(1      ,					out_channels // config.groups_width      )
								a      :		int	=				(
								    RegNetShortCut(lowerCAmelCase__      ,					lowerCAmelCase__      ,					stride=lowerCAmelCase__      ) if should_apply_shortcut else nn.Identity()
								)
								a      :		Tuple	=				nn.Sequential(
								    RegNetConvLayer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      ,					activation=config.hidden_act      )      ,					RegNetConvLayer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					stride=lowerCAmelCase__      ,					groups=lowerCAmelCase__      ,					activation=config.hidden_act      )      ,					RegNetConvLayer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      ,					activation=lowerCAmelCase__      )      ,					)
								a      :		List[Any]	=				ACTaFN[config.hidden_act]






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Union[str, Any]:
								a      :		Any	=				hidden_state
								a      :		int	=				self.layer(lowerCAmelCase__      )
								a      :		Union[str, Any]	=				self.shortcut(lowerCAmelCase__      )
								hidden_state += residual
								a      :		Tuple	=				self.activation(lowerCAmelCase__      )
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 1      )	-> str:
								super().__init__()
								a      :		Optional[int]	=				in_channels != out_channels or stride != 1
								a      :		str	=				max(1      ,					out_channels // config.groups_width      )
								a      :		int	=				(
								    RegNetShortCut(lowerCAmelCase__      ,					lowerCAmelCase__      ,					stride=lowerCAmelCase__      ) if should_apply_shortcut else nn.Identity()
								)
								a      :		int	=				nn.Sequential(
								    RegNetConvLayer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      ,					activation=config.hidden_act      )      ,					RegNetConvLayer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					stride=lowerCAmelCase__      ,					groups=lowerCAmelCase__      ,					activation=config.hidden_act      )      ,					RegNetSELayer(lowerCAmelCase__      ,					reduced_channels=int(round(in_channels / 4      )      )      )      ,					RegNetConvLayer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					kernel_size=1      ,					activation=lowerCAmelCase__      )      ,					)
								a      :		Optional[Any]	=				ACTaFN[config.hidden_act]






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Optional[Any]:
								a      :		str	=				hidden_state
								a      :		int	=				self.layer(lowerCAmelCase__      )
								a      :		Any	=				self.shortcut(lowerCAmelCase__      )
								hidden_state += residual
								a      :		int	=				self.activation(lowerCAmelCase__      )
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = 2      ,					lowerCAmelCase__ = 2      ,					)	-> int:
								super().__init__()

								a      :		Optional[int]	=				RegNetXLayer if config.layer_type == "x" else RegNetYLayer

								a      :		Optional[int]	=				nn.Sequential(
								    # downsampling is done in the first layer with stride of 2
								    layer(
								        lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					stride=lowerCAmelCase__      ,					)      ,					*[layer(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ) for _ in range(depth - 1      )]      ,					)






							def     __a   (   self      ,					lowerCAmelCase__      )	-> Optional[Any]:
								a      :		Optional[Any]	=				self.layers(lowerCAmelCase__      )
								return hidden_state


class        __UpperCamelCase				(						nn.Module						):






							def __init__(   self      ,					lowerCAmelCase__      )	-> str:
								super().__init__()
								a      :		Any	=				nn.ModuleList([]      )
								# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
								self.stages.append(
								    RegNetStage(
								        lowerCAmelCase__      ,					config.embedding_size      ,					config.hidden_sizes[0]      ,					stride=2 if config.downsample_in_first_stage else 1      ,					depth=config.depths[0]      ,					)      )
								a      :		Any	=				zip(config.hidden_sizes      ,					config.hidden_sizes[1:]      )
								for (in_channels, out_channels), depth in zip(lowerCAmelCase__      ,					config.depths[1:]      ):
									self.stages.append(RegNetStage(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					depth=lowerCAmelCase__      )      )






							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = False      ,					lowerCAmelCase__ = True      )	-> BaseModelOutputWithNoAttention:
								a      :		Any	=				() if output_hidden_states else None

								for stage_module in self.stages:
									if output_hidden_states:
										a      :		Any	=				hidden_states + (hidden_state,)

									a      :		Any	=				stage_module(lowerCAmelCase__      )

								if output_hidden_states:
									a      :		Dict	=				hidden_states + (hidden_state,)

								if not return_dict:
									return tuple(v for v in [hidden_state, hidden_states] if v is not None      )

								return BaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase__      ,					hidden_states=lowerCAmelCase__      )


class        __UpperCamelCase				(						a__						):
							lowerCamelCase   :					Union[str, Any]      					=RegNetConfig
							lowerCamelCase   :					Dict      					="""regnet"""
							lowerCamelCase   :					Tuple      					="""pixel_values"""
							lowerCamelCase   :					List[Any]      					=True






							def     __a   (   self      ,					lowerCAmelCase__      )	-> List[Any]:
								if isinstance(lowerCAmelCase__      ,					nn.Convad      ):
									nn.init.kaiming_normal_(module.weight      ,					mode="fan_out"      ,					nonlinearity="relu"      )
								elif isinstance(lowerCAmelCase__      ,					(nn.BatchNormad, nn.GroupNorm)      ):
									nn.init.constant_(module.weight      ,					1      )
									nn.init.constant_(module.bias      ,					0      )






							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__=False      )	-> List[Any]:
								if isinstance(lowerCAmelCase__      ,					lowerCAmelCase__      ):
									a      :		Any	=				value
a						: str     	=			R'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

a						: Optional[int]     	=			R'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
'''


@add_start_docstrings(
    """The bare RegNet model outputting raw features without any specific head on top."""		,       a__		,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class        __UpperCamelCase				(						a__						):






							def __init__(   self      ,					lowerCAmelCase__      )	-> int:
								super().__init__(lowerCAmelCase__      )
								a      :		Tuple	=				config
								a      :		Optional[int]	=				RegNetEmbeddings(lowerCAmelCase__      )
								a      :		List[str]	=				RegNetEncoder(lowerCAmelCase__      )
								a      :		Tuple	=				nn.AdaptiveAvgPoolad((1, 1)      )
								# Initialize weights and apply final processing
								self.post_init()






							@add_start_docstrings_to_model_forward(lowerCAmelCase__      )
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC      ,					output_type=lowerCAmelCase__      ,					config_class=_CONFIG_FOR_DOC      ,					modality="vision"      ,					expected_output=_EXPECTED_OUTPUT_SHAPE      ,					)
							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = None      )	-> BaseModelOutputWithPoolingAndNoAttention:
								a      :		Optional[Any]	=				(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								a      :		str	=				return_dict if return_dict is not None else self.config.use_return_dict

								a      :		Tuple	=				self.embedder(lowerCAmelCase__      )

								a      :		Any	=				self.encoder(
								    lowerCAmelCase__      ,					output_hidden_states=lowerCAmelCase__      ,					return_dict=lowerCAmelCase__      )

								a      :		Any	=				encoder_outputs[0]

								a      :		Union[str, Any]	=				self.pooler(lowerCAmelCase__      )

								if not return_dict:
									return (last_hidden_state, pooled_output) + encoder_outputs[1:]

								return BaseModelOutputWithPoolingAndNoAttention(
								    last_hidden_state=lowerCAmelCase__      ,					pooler_output=lowerCAmelCase__      ,					hidden_states=encoder_outputs.hidden_states      ,					)


@add_start_docstrings(
    """
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """		,       a__		,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class        __UpperCamelCase				(						a__						):






							def __init__(   self      ,					lowerCAmelCase__      )	-> str:
								super().__init__(lowerCAmelCase__      )
								a      :		List[str]	=				config.num_labels
								a      :		Dict	=				RegNetModel(lowerCAmelCase__      )
								# classification head
								a      :		Optional[Any]	=				nn.Sequential(
								    nn.Flatten()      ,					nn.Linear(config.hidden_sizes[-1]      ,					config.num_labels      ) if config.num_labels > 0 else nn.Identity()      ,					)
								# initialize weights and apply final processing
								self.post_init()






							@add_start_docstrings_to_model_forward(lowerCAmelCase__      )
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT      ,					output_type=lowerCAmelCase__      ,					config_class=_CONFIG_FOR_DOC      ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,					)
							def     __a   (   self      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = None      ,					lowerCAmelCase__ = None      ,					)	-> ImageClassifierOutputWithNoAttention:
								a      :		Dict	=				return_dict if return_dict is not None else self.config.use_return_dict

								a      :		List[Any]	=				self.regnet(lowerCAmelCase__      ,					output_hidden_states=lowerCAmelCase__      ,					return_dict=lowerCAmelCase__      )

								a      :		Any	=				outputs.pooler_output if return_dict else outputs[1]

								a      :		List[str]	=				self.classifier(lowerCAmelCase__      )

								a      :		str	=				None

								if labels is not None:
									if self.config.problem_type is None:
										if self.num_labels == 1:
											a      :		Optional[int]	=				"regression"
										elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
											a      :		Optional[Any]	=				"single_label_classification"
										else:
											a      :		str	=				"multi_label_classification"
									if self.config.problem_type == "regression":
										a      :		Optional[Any]	=				MSELoss()
										if self.num_labels == 1:
											a      :		List[Any]	=				loss_fct(logits.squeeze()      ,					labels.squeeze()      )
										else:
											a      :		str	=				loss_fct(lowerCAmelCase__      ,					lowerCAmelCase__      )
									elif self.config.problem_type == "single_label_classification":
										a      :		Union[str, Any]	=				CrossEntropyLoss()
										a      :		Tuple	=				loss_fct(logits.view(-1      ,					self.num_labels      )      ,					labels.view(-1      )      )
									elif self.config.problem_type == "multi_label_classification":
										a      :		Dict	=				BCEWithLogitsLoss()
										a      :		List[Any]	=				loss_fct(lowerCAmelCase__      ,					lowerCAmelCase__      )

								if not return_dict:
									a      :		int	=				(logits,) + outputs[2:]
									return (loss,) + output if loss is not None else output

								return ImageClassifierOutputWithNoAttention(loss=lowerCAmelCase__      ,					logits=lowerCAmelCase__      ,					hidden_states=outputs.hidden_states      )









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






									@staticmethod
									def     __a   (   *lowerCAmelCase__      ,					**lowerCAmelCase__      )	-> str:
										pass






		def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Tuple					) ->Dict:






			'''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.
a						: Optional[Any]     	=			(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


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






							@require_pytesseract
							@require_vision
							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Tuple:
								a      :		Tuple	=				pipeline(
								    "document-question-answering"      ,					model=lowerCAmelCase__      ,					tokenizer=lowerCAmelCase__      ,					image_processor=lowerCAmelCase__      )

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






							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Dict:
								a      :		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     __a   (   self      )	-> List[Any]:
								a      :		List[Any]	=				pipeline("document-question-answering"      ,					model="hf-internal-testing/tiny-random-layoutlmv2"      )
								a      :		Dict	=				INVOICE_URL
								a      :		List[str]	=				"How many cats are there?"

								a      :		Tuple	=				[
								    {"score": 0.0_001, "answer": "oy 2312/2019", "start": 38, "end": 39},
								    {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
								]
								a      :		Optional[int]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					lowerCAmelCase__      )

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

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

								a      :		int	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		str	=				dqa_pipeline({"image": image, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		Any	=				dqa_pipeline(
								    [{"image": image, "question": question}, {"image": image, "question": question}]      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        [
								            {"score": 0.9_944, "answer": "us-001", "start": 16, "end": 16},
								            {"score": 0.0_009, "answer": "us-001", "start": 16, "end": 16},
								        ],
								    ]
								    * 2      ,					)






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

								a      :		List[Any]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
								        {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		str	=				dqa_pipeline({"image": image, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
								        {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		Tuple	=				dqa_pipeline(
								    [{"image": image, "question": question}, {"image": image, "question": question}]      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        [
								            {"score": 0.9_974, "answer": "1110212019", "start": 23, "end": 23},
								            {"score": 0.9_948, "answer": "us-001", "start": 16, "end": 16},
								        ]
								    ]
								    * 2      ,					)






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

								a      :		List[str]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
								    ]      ,					)

								a      :		Dict	=				dqa_pipeline({"image": image, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.4_251, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
								    ]      ,					)

								a      :		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_251, "answer": "us-001", "start": 16, "end": 16},
								            {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
								        ]
								    ]
								    * 2      ,					)

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

								# This model should also work if `image` is set to None
								a      :		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_251, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.0_819, "answer": "1110212019", "start": 23, "end": 23},
								    ]      ,					)






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

								a      :		List[Any]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)

								a      :		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_999, "answer": "us-001", "start": 16, "end": 16},
								            {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
								        ]
								    ]
								    * 2      ,					)

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

								# This model should also work if `image` is set to None
								a      :		Any	=				dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}      ,					top_k=2      )
								self.assertEqual(
								    nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					[
								        {"score": 0.9_999, "answer": "us-001", "start": 16, "end": 16},
								        {"score": 0.9_998, "answer": "us-001", "start": 16, "end": 16},
								    ]      ,					)






							@slow
							@require_torch
							def     __a   (   self      )	-> int:
								a      :		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"      ,					)

								a      :		Optional[Any]	=				INVOICE_URL
								a      :		Tuple	=				"What is the invoice number?"
								a      :		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     __a   (   self      )	-> int:
								pass


