


'''simple docstring'''
from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
    import timm


if is_torch_available():
    from torch import Tensor






class        lowerCAmelCase_  (     UpperCAmelCase      ,							UpperCAmelCase	):
       __UpperCAmelCase					='pixel_values'
       __UpperCAmelCase					=False
       __UpperCAmelCase					=TimmBackboneConfig






       def __init__( self			,     _UpperCamelCase			,     **_UpperCamelCase   )->      Optional[Any]:
            requires_backends(self			,     'timm'   )
            super().__init__(_UpperCamelCase   )
            _A				=							config

            if config.backbone is None:
                 raise ValueError('backbone is not set in the config. Please set it to a timm model name.'   )

            if config.backbone not in timm.list_models():
                 raise ValueError(F'backbone {config.backbone} is not supported by timm.'   )

            if hasattr(_UpperCamelCase			,     'out_features'   ) and config.out_features is not None:
                 raise ValueError('out_features is not supported by TimmBackbone. Please use out_indices instead.'   )

            _A				=							getattr(_UpperCamelCase			,     'use_pretrained_backbone'			,     _UpperCamelCase   )
            if pretrained is None:
                 raise ValueError('use_pretrained_backbone is not set in the config. Please set it to True or False.'   )

            # We just take the final layer by default. This matches the default for the transformers models.
            _A				=							config.out_indices if getattr(_UpperCamelCase			,     'out_indices'			,     _UpperCamelCase   ) is not None else (-1,)

            _A				=							timm.create_model(
                config.backbone			,     pretrained=_UpperCamelCase			,     features_only=config.features_only			,     in_chans=config.num_channels			,     out_indices=_UpperCamelCase			,     **_UpperCamelCase			,     )
            # These are used to control the output of the model when called. If output_hidden_states is True, then
            # return_layers is modified to include all layers.
            _A				=							self._backbone.return_layers
            _A				=							{layer['module']: str(_UpperCamelCase   ) for i, layer in enumerate(self._backbone.feature_info.info   )}
            super()._init_backbone(_UpperCamelCase   )






       @classmethod
       def   UpperCamelCase						( cls			,     _UpperCamelCase			,     *_UpperCamelCase			,     **_UpperCamelCase   )->      Tuple:
            requires_backends(cls			,     ['vision', 'timm']   )
            from ...models.timm_backbone import TimmBackboneConfig

            _A				=							kwargs.pop('config'			,     TimmBackboneConfig()   )

            _A				=							kwargs.pop('use_timm_backbone'			,     _UpperCamelCase   )
            if not use_timm:
                 raise ValueError('use_timm_backbone must be True for timm backbones'   )

            _A				=							kwargs.pop('num_channels'			,     config.num_channels   )
            _A				=							kwargs.pop('features_only'			,     config.features_only   )
            _A				=							kwargs.pop('use_pretrained_backbone'			,     config.use_pretrained_backbone   )
            _A				=							kwargs.pop('out_indices'			,     config.out_indices   )
            _A				=							TimmBackboneConfig(
                backbone=_UpperCamelCase			,     num_channels=_UpperCamelCase			,     features_only=_UpperCamelCase			,     use_pretrained_backbone=_UpperCamelCase			,     out_indices=_UpperCamelCase			,     )
            return super()._from_config(_UpperCamelCase			,     **_UpperCamelCase   )






       def   UpperCamelCase						( self			,     _UpperCamelCase   )->      Optional[Any]:
            pass






       def   UpperCamelCase						( self			,     _UpperCamelCase			,     _UpperCamelCase=None			,     _UpperCamelCase=None			,     _UpperCamelCase=None			,     **_UpperCamelCase   )->      Union[BackboneOutput, Tuple[Tensor, ...]]:
            _A				=							return_dict if return_dict is not None else self.config.use_return_dict
            _A				=							(
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )
            _A				=							output_attentions if output_attentions is not None else self.config.output_attentions

            if output_attentions:
                 raise ValueError('Cannot output attentions for timm backbones at the moment'   )

            if output_hidden_states:
                 # We modify the return layers to include all the stages of the backbone
                 _A				=							self._all_layers
                 _A				=							self._backbone(_UpperCamelCase			,     **_UpperCamelCase   )
                 _A				=							self._return_layers
                 _A				=							tuple(hidden_states[i] for i in self.out_indices   )
            else:
                 _A				=							self._backbone(_UpperCamelCase			,     **_UpperCamelCase   )
                 _A				=							None

            _A				=							tuple(_UpperCamelCase   )
            _A				=							tuple(_UpperCamelCase   ) if hidden_states is not None else None

            if not return_dict:
                 _A				=							(feature_maps,)
                 if output_hidden_states:
                      _A				=							output + (hidden_states,)
                 return output

            return BackboneOutput(feature_maps=_UpperCamelCase			,     hidden_states=_UpperCamelCase			,     attentions=_UpperCamelCase   )









