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


__lowercase											=      get_tests_dir('''fixtures''')
__lowercase											=      get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
__lowercase											=      get_tests_dir('''fixtures/dummy-config.json''')


class 			lowerCamelCase_  (     unittest.TestCase				):






    '''simple docstring'''






    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        __UpperCamelCase  :str    						=	0







    def     UpperCamelCase__     (			self) ->			List[str]:
        __UpperCamelCase  :Optional[Any]    						=	AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''')
        self.assertIsInstance(__lowercase				,				__lowercase)







    def     UpperCamelCase__     (			self) ->			str:
        __UpperCamelCase  :Optional[int]    						=	AutoFeatureExtractor.from_pretrained(__lowercase)
        self.assertIsInstance(__lowercase				,				__lowercase)







    def     UpperCamelCase__     (			self) ->			int:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase  :Tuple    						=	WavaVecaConfig()

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

            config_dict.pop('''feature_extractor_type''')
            __UpperCamelCase  :str    						=	WavaVecaFeatureExtractor(**__lowercase)

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

            __UpperCamelCase  :Any    						=	AutoFeatureExtractor.from_pretrained(__lowercase)

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

        self.assertIsInstance(__lowercase				,				__lowercase)







    def     UpperCamelCase__     (			self) ->			str:
        __UpperCamelCase  :Tuple    						=	AutoFeatureExtractor.from_pretrained(__lowercase)
        self.assertIsInstance(__lowercase				,				__lowercase)







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







    def     UpperCamelCase__     (			self) ->			Any:
        with self.assertRaisesRegex(
            __lowercase				,				r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
            __UpperCamelCase  :Any    						=	AutoFeatureExtractor.from_pretrained(__lowercase				,				revision='''aaaaaa''')







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







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

        __UpperCamelCase  :Tuple    						=	AutoFeatureExtractor.from_pretrained(
            '''hf-internal-testing/test_dynamic_feature_extractor'''				,				trust_remote_code=__lowercase)
        self.assertEqual(feature_extractor.__class__.__name__				,				'''NewFeatureExtractor''')

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







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

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

        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     UpperCamelCase__     (			self) ->			str:


        class 			lowerCamelCase_  (     UpperCAmelCase_				):






            '''simple docstring'''






            a__			:		Any      			=   True

        try:
            AutoConfig.register('''custom'''				,				__lowercase)
            AutoFeatureExtractor.register(__lowercase				,				__lowercase)
            # If remote code is not set, the default is to use local
            __UpperCamelCase  :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.
            __UpperCamelCase  :Tuple    						=	AutoFeatureExtractor.from_pretrained(
                '''hf-internal-testing/test_dynamic_feature_extractor'''				,				trust_remote_code=__lowercase)
            self.assertEqual(feature_extractor.__class__.__name__				,				'''NewFeatureExtractor''')
            self.assertTrue(feature_extractor.is_local)

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






import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowercase											=      logging.get_logger(__name__)

__lowercase											=      {
    '''microsoft/wavlm-base''': '''https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json''',
    # See all WavLM models at https://huggingface.co/models?filter=wavlm
}


class 			lowerCamelCase_  (     UpperCAmelCase_				):






    '''simple docstring'''






    a__			:		List[Any]      			=   """wavlm"""







    def __init__(			self				,				__lowercase=32				,				__lowercase=768				,				__lowercase=12				,				__lowercase=12				,				__lowercase=3_072				,				__lowercase="gelu"				,				__lowercase=0.1				,				__lowercase=0.1				,				__lowercase=0.1				,				__lowercase=0.0				,				__lowercase=0.1				,				__lowercase=0.1				,				__lowercase=0.02				,				__lowercase=1E-5				,				__lowercase="group"				,				__lowercase="gelu"				,				__lowercase=(512, 512, 512, 512, 512, 512, 512)				,				__lowercase=(5, 2, 2, 2, 2, 2, 2)				,				__lowercase=(10, 3, 3, 3, 3, 2, 2)				,				__lowercase=False				,				__lowercase=128				,				__lowercase=16				,				__lowercase=320				,				__lowercase=800				,				__lowercase=False				,				__lowercase=True				,				__lowercase=0.05				,				__lowercase=10				,				__lowercase=2				,				__lowercase=0.0				,				__lowercase=10				,				__lowercase=320				,				__lowercase=2				,				__lowercase=0.1				,				__lowercase=100				,				__lowercase=256				,				__lowercase=256				,				__lowercase=0.1				,				__lowercase="mean"				,				__lowercase=False				,				__lowercase=False				,				__lowercase=256				,				__lowercase=(512, 512, 512, 512, 1_500)				,				__lowercase=(5, 3, 3, 1, 1)				,				__lowercase=(1, 2, 3, 1, 1)				,				__lowercase=512				,				__lowercase=80				,				__lowercase=0				,				__lowercase=1				,				__lowercase=2				,				__lowercase=False				,				__lowercase=3				,				__lowercase=2				,				__lowercase=3				,				__lowercase=None				,				**__lowercase				,				) ->			Dict:
        super().__init__(**__lowercase				,				pad_token_id=__lowercase				,				bos_token_id=__lowercase				,				eos_token_id=__lowercase)
        __UpperCamelCase  :Any    						=	hidden_size
        __UpperCamelCase  :Tuple    						=	feat_extract_norm
        __UpperCamelCase  :List[str]    						=	feat_extract_activation
        __UpperCamelCase  :int    						=	list(__lowercase)
        __UpperCamelCase  :List[Any]    						=	list(__lowercase)
        __UpperCamelCase  :Union[str, Any]    						=	list(__lowercase)
        __UpperCamelCase  :Optional[Any]    						=	conv_bias
        __UpperCamelCase  :Tuple    						=	num_buckets
        __UpperCamelCase  :Optional[int]    						=	max_bucket_distance
        __UpperCamelCase  :Union[str, Any]    						=	num_conv_pos_embeddings
        __UpperCamelCase  :Optional[Any]    						=	num_conv_pos_embedding_groups
        __UpperCamelCase  :List[Any]    						=	len(self.conv_dim)
        __UpperCamelCase  :Tuple    						=	num_hidden_layers
        __UpperCamelCase  :str    						=	intermediate_size
        __UpperCamelCase  :Union[str, Any]    						=	hidden_act
        __UpperCamelCase  :Optional[int]    						=	num_attention_heads
        __UpperCamelCase  :str    						=	hidden_dropout
        __UpperCamelCase  :int    						=	attention_dropout
        __UpperCamelCase  :Optional[int]    						=	activation_dropout
        __UpperCamelCase  :str    						=	feat_proj_dropout
        __UpperCamelCase  :List[Any]    						=	final_dropout
        __UpperCamelCase  :int    						=	layerdrop
        __UpperCamelCase  :List[Any]    						=	layer_norm_eps
        __UpperCamelCase  :Optional[int]    						=	initializer_range
        __UpperCamelCase  :Any    						=	num_ctc_classes
        __UpperCamelCase  :Optional[int]    						=	vocab_size
        __UpperCamelCase  :List[Any]    						=	do_stable_layer_norm
        __UpperCamelCase  :str    						=	use_weighted_layer_sum
        __UpperCamelCase  :Any    						=	classifier_proj_size

        if (
            (len(self.conv_stride) != self.num_feat_extract_layers)
            or (len(self.conv_kernel) != self.num_feat_extract_layers)
            or (len(self.conv_dim) != self.num_feat_extract_layers)
        ):
            raise ValueError(
                '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='''
                ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='''
                f""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"""
                f""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""")

        # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
        __UpperCamelCase  :Union[str, Any]    						=	apply_spec_augment
        __UpperCamelCase  :Optional[Any]    						=	mask_time_prob
        __UpperCamelCase  :Union[str, Any]    						=	mask_time_length
        __UpperCamelCase  :Optional[int]    						=	mask_time_min_masks
        __UpperCamelCase  :str    						=	mask_feature_prob
        __UpperCamelCase  :Tuple    						=	mask_feature_length

        # parameters for pretraining with codevector quantized representations
        __UpperCamelCase  :Optional[Any]    						=	num_codevectors_per_group
        __UpperCamelCase  :List[Any]    						=	num_codevector_groups
        __UpperCamelCase  :str    						=	contrastive_logits_temperature
        __UpperCamelCase  :Tuple    						=	num_negatives
        __UpperCamelCase  :Any    						=	codevector_dim
        __UpperCamelCase  :Union[str, Any]    						=	proj_codevector_dim
        __UpperCamelCase  :Tuple    						=	diversity_loss_weight

        # ctc loss
        __UpperCamelCase  :int    						=	ctc_loss_reduction
        __UpperCamelCase  :Any    						=	ctc_zero_infinity

        # adapter
        __UpperCamelCase  :List[Any]    						=	add_adapter
        __UpperCamelCase  :Dict    						=	adapter_kernel_size
        __UpperCamelCase  :Any    						=	adapter_stride
        __UpperCamelCase  :Optional[int]    						=	num_adapter_layers
        __UpperCamelCase  :Union[str, Any]    						=	output_hidden_size or hidden_size

        # SequenceClassification-specific parameter. Feel free to ignore for other classes.
        __UpperCamelCase  :int    						=	classifier_proj_size

        # XVector-specific parameters. Feel free to ignore for other classes.
        __UpperCamelCase  :Optional[Any]    						=	list(__lowercase)
        __UpperCamelCase  :Optional[Any]    						=	list(__lowercase)
        __UpperCamelCase  :List[str]    						=	list(__lowercase)
        __UpperCamelCase  :List[Any]    						=	xvector_output_dim







    @property
    def     UpperCamelCase__     (			self) ->			Any:
        return functools.reduce(operator.mul				,				self.conv_stride				,				1)





