
import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
							from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import MobileNetVaImageProcessor




class   __lowercase						(						__snake_case       ):






	def       _a(self				: Union[str, Any]    ) ->			Optional[int]:
							_lowercase       :	Tuple           =   self.config_class(**self.inputs_dict    )
							self.parent.assertTrue(hasattr(snake_case      ,	"tf_padding"    )    )
							self.parent.assertTrue(hasattr(snake_case      ,	"depth_multiplier"    )    )




class   __lowercase						:






	def __init__(self				: Union[str, Any]      ,	snake_case				: Optional[Any]      ,	snake_case				: Optional[int]=13      ,	snake_case				: Optional[int]=3      ,	snake_case				: Optional[int]=32      ,	snake_case				: str=0.25      ,	snake_case				: Optional[Any]=8      ,	snake_case				: List[str]=8      ,	snake_case				: Union[str, Any]=6      ,	snake_case				: Dict=32      ,	snake_case				: Tuple=True      ,	snake_case				: str=True      ,	snake_case				: Optional[Any]=True      ,	snake_case				: str="relu6"      ,	snake_case				: Optional[int]=1280      ,	snake_case				: List[Any]=0.1      ,	snake_case				: List[Any]=0.02      ,	snake_case				: Optional[Any]=True      ,	snake_case				: Union[str, Any]=True      ,	snake_case				: List[Any]=10      ,	snake_case				: Tuple=None      ,	) ->			Tuple:
							_lowercase       :	Optional[Any]           =   parent
							_lowercase       :	Optional[int]           =   batch_size
							_lowercase       :	List[Any]           =   num_channels
							_lowercase       :	List[Any]           =   image_size
							_lowercase       :	List[Any]           =   depth_multiplier
							_lowercase       :	Optional[Any]           =   depth_divisible_by
							_lowercase       :	List[Any]           =   min_depth
							_lowercase       :	Dict           =   expand_ratio
							_lowercase       :	Optional[int]           =   tf_padding
							_lowercase       :	List[str]           =   output_stride
							_lowercase       :	List[str]           =   first_layer_is_expansion
							_lowercase       :	Tuple           =   finegrained_output
							_lowercase       :	List[Any]           =   hidden_act
							_lowercase       :	Tuple           =   last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier    )
							_lowercase       :	Any           =   classifier_dropout_prob
							_lowercase       :	List[Any]           =   use_labels
							_lowercase       :	Tuple           =   is_training
							_lowercase       :	int           =   num_labels
							_lowercase       :	Tuple           =   initializer_range
							_lowercase       :	Optional[Any]           =   scope






	def       _a(self				: Union[str, Any]    ) ->			Any:
							_lowercase       :	int           =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

							_lowercase       :	Optional[int]           =   None
							_lowercase       :	List[Any]           =   None
							if self.use_labels:
													_lowercase       :	Any           =   ids_tensor([self.batch_size]      ,	self.num_labels    )
													_lowercase       :	Optional[int]           =   ids_tensor([self.batch_size, self.image_size, self.image_size]      ,	self.num_labels    )

							_lowercase       :	Union[str, Any]           =   self.get_config()

							return config, pixel_values, labels, pixel_labels






	def       _a(self				: Tuple    ) ->			Optional[int]:
							return MobileNetVaConfig(
							    num_channels=self.num_channels      ,	image_size=self.image_size      ,	depth_multiplier=self.depth_multiplier      ,	depth_divisible_by=self.depth_divisible_by      ,	min_depth=self.min_depth      ,	expand_ratio=self.expand_ratio      ,	output_stride=self.output_stride      ,	first_layer_is_expansion=self.first_layer_is_expansion      ,	finegrained_output=self.finegrained_output      ,	hidden_act=self.hidden_act      ,	tf_padding=self.tf_padding      ,	classifier_dropout_prob=self.classifier_dropout_prob      ,	initializer_range=self.initializer_range      ,	)






	def       _a(self				: int      ,	snake_case				: Optional[int]      ,	snake_case				: Tuple      ,	snake_case				: Optional[int]      ,	snake_case				: List[Any]    ) ->			str:
							_lowercase       :	List[Any]           =   MobileNetVaModel(config=snake_case    )
							model.to(snake_case    )
							model.eval()
							_lowercase       :	Tuple           =   model(snake_case    )
							self.parent.assertEqual(
							    result.last_hidden_state.shape      ,	(
							        self.batch_size,
							        self.last_hidden_size,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )      ,	)
							self.parent.assertEqual(
							    result.pooler_output.shape      ,	(self.batch_size, self.last_hidden_size)      ,	)






	def       _a(self				: Optional[Any]      ,	snake_case				: str      ,	snake_case				: Dict      ,	snake_case				: Dict      ,	snake_case				: Tuple    ) ->			int:
							_lowercase       :	Dict           =   self.num_labels
							_lowercase       :	Tuple           =   MobileNetVaForImageClassification(snake_case    )
							model.to(snake_case    )
							model.eval()
							_lowercase       :	Dict           =   model(snake_case      ,	labels=snake_case    )
							self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.num_labels)    )






	def       _a(self				: Dict      ,	snake_case				: List[str]      ,	snake_case				: int      ,	snake_case				: List[Any]      ,	snake_case				: Union[str, Any]    ) ->			Optional[Any]:
							_lowercase       :	int           =   self.num_labels
							_lowercase       :	Dict           =   MobileNetVaForSemanticSegmentation(snake_case    )
							model.to(snake_case    )
							model.eval()
							_lowercase       :	Dict           =   model(snake_case    )
							self.parent.assertEqual(
							    result.logits.shape      ,	(
							        self.batch_size,
							        self.num_labels,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )      ,	)
							_lowercase       :	int           =   model(snake_case      ,	labels=snake_case    )
							self.parent.assertEqual(
							    result.logits.shape      ,	(
							        self.batch_size,
							        self.num_labels,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )      ,	)






	def       _a(self				: Any    ) ->			int:
							_lowercase       :	Union[str, Any]           =   self.prepare_config_and_inputs()
							_lowercase      ,    _lowercase      ,    _lowercase      ,    _lowercase       :	Union[str, Any]           =   config_and_inputs
							_lowercase       :	Any           =   {"pixel_values": pixel_values}
							return config, inputs_dict




