


import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
       import torch

       from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
       __lowerCamelCase        =     False

if is_vision_available():
       from PIL import Image

       from transformers import PixaStructImageProcessor


class   a__	(						unittest.TestCase    ):

       def __init__(   self      :     Any      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     Optional[Any]=7      ,							lowerCamelCase_      :     Union[str, Any]=3      ,							lowerCamelCase_      :     Union[str, Any]=1_8      ,							lowerCamelCase_      :     List[Any]=3_0      ,							lowerCamelCase_      :     Optional[Any]=4_0_0      ,							lowerCamelCase_      :     int=None      ,							lowerCamelCase_      :     List[Any]=True      ,							lowerCamelCase_      :     Optional[Any]=True      ,							lowerCamelCase_      :     int=None      ,							):
            a_    :     Optional[int]										=    size if size is not None else {"""height""": 2_0, """width""": 2_0}
            a_    :     List[str]										=    parent
            a_    :     Union[str, Any]										=    batch_size
            a_    :     str										=    num_channels
            a_    :     str										=    image_size
            a_    :     Dict										=    min_resolution
            a_    :     List[str]										=    max_resolution
            a_    :     Dict										=    size
            a_    :     int										=    do_normalize
            a_    :     List[str]										=    do_convert_rgb
            a_    :     int										=    [5_1_2, 1_0_2_4, 2_0_4_8, 4_0_9_6]
            a_    :     Dict										=    patch_size if patch_size is not None else {"""height""": 1_6, """width""": 1_6}

       def 						UpperCAmelCase(   self      :     Dict    ):
            return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}

       def 						UpperCAmelCase(   self      :     int    ):
            a_    :     Tuple										=    """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"""
            a_    :     str										=    Image.open(requests.get(lowerCamelCase_      ,							stream=lowerCamelCase_    ).raw    ).convert("""RGB"""    )
            return raw_image


