



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


A_		:     List[str]        =     logging.get_logger(__name__)


if is_vision_available():
     import PIL



class 		_lowercase		(       UpperCAmelCase__	):
   _UpperCAmelCase     	=			['''pixel_values''']

   def __init__(      self			:       Dict							,   __lowerCAmelCase			:       bool = True							,   __lowerCAmelCase			:       Dict[str, int] = None							,   __lowerCAmelCase			:       PILImageResampling = PILImageResampling.BICUBIC							,   __lowerCAmelCase			:       bool = True							,   __lowerCAmelCase			:       Dict[str, int] = None							,   __lowerCAmelCase			:       bool = True							,   __lowerCAmelCase			:       Union[int, float] = 1 / 255							,   __lowerCAmelCase			:       bool = True							,   __lowerCAmelCase			:       Optional[Union[float, List[float]]] = None							,   __lowerCAmelCase			:       Optional[Union[float, List[float]]] = None							,   __lowerCAmelCase			:       bool = True							,   **__lowerCAmelCase			:       List[str]							,   )       ->				None:


    """simple docstring"""






    super().__init__(**__lowerCAmelCase							)
    a						=		size if size is not None else {"shortest_edge": 224}
    a						=		get_size_dict(__lowerCAmelCase							,   default_to_square=__lowerCAmelCase							)
    a						=		crop_size if crop_size is not None else {"height": 224, "width": 224}
    a						=		get_size_dict(__lowerCAmelCase							,   default_to_square=__lowerCAmelCase							,   param_name="crop_size"							)

    a						=		do_resize
    a						=		size
    a						=		resample
    a						=		do_center_crop
    a						=		crop_size
    a						=		do_rescale
    a						=		rescale_factor
    a						=		do_normalize
    a						=		image_mean if image_mean is not None else OPENAI_CLIP_MEAN
    a						=		image_std if image_std is not None else OPENAI_CLIP_STD
    a						=		do_convert_rgb

   def 		A							(      self			:       int							,   __lowerCAmelCase			:       np.ndarray							,   __lowerCAmelCase			:       Dict[str, int]							,   __lowerCAmelCase			:       PILImageResampling = PILImageResampling.BICUBIC							,   __lowerCAmelCase			:       Optional[Union[str, ChannelDimension]] = None							,   **__lowerCAmelCase			:       List[str]							,   )       ->				np.ndarray:


    """simple docstring"""






    a						=		get_size_dict(__lowerCAmelCase							,   default_to_square=__lowerCAmelCase							)
    if "shortest_edge" not in size:
     raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""							)
    a						=		get_resize_output_image_size(__lowerCAmelCase							,   size=size["shortest_edge"]							,   default_to_square=__lowerCAmelCase							)
    return resize(__lowerCAmelCase							,   size=__lowerCAmelCase							,   resample=__lowerCAmelCase							,   data_format=__lowerCAmelCase							,   **__lowerCAmelCase							)

   def 		A							(      self			:       Dict							,   __lowerCAmelCase			:       np.ndarray							,   __lowerCAmelCase			:       Dict[str, int]							,   __lowerCAmelCase			:       Optional[Union[str, ChannelDimension]] = None							,   **__lowerCAmelCase			:       Any							,   )       ->				np.ndarray:


    """simple docstring"""






    a						=		get_size_dict(__lowerCAmelCase							)
    if "height" not in size or "width" not in size:
     raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""							)
    return center_crop(__lowerCAmelCase							,   size=(size["height"], size["width"])							,   data_format=__lowerCAmelCase							,   **__lowerCAmelCase							)

   def 		A							(      self			:       int							,   __lowerCAmelCase			:       np.ndarray							,   __lowerCAmelCase			:       Union[int, float]							,   __lowerCAmelCase			:       Optional[Union[str, ChannelDimension]] = None							,   **__lowerCAmelCase			:       List[Any]							,   )       ->				int:


    """simple docstring"""






    return rescale(__lowerCAmelCase							,   scale=__lowerCAmelCase							,   data_format=__lowerCAmelCase							,   **__lowerCAmelCase							)

   def 		A							(      self			:       Any							,   __lowerCAmelCase			:       np.ndarray							,   __lowerCAmelCase			:       Union[float, List[float]]							,   __lowerCAmelCase			:       Union[float, List[float]]							,   __lowerCAmelCase			:       Optional[Union[str, ChannelDimension]] = None							,   **__lowerCAmelCase			:       int							,   )       ->				np.ndarray:


    """simple docstring"""






    return normalize(__lowerCAmelCase							,   mean=__lowerCAmelCase							,   std=__lowerCAmelCase							,   data_format=__lowerCAmelCase							,   **__lowerCAmelCase							)




   def 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       ImageInput							,   __lowerCAmelCase			:       bool = None							,   __lowerCAmelCase			:       Dict[str, int] = None							,   __lowerCAmelCase			:       PILImageResampling = None							,   __lowerCAmelCase			:       bool = None							,   __lowerCAmelCase			:       int = None							,   __lowerCAmelCase			:       bool = None							,   __lowerCAmelCase			:       float = None							,   __lowerCAmelCase			:       bool = None							,   __lowerCAmelCase			:       Optional[Union[float, List[float]]] = None							,   __lowerCAmelCase			:       Optional[Union[float, List[float]]] = None							,   __lowerCAmelCase			:       bool = None							,   __lowerCAmelCase			:       Optional[Union[str, TensorType]] = None							,   __lowerCAmelCase			:       Optional[ChannelDimension] = ChannelDimension.FIRST							,   **__lowerCAmelCase			:       Tuple							,   )       ->				PIL.Image.Image:


    """simple docstring"""






    a						=		do_resize if do_resize is not None else self.do_resize
    a						=		size if size is not None else self.size
    a						=		get_size_dict(__lowerCAmelCase							,   param_name="size"							,   default_to_square=__lowerCAmelCase							)
    a						=		resample if resample is not None else self.resample
    a						=		do_center_crop if do_center_crop is not None else self.do_center_crop
    a						=		crop_size if crop_size is not None else self.crop_size
    a						=		get_size_dict(__lowerCAmelCase							,   param_name="crop_size"							,   default_to_square=__lowerCAmelCase							)
    a						=		do_rescale if do_rescale is not None else self.do_rescale
    a						=		rescale_factor if rescale_factor is not None else self.rescale_factor
    a						=		do_normalize if do_normalize is not None else self.do_normalize
    a						=		image_mean if image_mean is not None else self.image_mean
    a						=		image_std if image_std is not None else self.image_std
    a						=		do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

    a						=		make_list_of_images(__lowerCAmelCase							)

    if not valid_images(__lowerCAmelCase							):
     raise ValueError(
         "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
         "torch.Tensor, tf.Tensor or jax.ndarray."							)

    if do_resize and size is None:
     raise ValueError("Size must be specified if do_resize is True."							)

    if do_center_crop and crop_size is None:
     raise ValueError("Crop size must be specified if do_center_crop is True."							)

    if do_rescale and rescale_factor is None:
     raise ValueError("Rescale factor must be specified if do_rescale is True."							)

    if do_normalize and (image_mean is None or image_std is None):
     raise ValueError("Image mean and std must be specified if do_normalize is True."							)

    # PIL RGBA images are converted to RGB
    if do_convert_rgb:
     a						=		[convert_to_rgb(__lowerCAmelCase							) for image in images]

    # All transformations expect numpy arrays.
    a						=		[to_numpy_array(__lowerCAmelCase							) for image in images]

    if do_resize:
     a						=		[self.resize(image=__lowerCAmelCase							,   size=__lowerCAmelCase							,   resample=__lowerCAmelCase							) for image in images]

    if do_center_crop:
     a						=		[self.center_crop(image=__lowerCAmelCase							,   size=__lowerCAmelCase							) for image in images]

    if do_rescale:
     a						=		[self.rescale(image=__lowerCAmelCase							,   scale=__lowerCAmelCase							) for image in images]

    if do_normalize:
     a						=		[self.normalize(image=__lowerCAmelCase							,   mean=__lowerCAmelCase							,   std=__lowerCAmelCase							) for image in images]

    a						=		[to_channel_dimension_format(__lowerCAmelCase							,   __lowerCAmelCase							) for image in images]

    a						=		{"pixel_values": images}
    return BatchFeature(data=__lowerCAmelCase							,   tensor_type=__lowerCAmelCase							)






