

import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union

class   __UpperCamelCase      (   enum.Enum  ):
	SCREAMING_SNAKE_CASE__      			=       'timm'
	SCREAMING_SNAKE_CASE__      			=       'transformers'



def  __lowerCAmelCase (  A    ,       A    ,       A      ):
	if stage_names is None:
		raise ValueError("Stage_names must be set for transformers backbones"      )

	if out_features is not None:
		if not isinstance(A    ,       (list,)      ):
			raise ValueError(F"out_features must be a list {type(A      )}"      )
		if any(feat not in stage_names for feat in out_features      ):
			raise ValueError(F"out_features must be a subset of stage_names: {stage_names} got {out_features}"      )

	if out_indices is not None:
		if not isinstance(A    ,       (list, tuple)      ):
			raise ValueError(F"out_indices must be a list or tuple, got {type(A      )}"      )
		if any(idx >= len(A      ) for idx in out_indices      ):
			raise ValueError("out_indices must be valid indices for stage_names {stage_names}, got {out_indices}"      )

	if out_features is not None and out_indices is not None:
		if len(A      ) != len(A      ):
			raise ValueError("out_features and out_indices should have the same length if both are set"      )
		if out_features != [stage_names[idx] for idx in out_indices]:
			raise ValueError("out_features and out_indices should correspond to the same stages if both are set"      )



def  __lowerCAmelCase (  A    ,       A    ,       A    ,       ):
	if out_indices is None and out_features is None:
		UpperCAmelCase_    			=     [len(A      ) - 1]
		UpperCAmelCase_    			=     [stage_names[-1]]
	elif out_indices is None and out_features is not None:
		UpperCAmelCase_    			=     [stage_names.index(A      ) for layer in out_features]
	elif out_features is None and out_indices is not None:
		UpperCAmelCase_    			=     [stage_names[idx] for idx in out_indices]
	return out_features, out_indices



def  __lowerCAmelCase (  A    ,       A    ,       A    ,       ):
	verify_out_features_out_indices(out_features=A    ,       out_indices=A    ,       stage_names=A      )
	UpperCAmelCase_			,				UpperCAmelCase_    			=     _align_output_features_output_indices(
	    out_features=A    ,       out_indices=A    ,       stage_names=A      )
	# Verify that the aligned out_features and out_indices are valid
	verify_out_features_out_indices(out_features=A    ,       out_indices=A    ,       stage_names=A      )
	return output_features, output_indices

