

'''simple docstring'''




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   _SCREAMING_SNAKE_CASE   :



 def __init__(   self		:   Any			,				a__		:   Optional[Any]			,				a__		:   Dict=13			,				a__		:   Union[str, Any]=32			,				a__		:   Dict=3			,				a__		:   Any=4			,				a__		:   Any=[10, 20, 30, 40]			,				a__		:   Optional[int]=[2, 2, 3, 2]			,				a__		:   Tuple=True			,				a__		:   str=True			,				a__		:   str=37			,				a__		:   Optional[int]="gelu"			,				a__		:   Dict=10			,				a__		:   Union[str, Any]=0.02			,				a__		:   List[Any]=["stage2", "stage3", "stage4"]			,				a__		:   Union[str, Any]=[2, 3, 4]			,				a__		:   List[Any]=None			,				):
      __magic_name__						       =    parent
      __magic_name__						       =    batch_size
      __magic_name__						       =    image_size
      __magic_name__						       =    num_channels
      __magic_name__						       =    num_stages
      __magic_name__						       =    hidden_sizes
      __magic_name__						       =    depths
      __magic_name__						       =    is_training
      __magic_name__						       =    use_labels
      __magic_name__						       =    intermediate_size
      __magic_name__						       =    hidden_act
      __magic_name__						       =    num_labels
      __magic_name__						       =    initializer_range
      __magic_name__						       =    out_features
      __magic_name__						       =    out_indices
      __magic_name__						       =    scope



 def 			snake_case__  (   self		:   str      ):
      __magic_name__						       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

      __magic_name__						       =    self.get_config()
      return config, pixel_values, labels



 def 			snake_case__  (   self		:   Tuple      ):
      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=a__			,				initializer_range=self.initializer_range			,				out_features=self.out_features			,				out_indices=self.out_indices			,				num_labels=self.num_labels			,				)



 def 			snake_case__  (   self		:   Dict			,				a__		:   Optional[int]			,				a__		:   Any			,				a__		:   Tuple      ):
      __magic_name__						       =    ConvNextModel(config=a__      )
      model.to(a__      )
      model.eval()
      __magic_name__						       =    model(a__      )
      # 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 			snake_case__  (   self		:   int			,				a__		:   Union[str, Any]			,				a__		:   List[Any]			,				a__		:   Dict      ):
      __magic_name__						       =    ConvNextForImageClassification(a__      )
      model.to(a__      )
      model.eval()
      __magic_name__						       =    model(a__			,				labels=a__      )
      self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.num_labels)      )



 def 			snake_case__  (   self		:   Optional[Any]			,				a__		:   Dict			,				a__		:   List[str]			,				a__		:   Union[str, Any]      ):
      __magic_name__						       =    ConvNextBackbone(config=a__      )
      model.to(a__      )
      model.eval()
      __magic_name__						       =    model(a__      )

      # 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
      __magic_name__						       =    None
      __magic_name__						       =    ConvNextBackbone(config=a__      )
      model.to(a__      )
      model.eval()
      __magic_name__						       =    model(a__      )

      # 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 			snake_case__  (   self		:   int      ):
      __magic_name__						       =    self.prepare_config_and_inputs()
      __magic_name__       ,  __magic_name__       ,  __magic_name__						       =    config_and_inputs
      __magic_name__						       =    {'''pixel_values''': pixel_values}
      return config, inputs_dict