import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
     from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor



class 		_lowercase		:

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


    """simple docstring"""






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

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


    """simple docstring"""






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

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

    a						=		self.get_config()

    return config, pixel_values, labels

   def 		A							(      self			:       Union[str, Any]							)       ->				Optional[int]:


    """simple docstring"""






    return ConvNextVaConfig(
        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=__lowerCAmelCase							,   initializer_range=self.initializer_range							,   out_features=self.out_features							,   out_indices=self.out_indices							,   num_labels=self.num_labels							,   )

   def 		A							(      self			:       Any							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Dict							)       ->				Optional[int]:


    """simple docstring"""






    a						=		ConvNextVaModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							)
    # 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 		A							(      self			:       int							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Union[str, Any]							)       ->				Dict:


    """simple docstring"""






    a						=		ConvNextVaForImageClassification(__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)							)

   def 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[int]							)       ->				int:


    """simple docstring"""






    a						=		ConvNextVaBackbone(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							)

    # 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						=		None
    a						=		ConvNextVaBackbone(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							)

    # 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 		A							(      self			:       Union[str, Any]							)       ->				Dict:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    a		,  a		,  a						=		config_and_inputs
    a						=		{"pixel_values": pixel_values}
    return config, inputs_dict




   def 		A							(      self			:       Dict							)       ->				Optional[int]:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    a		,  a		,  a						=		config_and_inputs
    a						=		{"pixel_values": pixel_values, "labels": labels}
    return config, inputs_dict