'''simple docstring'''
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        lowerCAmelCase_  (     unittest.TestCase	):






       def __init__( self			,     _UpperCamelCase			,     _UpperCamelCase=7			,     _UpperCamelCase=3			,     _UpperCamelCase=18			,     _UpperCamelCase=30			,     _UpperCamelCase=400			,     _UpperCamelCase=None			,     _UpperCamelCase=True			,     _UpperCamelCase=True			,     _UpperCamelCase=None			,     )->      Dict:
            _A				=							size if size is not None else {'height': 20, 'width': 20}
            _A				=							parent
            _A				=							batch_size
            _A				=							num_channels
            _A				=							image_size
            _A				=							min_resolution
            _A				=							max_resolution
            _A				=							size
            _A				=							do_normalize
            _A				=							do_convert_rgb
            _A				=							[512, 1024, 2048, 4096]
            _A				=							patch_size if patch_size is not None else {'height': 16, 'width': 16}






       def   UpperCamelCase						( self   )->      Dict:
            return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






       def   UpperCamelCase						( self   )->      Tuple:
            _A				=							'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
            _A				=							Image.open(requests.get(_UpperCamelCase			,     stream=_UpperCamelCase   ).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        lowerCAmelCase_  (     UpperCAmelCase      ,							unittest.TestCase	):
       __UpperCAmelCase					=PixaStructImageProcessor if is_vision_available() else None






       def   UpperCamelCase						( self   )->      Optional[int]:
            _A				=							PixaStructImageProcessingTester(self   )






       @property
       def   UpperCamelCase						( self   )->      Tuple:
            return self.image_processor_tester.prepare_image_processor_dict()






       def   UpperCamelCase						( self   )->      List[Any]:
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_normalize'   )   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_convert_rgb'   )   )






       def   UpperCamelCase						( self   )->      Any:
            _A				=							self.image_processor_tester.prepare_dummy_image()

            _A				=							self.image_processing_class(**self.image_processor_dict   )
            _A				=							2048

            _A				=							image_processor(_UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   )
            self.assertTrue(torch.allclose(inputs.flattened_patches.mean()			,     torch.tensor(0.0606   )			,     atol=1e-3			,     rtol=1e-3   )   )






       def   UpperCamelCase						( self   )->      int:
            # Initialize image_processor
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            # create random PIL images
            _A				=							prepare_image_inputs(self.image_processor_tester			,     equal_resolution=_UpperCamelCase   )
            for image in image_inputs:
                 self.assertIsInstance(_UpperCamelCase			,     Image.Image   )

            # Test not batched input
            _A				=							(
                (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				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






       def   UpperCamelCase						( self   )->      List[str]:
            # Initialize image_processor
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            # create random PIL images
            _A				=							prepare_image_inputs(self.image_processor_tester			,     equal_resolution=_UpperCamelCase   )
            for image in image_inputs:
                 self.assertIsInstance(_UpperCamelCase			,     Image.Image   )

            # Test not batched input
            _A				=							(
                (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
                * self.image_processor_tester.num_channels
            ) + 2

            _A				=							True

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 with self.assertRaises(_UpperCamelCase   ):
                      _A				=							image_processor(
                          image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches

                 _A				=							'Hello'

                 _A				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase			,     header_text=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase			,     header_text=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






       def   UpperCamelCase						( self   )->      Optional[int]:
            # Initialize image_processor
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            # create random numpy tensors
            _A				=							prepare_image_inputs(self.image_processor_tester			,     equal_resolution=_UpperCamelCase			,     numpify=_UpperCamelCase   )
            for image in image_inputs:
                 self.assertIsInstance(_UpperCamelCase			,     np.ndarray   )

            _A				=							(
                (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				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






       def   UpperCamelCase						( self   )->      Union[str, Any]:
            # Initialize image_processor
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            # create random PyTorch tensors
            _A				=							prepare_image_inputs(self.image_processor_tester			,     equal_resolution=_UpperCamelCase			,     torchify=_UpperCamelCase   )
            for image in image_inputs:
                 self.assertIsInstance(_UpperCamelCase			,     torch.Tensor   )

            # Test not batched input
            _A				=							(
                (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				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).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        lowerCAmelCase_  (     UpperCAmelCase      ,							unittest.TestCase	):
       __UpperCAmelCase					=PixaStructImageProcessor if is_vision_available() else None






       def   UpperCamelCase						( self   )->      str:
            _A				=							PixaStructImageProcessingTester(self			,     num_channels=4   )
            _A				=							3






       @property
       def   UpperCamelCase						( self   )->      str:
            return self.image_processor_tester.prepare_image_processor_dict()






       def   UpperCamelCase						( self   )->      Any:
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_normalize'   )   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_convert_rgb'   )   )






       def   UpperCamelCase						( self   )->      Optional[Any]:
            # Initialize image_processor
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            # create random PIL images
            _A				=							prepare_image_inputs(self.image_processor_tester			,     equal_resolution=_UpperCamelCase   )
            for image in image_inputs:
                 self.assertIsInstance(_UpperCamelCase			,     Image.Image   )

            # Test not batched input
            _A				=							(
                (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				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )





