






import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
			from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor




class 							snake_case_       :

						"""simple docstring"""



						def __init__(self:					Tuple ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					str=13 ,					__UpperCAmelCase:					List[Any]=32 ,					__UpperCAmelCase:					Optional[int]=3 ,					__UpperCAmelCase:					Any=4 ,					__UpperCAmelCase:					Tuple=[10, 20, 30, 40] ,					__UpperCAmelCase:					Any=[2, 2, 3, 2] ,					__UpperCAmelCase:					Optional[int]=True ,					__UpperCAmelCase:					List[str]=True ,					__UpperCAmelCase:					Tuple=37 ,					__UpperCAmelCase:					Dict="gelu" ,					__UpperCAmelCase:					Any=10 ,					__UpperCAmelCase:					Tuple=0.02 ,					__UpperCAmelCase:					int=["stage2", "stage3", "stage4"] ,					__UpperCAmelCase:					Tuple=[2, 3, 4] ,					__UpperCAmelCase:					List[Any]=None ,					)    ->     Optional[int]:




											'''simple docstring'''



											__a					:						List[str]      =					parent
											__a					:						Union[str, Any]      =					batch_size
											__a					:						Optional[int]      =					image_size
											__a					:						List[str]      =					num_channels
											__a					:						int      =					num_stages
											__a					:						List[Any]      =					hidden_sizes
											__a					:						List[Any]      =					depths
											__a					:						List[Any]      =					is_training
											__a					:						Tuple      =					use_labels
											__a					:						List[str]      =					intermediate_size
											__a					:						int      =					hidden_act
											__a					:						Union[str, Any]      =					num_labels
											__a					:						str      =					initializer_range
											__a					:						List[Any]      =					out_features
											__a					:						Union[str, Any]      =					out_indices
											__a					:						List[Any]      =					scope



						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     Tuple:




											'''simple docstring'''



											__a					:						str      =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

											__a					:						Any      =					None
											if self.use_labels:
																__a					:						Any      =					ids_tensor([self.batch_size] ,					self.num_labels   )

											__a					:						str      =					self.get_config()
											return config, pixel_values, labels



						def        UpperCAmelCase__					(self:					int   )    ->     Any:




											'''simple docstring'''



											return ConvNextConfig(
											    num_channels=self.num_channels ,					hidden_sizes=self.hidden_sizes ,					depths=self.depths ,					num_stages=self.num_stages ,					hidden_act=self.hidden_act ,					is_decoder=__UpperCAmelCase ,					initializer_range=self.initializer_range ,					out_features=self.out_features ,					out_indices=self.out_indices ,					num_labels=self.num_labels ,					)



						def        UpperCAmelCase__					(self:					List[Any] ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					Optional[int]   )    ->     int:




											'''simple docstring'''



											__a					:						List[Any]      =					ConvNextModel(config=__UpperCAmelCase   )
											model.to(__UpperCAmelCase   )
											model.eval()
											__a					:						int      =					model(__UpperCAmelCase   )
											# expected last hidden states: B, C, H // 32, W // 32
											self.parent.assertEqual(
											    result.last_hidden_state.shape ,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,					)



						def        UpperCAmelCase__					(self:					Dict ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					Any   )    ->     int:




											'''simple docstring'''



											__a					:						List[str]      =					ConvNextForImageClassification(__UpperCAmelCase   )
											model.to(__UpperCAmelCase   )
											model.eval()
											__a					:						Optional[int]      =					model(__UpperCAmelCase ,					labels=__UpperCAmelCase   )
											self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)   )



						def        UpperCAmelCase__					(self:					str ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					Tuple ,					__UpperCAmelCase:					int   )    ->     Tuple:




											'''simple docstring'''



											__a					:						Tuple      =					ConvNextBackbone(config=__UpperCAmelCase   )
											model.to(__UpperCAmelCase   )
											model.eval()
											__a					:						List[Any]      =					model(__UpperCAmelCase   )

											# verify hidden states
											self.parent.assertEqual(len(result.feature_maps   ) ,					len(config.out_features   )   )
											self.parent.assertListEqual(list(result.feature_maps[0].shape   ) ,					[self.batch_size, self.hidden_sizes[1], 4, 4]   )

											# verify channels
											self.parent.assertEqual(len(model.channels   ) ,					len(config.out_features   )   )
											self.parent.assertListEqual(model.channels ,					config.hidden_sizes[1:]   )

											# verify backbone works with out_features=None
											__a					:						List[str]      =					None
											__a					:						List[Any]      =					ConvNextBackbone(config=__UpperCAmelCase   )
											model.to(__UpperCAmelCase   )
											model.eval()
											__a					:						Optional[Any]      =					model(__UpperCAmelCase   )

											# verify feature maps
											self.parent.assertEqual(len(result.feature_maps   ) ,					1   )
											self.parent.assertListEqual(list(result.feature_maps[0].shape   ) ,					[self.batch_size, self.hidden_sizes[-1], 1, 1]   )

											# verify channels
											self.parent.assertEqual(len(model.channels   ) ,					1   )
											self.parent.assertListEqual(model.channels ,					[config.hidden_sizes[-1]]   )



						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     Dict:




											'''simple docstring'''



											__a					:						List[Any]      =					self.prepare_config_and_inputs()
											__a      ,			__a      ,			__a					:						List[Any]      =					config_and_inputs
											__a					:						Optional[int]      =					{"pixel_values": pixel_values}
											return config, inputs_dict