@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11						,       reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""						,       )
@require_torch
@require_vision
class   a__	(						lowerCAmelCase_						,       unittest.TestCase    ):
       lowerCamelCase__:     str							    =     PixaStructImageProcessor if is_vision_available() else None

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            a_    :     Union[str, Any]										=    PixaStructImageProcessingTester(self    )

       @property
       def 						UpperCAmelCase(   self      :     Optional[Any]    ):
            return self.image_processor_tester.prepare_image_processor_dict()

       def 						UpperCAmelCase(   self      :     int    ):
            a_    :     List[Any]										=    self.image_processing_class(**self.image_processor_dict    )
            self.assertTrue(hasattr(lowerCamelCase_      ,							"""do_normalize"""    )    )
            self.assertTrue(hasattr(lowerCamelCase_      ,							"""do_convert_rgb"""    )    )

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            a_    :     Tuple										=    self.image_processor_tester.prepare_dummy_image()

            a_    :     Optional[Any]										=    self.image_processing_class(**self.image_processor_dict    )
            a_    :     Tuple										=    2_0_4_8

            a_    :     Optional[Any]										=    image_processor(lowerCamelCase_      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    )
            self.assertTrue(torch.allclose(inputs.flattened_patches.mean()      ,							torch.tensor(0.0_6_0_6    )      ,							atol=1E-3      ,							rtol=1E-3    )    )

       def 						UpperCAmelCase(   self      :     str    ):
            # Initialize image_processor
            a_    :     List[str]										=    self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            a_    :     List[Any]										=    prepare_image_inputs(self.image_processor_tester      ,							equal_resolution=lowerCamelCase_    )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_      ,							Image.Image    )

            # Test not batched input
            a_    :     Optional[int]										=    (
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 a_    :     Union[str, Any]										=    image_processor(
                     image_inputs[0]      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(1, max_patch, expected_hidden_dim)      ,							)

                 # Test batched
                 a_    :     Dict										=    image_processor(
                     lowerCamelCase_      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,							)

       def 						UpperCAmelCase(   self      :     Tuple    ):
            # Initialize image_processor
            a_    :     Optional[Any]										=    self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            a_    :     Optional[int]										=    prepare_image_inputs(self.image_processor_tester      ,							equal_resolution=lowerCamelCase_    )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_      ,							Image.Image    )

            # Test not batched input
            a_    :     str										=    (
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            a_    :     Optional[int]										=    True

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 with self.assertRaises(lowerCamelCase_    ):
                      a_    :     int										=    image_processor(
                          image_inputs[0]      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches

                 a_    :     List[str]										=    """Hello"""

                 a_    :     str										=    image_processor(
                     image_inputs[0]      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_      ,							header_text=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(1, max_patch, expected_hidden_dim)      ,							)

                 # Test batched
                 a_    :     int										=    image_processor(
                     lowerCamelCase_      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_      ,							header_text=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,							)

       def 						UpperCAmelCase(   self      :     Any    ):
            # Initialize image_processor
            a_    :     List[str]										=    self.image_processing_class(**self.image_processor_dict    )
            # create random numpy tensors
            a_    :     Any										=    prepare_image_inputs(self.image_processor_tester      ,							equal_resolution=lowerCamelCase_      ,							numpify=lowerCamelCase_    )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_      ,							np.ndarray    )

            a_    :     List[Any]										=    (
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 a_    :     Any										=    image_processor(
                     image_inputs[0]      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(1, max_patch, expected_hidden_dim)      ,							)

                 # Test batched
                 a_    :     Union[str, Any]										=    image_processor(
                     lowerCamelCase_      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,							)

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            # Initialize image_processor
            a_    :     Optional[Any]										=    self.image_processing_class(**self.image_processor_dict    )
            # create random PyTorch tensors
            a_    :     Union[str, Any]										=    prepare_image_inputs(self.image_processor_tester      ,							equal_resolution=lowerCamelCase_      ,							torchify=lowerCamelCase_    )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_      ,							torch.Tensor    )

            # Test not batched input
            a_    :     List[str]										=    (
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 a_    :     int										=    image_processor(
                     image_inputs[0]      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(1, max_patch, expected_hidden_dim)      ,							)

                 # Test batched
                 a_    :     Tuple										=    image_processor(
                     lowerCamelCase_      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,							)


@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11						,       reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""						,       )
@require_torch
@require_vision
class   a__	(						lowerCAmelCase_						,       unittest.TestCase    ):
       lowerCamelCase__:     int							    =     PixaStructImageProcessor if is_vision_available() else None

       def 						UpperCAmelCase(   self      :     int    ):
            a_    :     Optional[Any]										=    PixaStructImageProcessingTester(self      ,							num_channels=4    )
            a_    :     int										=    3

       @property
       def 						UpperCAmelCase(   self      :     List[str]    ):
            return self.image_processor_tester.prepare_image_processor_dict()

       def 						UpperCAmelCase(   self      :     List[str]    ):
            a_    :     List[str]										=    self.image_processing_class(**self.image_processor_dict    )
            self.assertTrue(hasattr(lowerCamelCase_      ,							"""do_normalize"""    )    )
            self.assertTrue(hasattr(lowerCamelCase_      ,							"""do_convert_rgb"""    )    )

       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            # Initialize image_processor
            a_    :     Union[str, Any]										=    self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            a_    :     Any										=    prepare_image_inputs(self.image_processor_tester      ,							equal_resolution=lowerCamelCase_    )
            for image in image_inputs:
                 self.assertIsInstance(lowerCamelCase_      ,							Image.Image    )

            # Test not batched input
            a_    :     int										=    (
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * (self.image_processor_tester.num_channels - 1)
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 a_    :     List[str]										=    image_processor(
                     image_inputs[0]      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(1, max_patch, expected_hidden_dim)      ,							)

                 # Test batched
                 a_    :     int										=    image_processor(
                     lowerCamelCase_      ,							return_tensors="""pt"""      ,							max_patches=lowerCamelCase_    ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape      ,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)      ,							)






from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


__lowerCamelCase        =     logging.get_logger(__name__)

__lowerCamelCase        =     {
    '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''',
}


class   a__	(						lowerCAmelCase_						,       lowerCAmelCase_    ):
       lowerCamelCase__:     str							    =     """convnextv2"""

       def __init__(   self      :     Tuple      ,							lowerCamelCase_      :     str=3      ,							lowerCamelCase_      :     Tuple=4      ,							lowerCamelCase_      :     Any=4      ,							lowerCamelCase_      :     Optional[int]=None      ,							lowerCamelCase_      :     Optional[int]=None      ,							lowerCamelCase_      :     Optional[int]="gelu"      ,							lowerCamelCase_      :     Optional[Any]=0.0_2      ,							lowerCamelCase_      :     str=1E-12      ,							lowerCamelCase_      :     Dict=0.0      ,							lowerCamelCase_      :     Union[str, Any]=2_2_4      ,							lowerCamelCase_      :     Dict=None      ,							lowerCamelCase_      :     Optional[Any]=None      ,							**lowerCamelCase_      :     List[Any]      ,							):
            super().__init__(**lowerCamelCase_    )

            a_    :     Dict										=    num_channels
            a_    :     Optional[int]										=    patch_size
            a_    :     int										=    num_stages
            a_    :     Any										=    [9_6, 1_9_2, 3_8_4, 7_6_8] if hidden_sizes is None else hidden_sizes
            a_    :     Any										=    [3, 3, 9, 3] if depths is None else depths
            a_    :     Any										=    hidden_act
            a_    :     Dict										=    initializer_range
            a_    :     Optional[Any]										=    layer_norm_eps
            a_    :     int										=    drop_path_rate
            a_    :     Optional[Any]										=    image_size
            a_    :     Dict										=    ["""stem"""] + [F'''stage{idx}''' for idx in range(1      ,							len(self.depths    ) + 1    )]
            a_			,			a_    :     int										=    get_aligned_output_features_output_indices(
                out_features=lowerCamelCase_      ,							out_indices=lowerCamelCase_      ,							stage_names=self.stage_names    )



