

from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
			import tensorflow as tf

			from ..tf_utils import stable_softmax


if is_torch_available():
			import torch


a_     =			logging.get_logger(__name__)






@add_end_docstrings(
    __A							,		R'\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    '							,		)
class _UpperCamelCase							(							__A      ):
			'''simple docstring'''







			def 							__UpperCamelCase       (	self							:       int					,					a							:       GenericTensor		)							->				np.ndarray:

				"""simple docstring"""

				if self.framework == "tf":
					SCREAMING_SNAKE_CASE      :					List[Any]    =				tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()
				elif self.framework == "pt":
					SCREAMING_SNAKE_CASE      :					Optional[int]    =				torch.nonzero(input_ids == self.tokenizer.mask_token_id					,					as_tuple=a		)
				else:
					raise ValueError("Unsupported framework"		)
				return masked_index
			def 							__UpperCamelCase       (	self							:       Union[str, Any]					,					a							:       GenericTensor		)							->				np.ndarray:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.get_masked_index(a		)
				SCREAMING_SNAKE_CASE      :					Any    =				np.prod(masked_index.shape		)
				if numel < 1:
					raise PipelineException(
					    "fill-mask"					,					self.model.base_model_prefix					,					F"No mask_token ({self.tokenizer.mask_token}) found on the input"					,					)
			def 							__UpperCamelCase       (	self							:       Dict					,					a							:       GenericTensor		)							->				int:

				"""simple docstring"""

				if isinstance(a					,					a		):
					for model_input in model_inputs:
						self._ensure_exactly_one_mask_token(model_input["input_ids"][0]		)
				else:
					for input_ids in model_inputs["input_ids"]:
						self._ensure_exactly_one_mask_token(a		)
			def 							__UpperCamelCase       (	self							:       int					,					a							:       List[str]					,					a							:       int=None					,					**a							:       Any		)							->				Dict[str, GenericTensor]:

				"""simple docstring"""

				if return_tensors is None:
					SCREAMING_SNAKE_CASE      :					List[Any]    =				self.framework
				SCREAMING_SNAKE_CASE      :					Dict    =				self.tokenizer(a					,					return_tensors=a		)
				self.ensure_exactly_one_mask_token(a		)
				return model_inputs
			def 							__UpperCamelCase       (	self							:       str					,					a							:       int		)							->				Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.model(**a		)
				SCREAMING_SNAKE_CASE      :					List[str]    =				model_inputs["input_ids"]
				return model_outputs
			def 							__UpperCamelCase       (	self							:       List[str]					,					a							:       Optional[int]					,					a							:       Dict=5					,					a							:       Optional[int]=None		)							->				Optional[Any]:

				"""simple docstring"""

				if target_ids is not None and target_ids.shape[0] < top_k:
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				target_ids.shape[0]
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				model_outputs["input_ids"][0]
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				model_outputs["logits"]

				if self.framework == "tf":
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()[:, 0]

					SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				outputs.numpy()

					SCREAMING_SNAKE_CASE      :					Dict    =				outputs[0, masked_index, :]
					SCREAMING_SNAKE_CASE      :					Dict    =				stable_softmax(a					,					axis=-1		)
					if target_ids is not None:
						SCREAMING_SNAKE_CASE      :					str    =				tf.gather_nd(tf.squeeze(a					,					0		)					,					target_ids.reshape(-1					,					1		)		)
						SCREAMING_SNAKE_CASE      :					int    =				tf.expand_dims(a					,					0		)

					SCREAMING_SNAKE_CASE      :					List[Any]    =				tf.math.top_k(a					,					k=a		)
					SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Optional[int]    =				topk.values.numpy(), topk.indices.numpy()
				else:
					SCREAMING_SNAKE_CASE      :					Tuple    =				torch.nonzero(input_ids == self.tokenizer.mask_token_id					,					as_tuple=a		).squeeze(-1		)
					# Fill mask pipeline supports only one ${mask_token} per sample

					SCREAMING_SNAKE_CASE      :					Any    =				outputs[0, masked_index, :]
					SCREAMING_SNAKE_CASE      :					str    =				logits.softmax(dim=-1		)
					if target_ids is not None:
						SCREAMING_SNAKE_CASE      :					Optional[Any]    =				probs[..., target_ids]

					SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Optional[int]    =				probs.topk(a		)

				SCREAMING_SNAKE_CASE      :					int    =				[]
				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				values.shape[0] == 1
				for i, (_values, _predictions) in enumerate(zip(values.tolist()					,					predictions.tolist()		)		):
					SCREAMING_SNAKE_CASE      :					Optional[int]    =				[]
					for v, p in zip(_values					,					_predictions		):
						# Copy is important since we're going to modify this array in place
						SCREAMING_SNAKE_CASE      :					Dict    =				input_ids.numpy().copy()
						if target_ids is not None:
							SCREAMING_SNAKE_CASE      :					Tuple    =				target_ids[p].tolist()

						SCREAMING_SNAKE_CASE      :					Any    =				p
						# Filter padding out:
						SCREAMING_SNAKE_CASE      :					Optional[int]    =				tokens[np.where(tokens != self.tokenizer.pad_token_id		)]
						# Originally we skip special tokens to give readable output.
						# For multi masks though, the other [MASK] would be removed otherwise
						# making the output look odd, so we add them back
						SCREAMING_SNAKE_CASE      :					List[Any]    =				self.tokenizer.decode(a					,					skip_special_tokens=a		)
						SCREAMING_SNAKE_CASE      :					Optional[int]    =				{"score": v, "token": p, "token_str": self.tokenizer.decode([p]		), "sequence": sequence}
						row.append(a		)
					result.append(a		)
				if single_mask:
					return result[0]
				return result
			def 							__UpperCamelCase       (	self							:       Dict					,					a							:       Tuple					,					a							:       Tuple=None		)							->				Dict:

				"""simple docstring"""

				if isinstance(a					,					a		):
					SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				[targets]
				try:
					SCREAMING_SNAKE_CASE      :					Tuple    =				self.tokenizer.get_vocab()
				except Exception:
					SCREAMING_SNAKE_CASE      :					int    =				{}
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				[]
				for target in targets:
					SCREAMING_SNAKE_CASE      :					int    =				vocab.get(a					,					a		)
					if id_ is None:
						SCREAMING_SNAKE_CASE      :					Any    =				self.tokenizer(
						    a					,					add_special_tokens=a					,					return_attention_mask=a					,					return_token_type_ids=a					,					max_length=1					,					truncation=a					,					)["input_ids"]
						if len(a		) == 0:
							logger.warning(
							    F"The specified target token `{target}` does not exist in the model vocabulary. "
							    "We cannot replace it with anything meaningful, ignoring it"		)
							continue
						SCREAMING_SNAKE_CASE      :					Optional[Any]    =				input_ids[0]
						# XXX: If users encounter this pass
						# it becomes pretty slow, so let's make sure
						# The warning enables them to fix the input to
						# get faster performance.
						logger.warning(
						    F"The specified target token `{target}` does not exist in the model vocabulary. "
						    F"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_		)}`."		)
					target_ids.append(id_		)
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				list(set(a		)		)
				if len(a		) == 0:
					raise ValueError("At least one target must be provided when passed."		)
				SCREAMING_SNAKE_CASE      :					Dict    =				np.array(a		)
				return target_ids
			def 							__UpperCamelCase       (	self							:       int					,					a							:       List[Any]=None					,					a							:       List[Any]=None		)							->				Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Any    =				{}

				if targets is not None:
					SCREAMING_SNAKE_CASE      :					str    =				self.get_target_ids(a					,					a		)
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				target_ids

				if top_k is not None:
					SCREAMING_SNAKE_CASE      :					Tuple    =				top_k

				if self.tokenizer.mask_token_id is None:
					raise PipelineException(
					    "fill-mask"					,					self.model.base_model_prefix					,					"The tokenizer does not define a `mask_token`."		)
				return {}, {}, postprocess_params






			def __call__(	self							:       Any					,					a							:       Optional[int]					,					*a							:       Dict					,					**a							:       int		)							->				Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				super().__call__(a					,					**a		)
				if isinstance(a					,					a		) and len(a		) == 1:
					return outputs[0]
				return outputs