@require_torch
class 							snake_case_       (    __UpperCamelCase		,							__UpperCamelCase		,							unittest.TestCase      ):

						"""simple docstring"""



						snake_case__        =      (
						    (
						        ConvNextModel,
						        ConvNextForImageClassification,
						        ConvNextBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						snake_case__        =      (
						    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
						    if is_torch_available()
						    else {}
						)

						snake_case__        =      True
						snake_case__        =      False
						snake_case__        =      False
						snake_case__        =      False
						snake_case__        =      False



						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						Optional[Any]      =					ConvNextModelTester(self   )
											__a					:						str      =					ConfigTester(self ,					config_class=__UpperCAmelCase ,					has_text_modality=__UpperCAmelCase ,					hidden_size=37   )



						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     Dict:




											'''simple docstring'''



											self.create_and_test_config_common_properties()
											self.config_tester.create_and_test_config_to_json_string()
											self.config_tester.create_and_test_config_to_json_file()
											self.config_tester.create_and_test_config_from_and_save_pretrained()
											self.config_tester.create_and_test_config_with_num_labels()
											self.config_tester.check_config_can_be_init_without_params()
											self.config_tester.check_config_arguments_init()



						def        UpperCAmelCase__					(self:					str   )    ->     int:




											'''simple docstring'''



											return



						@unittest.skip(reason="ConvNext does not use inputs_embeds"   )
						def        UpperCAmelCase__					(self:					List[Any]   )    ->     Optional[int]:




											'''simple docstring'''



											pass



						@unittest.skip(reason="ConvNext does not support input and output embeddings"   )
						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     Dict:




											'''simple docstring'''



											pass



						@unittest.skip(reason="ConvNext does not use feedforward chunking"   )
						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     List[str]:




											'''simple docstring'''



											pass



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




											'''simple docstring'''



											__a      ,			__a					:						Tuple      =					self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__a					:						List[Any]      =					model_class(__UpperCAmelCase   )
																__a					:						Tuple      =					inspect.signature(model.forward   )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																__a					:						Optional[int]      =					[*signature.parameters.keys()]

																__a					:						Any      =					["pixel_values"]
																self.assertListEqual(arg_names[:1] ,					__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     Tuple:




											'''simple docstring'''



											__a					:						Optional[Any]      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					str   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						Tuple      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_backbone(*__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Any   )    ->     Any:




											'''simple docstring'''



											def check_hidden_states_output(__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					Any   ):
																__a					:						Any      =					model_class(__UpperCAmelCase   )
																model.to(__UpperCAmelCase   )
																model.eval()

																with torch.no_grad():
																					__a					:						Tuple      =					model(**self._prepare_for_class(__UpperCAmelCase ,					__UpperCAmelCase   )   )

																__a					:						Dict      =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																__a					:						List[str]      =					self.model_tester.num_stages
																self.assertEqual(len(__UpperCAmelCase   ) ,					expected_num_stages + 1   )

																# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
																self.assertListEqual(
																    list(hidden_states[0].shape[-2:]   ) ,					[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,					)

											__a      ,			__a					:						List[str]      =					self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__a					:						Optional[int]      =					True
																check_hidden_states_output(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase   )

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

																check_hidden_states_output(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					List[Any]   )    ->     List[str]:




											'''simple docstring'''



											__a					:						Dict      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase   )



						@slow
						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     Union[str, Any]:




											'''simple docstring'''



											for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__a					:						int      =					ConvNextModel.from_pretrained(__UpperCAmelCase   )
																self.assertIsNotNone(__UpperCAmelCase   )







def     a_   ()				->						Any:



					"""simple docstring"""
					__a					:						List[Any]      =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
					return image




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

						"""simple docstring"""



						@cached_property
						def        UpperCAmelCase__					(self:					Union[str, Any]   )    ->     Dict:




											'''simple docstring'''



											return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"   ) if is_vision_available() else None



						@slow
						def        UpperCAmelCase__					(self:					Any   )    ->     int:




											'''simple docstring'''



											__a					:						Any      =					ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"   ).to(__UpperCAmelCase   )

											__a					:						Optional[Any]      =					self.default_image_processor
											__a					:						Optional[Any]      =					prepare_img()
											__a					:						Optional[Any]      =					image_processor(images=__UpperCAmelCase ,					return_tensors="pt"   ).to(__UpperCAmelCase   )

											# forward pass
											with torch.no_grad():
																__a					:						List[str]      =					model(**__UpperCAmelCase   )

											# verify the logits
											__a					:						Any      =					torch.Size((1, 1000)   )
											self.assertEqual(outputs.logits.shape ,					__UpperCAmelCase   )

											__a					:						List[Any]      =					torch.tensor([-0.02_60, -0.47_39, 0.19_11]   ).to(__UpperCAmelCase   )

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




@require_torch
class 							snake_case_       (    unittest.TestCase		,							__UpperCamelCase      ):

						"""simple docstring"""



						snake_case__        =      (ConvNextBackbone,) if is_torch_available() else ()
						snake_case__        =      ConvNextConfig

						snake_case__        =      False



						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     str:




											'''simple docstring'''



											__a					:						List[Any]      =					ConvNextModelTester(self   )













from collections import defaultdict
from typing import Optional

from ..image_utils import load_image
from ..utils import (
    add_end_docstrings,
    is_torch_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_torch_available():
			import torch

			from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING

UpperCAmelCase__      			=						logging.get_logger(__name__)




@add_end_docstrings(__UpperCamelCase      )
class 							snake_case_       (    __UpperCamelCase      ):

						"""simple docstring"""



						def __init__(self:					int ,					**__UpperCAmelCase:					Optional[Any]   )    ->     str:




											'''simple docstring'''



											super().__init__(**__UpperCAmelCase   )
											requires_backends(self ,					"vision"   )
											requires_backends(self ,					"torch"   )

											if self.framework != "pt":
																raise ValueError(f'The {self.__class__} is only available in PyTorch.'   )

											self.check_model_type(__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Optional[int] ,					**__UpperCAmelCase:					Optional[int]   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						Any      =					{}
											__a					:						Union[str, Any]      =					{}
											__a					:						List[str]      =					{}
											# preprocess args
											if "points_per_batch" in kwargs:
																__a					:						Dict      =					kwargs["points_per_batch"]
											if "points_per_crop" in kwargs:
																__a					:						Tuple      =					kwargs["points_per_crop"]
											if "crops_n_layers" in kwargs:
																__a					:						Dict      =					kwargs["crops_n_layers"]
											if "crop_overlap_ratio" in kwargs:
																__a					:						int      =					kwargs["crop_overlap_ratio"]
											if "crop_n_points_downscale_factor" in kwargs:
																__a					:						Optional[int]      =					kwargs["crop_n_points_downscale_factor"]
											# postprocess args
											if "pred_iou_thresh" in kwargs:
																__a					:						int      =					kwargs["pred_iou_thresh"]
											if "stability_score_offset" in kwargs:
																__a					:						Any      =					kwargs["stability_score_offset"]
											if "mask_threshold" in kwargs:
																__a					:						int      =					kwargs["mask_threshold"]
											if "stability_score_thresh" in kwargs:
																__a					:						Any      =					kwargs["stability_score_thresh"]
											if "crops_nms_thresh" in kwargs:
																__a					:						int      =					kwargs["crops_nms_thresh"]
											if "output_rle_mask" in kwargs:
																__a					:						Optional[Any]      =					kwargs["output_rle_mask"]
											if "output_bboxes_mask" in kwargs:
																__a					:						Optional[Any]      =					kwargs["output_bboxes_mask"]
											return preprocess_kwargs, forward_params, postprocess_kwargs



						def __call__(self:					Union[str, Any] ,					__UpperCAmelCase:					str ,					*__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					str=None ,					__UpperCAmelCase:					Union[str, Any]=None ,					**__UpperCAmelCase:					Optional[int]   )    ->     Tuple:




											'''simple docstring'''



											return super().__call__(__UpperCAmelCase ,					*__UpperCAmelCase ,					num_workers=__UpperCAmelCase ,					batch_size=__UpperCAmelCase ,					**__UpperCAmelCase   )



						def        UpperCAmelCase__					(self:					Optional[Any] ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					int=64 ,					__UpperCAmelCase:					int = 0 ,					__UpperCAmelCase:					float = 512 / 1500 ,					__UpperCAmelCase:					Optional[int] = 32 ,					__UpperCAmelCase:					Optional[int] = 1 ,					)    ->     str:




											'''simple docstring'''



											__a					:						Union[str, Any]      =					load_image(__UpperCAmelCase   )
											__a					:						List[str]      =					self.image_processor.size["longest_edge"]
											__a      ,			__a      ,			__a      ,			__a					:						int      =					self.image_processor.generate_crop_boxes(
											    __UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase   )
											__a					:						Union[str, Any]      =					self.image_processor(images=__UpperCAmelCase ,					return_tensors="pt"   )

											with self.device_placement():
																if self.framework == "pt":
																					__a					:						str      =					self.get_inference_context()
																					with inference_context():
																										__a					:						int      =					self._ensure_tensor_on_device(__UpperCAmelCase ,					device=self.device   )
																										__a					:						Union[str, Any]      =					self.model.get_image_embeddings(model_inputs.pop("pixel_values"   )   )
																										__a					:						Optional[Any]      =					image_embeddings

											__a					:						Dict      =					grid_points.shape[1]
											__a					:						Any      =					points_per_batch if points_per_batch is not None else n_points

											if points_per_batch <= 0:
																raise ValueError(
																    "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
																    "To return all points at once, set points_per_batch to None"   )

											for i in range(0 ,					__UpperCAmelCase ,					__UpperCAmelCase   ):
																__a					:						List[str]      =					grid_points[:, i : i + points_per_batch, :, :]
																__a					:						str      =					input_labels[:, i : i + points_per_batch]
																__a					:						str      =					i == n_points - points_per_batch
																yield {
																    "input_points": batched_points,
																    "input_labels": labels,
																    "input_boxes": crop_boxes,
																    "is_last": is_last,
																    **model_inputs,
																}



						def        UpperCAmelCase__					(self:					Any ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					Any=0.88 ,					__UpperCAmelCase:					Optional[int]=0.95 ,					__UpperCAmelCase:					Optional[int]=0 ,					__UpperCAmelCase:					int=1 ,					)    ->     List[str]:




											'''simple docstring'''



											__a					:						List[Any]      =					model_inputs.pop("input_boxes"   )
											__a					:						Optional[Any]      =					model_inputs.pop("is_last"   )
											__a					:						Dict      =					model_inputs.pop("original_sizes"   ).tolist()
											__a					:						int      =					model_inputs.pop("reshaped_input_sizes"   ).tolist()

											__a					:						Optional[Any]      =					self.model(**__UpperCAmelCase   )

											# post processing happens here in order to avoid CPU GPU copies of ALL the masks
											__a					:						Union[str, Any]      =					model_outputs["pred_masks"]
											__a					:						Optional[Any]      =					self.image_processor.post_process_masks(
											    __UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					binarize=__UpperCAmelCase   )
											__a					:						Optional[Any]      =					model_outputs["iou_scores"]
											__a      ,			__a      ,			__a					:						Dict      =					self.image_processor.filter_masks(
											    masks[0] ,					iou_scores[0] ,					original_sizes[0] ,					input_boxes[0] ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					)
											return {
											    "masks": masks,
											    "is_last": is_last,
											    "boxes": boxes,
											    "iou_scores": iou_scores,
											}



						def        UpperCAmelCase__					(self:					Any ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					List[str]=False ,					__UpperCAmelCase:					int=False ,					__UpperCAmelCase:					List[str]=0.7 ,					)    ->     Dict:




											'''simple docstring'''



											__a					:						Dict      =					[]
											__a					:						Optional[Any]      =					[]
											__a					:						Optional[Any]      =					[]
											for model_output in model_outputs:
																all_scores.append(model_output.pop("iou_scores"   )   )
																all_masks.extend(model_output.pop("masks"   )   )
																all_boxes.append(model_output.pop("boxes"   )   )

											__a					:						Any      =					torch.cat(__UpperCAmelCase   )
											__a					:						Union[str, Any]      =					torch.cat(__UpperCAmelCase   )
											__a      ,			__a      ,			__a      ,			__a					:						Tuple      =					self.image_processor.post_process_for_mask_generation(
											    __UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase   )

											__a					:						Optional[int]      =					defaultdict(__UpperCAmelCase   )
											for output in model_outputs:
																for k, v in output.items():
																					extra[k].append(__UpperCAmelCase   )

											__a					:						int      =					{}
											if output_rle_mask:
																__a					:						Optional[int]      =					rle_mask

											if output_bboxes_mask:
																__a					:						List[str]      =					bounding_boxes

											return {"masks": output_masks, "scores": iou_scores, **optional, **extra}





