





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__):
      _lowercase				:					Dict						=			"""pixel_values"""
      _lowercase				:					List[Any]						=			False
      _lowercase				:					int						=			TimmBackboneConfig







      def __init__(    self		,      lowerCAmelCase__		,      **lowerCAmelCase__							)   ->						Union[str, Any]:



        '''simple docstring'''




        requires_backends(self		,      "timm"							)
        super().__init__(lowerCAmelCase__							)
        a__	:					Optional[Any]										=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(lowerCAmelCase__		,      "out_features"							) and config.out_features is not None:
          raise ValueError("out_features is not supported by TimmBackbone. Please use out_indices instead."							)

        a__	:					List[Any]										=getattr(lowerCAmelCase__		,      "use_pretrained_backbone"		,      lowerCAmelCase__							)
        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__	:					Dict										=config.out_indices if getattr(lowerCAmelCase__		,      "out_indices"		,      lowerCAmelCase__							) is not None else (-1,)

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







      @classmethod
      def    _lowercase  (    cls		,      lowerCAmelCase__		,      *lowerCAmelCase__		,      **lowerCAmelCase__							)   ->						str:



        '''simple docstring'''




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

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

        a__	:					List[Any]										=kwargs.pop("use_timm_backbone"		,      lowerCAmelCase__							)
        if not use_timm:
          raise ValueError("use_timm_backbone must be True for timm backbones"							)

        a__	:					Optional[Any]										=kwargs.pop("num_channels"		,      config.num_channels							)
        a__	:					List[Any]										=kwargs.pop("features_only"		,      config.features_only							)
        a__	:					List[Any]										=kwargs.pop("use_pretrained_backbone"		,      config.use_pretrained_backbone							)
        a__	:					Any										=kwargs.pop("out_indices"		,      config.out_indices							)
        a__	:					List[Any]										=TimmBackboneConfig(
            backbone=lowerCAmelCase__		,      num_channels=lowerCAmelCase__		,      features_only=lowerCAmelCase__		,      use_pretrained_backbone=lowerCAmelCase__		,      out_indices=lowerCAmelCase__		,      )
        return super()._from_config(lowerCAmelCase__		,      **lowerCAmelCase__							)







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						str:



        '''simple docstring'''




        pass







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      **lowerCAmelCase__							)   ->						Union[BackboneOutput, Tuple[Tensor, ...]]:



        '''simple docstring'''




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

        a__	:					Optional[Any]										=tuple(lowerCAmelCase__							)
        a__	:					int										=tuple(lowerCAmelCase__							) if hidden_states is not None else None

        if not return_dict:
          a__	:					str										=(feature_maps,)
          if output_hidden_states:
            a__	:					Union[str, Any]										=output + (hidden_states,)
          return output

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













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 MobileNetVaImageProcessor







class 				__lowerCAmelCase       (    unittest.TestCase):







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__=7		,      lowerCAmelCase__=3		,      lowerCAmelCase__=1_8		,      lowerCAmelCase__=3_0		,      lowerCAmelCase__=4_0_0		,      lowerCAmelCase__=True		,      lowerCAmelCase__=None		,      lowerCAmelCase__=True		,      lowerCAmelCase__=None		,      )   ->						Optional[int]:



        '''simple docstring'''




        a__	:					str										=size if size is not None else {"shortest_edge": 2_0}
        a__	:					Union[str, Any]										=crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
        a__	:					Tuple										=parent
        a__	:					Optional[int]										=batch_size
        a__	:					Any										=num_channels
        a__	:					List[str]										=image_size
        a__	:					Dict										=min_resolution
        a__	:					List[Any]										=max_resolution
        a__	:					Dict										=do_resize
        a__	:					Union[str, Any]										=size
        a__	:					str										=do_center_crop
        a__	:					List[str]										=crop_size







      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
        }







@require_torch
@require_vision
class 				__lowerCAmelCase       (    UpperCamelCase__						,				unittest.TestCase):
      _lowercase				:					Optional[Any]						=			MobileNetVaImageProcessor if is_vision_available() else None







      def    _lowercase  (    self							)   ->						Tuple:



        '''simple docstring'''




        a__	:					Optional[int]										=MobileNetVaImageProcessingTester(self							)







      @property
      def    _lowercase  (    self							)   ->						List[str]:



        '''simple docstring'''




        return self.image_processor_tester.prepare_image_processor_dict()







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        a__	:					List[str]										=self.image_processing_class(**self.image_processor_dict							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "do_resize"							)							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "size"							)							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "do_center_crop"							)							)
        self.assertTrue(hasattr(lowerCAmelCase__		,      "crop_size"							)							)







      def    _lowercase  (    self							)   ->						str:



        '''simple docstring'''




        a__	:					Any										=self.image_processing_class.from_dict(self.image_processor_dict							)
        self.assertEqual(image_processor.size		,      {"shortest_edge": 2_0}							)
        self.assertEqual(image_processor.crop_size		,      {"height": 1_8, "width": 1_8}							)

        a__	:					Dict										=self.image_processing_class.from_dict(self.image_processor_dict		,      size=4_2		,      crop_size=8_4							)
        self.assertEqual(image_processor.size		,      {"shortest_edge": 4_2}							)
        self.assertEqual(image_processor.crop_size		,      {"height": 8_4, "width": 8_4}							)







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        pass







      def    _lowercase  (    self							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Dict										=self.image_processing_class(**self.image_processor_dict							)
        # create random PIL images
        a__	:					Optional[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__	:					List[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
        a__	:					Dict										=image_processing(lowerCAmelCase__		,      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							)   ->						int:



        '''simple docstring'''




        a__	:					str										=self.image_processing_class(**self.image_processor_dict							)
        # create random numpy tensors
        a__	:					str										=prepare_image_inputs(self.image_processor_tester		,      equal_resolution=lowerCAmelCase__		,      numpify=lowerCAmelCase__							)
        for image in image_inputs:
          self.assertIsInstance(lowerCAmelCase__		,      np.ndarray							)

        # Test not batched input
        a__	:					List[str]										=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
        a__	:					Union[str, Any]										=image_processing(lowerCAmelCase__		,      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							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Any										=self.image_processing_class(**self.image_processor_dict							)
        # create random PyTorch tensors
        a__	:					int										=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__	:					Optional[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
        a__	:					str										=image_processing(lowerCAmelCase__		,      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"],
            )		,      )