import unittest

from transformers import (
    MODEL_FOR_OBJECT_DETECTION_MAPPING,
    AutoFeatureExtractor,
    AutoModelForObjectDetection,
    ObjectDetectionPipeline,
    is_vision_available,
    pipeline,
)
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_pytesseract,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
			from PIL import Image
else:





			class 	_lowerCAmelCase					:




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





@is_pipeline_test
@require_vision
@require_timm
@require_torch
class 	_lowerCAmelCase					(	unittest.TestCase       ):
				_lowercase					=MODEL_FOR_OBJECT_DETECTION_MAPPING




				def      __a						(					self				,				_UpperCamelCase				,				_UpperCamelCase				,				_UpperCamelCase     )				->      str:
							lowerCAmelCase_						=	ObjectDetectionPipeline(model=_UpperCamelCase				,				image_processor=_UpperCamelCase     )
							return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]




				def      __a						(					self				,				_UpperCamelCase				,				_UpperCamelCase     )				->      Any:
							lowerCAmelCase_						=	object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png"				,				threshold=0.0     )

							self.assertGreater(len(_UpperCamelCase     )				,				0     )
							for detected_object in outputs:
										self.assertEqual(
										    _UpperCamelCase				,				{
										        "score": ANY(_UpperCamelCase     ),
										        "label": ANY(_UpperCamelCase     ),
										        "box": {"xmin": ANY(_UpperCamelCase     ), "ymin": ANY(_UpperCamelCase     ), "xmax": ANY(_UpperCamelCase     ), "ymax": ANY(_UpperCamelCase     )},
										    }				,				)

							import datasets

							lowerCAmelCase_						=	datasets.load_dataset("hf-internal-testing/fixtures_image_utils"				,				"image"				,				split="test"     )

							lowerCAmelCase_						=	[
							    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"],
							]
							lowerCAmelCase_						=	object_detector(_UpperCamelCase				,				threshold=0.0     )

							self.assertEqual(len(_UpperCamelCase     )				,				len(_UpperCamelCase     )     )
							for outputs in batch_outputs:
										self.assertGreater(len(_UpperCamelCase     )				,				0     )
										for detected_object in outputs:
													self.assertEqual(
													    _UpperCamelCase				,				{
													        "score": ANY(_UpperCamelCase     ),
													        "label": ANY(_UpperCamelCase     ),
													        "box": {"xmin": ANY(_UpperCamelCase     ), "ymin": ANY(_UpperCamelCase     ), "xmax": ANY(_UpperCamelCase     ), "ymax": ANY(_UpperCamelCase     )},
													    }				,				)




				@require_tf
				@unittest.skip("Object detection not implemented in TF"     )
				def      __a						(					self     )				->      Optional[int]:
							pass




				@require_torch
				def      __a						(					self     )				->      str:
							lowerCAmelCase_						=	"hf-internal-testing/tiny-detr-mobilenetsv3"

							lowerCAmelCase_						=	AutoModelForObjectDetection.from_pretrained(_UpperCamelCase     )
							lowerCAmelCase_						=	AutoFeatureExtractor.from_pretrained(_UpperCamelCase     )
							lowerCAmelCase_						=	ObjectDetectionPipeline(model=_UpperCamelCase				,				feature_extractor=_UpperCamelCase     )

							lowerCAmelCase_						=	object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"				,				threshold=0.0     )

							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
							        {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
							    ]				,				)

							lowerCAmelCase_						=	object_detector(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]				,				threshold=0.0				,				)

							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        [
							            {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
							            {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
							        ],
							        [
							            {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
							            {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
							        ],
							    ]				,				)




				@require_torch
				@slow
				def      __a						(					self     )				->      Optional[Any]:
							lowerCAmelCase_						=	"facebook/detr-resnet-50"

							lowerCAmelCase_						=	AutoModelForObjectDetection.from_pretrained(_UpperCamelCase     )
							lowerCAmelCase_						=	AutoFeatureExtractor.from_pretrained(_UpperCamelCase     )
							lowerCAmelCase_						=	ObjectDetectionPipeline(model=_UpperCamelCase				,				feature_extractor=_UpperCamelCase     )

							lowerCAmelCase_						=	object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"     )
							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
							        {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
							        {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
							        {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							        {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							    ]				,				)

							lowerCAmelCase_						=	object_detector(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]     )
							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        [
							            {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
							            {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
							            {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
							            {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							            {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							        ],
							        [
							            {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
							            {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
							            {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
							            {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							            {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							        ],
							    ]				,				)




				@require_torch
				@slow
				def      __a						(					self     )				->      str:
							lowerCAmelCase_						=	"facebook/detr-resnet-50"

							lowerCAmelCase_						=	pipeline("object-detection"				,				model=_UpperCamelCase     )

							lowerCAmelCase_						=	object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"     )
							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
							        {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
							        {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
							        {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							        {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							    ]				,				)

							lowerCAmelCase_						=	object_detector(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]     )
							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        [
							            {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
							            {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
							            {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
							            {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							            {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							        ],
							        [
							            {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
							            {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
							            {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
							            {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							            {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							        ],
							    ]				,				)




				@require_torch
				@slow
				def      __a						(					self     )				->      Optional[Any]:
							lowerCAmelCase_						=	0.9985
							lowerCAmelCase_						=	"facebook/detr-resnet-50"

							lowerCAmelCase_						=	pipeline("object-detection"				,				model=_UpperCamelCase     )

							lowerCAmelCase_						=	object_detector("http://images.cocodataset.org/val2017/000000039769.jpg"				,				threshold=_UpperCamelCase     )
							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
							        {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
							    ]				,				)




				@require_torch
				@require_pytesseract
				@slow
				def      __a						(					self     )				->      List[str]:
							lowerCAmelCase_						=	"Narsil/layoutlmv3-finetuned-funsd"
							lowerCAmelCase_						=	0.9993

							lowerCAmelCase_						=	pipeline("object-detection"				,				model=_UpperCamelCase				,				threshold=_UpperCamelCase     )

							lowerCAmelCase_						=	object_detector(
							    "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png"     )
							self.assertEqual(
							    nested_simplify(_UpperCamelCase				,				decimals=4     )				,				[
							        {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
							        {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
							    ]				,				)



