






"""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 					_UpperCAmelCase       ( _A   ,						_A							):
					SCREAMING_SNAKE_CASE_		:				Optional[Any]							    =   "pixel_values"
					SCREAMING_SNAKE_CASE_		:				Optional[Any]							    =   False
					SCREAMING_SNAKE_CASE_		:				Union[str, Any]							    =   TimmBackboneConfig




					def __init__(				self     :						str    ,						A     :						Any    ,						**A     :						Union[str, Any]   )  ->  List[Any]:
							requires_backends(self    ,						'''timm'''   )
							super().__init__(A   )
							lowercase_ : 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(A    ,						'''out_features'''   ) and config.out_features is not None:
									raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.'''   )

							lowercase_ : Optional[Any]							       =   getattr(A    ,						'''use_pretrained_backbone'''    ,						A   )
							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.
							lowercase_ : Union[str, Any]							       =   config.out_indices if getattr(A    ,						'''out_indices'''    ,						A   ) is not None else (-1,)

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




					@classmethod
					def   A  (				cls     :						Dict    ,						A     :						Union[str, Any]    ,						*A     :						Tuple    ,						**A     :						str   )  ->  Optional[Any]:
							requires_backends(cls    ,						['''vision''', '''timm''']   )
							from ...models.timm_backbone import TimmBackboneConfig

							lowercase_ : Optional[Any]							       =   kwargs.pop('''config'''    ,						TimmBackboneConfig()   )

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

							lowercase_ : Any							       =   kwargs.pop('''num_channels'''    ,						config.num_channels   )
							lowercase_ : Any							       =   kwargs.pop('''features_only'''    ,						config.features_only   )
							lowercase_ : Any							       =   kwargs.pop('''use_pretrained_backbone'''    ,						config.use_pretrained_backbone   )
							lowercase_ : List[str]							       =   kwargs.pop('''out_indices'''    ,						config.out_indices   )
							lowercase_ : List[Any]							       =   TimmBackboneConfig(
							    backbone=A    ,						num_channels=A    ,						features_only=A    ,						use_pretrained_backbone=A    ,						out_indices=A    ,						)
							return super()._from_config(A    ,						**A   )




					def   A  (				self     :						Tuple    ,						A     :						int   )  ->  int:
							pass






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

							lowercase_ : Tuple							       =   tuple(A   )
							lowercase_ : List[str]							       =   tuple(A   ) if hidden_states is not None else None

							if not return_dict:
									lowercase_ : Optional[int]							       =   (feature_maps,)
									if output_hidden_states:
											lowercase_ : List[Any]							       =   output + (hidden_states,)
									return output

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










import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin







class     __snake_case       (							unittest.TestCase   ,			__lowerCamelCase			):





       '''simple docstring'''







       def 							UpperCAmelCase__ (  self :    Union[str, Any]		):
         __snake_case:						Optional[int]   =						load_tool("""text-classification"""		)
         self.tool.setup()
         __snake_case:						Dict   =						load_tool("""text-classification"""							,				remote=A		)




       def 							UpperCAmelCase__ (  self :    Optional[int]		):
         __snake_case:						List[str]   =						self.tool("""That's quite cool"""							,				["""positive""", """negative"""]		)
         self.assertEqual(A							,				"""positive"""		)




       def 							UpperCAmelCase__ (  self :    Dict		):
         __snake_case:						List[str]   =						self.remote_tool("""That's quite cool"""							,				["""positive""", """negative"""]		)
         self.assertEqual(A							,				"""positive"""		)




       def 							UpperCAmelCase__ (  self :    Optional[Any]		):
         __snake_case:						Optional[Any]   =						self.tool(text="""That's quite cool"""							,				labels=["""positive""", """negative"""]		)
         self.assertEqual(A							,				"""positive"""		)






       def 							UpperCAmelCase__ (  self :    Tuple		):
         __snake_case:						int   =						self.remote_tool(text="""That's quite cool"""							,				labels=["""positive""", """negative"""]		)
         self.assertEqual(A							,				"""positive"""		)






