

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

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
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


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






class _UpperCamelCase				(				unittest.TestCase ):
			'''simple docstring'''







			def 				__UpperCamelCase			(      self				:			Optional[int]						)				->							Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   str					  =							0
			def 				__UpperCamelCase			(      self				:			List[str]						)				->							str:

				"""simple docstring"""

				self.assertIsNotNone(transformers.models.auto.__spec__						)
				self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"						)						)
			def 				__UpperCamelCase			(      self				:			Tuple						)				->							Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   List[str]					  =							AutoConfig.from_pretrained("bert-base-uncased"						)
				self.assertIsInstance(__A   ,   __A						)
			def 				__UpperCamelCase			(      self				:			Union[str, Any]						)				->							List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							AutoConfig.from_pretrained(__A						)
				self.assertIsInstance(__A   ,   __A						)
			def 				__UpperCamelCase			(      self				:			Dict						)				->							Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[Any]					  =							AutoConfig.from_pretrained(__A						)
				self.assertIsInstance(__A   ,   __A						)
			def 				__UpperCamelCase			(      self				:			str						)				->							Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							AutoConfig.for_model("roberta"						)
				self.assertIsInstance(__A   ,   __A						)
			def 				__UpperCamelCase			(      self				:			int						)				->							str:

				"""simple docstring"""

				with tempfile.TemporaryDirectory() as tmp_dir:
					# This model name contains bert and roberta, but roberta ends up being picked.
					SCREAMING_SNAKE_CASE :   Dict					  =							os.path.join(__A   ,   "fake-roberta"						)
					os.makedirs(__A   ,   exist_ok=__A						)
					with open(os.path.join(__A   ,   "config.json"						)   ,   "w"						) as f:
						f.write(json.dumps({}						)						)
					SCREAMING_SNAKE_CASE :   Optional[Any]					  =							AutoConfig.from_pretrained(__A						)
					self.assertEqual(type(__A						)   ,   __A						)
			def 				__UpperCamelCase			(      self				:			Dict						)				->							Any:

				"""simple docstring"""

				try:
					AutoConfig.register("custom"   ,   __A						)
					# Wrong model type will raise an error
					with self.assertRaises(__A						):
						AutoConfig.register("model"   ,   __A						)
					# Trying to register something existing in the Transformers library will raise an error
					with self.assertRaises(__A						):
						AutoConfig.register("bert"   ,   __A						)

					# Now that the config is registered, it can be used as any other config with the auto-API
					SCREAMING_SNAKE_CASE :   Any					  =							CustomConfig()
					with tempfile.TemporaryDirectory() as tmp_dir:
						config.save_pretrained(__A						)
						SCREAMING_SNAKE_CASE :   List[str]					  =							AutoConfig.from_pretrained(__A						)
						self.assertIsInstance(__A   ,   __A						)

				finally:
					if "custom" in CONFIG_MAPPING._extra_content:
						del CONFIG_MAPPING._extra_content["custom"]
			def 				__UpperCamelCase			(      self				:			Tuple						)				->							Any:

				"""simple docstring"""

				with self.assertRaisesRegex(
				    __A   ,   "bert-base is not a local folder and is not a valid model identifier"						):
					SCREAMING_SNAKE_CASE :   int					  =							AutoConfig.from_pretrained("bert-base"						)
			def 				__UpperCamelCase			(      self				:			Tuple						)				->							Optional[Any]:

				"""simple docstring"""

				with self.assertRaisesRegex(
				    __A   ,   R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"						):
					SCREAMING_SNAKE_CASE :   Dict					  =							AutoConfig.from_pretrained(__A   ,   revision="aaaaaa"						)
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							Any:

				"""simple docstring"""

				with self.assertRaisesRegex(
				    __A   ,   "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."   ,   ):
					SCREAMING_SNAKE_CASE :   Dict					  =							AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo"						)
			def 				__UpperCamelCase			(      self				:			List[Any]						)				->							Optional[int]:

				"""simple docstring"""

				with self.assertRaises(__A						):
					SCREAMING_SNAKE_CASE :   List[str]					  =							AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"						)
				# If remote code is disabled, we can't load this config.
				with self.assertRaises(__A						):
					SCREAMING_SNAKE_CASE :   Optional[Any]					  =							AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"   ,   trust_remote_code=__A						)

				SCREAMING_SNAKE_CASE :   str					  =							AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"   ,   trust_remote_code=__A						)
				self.assertEqual(config.__class__.__name__   ,   "NewModelConfig"						)

				# Test config can be reloaded.
				with tempfile.TemporaryDirectory() as tmp_dir:
					config.save_pretrained(__A						)
					SCREAMING_SNAKE_CASE :   str					  =							AutoConfig.from_pretrained(__A   ,   trust_remote_code=__A						)
				self.assertEqual(reloaded_config.__class__.__name__   ,   "NewModelConfig"						)






			def 				__UpperCamelCase			(      self				:			Optional[int]						)				->							Optional[int]:

				"""simple docstring"""

				class _UpperCamelCase				(				_lowercase ):
							'''simple docstring'''







							lowerCamelCase__							     ='''new-model'''

				try:
					AutoConfig.register("new-model"   ,   __A						)
					# If remote code is not set, the default is to use local
					SCREAMING_SNAKE_CASE :   Any					  =							AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"						)
					self.assertEqual(config.__class__.__name__   ,   "NewModelConfigLocal"						)

					# If remote code is disabled, we load the local one.
					SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"   ,   trust_remote_code=__A						)
					self.assertEqual(config.__class__.__name__   ,   "NewModelConfigLocal"						)

					# If remote is enabled, we load from the Hub
					SCREAMING_SNAKE_CASE :   List[Any]					  =							AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"   ,   trust_remote_code=__A						)
					self.assertEqual(config.__class__.__name__   ,   "NewModelConfig"						)

				finally:
					if "new-model" in CONFIG_MAPPING._extra_content:
						del CONFIG_MAPPING._extra_content["new-model"]


import functools
import operator

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


UpperCAmelCase_							:					List[str]		 =   logging.get_logger(__name__)

UpperCAmelCase_							:					str		 =   {
    '''microsoft/unispeech-large-1500h-cv''': (
        '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json'''
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}






class      lowerCamelCase_      (	_lowercase	):
	_lowercase		:   Dict     					=				'''unispeech'''




	def __init__(     self						:     str					,      __A						:     Tuple=32					,      __A						:     List[str]=768					,      __A						:     Dict=12					,      __A						:     Union[str, Any]=12					,      __A						:     Tuple=3072					,      __A						:     Any="gelu"					,      __A						:     int=0.1					,      __A						:     Optional[int]=0.1					,      __A						:     List[Any]=0.1					,      __A						:     Any=0.0					,      __A						:     List[str]=0.0					,      __A						:     int=0.1					,      __A						:     List[Any]=0.1					,      __A						:     List[str]=0.0_2					,      __A						:     List[str]=1e-5					,      __A						:     List[Any]="group"					,      __A						:     int="gelu"					,      __A						:     Any=(512, 512, 512, 512, 512, 512, 512)					,      __A						:     Union[str, Any]=(5, 2, 2, 2, 2, 2, 2)					,      __A						:     Tuple=(10, 3, 3, 3, 3, 2, 2)					,      __A						:     Optional[int]=False					,      __A						:     Any=128					,      __A						:     Union[str, Any]=16					,      __A						:     Optional[Any]=False					,      __A						:     str=True					,      __A						:     Dict=0.0_5					,      __A						:     Optional[Any]=10					,      __A						:     Dict=2					,      __A						:     int=0.0					,      __A						:     List[str]=10					,      __A						:     str=0					,      __A						:     List[str]=320					,      __A						:     List[Any]=2					,      __A						:     Tuple=0.1					,      __A						:     Optional[int]=100					,      __A						:     Any=256					,      __A						:     Dict=256					,      __A						:     Tuple=0.1					,      __A						:     List[str]="mean"					,      __A						:     int=False					,      __A						:     List[str]=False					,      __A						:     List[Any]=256					,      __A						:     str=80					,      __A						:     Tuple=0					,      __A						:     Tuple=1					,      __A						:     int=2					,      __A						:     Dict=0.5					,      **__A						:     List[Any]					,      ):
		super().__init__(**__A					,      pad_token_id=__A					,      bos_token_id=__A					,      eos_token_id=__A							)
		__A :			Dict		    =			hidden_size
		__A :			Optional[Any]		    =			feat_extract_norm
		__A :			List[Any]		    =			feat_extract_activation
		__A :			str		    =			list(__A							)
		__A :			Optional[Any]		    =			list(__A							)
		__A :			Optional[int]		    =			list(__A							)
		__A :			List[Any]		    =			conv_bias
		__A :			Optional[int]		    =			num_conv_pos_embeddings
		__A :			List[Any]		    =			num_conv_pos_embedding_groups
		__A :			int		    =			len(self.conv_dim							)
		__A :			Optional[Any]		    =			num_hidden_layers
		__A :			List[str]		    =			intermediate_size
		__A :			Union[str, Any]		    =			hidden_act
		__A :			Optional[int]		    =			num_attention_heads
		__A :			Tuple		    =			hidden_dropout
		__A :			Optional[Any]		    =			attention_dropout
		__A :			Union[str, Any]		    =			activation_dropout
		__A :			Dict		    =			feat_proj_dropout
		__A :			Optional[int]		    =			final_dropout
		__A :			Dict		    =			layerdrop
		__A :			Optional[int]		    =			layer_norm_eps
		__A :			Optional[Any]		    =			initializer_range
		__A :			Optional[int]		    =			num_ctc_classes
		__A :			Dict		    =			vocab_size
		__A :			List[str]		    =			do_stable_layer_norm
		__A :			Tuple		    =			use_weighted_layer_sum
		__A :			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
		__A :			Tuple		    =			apply_spec_augment
		__A :			Union[str, Any]		    =			mask_time_prob
		__A :			Optional[Any]		    =			mask_time_length
		__A :			List[Any]		    =			mask_time_min_masks
		__A :			List[Any]		    =			mask_feature_prob
		__A :			Any		    =			mask_feature_length
		__A :			List[Any]		    =			mask_feature_min_masks

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

		# ctc loss
		__A :			List[str]		    =			ctc_loss_reduction
		__A :			Any		    =			ctc_zero_infinity

		# pretraining loss
		__A :			Union[str, Any]		    =			replace_prob




	@property
	def        lowerCAmelCase_       (     self						:     int							):
		return functools.reduce(operator.mul					,      self.conv_stride					,      1							)





