




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






       def __init__(							self,		lowerCAmelCase,		lowerCAmelCase=13,		lowerCAmelCase=32,		lowerCAmelCase=3,		lowerCAmelCase=4,		lowerCAmelCase=[10, 20, 30, 40],		lowerCAmelCase=[2, 2, 3, 2],		lowerCAmelCase=True,		lowerCAmelCase=True,		lowerCAmelCase=37,		lowerCAmelCase="gelu",		lowerCAmelCase=10,		lowerCAmelCase=0.0_2,		lowerCAmelCase=["stage2", "stage3", "stage4"],		lowerCAmelCase=[2, 3, 4],		lowerCAmelCase=None,		):



              """simple docstring"""







              lowerCamelCase_							=parent
              lowerCamelCase_							=batch_size
              lowerCamelCase_							=image_size
              lowerCamelCase_							=num_channels
              lowerCamelCase_							=num_stages
              lowerCamelCase_							=hidden_sizes
              lowerCamelCase_							=depths
              lowerCamelCase_							=is_training
              lowerCamelCase_							=use_labels
              lowerCamelCase_							=intermediate_size
              lowerCamelCase_							=hidden_act
              lowerCamelCase_							=num_labels
              lowerCamelCase_							=initializer_range
              lowerCamelCase_							=out_features
              lowerCamelCase_							=out_indices
              lowerCamelCase_							=scope






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

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






       def      lowercase__     (							self  ):



              """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=a__,		initializer_range=self.initializer_range,		out_features=self.out_features,		out_indices=self.out_indices,		num_labels=self.num_labels,		)






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=ConvNextModel(config=a__  )
              model.to(a__  )
              model.eval()
              lowerCamelCase_							=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      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=ConvNextForImageClassification(a__  )
              model.to(a__  )
              model.eval()
              lowerCamelCase_							=model(a__,		labels=a__  )
              self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_labels)  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=ConvNextBackbone(config=a__  )
              model.to(a__  )
              model.eval()
              lowerCamelCase_							=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
              lowerCamelCase_							=None
              lowerCamelCase_							=ConvNextBackbone(config=a__  )
              model.to(a__  )
              model.eval()
              lowerCamelCase_							=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      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.prepare_config_and_inputs()
              lowerCamelCase_,      lowerCamelCase_,      lowerCamelCase_							=config_and_inputs
              lowerCamelCase_							={'''pixel_values''': pixel_values}
              return config, inputs_dict





@require_torch
class   __UpperCamelCase       ( _UpperCAmelCase			,					_UpperCAmelCase			,					unittest.TestCase				):
       lowercase	:    Dict      						=(
           (
               ConvNextModel,
               ConvNextForImageClassification,
               ConvNextBackbone,
           )
           if is_torch_available()
           else ()
       )
       lowercase	:    Optional[Any]      						=(
           {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
           if is_torch_available()
           else {}
       )

       lowercase	:    Dict      						=True
       lowercase	:    Optional[Any]      						=False
       lowercase	:    int      						=False
       lowercase	:    int      						=False
       lowercase	:    List[str]      						=False






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=ConvNextModelTester(self  )
              lowerCamelCase_							=ConfigTester(self,		config_class=a__,		has_text_modality=a__,		hidden_size=37  )






       def      lowercase__     (							self  ):



              """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      lowercase__     (							self  ):



              """simple docstring"""







              return






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



              """simple docstring"""







              pass






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



              """simple docstring"""







              pass






       @unittest.skip(reason='''ConvNext does not use feedforward chunking'''  )
       def      lowercase__     (							self  ):



              """simple docstring"""







              pass






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_,      lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

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

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






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*a__  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_backbone(*a__  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              def check_hidden_states_output(lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase  ):
                     lowerCamelCase_							=model_class(a__  )
                     model.to(a__  )
                     model.eval()

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

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

                     lowerCamelCase_							=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],		)

              lowerCamelCase_,      lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

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

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

                     check_hidden_states_output(a__,		a__,		a__  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*a__  )






       @slow
       def      lowercase__     (							self  ):



              """simple docstring"""







              for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     lowerCamelCase_							=ConvNextModel.from_pretrained(a__  )
                     self.assertIsNotNone(a__  )





def      a_							(      )							->						List[str]:



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


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






       @cached_property
       def      lowercase__     (							self  ):



              """simple docstring"""







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






       @slow
       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''  ).to(a__  )

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

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

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

              lowerCamelCase_							=torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]  ).to(a__  )

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





@require_torch
class   __UpperCamelCase       ( unittest.TestCase			,					_UpperCAmelCase				):
       lowercase	:    Union[str, Any]      						=(ConvNextBackbone,) if is_torch_available() else ()
       lowercase	:    List[Any]      						=ConvNextConfig

       lowercase	:    Optional[Any]      						=False






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=ConvNextModelTester(self  )











from typing import List, Union

import numpy as np

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 PIL import Image

    from ..image_utils import load_image

if is_torch_available():
    import torch

    from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING

snake_case_				=			logging.get_logger(__name__)

@add_end_docstrings(_UpperCAmelCase  )
class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase  ):


      def __init__(self       :      Optional[int]				,			*a__       :      Any				,			**a__       :      Dict      ):





         """simple docstring"""



         super().__init__(*a__				,			**a__      )
         requires_backends(self				,			'''vision'''      )
         self.check_model_type(a__      )


      def __call__(self       :      Optional[int]				,			a__       :      Union[str, List[str], "Image.Image", List["Image.Image"]]				,			**a__       :      Tuple      ):





         """simple docstring"""



         return super().__call__(a__				,			**a__      )


      def    a (self       :      Dict				,			**a__       :      Any      ):





         """simple docstring"""



         return {}, {}, {}


      def    a (self       :      List[str]				,			a__       :      Any      ):





         """simple docstring"""



         __snake_case							       =   load_image(a__      )
         __snake_case							       =   image.size
         __snake_case							       =   self.image_processor(images=a__				,			return_tensors=self.framework      )
         return model_inputs


      def    a (self       :      int				,			a__       :      List[Any]      ):





         """simple docstring"""



         __snake_case							       =   self.model(**a__      )
         return model_outputs


      def    a (self       :      int				,			a__       :      str      ):





         """simple docstring"""



         __snake_case							       =   model_outputs.predicted_depth
         __snake_case							       =   torch.nn.functional.interpolate(
             predicted_depth.unsqueeze(1      )				,			size=self.image_size[::-1]				,			mode='''bicubic'''				,			align_corners=a__      )
         __snake_case							       =   prediction.squeeze().cpu().numpy()
         __snake_case							       =   (output * 255 / np.max(a__      )).astype('''uint8'''      )
         __snake_case							       =   Image.fromarray(a__      )
         __snake_case							       =   {}
         __snake_case							       =   predicted_depth
         __snake_case							       =   depth
         return output_dict

