





"""simple docstring"""
import os
import sys
import unittest


__UpperCamelCase     :						List[str]						       =  os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__UpperCamelCase     :						int						       =  os.path.join(git_repo_path, '''src''', '''diffusers''')







class       a							(   unittest.TestCase  ):



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= find_backend('    if not is_torch_available():'     )
  self.assertEqual(__lowerCAmelCase				,       'torch'     )

  # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
  # self.assertEqual(backend_with_underscore, "tensorflow_text")

  lowerCAmelCase    				= find_backend('    if not (is_torch_available() and is_transformers_available()):'     )
  self.assertEqual(__lowerCAmelCase				,       'torch_and_transformers'     )

  # double_backend_with_underscore = find_backend(
  #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
  # )
  # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

  lowerCAmelCase    				= find_backend(
      '    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'     )
  self.assertEqual(__lowerCAmelCase				,       'torch_and_transformers_and_onnx'     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= read_init()
  # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
  self.assertIn('torch'				,       __lowerCAmelCase     )
  self.assertIn('torch_and_transformers'				,       __lowerCAmelCase     )
  self.assertIn('flax_and_transformers'				,       __lowerCAmelCase     )
  self.assertIn('torch_and_transformers_and_onnx'				,       __lowerCAmelCase     )

  # Likewise, we can't assert on the exact content of a key
  self.assertIn('UNet2DModel'				,       objects['torch']     )
  self.assertIn('FlaxUNet2DConditionModel'				,       objects['flax']     )
  self.assertIn('StableDiffusionPipeline'				,       objects['torch_and_transformers']     )
  self.assertIn('FlaxStableDiffusionPipeline'				,       objects['flax_and_transformers']     )
  self.assertIn('LMSDiscreteScheduler'				,       objects['torch_and_scipy']     )
  self.assertIn('OnnxStableDiffusionPipeline'				,       objects['torch_and_transformers_and_onnx']     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= create_dummy_object('CONSTANT'				,       '\'torch\''     )
  self.assertEqual(__lowerCAmelCase				,       '\nCONSTANT = None\n'     )

  lowerCAmelCase    				= create_dummy_object('function'				,       '\'torch\''     )
  self.assertEqual(
      __lowerCAmelCase				,       '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'     )

  lowerCAmelCase    				= '\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n'
  lowerCAmelCase    				= create_dummy_object('FakeClass'				,       '\'torch\''     )
  self.assertEqual(__lowerCAmelCase				,       __lowerCAmelCase     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = [\"torch\"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, [\"torch\"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n'
  lowerCAmelCase    				= create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}     )
  self.assertEqual(dummy_files['torch']				,       __lowerCAmelCase     )












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 							__SCREAMING_SNAKE_CASE       (  _a ,		_a							):
							snake_case  :   int      =							"""pixel_values"""
							snake_case  :   List[Any]      =							False
							snake_case  :   str      =							TimmBackboneConfig






							def __init__(    self	,			__lowerCAmelCase	,			**__lowerCAmelCase	):
														requires_backends(self	,			"""timm"""	)
														super().__init__(__lowerCAmelCase	)
														UpperCamelCase__					  =      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."""	)

														UpperCamelCase__					  =      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.
														UpperCamelCase__					  =      config.out_indices if getattr(__lowerCAmelCase	,			"""out_indices"""	,			__lowerCAmelCase	) is not None else (-1,)

														UpperCamelCase__					  =      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.
														UpperCamelCase__					  =      self._backbone.return_layers
														UpperCamelCase__					  =      {layer["""module"""]: str(__lowerCAmelCase	) for i, layer in enumerate(self._backbone.feature_info.info	)}
														super()._init_backbone(__lowerCAmelCase	)






							@classmethod
							def 					_lowerCamelCase		(    cls	,			__lowerCAmelCase	,			*__lowerCAmelCase	,			**__lowerCAmelCase	):
														requires_backends(cls	,			["""vision""", """timm"""]	)
														from ...models.timm_backbone import TimmBackboneConfig

														UpperCamelCase__					  =      kwargs.pop("""config"""	,			TimmBackboneConfig()	)

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

														UpperCamelCase__					  =      kwargs.pop("""num_channels"""	,			config.num_channels	)
														UpperCamelCase__					  =      kwargs.pop("""features_only"""	,			config.features_only	)
														UpperCamelCase__					  =      kwargs.pop("""use_pretrained_backbone"""	,			config.use_pretrained_backbone	)
														UpperCamelCase__					  =      kwargs.pop("""out_indices"""	,			config.out_indices	)
														UpperCamelCase__					  =      TimmBackboneConfig(
														    backbone=__lowerCAmelCase	,			num_channels=__lowerCAmelCase	,			features_only=__lowerCAmelCase	,			use_pretrained_backbone=__lowerCAmelCase	,			out_indices=__lowerCAmelCase	,			)
														return super()._from_config(__lowerCAmelCase	,			**__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	):
														pass







							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase=None	,			__lowerCAmelCase=None	,			__lowerCAmelCase=None	,			**__lowerCAmelCase	):
														UpperCamelCase__					  =      return_dict if return_dict is not None else self.config.use_return_dict
														UpperCamelCase__					  =      (
														    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
														)
														UpperCamelCase__					  =      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__					  =      self._all_layers
																					UpperCamelCase__					  =      self._backbone(__lowerCAmelCase	,			**__lowerCAmelCase	)
																					UpperCamelCase__					  =      self._return_layers
																					UpperCamelCase__					  =      tuple(hidden_states[i] for i in self.out_indices	)
														else:
																					UpperCamelCase__					  =      self._backbone(__lowerCAmelCase	,			**__lowerCAmelCase	)
																					UpperCamelCase__					  =      None

														UpperCamelCase__					  =      tuple(__lowerCAmelCase	)
														UpperCamelCase__					  =      tuple(__lowerCAmelCase	) if hidden_states is not None else None

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

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




