"""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      (   lowercase				,     lowercase						):






				"""simple docstring"""




				UpperCAmelCase    :				Dict   =		"""pixel_values"""
				UpperCAmelCase    :				int   =		False
				UpperCAmelCase    :				Optional[Any]   =		TimmBackboneConfig



				def __init__(self    :				Union[str, Any]     ,  _A    :				Tuple     ,  **_A    :				Optional[int])   ->     Tuple:
					requires_backends(self     ,  'timm')
					super().__init__(_A)
					__snake_case      :							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.')

					__snake_case      :							str						=			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.
					__snake_case      :							int						=			config.out_indices if getattr(_A     ,  'out_indices'     ,  _A) is not None else (-1,)

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



				@classmethod
				def  _lowercase					(cls    :				Any     ,  _A    :				Optional[int]     ,  *_A    :				int     ,  **_A    :				Optional[int])   ->     str:
					requires_backends(cls     ,  ['vision', 'timm'])
					from ...models.timm_backbone import TimmBackboneConfig

					__snake_case      :							Union[str, Any]						=			kwargs.pop('config'     ,  TimmBackboneConfig())

					__snake_case      :							Any						=			kwargs.pop('use_timm_backbone'     ,  _A)
					if not use_timm:
						raise ValueError('use_timm_backbone must be True for timm backbones')

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



				def  _lowercase					(self    :				Optional[Any]     ,  _A    :				Tuple)   ->     str:
					pass






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

					__snake_case      :							Dict						=			tuple(_A)
					__snake_case      :							List[str]						=			tuple(_A) if hidden_states is not None else None

					if not return_dict:
						__snake_case      :							Any						=			(feature_maps,)
						if output_hidden_states:
							__snake_case      :							int						=			output + (hidden_states,)
						return output

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






"""simple docstring"""







import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402

class 		UpperCamelCase      (   unittest.TestCase						):



				def  _lowercase					(self    :				Union[str, Any])   ->     Optional[int]:
					__snake_case      :							Optional[Any]						=			0



				def  _lowercase					(self    :				Tuple)   ->     int:
					__snake_case      :							Optional[Any]						=			AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32')
					self.assertIsInstance(_A     ,  _A)



				def  _lowercase					(self    :				str)   ->     List[str]:
					with tempfile.TemporaryDirectory() as tmpdirname:
						__snake_case      :							List[str]						=			Path(_A) / 'preprocessor_config.json'
						__snake_case      :							Optional[Any]						=			Path(_A) / 'config.json'
						json.dump(
						    {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}     ,  open(_A     ,  'w')     ,  )
						json.dump({'model_type': 'clip'}     ,  open(_A     ,  'w'))

						__snake_case      :							Optional[int]						=			AutoImageProcessor.from_pretrained(_A)
						self.assertIsInstance(_A     ,  _A)



				def  _lowercase					(self    :				Any)   ->     Optional[int]:
					# Ensure we can load the image processor from the feature extractor config
					with tempfile.TemporaryDirectory() as tmpdirname:
						__snake_case      :							Any						=			Path(_A) / 'preprocessor_config.json'
						__snake_case      :							List[Any]						=			Path(_A) / 'config.json'
						json.dump(
						    {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'}     ,  open(_A     ,  'w')     ,  )
						json.dump({'model_type': 'clip'}     ,  open(_A     ,  'w'))

						__snake_case      :							Tuple						=			AutoImageProcessor.from_pretrained(_A)
						self.assertIsInstance(_A     ,  _A)



				def  _lowercase					(self    :				List[Any])   ->     Optional[Any]:
					with tempfile.TemporaryDirectory() as tmpdirname:
						__snake_case      :							str						=			CLIPConfig()

						# Create a dummy config file with image_proceesor_type
						__snake_case      :							List[Any]						=			Path(_A) / 'preprocessor_config.json'
						__snake_case      :							Optional[Any]						=			Path(_A) / 'config.json'
						json.dump(
						    {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}     ,  open(_A     ,  'w')     ,  )
						json.dump({'model_type': 'clip'}     ,  open(_A     ,  'w'))

						# remove image_processor_type to make sure config.json alone is enough to load image processor locally
						__snake_case      :							List[str]						=			AutoImageProcessor.from_pretrained(_A).to_dict()

						config_dict.pop('image_processor_type')
						__snake_case      :							Optional[int]						=			CLIPImageProcessor(**_A)

						# save in new folder
						model_config.save_pretrained(_A)
						config.save_pretrained(_A)

						__snake_case      :							Optional[int]						=			AutoImageProcessor.from_pretrained(_A)

						# make sure private variable is not incorrectly saved
						__snake_case      :							int						=			json.loads(config.to_json_string())
						self.assertTrue('_processor_class' not in dict_as_saved)

					self.assertIsInstance(_A     ,  _A)



				def  _lowercase					(self    :				Union[str, Any])   ->     Optional[Any]:
					with tempfile.TemporaryDirectory() as tmpdirname:
						__snake_case      :							int						=			Path(_A) / 'preprocessor_config.json'
						json.dump(
						    {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'}     ,  open(_A     ,  'w')     ,  )

						__snake_case      :							List[str]						=			AutoImageProcessor.from_pretrained(_A)
						self.assertIsInstance(_A     ,  _A)



				def  _lowercase					(self    :				Optional[int])   ->     Dict:
					with self.assertRaisesRegex(
					    _A     ,  'clip-base is not a local folder and is not a valid model identifier'):
						__snake_case      :							Tuple						=			AutoImageProcessor.from_pretrained('clip-base')



				def  _lowercase					(self    :				str)   ->     int:
					with self.assertRaisesRegex(
					    _A     ,  r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'):
						__snake_case      :							str						=			AutoImageProcessor.from_pretrained(_A     ,  revision='aaaaaa')



				def  _lowercase					(self    :				List[Any])   ->     str:
					with self.assertRaisesRegex(
					    _A     ,  'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'     ,  ):
						__snake_case      :							List[Any]						=			AutoImageProcessor.from_pretrained('hf-internal-testing/config-no-model')



				def  _lowercase					(self    :				Optional[int])   ->     List[str]:
					# If remote code is not set, we will time out when asking whether to load the model.
					with self.assertRaises(_A):
						__snake_case      :							Any						=			AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor')
					# If remote code is disabled, we can't load this config.
					with self.assertRaises(_A):
						__snake_case      :							Tuple						=			AutoImageProcessor.from_pretrained(
						    'hf-internal-testing/test_dynamic_image_processor'     ,  trust_remote_code=_A)

					__snake_case      :							Union[str, Any]						=			AutoImageProcessor.from_pretrained(
					    'hf-internal-testing/test_dynamic_image_processor'     ,  trust_remote_code=_A)
					self.assertEqual(image_processor.__class__.__name__     ,  'NewImageProcessor')

					# Test image processor can be reloaded.
					with tempfile.TemporaryDirectory() as tmp_dir:
						image_processor.save_pretrained(_A)
						__snake_case      :							Optional[int]						=			AutoImageProcessor.from_pretrained(_A     ,  trust_remote_code=_A)
					self.assertEqual(reloaded_image_processor.__class__.__name__     ,  'NewImageProcessor')



				def  _lowercase					(self    :				int)   ->     Optional[int]:
					try:
						AutoConfig.register('custom'     ,  _A)
						AutoImageProcessor.register(_A     ,  _A)
						# Trying to register something existing in the Transformers library will raise an error
						with self.assertRaises(_A):
							AutoImageProcessor.register(_A     ,  _A)

						with tempfile.TemporaryDirectory() as tmpdirname:
							__snake_case      :							Tuple						=			Path(_A) / 'preprocessor_config.json'
							__snake_case      :							Dict						=			Path(_A) / 'config.json'
							json.dump(
							    {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'}     ,  open(_A     ,  'w')     ,  )
							json.dump({'model_type': 'clip'}     ,  open(_A     ,  'w'))

							__snake_case      :							Tuple						=			CustomImageProcessor.from_pretrained(_A)

						# Now that the config is registered, it can be used as any other config with the auto-API
						with tempfile.TemporaryDirectory() as tmp_dir:
							image_processor.save_pretrained(_A)
							__snake_case      :							Tuple						=			AutoImageProcessor.from_pretrained(_A)
							self.assertIsInstance(_A     ,  _A)

					finally:
						if "custom" in CONFIG_MAPPING._extra_content:
							del CONFIG_MAPPING._extra_content["custom"]
						if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
							del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]






				def  _lowercase					(self    :				List[Any])   ->     Tuple:

					class 		UpperCamelCase      (   lowercase						):
									UpperCAmelCase    :				str   =		True

					try:
						AutoConfig.register('custom'     ,  _A)
						AutoImageProcessor.register(_A     ,  _A)
						# If remote code is not set, the default is to use local
						__snake_case      :							Tuple						=			AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor')
						self.assertEqual(image_processor.__class__.__name__     ,  'NewImageProcessor')
						self.assertTrue(image_processor.is_local)

						# If remote code is disabled, we load the local one.
						__snake_case      :							Optional[int]						=			AutoImageProcessor.from_pretrained(
						    'hf-internal-testing/test_dynamic_image_processor'     ,  trust_remote_code=_A)
						self.assertEqual(image_processor.__class__.__name__     ,  'NewImageProcessor')
						self.assertTrue(image_processor.is_local)

						# If remote is enabled, we load from the Hub
						__snake_case      :							List[Any]						=			AutoImageProcessor.from_pretrained(
						    'hf-internal-testing/test_dynamic_image_processor'     ,  trust_remote_code=_A)
						self.assertEqual(image_processor.__class__.__name__     ,  'NewImageProcessor')
						self.assertTrue(not hasattr(_A     ,  'is_local'))

					finally:
						if "custom" in CONFIG_MAPPING._extra_content:
							del CONFIG_MAPPING._extra_content["custom"]
						if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
							del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