@require_torch
class   _SCREAMING_SNAKE_CASE   (   __a		,__a		,unittest.TestCase     ):
 __SCREAMING_SNAKE_CASE					:Dict      	=					(
     (
         ConvNextModel,
         ConvNextForImageClassification,
         ConvNextBackbone,
     )
     if is_torch_available()
     else ()
 )
 __SCREAMING_SNAKE_CASE					:Union[str, Any]      	=					(
     {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
     if is_torch_available()
     else {}
 )

 __SCREAMING_SNAKE_CASE					:Optional[int]      	=					True
 __SCREAMING_SNAKE_CASE					:str      	=					False
 __SCREAMING_SNAKE_CASE					:List[Any]      	=					False
 __SCREAMING_SNAKE_CASE					:Union[str, Any]      	=					False
 __SCREAMING_SNAKE_CASE					:int      	=					False



 def 			snake_case__  (   self		:   int      ):
      __magic_name__						       =    ConvNextModelTester(self      )
      __magic_name__						       =    ConfigTester(self			,				config_class=a__			,				has_text_modality=a__			,				hidden_size=37      )



 def 			snake_case__  (   self		:   Optional[int]      ):
      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 			snake_case__  (   self		:   str      ):
      return



 @unittest.skip(reason='''ConvNext does not use inputs_embeds'''      )
 def 			snake_case__  (   self		:   Tuple      ):
      pass



 @unittest.skip(reason='''ConvNext does not support input and output embeddings'''      )
 def 			snake_case__  (   self		:   Dict      ):
      pass



 @unittest.skip(reason='''ConvNext does not use feedforward chunking'''      )
 def 			snake_case__  (   self		:   Union[str, Any]      ):
      pass



 def 			snake_case__  (   self		:   Any      ):
      __magic_name__       ,  __magic_name__						       =    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           __magic_name__						       =    model_class(a__      )
           __magic_name__						       =    inspect.signature(model.forward      )
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           __magic_name__						       =    [*signature.parameters.keys()]

           __magic_name__						       =    ['''pixel_values''']
           self.assertListEqual(arg_names[:1]			,				a__      )



 def 			snake_case__  (   self		:   List[str]      ):
      __magic_name__						       =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*a__      )



 def 			snake_case__  (   self		:   Optional[int]      ):
      __magic_name__						       =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_backbone(*a__      )



 def 			snake_case__  (   self		:   Optional[int]      ):
      def check_hidden_states_output(a__		:   Optional[int]			,				a__		:   List[str]			,				a__		:   Optional[Any]      ):
           __magic_name__						       =    model_class(a__      )
           model.to(a__      )
           model.eval()

           with torch.no_grad():
                __magic_name__						       =    model(**self._prepare_for_class(a__			,				a__      )      )

           __magic_name__						       =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           __magic_name__						       =    self.model_tester.num_stages
           self.assertEqual(len(a__      )			,				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]			,				)

      __magic_name__       ,  __magic_name__						       =    self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           __magic_name__						       =    True
           check_hidden_states_output(a__			,				a__			,				a__      )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           __magic_name__						       =    True

           check_hidden_states_output(a__			,				a__			,				a__      )



 def 			snake_case__  (   self		:   Any      ):
      __magic_name__						       =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*a__      )



 @slow
 def 			snake_case__  (   self		:   Union[str, Any]      ):
      for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __magic_name__						       =    ConvNextModel.from_pretrained(a__      )
           self.assertIsNotNone(a__      )




def 						UpperCamelCase	(			)				->     Optional[Any]:






     '''simple docstring'''
     __magic_name__						       =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
     return image






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



 @cached_property
 def 			snake_case__  (   self		:   Any      ):
      return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''      ) if is_vision_available() else None



 @slow
 def 			snake_case__  (   self		:   Optional[int]      ):
      __magic_name__						       =    ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''      ).to(a__      )

      __magic_name__						       =    self.default_image_processor
      __magic_name__						       =    prepare_img()
      __magic_name__						       =    image_processor(images=a__			,				return_tensors='''pt'''      ).to(a__      )

      # forward pass
      with torch.no_grad():
           __magic_name__						       =    model(**a__      )

      # verify the logits
      __magic_name__						       =    torch.Size((1, 1000)      )
      self.assertEqual(outputs.logits.shape			,				a__      )

      __magic_name__						       =    torch.tensor([-0.0_260, -0.4_739, 0.1_911]      ).to(a__      )

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






@require_torch
class   _SCREAMING_SNAKE_CASE   (   unittest.TestCase		,__a     ):
 __SCREAMING_SNAKE_CASE					:List[Any]      	=					(ConvNextBackbone,) if is_torch_available() else ()
 __SCREAMING_SNAKE_CASE					:List[str]      	=					ConvNextConfig

 __SCREAMING_SNAKE_CASE					:int      	=					False



 def 			snake_case__  (   self		:   List[str]      ):
      __magic_name__						       =    ConvNextModelTester(self      )









'''simple docstring'''




import sys
from typing import Tuple

import numpy as np
import torch
from PIL import Image
from torch import nn

from transformers.image_utils import PILImageResampling
from utils import img_tensorize






class   _SCREAMING_SNAKE_CASE   :



 def __init__(   self		:   Optional[Any]			,				a__		:   Any			,				a__		:   Tuple=sys.maxsize      ):
      __magic_name__						       =    '''bilinear'''
      __magic_name__						       =    max_size
      __magic_name__						       =    short_edge_length



 def __call__(   self		:   Tuple			,				a__		:   List[str]      ):
      __magic_name__						       =    []
      for img in imgs:
           __magic_name__       ,  __magic_name__						       =    img.shape[:2]
           # later: provide list and randomly choose index for resize
           __magic_name__						       =    np.random.randint(self.short_edge_length[0]			,				self.short_edge_length[1] + 1      )
           if size == 0:
                return img
           __magic_name__						       =    size * 1.0 / min(a__			,				a__      )
           if h < w:
                __magic_name__       ,  __magic_name__						       =    size, scale * w
           else:
                __magic_name__       ,  __magic_name__						       =    scale * h, size
           if max(a__			,				a__      ) > self.max_size:
                __magic_name__						       =    self.max_size * 1.0 / max(a__			,				a__      )
                __magic_name__						       =    newh * scale
                __magic_name__						       =    neww * scale
           __magic_name__						       =    int(neww + 0.5      )
           __magic_name__						       =    int(newh + 0.5      )

           if img.dtype == np.uinta:
                __magic_name__						       =    Image.fromarray(a__      )
                __magic_name__						       =    pil_image.resize((neww, newh)			,				PILImageResampling.BILINEAR      )
                __magic_name__						       =    np.asarray(a__      )
           else:
                __magic_name__						       =    img.permute(2			,				0			,				1      ).unsqueeze(0      )  # 3, 0, 1)  # hw(c) -> nchw
                __magic_name__						       =    nn.functional.interpolate(
                    a__			,				(newh, neww)			,				mode=self.interp_method			,				align_corners=a__      ).squeeze(0      )
           img_augs.append(a__      )

      return img_augs






