

'''simple docstring'''


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

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase__										= get_tests_dir("fixtures")
lowerCAmelCase__										= get_tests_dir("fixtures/dummy_feature_extractor_config.json")
lowerCAmelCase__										= get_tests_dir("fixtures/dummy-config.json")



class 					lowercase						(  unittest.TestCase ):


							def 						_snake_case							(			self)							->				List[Any]:
								UpperCAmelCase_		:      List[Any]       	=					0


							def 						_snake_case							(			self)							->				int:
								UpperCAmelCase_		:      Union[str, Any]       	=					AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h')
								self.assertIsInstance(_snake_case    ,			_snake_case)


							def 						_snake_case							(			self)							->				List[str]:
								UpperCAmelCase_		:      Optional[int]       	=					AutoFeatureExtractor.from_pretrained(_snake_case)
								self.assertIsInstance(_snake_case    ,			_snake_case)


							def 						_snake_case							(			self)							->				Union[str, Any]:
								with tempfile.TemporaryDirectory() as tmpdirname:
									UpperCAmelCase_		:      List[Any]       	=					WavaVecaConfig()

									# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
									UpperCAmelCase_		:      List[str]       	=					AutoFeatureExtractor.from_pretrained(_snake_case).to_dict()

									config_dict.pop('feature_extractor_type')
									UpperCAmelCase_		:      Union[str, Any]       	=					WavaVecaFeatureExtractor(**_snake_case)

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

									UpperCAmelCase_		:      List[str]       	=					AutoFeatureExtractor.from_pretrained(_snake_case)

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

								self.assertIsInstance(_snake_case    ,			_snake_case)


							def 						_snake_case							(			self)							->				Optional[int]:
								UpperCAmelCase_		:      List[str]       	=					AutoFeatureExtractor.from_pretrained(_snake_case)
								self.assertIsInstance(_snake_case    ,			_snake_case)


							def 						_snake_case							(			self)							->				List[str]:
								with self.assertRaisesRegex(
								    _snake_case    ,			'bert-base is not a local folder and is not a valid model identifier'):
									UpperCAmelCase_		:      Any       	=					AutoFeatureExtractor.from_pretrained('bert-base')


							def 						_snake_case							(			self)							->				List[str]:
								with self.assertRaisesRegex(
								    _snake_case    ,			r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'):
									UpperCAmelCase_		:      str       	=					AutoFeatureExtractor.from_pretrained(_snake_case    ,			revision='aaaaaa')


							def 						_snake_case							(			self)							->				Tuple:
								with self.assertRaisesRegex(
								    _snake_case    ,			'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'    ,			):
									UpperCAmelCase_		:      Dict       	=					AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model')


							def 						_snake_case							(			self)							->				str:
								# If remote code is not set, we will time out when asking whether to load the model.
								with self.assertRaises(_snake_case):
									UpperCAmelCase_		:      Dict       	=					AutoFeatureExtractor.from_pretrained(
									    'hf-internal-testing/test_dynamic_feature_extractor')
								# If remote code is disabled, we can't load this config.
								with self.assertRaises(_snake_case):
									UpperCAmelCase_		:      str       	=					AutoFeatureExtractor.from_pretrained(
									    'hf-internal-testing/test_dynamic_feature_extractor'    ,			trust_remote_code=_snake_case)

								UpperCAmelCase_		:      Optional[int]       	=					AutoFeatureExtractor.from_pretrained(
								    'hf-internal-testing/test_dynamic_feature_extractor'    ,			trust_remote_code=_snake_case)
								self.assertEqual(feature_extractor.__class__.__name__    ,			'NewFeatureExtractor')

								# Test feature extractor can be reloaded.
								with tempfile.TemporaryDirectory() as tmp_dir:
									feature_extractor.save_pretrained(_snake_case)
									UpperCAmelCase_		:      Union[str, Any]       	=					AutoFeatureExtractor.from_pretrained(_snake_case    ,			trust_remote_code=_snake_case)
								self.assertEqual(reloaded_feature_extractor.__class__.__name__    ,			'NewFeatureExtractor')


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

									# Now that the config is registered, it can be used as any other config with the auto-API
									UpperCAmelCase_		:      Dict       	=					CustomFeatureExtractor.from_pretrained(_snake_case)
									with tempfile.TemporaryDirectory() as tmp_dir:
										feature_extractor.save_pretrained(_snake_case)
										UpperCAmelCase_		:      Dict       	=					AutoFeatureExtractor.from_pretrained(_snake_case)
										self.assertIsInstance(_snake_case    ,			_snake_case)

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





							def 						_snake_case							(			self)							->				Optional[Any]:



								class 					lowercase						(  a_ ):
															_lowerCamelCase		:      Any=   True

								try:
									AutoConfig.register('custom'    ,			_snake_case)
									AutoFeatureExtractor.register(_snake_case    ,			_snake_case)
									# If remote code is not set, the default is to use local
									UpperCAmelCase_		:      str       	=					AutoFeatureExtractor.from_pretrained(
									    'hf-internal-testing/test_dynamic_feature_extractor')
									self.assertEqual(feature_extractor.__class__.__name__    ,			'NewFeatureExtractor')
									self.assertTrue(feature_extractor.is_local)

									# If remote code is disabled, we load the local one.
									UpperCAmelCase_		:      int       	=					AutoFeatureExtractor.from_pretrained(
									    'hf-internal-testing/test_dynamic_feature_extractor'    ,			trust_remote_code=_snake_case)
									self.assertEqual(feature_extractor.__class__.__name__    ,			'NewFeatureExtractor')
									self.assertTrue(feature_extractor.is_local)

									# If remote is enabled, we load from the Hub
									UpperCAmelCase_		:      Dict       	=					AutoFeatureExtractor.from_pretrained(
									    'hf-internal-testing/test_dynamic_feature_extractor'    ,			trust_remote_code=_snake_case)
									self.assertEqual(feature_extractor.__class__.__name__    ,			'NewFeatureExtractor')
									self.assertTrue(not hasattr(_snake_case    ,			'is_local'))

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









'''simple docstring'''


from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowerCAmelCase__										= logging.get_logger(__name__)

lowerCAmelCase__										= {
    "microsoft/swin-tiny-patch4-window7-224": (
        "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json"
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}



class 					lowercase						(  a_,					a_ ):
							_lowerCamelCase		:      Optional[int]=   "swin"

							_lowerCamelCase		:      Dict=   {
							    "num_attention_heads": "num_heads",
							    "num_hidden_layers": "num_layers",
							}


							def __init__(			self    ,			_snake_case=224    ,			_snake_case=4    ,			_snake_case=3    ,			_snake_case=96    ,			_snake_case=[2, 2, 6, 2]    ,			_snake_case=[3, 6, 12, 24]    ,			_snake_case=7    ,			_snake_case=4.0    ,			_snake_case=True    ,			_snake_case=0.0    ,			_snake_case=0.0    ,			_snake_case=0.1    ,			_snake_case="gelu"    ,			_snake_case=False    ,			_snake_case=0.02    ,			_snake_case=1e-5    ,			_snake_case=32    ,			_snake_case=None    ,			_snake_case=None    ,			**_snake_case    ,			)							->				Tuple:
								super().__init__(**_snake_case)

								UpperCAmelCase_		:      Any       	=					image_size
								UpperCAmelCase_		:      Dict       	=					patch_size
								UpperCAmelCase_		:      int       	=					num_channels
								UpperCAmelCase_		:      Tuple       	=					embed_dim
								UpperCAmelCase_		:      Dict       	=					depths
								UpperCAmelCase_		:      Dict       	=					len(_snake_case)
								UpperCAmelCase_		:      List[Any]       	=					num_heads
								UpperCAmelCase_		:      Optional[int]       	=					window_size
								UpperCAmelCase_		:      Any       	=					mlp_ratio
								UpperCAmelCase_		:      Any       	=					qkv_bias
								UpperCAmelCase_		:      str       	=					hidden_dropout_prob
								UpperCAmelCase_		:      Optional[int]       	=					attention_probs_dropout_prob
								UpperCAmelCase_		:      Dict       	=					drop_path_rate
								UpperCAmelCase_		:      int       	=					hidden_act
								UpperCAmelCase_		:      Tuple       	=					use_absolute_embeddings
								UpperCAmelCase_		:      Optional[int]       	=					layer_norm_eps
								UpperCAmelCase_		:      Optional[int]       	=					initializer_range
								UpperCAmelCase_		:      Optional[Any]       	=					encoder_stride
								# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
								# this indicates the channel dimension after the last stage of the model
								UpperCAmelCase_		:      Union[str, Any]       	=					int(embed_dim * 2 ** (len(_snake_case) - 1))
								UpperCAmelCase_		:      Tuple       	=					['stem'] + [F"""stage{idx}""" for idx in range(1    ,			len(_snake_case) + 1)]
								UpperCAmelCase_	,    UpperCAmelCase_		:      Dict       	=					get_aligned_output_features_output_indices(
								    out_features=_snake_case    ,			out_indices=_snake_case    ,			stage_names=self.stage_names)



class 					lowercase						(  a_ ):
							_lowerCamelCase		:      Tuple=   version.parse("1.11" )


							@property
							def 						_snake_case							(			self)							->				Mapping[str, Mapping[int, str]]:
								return OrderedDict(
								    [
								        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
								    ])





							@property
							def 						_snake_case							(			self)							->				float:
								return 1e-4






