


"""simple docstring"""






import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)





class      lowerCamelCase__   (     unittest.TestCase				):







					"""simple docstring"""


					def lowerCamelCase__							(       self    : List[str]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[int]      							=					["""a""", """b""", """c"""]

												# Defaults to last layer if both are None
												__UpperCAmelCase							,__UpperCAmelCase   :						Dict      							=					get_aligned_output_features_output_indices(UpperCamelCase ,       UpperCamelCase ,       UpperCamelCase  )
												self.assertEqual(UpperCamelCase ,       ["""c"""]  )
												self.assertEqual(UpperCamelCase ,       [2]  )

												# Out indices set to match out features
												__UpperCAmelCase							,__UpperCAmelCase   :						Dict      							=					get_aligned_output_features_output_indices(["""a""", """c"""] ,       UpperCamelCase ,       UpperCamelCase  )
												self.assertEqual(UpperCamelCase ,       ["""a""", """c"""]  )
												self.assertEqual(UpperCamelCase ,       [0, 2]  )

												# Out features set to match out indices
												__UpperCAmelCase							,__UpperCAmelCase   :						Any      							=					get_aligned_output_features_output_indices(UpperCamelCase ,       [0, 2] ,       UpperCamelCase  )
												self.assertEqual(UpperCamelCase ,       ["""a""", """c"""]  )
												self.assertEqual(UpperCamelCase ,       [0, 2]  )

												# Out features selected from negative indices
												__UpperCAmelCase							,__UpperCAmelCase   :						List[str]      							=					get_aligned_output_features_output_indices(UpperCamelCase ,       [-3, -1] ,       UpperCamelCase  )
												self.assertEqual(UpperCamelCase ,       ["""a""", """c"""]  )
												self.assertEqual(UpperCamelCase ,       [-3, -1]  )






					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(["""a""", """b"""] ,       (0, 1) ,       UpperCamelCase  )

												# Out features must be a list
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(("""a""", """b""") ,       (0, 1) ,       ["""a""", """b"""]  )

												# Out features must be a subset of stage names
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(["""a""", """b"""] ,       (0, 1) ,       ["""a"""]  )

												# Out indices must be a list or tuple
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(UpperCamelCase ,       0 ,       ["""a""", """b"""]  )

												# Out indices must be a subset of stage names
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(UpperCamelCase ,       (0, 1) ,       ["""a"""]  )

												# Out features and out indices must be the same length
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(["""a""", """b"""] ,       (0,) ,       ["""a""", """b""", """c"""]  )

												# Out features should match out indices
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(["""a""", """b"""] ,       (0, 2) ,       ["""a""", """b""", """c"""]  )

												# Out features and out indices should be in order
												with self.assertRaises(UpperCamelCase  ):
																			verify_out_features_out_indices(["""b""", """a"""] ,       (0, 1) ,       ["""a""", """b"""]  )

												# Check passes with valid inputs
												verify_out_features_out_indices(["""a""", """b""", """d"""] ,       (0, 1, -1) ,       ["""a""", """b""", """c""", """d"""]  )






					def lowerCamelCase__							(       self    : Tuple  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					BackboneMixin()

												__UpperCAmelCase   :						Dict      							=					["""a""", """b""", """c"""]
												__UpperCAmelCase   :						int      							=					["""a""", """c"""]
												__UpperCAmelCase   :						Any      							=					[0, 2]

												# Check that the output features and indices are set correctly
												self.assertEqual(backbone.out_features ,       ["""a""", """c"""]  )
												self.assertEqual(backbone.out_indices ,       [0, 2]  )

												# Check out features and indices are updated correctly
												__UpperCAmelCase   :						str      							=					["""a""", """b"""]
												self.assertEqual(backbone.out_features ,       ["""a""", """b"""]  )
												self.assertEqual(backbone.out_indices ,       [0, 1]  )

												__UpperCAmelCase   :						int      							=					[-3, -1]
												self.assertEqual(backbone.out_features ,       ["""a""", """c"""]  )
												self.assertEqual(backbone.out_indices ,       [-3, -1]  )




"""simple docstring"""






from importlib import import_module

from .logging import get_logger


UpperCAmelCase    :     Any   						=		get_logger(__name__)





class      lowerCamelCase__   :







					"""simple docstring"""


					def __init__(       self    : Optional[int] ,       UpperCamelCase    : List[Any] ,       UpperCamelCase    : int=None  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Tuple      							=					attrs or []
												if module is not None:
																			for key in module.__dict__:
																										if key in attrs or not key.startswith("""__"""  ):
																																	setattr(self ,       UpperCamelCase ,       getattr(UpperCamelCase ,       UpperCamelCase  )  )
												__UpperCAmelCase   :						Any      							=					module._original_module if isinstance(UpperCamelCase ,       _PatchedModuleObj  ) else module






class      lowerCamelCase__   :







					"""simple docstring"""


					__a	       =							[]






					def __init__(       self    : str ,       UpperCamelCase    : Tuple ,       UpperCamelCase    : str ,       UpperCamelCase    : List[str] ,       UpperCamelCase    : Optional[Any]=None  ):
												'''simple docstring'''






												__UpperCAmelCase   :						int      							=					obj
												__UpperCAmelCase   :						Union[str, Any]      							=					target
												__UpperCAmelCase   :						List[str]      							=					new
												__UpperCAmelCase   :						Optional[int]      							=					target.split("""."""  )[0]
												__UpperCAmelCase   :						Tuple      							=					{}
												__UpperCAmelCase   :						Union[str, Any]      							=					attrs or []






					def __enter__(       self    : Dict  ):
												'''simple docstring'''






												*__UpperCAmelCase							,__UpperCAmelCase   :						str      							=					self.target.split("""."""  )

												# Patch modules:
												# it's used to patch attributes of submodules like "os.path.join";
												# in this case we need to patch "os" and "os.path"

												for i in range(len(UpperCamelCase  )  ):
																			try:
																										__UpperCAmelCase   :						List[Any]      							=					import_module(""".""".join(submodules[: i + 1]  )  )
																			except ModuleNotFoundError:
																										continue
																			# We iterate over all the globals in self.obj in case we find "os" or "os.path"
																			for attr in self.obj.__dir__():
																										__UpperCAmelCase   :						List[Any]      							=					getattr(self.obj ,       UpperCamelCase  )
																										# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																										# This allows to patch renamed modules like "from os import path as ospath".
																										if obj_attr is submodule or (
																										    (isinstance(UpperCamelCase ,       _PatchedModuleObj  ) and obj_attr._original_module is submodule)
																										):
																																	__UpperCAmelCase   :						Tuple      							=					obj_attr
																																	# patch at top level
																																	setattr(self.obj ,       UpperCamelCase ,       _PatchedModuleObj(UpperCamelCase ,       attrs=self.attrs  )  )
																																	__UpperCAmelCase   :						int      							=					getattr(self.obj ,       UpperCamelCase  )
																																	# construct lower levels patches
																																	for key in submodules[i + 1 :]:
																																								setattr(UpperCamelCase ,       UpperCamelCase ,       _PatchedModuleObj(getattr(UpperCamelCase ,       UpperCamelCase ,       UpperCamelCase  ) ,       attrs=self.attrs  )  )
																																								__UpperCAmelCase   :						Optional[int]      							=					getattr(UpperCamelCase ,       UpperCamelCase  )
																																	# finally set the target attribute
																																	setattr(UpperCamelCase ,       UpperCamelCase ,       self.new  )

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

												if submodules:  # if it's an attribute of a submodule like "os.path.join"
																			try:
																										__UpperCAmelCase   :						int      							=					getattr(import_module(""".""".join(UpperCamelCase  )  ) ,       UpperCamelCase  )
																			except (AttributeError, ModuleNotFoundError):
																										return
																			# We iterate over all the globals in self.obj in case we find "os.path.join"
																			for attr in self.obj.__dir__():
																										# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																										# This allows to patch renamed attributes like "from os.path import join as pjoin".
																										if getattr(self.obj ,       UpperCamelCase  ) is attr_value:
																																	__UpperCAmelCase   :						Union[str, Any]      							=					getattr(self.obj ,       UpperCamelCase  )
																																	setattr(self.obj ,       UpperCamelCase ,       self.new  )
												elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																			__UpperCAmelCase   :						str      							=					globals()["""__builtins__"""][target_attr]
																			setattr(self.obj ,       UpperCamelCase ,       self.new  )
												else:
																			raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''  )






					def __exit__(       self    : str ,       *UpperCamelCase    : Optional[int]  ):
												'''simple docstring'''






												for attr in list(self.original  ):
																			setattr(self.obj ,       UpperCamelCase ,       self.original.pop(UpperCamelCase  )  )






					def lowerCamelCase__							(       self    : int  ):
												'''simple docstring'''






												self.__enter__()
												self._active_patches.append(self  )






					def lowerCamelCase__							(       self    : List[Any]  ):
												'''simple docstring'''






												try:
																			self._active_patches.remove(self  )
												except ValueError:
																			# If the patch hasn't been started this will fail
																			return None

												return self.__exit__()