@require_torch
class   __lowercase						(						__snake_case   , __snake_case   , unittest.TestCase       ):
	_A       =   (
	    (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
	    if is_torch_available()
	    else ()
	)
	_A       =   (
	    {
	        "feature-extraction": MobileNetVaModel,
	        "image-classification": MobileNetVaForImageClassification,
	        "image-segmentation": MobileNetVaForSemanticSegmentation,
	    }
	    if is_torch_available()
	    else {}
	)

	_A       =   False
	_A       =   False
	_A       =   False
	_A       =   False






	def       _a(self				: Dict    ) ->			Any:
							_lowercase       :	Any           =   MobileNetVaModelTester(self    )
							_lowercase       :	Any           =   MobileNetVaConfigTester(self      ,	config_class=snake_case      ,	has_text_modality=snake_case    )






	def       _a(self				: Tuple    ) ->			List[Any]:
							self.config_tester.run_common_tests()






	@unittest.skip(reason="MobileNetV2 does not use inputs_embeds"    )
	def       _a(self				: Optional[int]    ) ->			Optional[int]:
							pass






	@unittest.skip(reason="MobileNetV2 does not support input and output embeddings"    )
	def       _a(self				: Optional[int]    ) ->			Tuple:
							pass






	@unittest.skip(reason="MobileNetV2 does not output attentions"    )
	def       _a(self				: List[Any]    ) ->			Dict:
							pass






	def       _a(self				: str    ) ->			List[str]:
							_lowercase      ,    _lowercase       :	Optional[int]           =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_lowercase       :	Dict           =   model_class(snake_case    )
													_lowercase       :	List[str]           =   inspect.signature(model.forward    )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													_lowercase       :	Any           =   [*signature.parameters.keys()]

													_lowercase       :	Any           =   ["pixel_values"]
													self.assertListEqual(arg_names[:1]      ,	snake_case    )






	def       _a(self				: Any    ) ->			Optional[Any]:
							_lowercase       :	List[str]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*snake_case    )






	def       _a(self				: Optional[Any]    ) ->			Tuple:
							def check_hidden_states_output(snake_case				: List[Any]      ,	snake_case				: Optional[int]      ,	snake_case				: Optional[int]    ):
													_lowercase       :	Optional[Any]           =   model_class(snake_case    )
													model.to(snake_case    )
													model.eval()

													with torch.no_grad():
																			_lowercase       :	Dict           =   model(**self._prepare_for_class(snake_case      ,	snake_case    )    )

													_lowercase       :	Optional[Any]           =   outputs.hidden_states

													_lowercase       :	Optional[Any]           =   16
													self.assertEqual(len(snake_case    )      ,	snake_case    )

							_lowercase      ,    _lowercase       :	Union[str, Any]           =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_lowercase       :	Optional[Any]           =   True
													check_hidden_states_output(snake_case      ,	snake_case      ,	snake_case    )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													_lowercase       :	Optional[Any]           =   True

													check_hidden_states_output(snake_case      ,	snake_case      ,	snake_case    )






	def       _a(self				: str    ) ->			List[Any]:
							_lowercase       :	Optional[int]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*snake_case    )






	def       _a(self				: Any    ) ->			Dict:
							_lowercase       :	Optional[Any]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*snake_case    )






	@slow
	def       _a(self				: Optional[Any]    ) ->			Optional[int]:
							for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_lowercase       :	Optional[Any]           =   MobileNetVaModel.from_pretrained(snake_case    )
													self.assertIsNotNone(snake_case    )