@require_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   unittest.TestCase	):
   _UpperCAmelCase     	=			(
       (
           ConvNextVaModel,
           ConvNextVaForImageClassification,
           ConvNextVaBackbone,
       )
       if is_torch_available()
       else ()
   )
   _UpperCAmelCase     	=			(
       {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
       if is_torch_available()
       else {}
   )

   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False

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


    """simple docstring"""






    a						=		ConvNextVaModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   has_text_modality=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       Tuple							)       ->				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 		A							(      self			:       List[Any]							)       ->				List[Any]:


    """simple docstring"""






    return

   @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"							)
   def 		A							(      self			:       List[Any]							)       ->				List[Any]:


    """simple docstring"""






    pass

   @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"							)
   def 		A							(      self			:       int							)       ->				List[Any]:


    """simple docstring"""






    pass

   @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"							)
   def 		A							(      self			:       Optional[int]							)       ->				Dict:


    """simple docstring"""






    pass

   def 		A							(      self			:       List[str]							)       ->				List[str]:


    """simple docstring"""






    if not self.model_tester.is_training:
     return

    for model_class in self.all_model_classes:
     a		,  a						=		self.model_tester.prepare_config_and_inputs_with_labels()
     a						=		True

     if model_class.__name__ in [
         *get_values(__lowerCAmelCase							),
         *get_values(__lowerCAmelCase							),
     ]:
      continue

     a						=		model_class(__lowerCAmelCase							)
     model.to(__lowerCAmelCase							)
     model.train()
     a						=		self._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							,   return_labels=__lowerCAmelCase							)
     a						=		model(**__lowerCAmelCase							).loss
     loss.backward()

   def 		A							(      self			:       Optional[int]							)       ->				List[str]:


    """simple docstring"""






    if not self.model_tester.is_training:
     return

    for model_class in self.all_model_classes:
     a		,  a						=		self.model_tester.prepare_config_and_inputs_with_labels()
     a						=		False
     a						=		True

     if (
         model_class.__name__
         in [*get_values(__lowerCAmelCase							), *get_values(__lowerCAmelCase							)]
         or not model_class.supports_gradient_checkpointing
     ):
      continue

     a						=		model_class(__lowerCAmelCase							)
     model.to(__lowerCAmelCase							)
     model.gradient_checkpointing_enable()
     model.train()
     a						=		self._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							,   return_labels=__lowerCAmelCase							)
     a						=		model(**__lowerCAmelCase							).loss
     loss.backward()

   def 		A							(      self			:       List[Any]							)       ->				Any:


    """simple docstring"""






    a		,  a						=		self.model_tester.prepare_config_and_inputs_for_common()

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

     a						=		["pixel_values"]
     self.assertListEqual(arg_names[:1]							,   __lowerCAmelCase							)

   def 		A							(      self			:       Dict							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase							)

   def 		A							(      self			:       Tuple							)       ->				List[Any]:


    """simple docstring"""






    def check_hidden_states_output(__lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Tuple							):
     a						=		model_class(__lowerCAmelCase							)
     model.to(__lowerCAmelCase							)
     model.eval()

     with torch.no_grad():
      a						=		model(**self._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							)							)

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

     a						=		self.model_tester.num_stages
     self.assertEqual(len(__lowerCAmelCase							)							,   expected_num_stages + 1							)

     # ConvNextV2'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						=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     a						=		True
     check_hidden_states_output(__lowerCAmelCase							,   __lowerCAmelCase							,   __lowerCAmelCase							)

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

     check_hidden_states_output(__lowerCAmelCase							,   __lowerCAmelCase							,   __lowerCAmelCase							)

   def 		A							(      self			:       Optional[Any]							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase							)




   @slow
   def 		A							(      self			:       Tuple							)       ->				List[str]:


    """simple docstring"""






    for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     a						=		ConvNextVaModel.from_pretrained(__lowerCAmelCase							)
     self.assertIsNotNone(__lowerCAmelCase							)


def 	UpperCAmelCase__      (      ):






 '''simple docstring'''

 a						=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
 return image




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

   @cached_property
   def 		A							(      self			:       Optional[int]							)       ->				str:


    """simple docstring"""






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




   @slow
   def 		A							(      self			:       List[str]							)       ->				Union[str, Any]:


    """simple docstring"""






    a						=		ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"							).to(__lowerCAmelCase							)

    a						=		self.default_image_processor
    a						=		prepare_img()
    a						=		preprocessor(images=__lowerCAmelCase							,   return_tensors="pt"							).to(__lowerCAmelCase							)

    # forward pass
    with torch.no_grad():
     a						=		model(**__lowerCAmelCase							)

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

    a						=		torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]							).to(__lowerCAmelCase							)
    self.assertTrue(torch.allclose(outputs.logits[0, :3]							,   __lowerCAmelCase							,   atol=1E-4							)							)