class   __UpperCamelCase      :
	SCREAMING_SNAKE_CASE__      			=       None




	def  __A   (						self		:  List[str]						,		lowerCAmelCase		:  List[Any]							):


		'''simple docstring'''







		if getattr(self						,		"_backbone"						,		lowerCAmelCase							) is None:
			raise ValueError("self._backbone must be set before calling _init_timm_backbone"							)

		# These will diagree with the defaults for the transformers models e.g. for resnet50
		# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
		# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
		UpperCAmelCase_    			=     [stage["module"] for stage in self._backbone.feature_info.info]
		UpperCAmelCase_    			=     [stage["num_chs"] for stage in self._backbone.feature_info.info]
		UpperCAmelCase_    			=     self._backbone.feature_info.out_indices
		UpperCAmelCase_    			=     self._backbone.feature_info.module_name()

		# We verify the out indices and out features are valid
		verify_out_features_out_indices(
		    out_features=lowerCAmelCase						,		out_indices=lowerCAmelCase						,		stage_names=self.stage_names							)
		UpperCAmelCase_			,				UpperCAmelCase_    			=     out_features, out_indices




	def  __A   (						self		:  int						,		lowerCAmelCase		:  List[str]							):


		'''simple docstring'''







		UpperCAmelCase_    			=     getattr(lowerCAmelCase						,		"stage_names"							)
		UpperCAmelCase_    			=     getattr(lowerCAmelCase						,		"out_features"						,		lowerCAmelCase							)
		UpperCAmelCase_    			=     getattr(lowerCAmelCase						,		"out_indices"						,		lowerCAmelCase							)

		UpperCAmelCase_    			=     stage_names
		UpperCAmelCase_			,				UpperCAmelCase_    			=     get_aligned_output_features_output_indices(
		    out_features=lowerCAmelCase						,		out_indices=lowerCAmelCase						,		stage_names=lowerCAmelCase							)
		# Number of channels for each stage. This is set in the transformer backbone model init
		UpperCAmelCase_    			=     None




	def  __A   (						self		:  Tuple						,		lowerCAmelCase		:  Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_    			=     config

		UpperCAmelCase_    			=     getattr(lowerCAmelCase						,		"use_timm_backbone"						,		lowerCAmelCase							)
		UpperCAmelCase_    			=     BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

		if self.backbone_type == BackboneType.TIMM:
			self._init_timm_backbone(lowerCAmelCase							)
		elif self.backbone_type == BackboneType.TRANSFORMERS:
			self._init_transformers_backbone(lowerCAmelCase							)
		else:
			raise ValueError(F"backbone_type {self.backbone_type} not supported."							)




	@property
	def  __A   (						self		:  int							):


		'''simple docstring'''







		return self._out_features




	@out_features.setter
	def  __A   (						self		:  int						,		lowerCAmelCase		:  List[str]							):


		'''simple docstring'''







		UpperCAmelCase_			,				UpperCAmelCase_    			=     get_aligned_output_features_output_indices(
		    out_features=lowerCAmelCase						,		out_indices=lowerCAmelCase						,		stage_names=self.stage_names							)




	@property
	def  __A   (						self		:  List[Any]							):


		'''simple docstring'''







		return self._out_indices




	@out_indices.setter
	def  __A   (						self		:  Any						,		lowerCAmelCase		:  Union[Tuple[int], List[int]]							):


		'''simple docstring'''







		UpperCAmelCase_			,				UpperCAmelCase_    			=     get_aligned_output_features_output_indices(
		    out_features=lowerCAmelCase						,		out_indices=lowerCAmelCase						,		stage_names=self.stage_names							)




	@property
	def  __A   (						self		:  List[str]							):


		'''simple docstring'''







		return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names							)}




	@property
	def  __A   (						self		:  Optional[Any]							):


		'''simple docstring'''







		return [self.out_feature_channels[name] for name in self.out_features]




	def  __A   (						self		:  List[Any]						,		*lowerCAmelCase		:  Optional[Any]						,		**lowerCAmelCase		:  List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_    			=     dict(inspect.signature(self.forward							).parameters							)
		UpperCAmelCase_    			=     {k: v for k, v in kwargs.items() if k in signature}
		return self(*lowerCAmelCase						,		**lowerCAmelCase							)




	def  __A   (						self		:  int						,		lowerCAmelCase		:  Tuple						,		lowerCAmelCase		:  Optional[bool] = None						,		lowerCAmelCase		:  Optional[bool] = None						,		lowerCAmelCase		:  Optional[bool] = None						,		):


		'''simple docstring'''







		raise NotImplementedError("This method should be implemented by the derived class."							)




	def  __A   (						self		:  Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_    			=     super().to_dict()
		UpperCAmelCase_    			=     output.pop("_out_features"							)
		UpperCAmelCase_    			=     output.pop("_out_indices"							)
		return output


class   __UpperCamelCase      :




	@property
	def  __A   (						self		:  str							):


		'''simple docstring'''







		return self._out_features




	@out_features.setter
	def  __A   (						self		:  int						,		lowerCAmelCase		:  List[str]							):


		'''simple docstring'''







		UpperCAmelCase_			,				UpperCAmelCase_    			=     get_aligned_output_features_output_indices(
		    out_features=lowerCAmelCase						,		out_indices=lowerCAmelCase						,		stage_names=self.stage_names							)




	@property
	def  __A   (						self		:  str							):


		'''simple docstring'''







		return self._out_indices




	@out_indices.setter
	def  __A   (						self		:  Tuple						,		lowerCAmelCase		:  Union[Tuple[int], List[int]]							):


		'''simple docstring'''







		UpperCAmelCase_			,				UpperCAmelCase_    			=     get_aligned_output_features_output_indices(
		    out_features=lowerCAmelCase						,		out_indices=lowerCAmelCase						,		stage_names=self.stage_names							)




	def  __A   (						self		:  Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_    			=     super().to_dict()
		UpperCAmelCase_    			=     output.pop("_out_features"							)
		UpperCAmelCase_    			=     output.pop("_out_indices"							)
		return output


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


_a:      Tuple								=     {
    """configuration_segformer""": ["""SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SegformerConfig""", """SegformerOnnxConfig"""]
}

try:
				if not is_vision_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_a:      List[str]								=     ["""SegformerFeatureExtractor"""]
				_a:      Union[str, Any]								=     ["""SegformerImageProcessor"""]

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_a:      Any								=     [
				    """SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """SegformerDecodeHead""",
				    """SegformerForImageClassification""",
				    """SegformerForSemanticSegmentation""",
				    """SegformerLayer""",
				    """SegformerModel""",
				    """SegformerPreTrainedModel""",
				]

try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_a:      Optional[Any]								=     [
				    """TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """TFSegformerDecodeHead""",
				    """TFSegformerForImageClassification""",
				    """TFSegformerForSemanticSegmentation""",
				    """TFSegformerModel""",
				    """TFSegformerPreTrainedModel""",
				]


if TYPE_CHECKING:
				from .configuration_segformer import SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SegformerConfig, SegformerOnnxConfig

				try:
								if not is_vision_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .feature_extraction_segformer import SegformerFeatureExtractor
								from .image_processing_segformer import SegformerImageProcessor

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_segformer import (
								    SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
								    SegformerDecodeHead,
								    SegformerForImageClassification,
								    SegformerForSemanticSegmentation,
								    SegformerLayer,
								    SegformerModel,
								    SegformerPreTrainedModel,
								)
				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_segformer import (
								    TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFSegformerDecodeHead,
								    TFSegformerForImageClassification,
								    TFSegformerForSemanticSegmentation,
								    TFSegformerModel,
								    TFSegformerPreTrainedModel,
								)

else:
				import sys

				_a:      Optional[int]								=     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)