def 		UpperCamelCase     (       )   ->			Union[str, Any]:






						'''simple docstring'''

						_lowercase       :	List[str]           =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
						return image




@require_torch
@require_vision
class   __lowercase						(						unittest.TestCase       ):






	@cached_property
	def       _a(self				: List[str]    ) ->			int:
							return (
							    MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"    ) if is_vision_available() else None
							)






	@slow
	def       _a(self				: int    ) ->			str:
							_lowercase       :	List[Any]           =   MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"    ).to(snake_case    )

							_lowercase       :	Dict           =   self.default_image_processor
							_lowercase       :	Tuple           =   prepare_img()
							_lowercase       :	Optional[Any]           =   image_processor(images=snake_case      ,	return_tensors="pt"    ).to(snake_case    )

							# forward pass
							with torch.no_grad():
													_lowercase       :	Union[str, Any]           =   model(**snake_case    )

							# verify the logits
							_lowercase       :	str           =   torch.Size((1, 1001)    )
							self.assertEqual(outputs.logits.shape      ,	snake_case    )

							_lowercase       :	List[Any]           =   torch.tensor([0.24_45, -1.19_93, 0.19_05]    ).to(snake_case    )

							self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,	snake_case      ,	atol=1e-4    )    )






	@slow
	def       _a(self				: Any    ) ->			Dict:
							_lowercase       :	int           =   MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"    )
							_lowercase       :	Dict           =   model.to(snake_case    )

							_lowercase       :	int           =   MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"    )

							_lowercase       :	str           =   prepare_img()
							_lowercase       :	Dict           =   image_processor(images=snake_case      ,	return_tensors="pt"    ).to(snake_case    )

							# forward pass
							with torch.no_grad():
													_lowercase       :	Any           =   model(**snake_case    )
							_lowercase       :	int           =   outputs.logits

							# verify the logits
							_lowercase       :	List[str]           =   torch.Size((1, 21, 65, 65)    )
							self.assertEqual(logits.shape      ,	snake_case    )

							_lowercase       :	str           =   torch.tensor(
							    [
							        [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
							        [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
							        [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
							    ]      ,	device=snake_case      ,	)

							self.assertTrue(torch.allclose(logits[0, :3, :3, :3]      ,	snake_case      ,	atol=1e-4    )    )






from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
							from ..image_utils import load_image


if is_torch_available():
							import torch

							from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING

UpperCamelCase_						:     int	       =							logging.get_logger(__name__)


UpperCamelCase_						:     List[Any]	       =							Dict[str, Any]
UpperCamelCase_						:     Optional[int]	       =							List[Prediction]




@add_end_docstrings(__snake_case       )
class   __lowercase						(						__snake_case       ):






	def __init__(self				: Dict      ,	*snake_case				: List[Any]      ,	**snake_case				: Tuple    ) ->			Any:
							super().__init__(*snake_case      ,	**snake_case    )

							if self.framework == "tf":
													raise ValueError(F"""The {self.__class__} is only available in PyTorch."""    )

							requires_backends(self      ,	"vision"    )
							self.check_model_type(
							    dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items()    )    )






	def       _a(self				: Optional[int]      ,	**snake_case				: Union[str, Any]    ) ->			Any:
							_lowercase       :	List[Any]           =   {}
							if "threshold" in kwargs:
													_lowercase       :	Optional[Any]           =   kwargs["threshold"]
							return {}, {}, postprocess_kwargs






	def __call__(self				: str      ,	*snake_case				: Dict      ,	**snake_case				: Optional[int]    ) ->			Union[Predictions, List[Prediction]]:
							return super().__call__(*snake_case      ,	**snake_case    )






	def       _a(self				: Tuple      ,	snake_case				: str    ) ->			Dict:
							_lowercase       :	List[str]           =   load_image(snake_case    )
							_lowercase       :	str           =   torch.IntTensor([[image.height, image.width]]    )
							_lowercase       :	int           =   self.image_processor(images=[image]      ,	return_tensors="pt"    )
							if self.tokenizer is not None:
													_lowercase       :	List[Any]           =   self.tokenizer(text=inputs["words"]      ,	boxes=inputs["boxes"]      ,	return_tensors="pt"    )
							_lowercase       :	str           =   target_size
							return inputs






	def       _a(self				: List[Any]      ,	snake_case				: Any    ) ->			str:
							_lowercase       :	Dict           =   model_inputs.pop("target_size"    )
							_lowercase       :	str           =   self.model(**snake_case    )
							_lowercase       :	Union[str, Any]           =   outputs.__class__({"target_size": target_size, **outputs}    )
							if self.tokenizer is not None:
													_lowercase       :	str           =   model_inputs["bbox"]
							return model_outputs






	def       _a(self				: str      ,	snake_case				: Tuple      ,	snake_case				: Dict=0.9    ) ->			List[str]:
							_lowercase       :	Optional[Any]           =   model_outputs["target_size"]
							if self.tokenizer is not None:
													# This is a LayoutLMForTokenClassification variant.
													# The OCR got the boxes and the model classified the words.
													_lowercase      ,    _lowercase       :	str           =   target_size[0].tolist()

													def unnormalize(snake_case				: str    ):
																			return self._get_bounding_box(
																			    torch.Tensor(
																			        [
																			            (width * bbox[0] / 1000),
																			            (height * bbox[1] / 1000),
																			            (width * bbox[2] / 1000),
																			            (height * bbox[3] / 1000),
																			        ]    )    )

													_lowercase      ,    _lowercase       :	Any           =   model_outputs["logits"].squeeze(0    ).softmax(dim=-1    ).max(dim=-1    )
													_lowercase       :	Optional[Any]           =   [self.model.config.idalabel[prediction] for prediction in classes.tolist()]
													_lowercase       :	Dict           =   [unnormalize(snake_case    ) for bbox in model_outputs["bbox"].squeeze(0    )]
													_lowercase       :	Tuple           =   ["score", "label", "box"]
													_lowercase       :	int           =   [dict(zip(snake_case      ,	snake_case    )    ) for vals in zip(scores.tolist()      ,	snake_case      ,	snake_case    ) if vals[0] > threshold]
							else:
													# This is a regular ForObjectDetectionModel
													_lowercase       :	str           =   self.image_processor.post_process_object_detection(snake_case      ,	snake_case      ,	snake_case    )
													_lowercase       :	List[Any]           =   raw_annotations[0]
													_lowercase       :	str           =   raw_annotation["scores"]
													_lowercase       :	Optional[int]           =   raw_annotation["labels"]
													_lowercase       :	Dict           =   raw_annotation["boxes"]

													_lowercase       :	int           =   scores.tolist()
													_lowercase       :	List[str]           =   [self.model.config.idalabel[label.item()] for label in labels]
													_lowercase       :	List[Any]           =   [self._get_bounding_box(snake_case    ) for box in boxes]

													# {"scores": [...], ...} --> [{"score":x, ...}, ...]
													_lowercase       :	Union[str, Any]           =   ["score", "label", "box"]
													_lowercase       :	Tuple           =   [
													    dict(zip(snake_case      ,	snake_case    )    )
													    for vals in zip(raw_annotation["scores"]      ,	raw_annotation["labels"]      ,	raw_annotation["boxes"]    )
													]

							return annotation






	def       _a(self				: int      ,	snake_case				: "torch.Tensor"    ) ->			Dict[str, int]:
							if self.framework != "pt":
													raise ValueError("The ObjectDetectionPipeline is only available in PyTorch."    )
							_lowercase      ,    _lowercase      ,    _lowercase      ,    _lowercase       :	Optional[int]           =   box.int().tolist()
							_lowercase       :	Tuple           =   {
							    "xmin": xmin,
							    "ymin": ymin,
							    "xmax": xmax,
							    "ymax": ymax,
							}
							return bbox