class   _SCREAMING_SNAKE_CASE   :



 def __init__(   self		:   List[Any]			,				a__		:   Tuple      ):
      __magic_name__						       =    ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST]			,				cfg.INPUT.MAX_SIZE_TEST      )
      __magic_name__						       =    cfg.INPUT.FORMAT
      __magic_name__						       =    cfg.SIZE_DIVISIBILITY
      __magic_name__						       =    cfg.PAD_VALUE
      __magic_name__						       =    cfg.INPUT.MAX_SIZE_TEST
      __magic_name__						       =    cfg.MODEL.DEVICE
      __magic_name__						       =    torch.tensor(cfg.MODEL.PIXEL_STD      ).to(self.device      ).view(len(cfg.MODEL.PIXEL_STD      )			,				1			,				1      )
      __magic_name__						       =    torch.tensor(cfg.MODEL.PIXEL_MEAN      ).to(self.device      ).view(len(cfg.MODEL.PIXEL_STD      )			,				1			,				1      )
      __magic_name__						       =    lambda a__      : (x - self.pixel_mean) / self.pixel_std



 def 			snake_case__  (   self		:   Union[str, Any]			,				a__		:   Dict      ):
      __magic_name__						       =    tuple(max(a__      ) for s in zip(*[img.shape for img in images]      )      )
      __magic_name__						       =    [im.shape[-2:] for im in images]
      __magic_name__						       =    [
          nn.functional.pad(
              a__			,				[0, max_size[-1] - size[1], 0, max_size[-2] - size[0]]			,				value=self.pad_value			,				)
          for size, im in zip(a__			,				a__      )
      ]

      return torch.stack(a__      ), torch.tensor(a__      )



 def __call__(   self		:   Dict			,				a__		:   Dict			,				a__		:   List[str]=False      ):
      with torch.no_grad():
           if not isinstance(a__			,				a__      ):
                __magic_name__						       =    [images]
           if single_image:
                assert len(a__      ) == 1
           for i in range(len(a__      )      ):
                if isinstance(images[i]			,				torch.Tensor      ):
                     images.insert(a__			,				images.pop(a__      ).to(self.device      ).float()      )
                elif not isinstance(images[i]			,				torch.Tensor      ):
                     images.insert(
                         a__			,				torch.as_tensor(img_tensorize(images.pop(a__      )			,				input_format=self.input_format      )      )
                         .to(self.device      )
                         .float()			,				)
            # resize smallest edge
           __magic_name__						       =    torch.tensor([im.shape[:2] for im in images]      )
           __magic_name__						       =    self.aug(a__      )
           # transpose images and convert to torch tensors
           # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
           # now normalize before pad to avoid useless arithmetic
           __magic_name__						       =    [self.normalizer(a__      ) for x in images]
           # now pad them to do the following operations
           __magic_name__       ,  __magic_name__						       =    self.pad(a__      )
           # Normalize

           if self.size_divisibility > 0:
                raise NotImplementedError()
           # pad
           __magic_name__						       =    torch.true_divide(a__			,				a__      )
           if single_image:
                return images[0], sizes[0], scales_yx[0]
           else:
                return images, sizes, scales_yx




def 						UpperCamelCase	(			a		,						a			)				->     List[Any]:






     '''simple docstring'''
     boxes[:, 0::2] *= scale_yx[:, 1]
     boxes[:, 1::2] *= scale_yx[:, 0]
     return boxes




def 						UpperCamelCase	(			a		,						a			)				->     Any:






     '''simple docstring'''
     assert torch.isfinite(a			).all(), "Box tensor contains infinite or NaN!"
     __magic_name__       ,  __magic_name__						       =    box_size
     tensor[:, 0].clamp_(min=0		,						max=a			)
     tensor[:, 1].clamp_(min=0		,						max=a			)
     tensor[:, 2].clamp_(min=0		,						max=a			)
     tensor[:, 3].clamp_(min=0		,						max=a			)






