'''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    a (       __lowerCAmelCase						,  __lowerCAmelCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					"""pixel_values"""
  __lowerCAmelCase				      =					False
  __lowerCAmelCase				      =					TimmBackboneConfig







  def __init__(							self   ,    snake_case_   ,    **snake_case_					):

    '''simple docstring'''







    requires_backends(self   ,    """timm"""					)
    super().__init__(snake_case_					)
    __UpperCAmelCase:					str		= 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(snake_case_   ,    """out_features"""					) and config.out_features is not None:
      raise ValueError("""out_features is not supported by TimmBackbone. Please use out_indices instead."""					)

    __UpperCAmelCase:					str		= getattr(snake_case_   ,    """use_pretrained_backbone"""   ,    snake_case_					)
    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.
    __UpperCAmelCase:					str		= config.out_indices if getattr(snake_case_   ,    """out_indices"""   ,    snake_case_					) is not None else (-1,)

    __UpperCAmelCase:					Optional[int]		= timm.create_model(
        config.backbone   ,    pretrained=snake_case_   ,    features_only=config.features_only   ,    in_chans=config.num_channels   ,    out_indices=snake_case_   ,    **snake_case_   ,    )
    # 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.
    __UpperCAmelCase:					Any		= self._backbone.return_layers
    __UpperCAmelCase:					Any		= {layer["""module"""]: str(snake_case_					) for i, layer in enumerate(self._backbone.feature_info.info					)}
    super()._init_backbone(snake_case_					)







  @classmethod
  def    lowercase_  (							cls   ,    snake_case_   ,    *snake_case_   ,    **snake_case_					):

    '''simple docstring'''







    requires_backends(cls   ,    ["""vision""", """timm"""]					)
    from ...models.timm_backbone import TimmBackboneConfig

    __UpperCAmelCase:					Any		= kwargs.pop("""config"""   ,    TimmBackboneConfig()					)

    __UpperCAmelCase:					str		= kwargs.pop("""use_timm_backbone"""   ,    snake_case_					)
    if not use_timm:
      raise ValueError("""use_timm_backbone must be True for timm backbones"""					)

    __UpperCAmelCase:					List[Any]		= kwargs.pop("""num_channels"""   ,    config.num_channels					)
    __UpperCAmelCase:					int		= kwargs.pop("""features_only"""   ,    config.features_only					)
    __UpperCAmelCase:					Any		= kwargs.pop("""use_pretrained_backbone"""   ,    config.use_pretrained_backbone					)
    __UpperCAmelCase:					Union[str, Any]		= kwargs.pop("""out_indices"""   ,    config.out_indices					)
    __UpperCAmelCase:					Optional[int]		= TimmBackboneConfig(
        backbone=snake_case_   ,    num_channels=snake_case_   ,    features_only=snake_case_   ,    use_pretrained_backbone=snake_case_   ,    out_indices=snake_case_   ,    )
    return super()._from_config(snake_case_   ,    **snake_case_					)







  def    lowercase_  (							self   ,    snake_case_					):

    '''simple docstring'''







    pass







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    **snake_case_					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= return_dict if return_dict is not None else self.config.use_return_dict
    __UpperCAmelCase:					List[str]		= (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    __UpperCAmelCase:					List[Any]		= 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
      __UpperCAmelCase:					int		= self._all_layers
      __UpperCAmelCase:					Optional[int]		= self._backbone(snake_case_   ,    **snake_case_					)
      __UpperCAmelCase:					List[Any]		= self._return_layers
      __UpperCAmelCase:					int		= tuple(hidden_states[i] for i in self.out_indices					)
    else:
      __UpperCAmelCase:					List[str]		= self._backbone(snake_case_   ,    **snake_case_					)
      __UpperCAmelCase:					List[Any]		= None

    __UpperCAmelCase:					Tuple		= tuple(snake_case_					)
    __UpperCAmelCase:					str		= tuple(snake_case_					) if hidden_states is not None else None

    if not return_dict:
      __UpperCAmelCase:					Tuple		= (feature_maps,)
      if output_hidden_states:
        __UpperCAmelCase:					Dict		= output + (hidden_states,)
      return output

    return BackboneOutput(feature_maps=snake_case_   ,    hidden_states=snake_case_   ,    attentions=snake_case_					)
'''simple docstring'''






import unittest

import numpy as np

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

if is_vision_available():
    from PIL import Image

    from transformers import PoolFormerImageProcessor




class    a (       unittest.TestCase				):



  """simple docstring"""







  def __init__(							self   ,    snake_case_   ,    snake_case_=7   ,    snake_case_=3   ,    snake_case_=30   ,    snake_case_=400   ,    snake_case_=True   ,    snake_case_=None   ,    snake_case_=0.9   ,    snake_case_=None   ,    snake_case_=True   ,    snake_case_=[0.5, 0.5, 0.5]   ,    snake_case_=[0.5, 0.5, 0.5]   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= size if size is not None else {"""shortest_edge""": 30}
    __UpperCAmelCase:					str		= crop_size if crop_size is not None else {"""height""": 30, """width""": 30}
    __UpperCAmelCase:					Dict		= parent
    __UpperCAmelCase:					Union[str, Any]		= batch_size
    __UpperCAmelCase:					List[Any]		= num_channels
    __UpperCAmelCase:					List[str]		= min_resolution
    __UpperCAmelCase:					List[str]		= max_resolution
    __UpperCAmelCase:					Tuple		= do_resize_and_center_crop
    __UpperCAmelCase:					Union[str, Any]		= size
    __UpperCAmelCase:					str		= crop_pct
    __UpperCAmelCase:					List[Any]		= crop_size
    __UpperCAmelCase:					str		= do_normalize
    __UpperCAmelCase:					Union[str, Any]		= image_mean
    __UpperCAmelCase:					List[str]		= image_std







  def    lowercase_  (							self					):

    '''simple docstring'''







    return {
        "size": self.size,
        "do_resize_and_center_crop": self.do_resize_and_center_crop,
        "crop_pct": self.crop_pct,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
    }




@require_torch
@require_vision
class    a (       __lowerCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					PoolFormerImageProcessor if is_vision_available() else None







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= PoolFormerImageProcessingTester(self					)







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return self.image_processor_tester.prepare_image_processor_dict()







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    self.assertTrue(hasattr(snake_case_   ,    """do_resize_and_center_crop"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """size"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """crop_pct"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """do_normalize"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_mean"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_std"""					)					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.image_processing_class.from_dict(self.image_processor_dict					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 30}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 30, """width""": 30}					)

    __UpperCAmelCase:					Dict		= self.image_processing_class.from_dict(self.image_processor_dict   ,    size=42   ,    crop_size=84					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 42}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 84, """width""": 84}					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PIL images
    __UpperCAmelCase:					Optional[Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    Image.Image					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values

    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Any		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    # create random numpy tensors
    __UpperCAmelCase:					Union[str, Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    numpify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    np.ndarray					)

    # Test not batched input
    __UpperCAmelCase:					Union[str, Any]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					str		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PyTorch tensors
    __UpperCAmelCase:					Dict		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    torchify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    torch.Tensor					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Optional[int]		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )