



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


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



class   UpperCAmelCase_    (       unittest.TestCase):







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							str    =    0







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
														self.assertIsInstance(__a,			__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[Any]    =    AutoFeatureExtractor.from_pretrained(__a)
														self.assertIsInstance(__a,			__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														with tempfile.TemporaryDirectory() as tmpdirname:
																					_lowerCAmelCase     :							Dict    =    WavaVecaConfig()

																					# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
																					_lowerCAmelCase     :							int    =    AutoFeatureExtractor.from_pretrained(__a).to_dict()

																					config_dict.pop("feature_extractor_type")
																					_lowerCAmelCase     :							List[Any]    =    WavaVecaFeatureExtractor(**__a)

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

																					_lowerCAmelCase     :							List[Any]    =    AutoFeatureExtractor.from_pretrained(__a)

																					# make sure private variable is not incorrectly saved
																					_lowerCAmelCase     :							Any    =    json.loads(config.to_json_string())
																					self.assertTrue("_processor_class" not in dict_as_saved)

														self.assertIsInstance(__a,			__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    AutoFeatureExtractor.from_pretrained(__a)
														self.assertIsInstance(__a,			__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														with self.assertRaisesRegex(
														    __a,			"bert-base is not a local folder and is not a valid model identifier"):
																					_lowerCAmelCase     :							Dict    =    AutoFeatureExtractor.from_pretrained("bert-base")







							def    snake_case__      (   self):

														'''simple docstring'''

														with self.assertRaisesRegex(
														    __a,			R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"):
																					_lowerCAmelCase     :							List[Any]    =    AutoFeatureExtractor.from_pretrained(__a,			revision="aaaaaa")







							def    snake_case__      (   self):

														'''simple docstring'''

														with self.assertRaisesRegex(
														    __a,			"hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.",			):
																					_lowerCAmelCase     :							Optional[int]    =    AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model")







							def    snake_case__      (   self):

														'''simple docstring'''

														with self.assertRaises(__a):
																					_lowerCAmelCase     :							List[str]    =    AutoFeatureExtractor.from_pretrained(
																					    "hf-internal-testing/test_dynamic_feature_extractor")
														# If remote code is disabled, we can't load this config.
														with self.assertRaises(__a):
																					_lowerCAmelCase     :							List[Any]    =    AutoFeatureExtractor.from_pretrained(
																					    "hf-internal-testing/test_dynamic_feature_extractor",			trust_remote_code=__a)

														_lowerCAmelCase     :							List[str]    =    AutoFeatureExtractor.from_pretrained(
														    "hf-internal-testing/test_dynamic_feature_extractor",			trust_remote_code=__a)
														self.assertEqual(feature_extractor.__class__.__name__,			"NewFeatureExtractor")

														# Test feature extractor can be reloaded.
														with tempfile.TemporaryDirectory() as tmp_dir:
																					feature_extractor.save_pretrained(__a)
																					_lowerCAmelCase     :							Optional[int]    =    AutoFeatureExtractor.from_pretrained(__a,			trust_remote_code=__a)
														self.assertEqual(reloaded_feature_extractor.__class__.__name__,			"NewFeatureExtractor")







							def    snake_case__      (   self):

														'''simple docstring'''

														try:
																					AutoConfig.register("custom",			__a)
																					AutoFeatureExtractor.register(__a,			__a)
																					# Trying to register something existing in the Transformers library will raise an error
																					with self.assertRaises(__a):
																												AutoFeatureExtractor.register(__a,			__a)

																					# Now that the config is registered, it can be used as any other config with the auto-API
																					_lowerCAmelCase     :							List[Any]    =    CustomFeatureExtractor.from_pretrained(__a)
																					with tempfile.TemporaryDirectory() as tmp_dir:
																												feature_extractor.save_pretrained(__a)
																												_lowerCAmelCase     :							List[Any]    =    AutoFeatureExtractor.from_pretrained(__a)
																												self.assertIsInstance(__a,			__a)

														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):

														'''simple docstring'''

														class   UpperCAmelCase_    (       a):
																					lowerCamelCase__   			=		True

														try:
																					AutoConfig.register("custom",			__a)
																					AutoFeatureExtractor.register(__a,			__a)
																					# If remote code is not set, the default is to use local
																					_lowerCAmelCase     :							Union[str, Any]    =    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.
																					_lowerCAmelCase     :							int    =    AutoFeatureExtractor.from_pretrained(
																					    "hf-internal-testing/test_dynamic_feature_extractor",			trust_remote_code=__a)
																					self.assertEqual(feature_extractor.__class__.__name__,			"NewFeatureExtractor")
																					self.assertTrue(feature_extractor.is_local)

																					# If remote is enabled, we load from the Hub
																					_lowerCAmelCase     :							str    =    AutoFeatureExtractor.from_pretrained(
																					    "hf-internal-testing/test_dynamic_feature_extractor",			trust_remote_code=__a)
																					self.assertEqual(feature_extractor.__class__.__name__,			"NewFeatureExtractor")
																					self.assertTrue(not hasattr(__a,			"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]





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


_snake_case		=  logging.get_logger(__name__)

_snake_case		=  {
    "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   UpperCAmelCase_    (       a   ,					a):
							lowerCamelCase__   			=		'swin'

							lowerCamelCase__   			=		{
							    'num_attention_heads': 'num_heads',
							    'num_hidden_layers': 'num_layers',
							}







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

														'''simple docstring'''

														super().__init__(**__a)

														_lowerCAmelCase     :							Any    =    image_size
														_lowerCAmelCase     :							Union[str, Any]    =    patch_size
														_lowerCAmelCase     :							Tuple    =    num_channels
														_lowerCAmelCase     :							List[Any]    =    embed_dim
														_lowerCAmelCase     :							Tuple    =    depths
														_lowerCAmelCase     :							Optional[Any]    =    len(__a)
														_lowerCAmelCase     :							int    =    num_heads
														_lowerCAmelCase     :							int    =    window_size
														_lowerCAmelCase     :							int    =    mlp_ratio
														_lowerCAmelCase     :							List[Any]    =    qkv_bias
														_lowerCAmelCase     :							str    =    hidden_dropout_prob
														_lowerCAmelCase     :							Union[str, Any]    =    attention_probs_dropout_prob
														_lowerCAmelCase     :							Any    =    drop_path_rate
														_lowerCAmelCase     :							int    =    hidden_act
														_lowerCAmelCase     :							Tuple    =    use_absolute_embeddings
														_lowerCAmelCase     :							Optional[int]    =    layer_norm_eps
														_lowerCAmelCase     :							Tuple    =    initializer_range
														_lowerCAmelCase     :							Tuple    =    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
														_lowerCAmelCase     :							List[str]    =    int(embed_dim * 2 ** (len(__a) - 1))
														_lowerCAmelCase     :							List[Any]    =    ["stem"] + [f"stage{idx}" for idx in range(1,			len(__a) + 1)]
														_lowerCAmelCase   ,    _lowerCAmelCase     :							Optional[int]    =    get_aligned_output_features_output_indices(
														    out_features=__a,			out_indices=__a,			stage_names=self.stage_names)



class   UpperCAmelCase_    (       a):
							lowerCamelCase__   			=		version.parse('1.11')







							@property
							def    snake_case__      (   self):

														'''simple docstring'''

														return OrderedDict(
														    [
														        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
														    ])







							@property
							def    snake_case__      (   self):

														'''simple docstring'''

														return 1E-4
