

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


_SCREAMING_SNAKE_CASE     :  Any   			=			get_tests_dir('''fixtures''')
_SCREAMING_SNAKE_CASE     :  Union[str, Any]   			=			get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
_SCREAMING_SNAKE_CASE     :  Dict   			=			get_tests_dir('''fixtures/dummy-config.json''')






class        UpperCAmelCase__		(       unittest.TestCase       ):






  """simple docstring"""


  def       lowercase_		(							self						:		Optional[int]					)		->							Optional[Any]:
       SCREAMING_SNAKE_CASE__    =    0






  def       lowercase_		(							self						:		str					)		->							Dict:
       SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h'''					)
       self.assertIsInstance(__a	,   __a					)






  def       lowercase_		(							self						:		Tuple					)		->							Dict:
       SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained(__a					)
       self.assertIsInstance(__a	,   __a					)






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

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

            config_dict.pop('''feature_extractor_type'''					)
            SCREAMING_SNAKE_CASE__    =    WavaVecaFeatureExtractor(**__a					)

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

            SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained(__a					)

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

       self.assertIsInstance(__a	,   __a					)






  def       lowercase_		(							self						:		Tuple					)		->							List[str]:
       SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained(__a					)
       self.assertIsInstance(__a	,   __a					)






  def       lowercase_		(							self						:		Union[str, Any]					)		->							Optional[Any]:
       with self.assertRaisesRegex(
           __a	,   '''bert-base is not a local folder and is not a valid model identifier'''					):
            SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained('''bert-base'''					)






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






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






  def       lowercase_		(							self						:		List[Any]					)		->							List[str]:
       # If remote code is not set, we will time out when asking whether to load the model.
       with self.assertRaises(__a					):
            SCREAMING_SNAKE_CASE__    =    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					):
            SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained(
                '''hf-internal-testing/test_dynamic_feature_extractor'''	,   trust_remote_code=__a					)

       SCREAMING_SNAKE_CASE__    =    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					)
            SCREAMING_SNAKE_CASE__    =    AutoFeatureExtractor.from_pretrained(__a	,   trust_remote_code=__a					)
       self.assertEqual(reloaded_feature_extractor.__class__.__name__	,   '''NewFeatureExtractor'''					)






  def       lowercase_		(							self						:		Any					)		->							Any:
       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
            SCREAMING_SNAKE_CASE__    =    CustomFeatureExtractor.from_pretrained(__a					)
            with tempfile.TemporaryDirectory() as tmp_dir:
                 feature_extractor.save_pretrained(__a					)
                 SCREAMING_SNAKE_CASE__    =    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       lowercase_		(							self						:		Tuple					)		->							List[str]:






       class        UpperCAmelCase__		(       lowerCamelCase_       ):






         """simple docstring"""


         a           =					True

       try:
            AutoConfig.register('''custom'''	,   __a					)
            AutoFeatureExtractor.register(__a	,   __a					)
            # If remote code is not set, the default is to use local
            SCREAMING_SNAKE_CASE__    =    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.
            SCREAMING_SNAKE_CASE__    =    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
            SCREAMING_SNAKE_CASE__    =    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]









'''simple docstring'''







import math
class 				__SCREAMING_SNAKE_CASE  :






				"""simple docstring"""







				def   UpperCamelCase__   (  self     :					List[str]					,				__a     :					list[list[float]]					,				__a     :					list[int]					):
								_a								= 0.0
								_a								= 0.0
								for i in range(len(__a					)					):
												da += math.pow((sample[i] - weights[0][i])					,				2					)
												da += math.pow((sample[i] - weights[1][i])					,				2					)
												return 0 if da > da else 1
								return 0




				def   UpperCamelCase__   (  self     :					List[Any]					,				__a     :					list[list[int | float]]					,				__a     :					list[int]					,				__a     :					int					,				__a     :					float					):
								for i in range(len(__a					)					):
												weights[j][i] += alpha * (sample[i] - weights[j][i])
								return weights






def  _lowerCamelCase				( )	->	None:
				# Training Examples ( m, n )
				_a								= [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]

				# weight initialization ( n, C )
				_a								= [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]

				# training
				_a								= SelfOrganizingMap()
				_a								= 3
				_a								= 0.5

				for _ in range(lowercase						):
								for j in range(len(lowercase						)						):
												# training sample
												_a								= training_samples[j]

												# Compute the winning vector
												_a								= self_organizing_map.get_winner(lowercase    ,							lowercase						)

												# Update the winning vector
												_a								= self_organizing_map.update(lowercase    ,							lowercase    ,							lowercase    ,							lowercase						)

    # classify test sample
				_a								= [0, 0, 0, 1]
				_a								= self_organizing_map.get_winner(lowercase    ,							lowercase						)

				# results
				print(F'Clusters that the test sample belongs to : {winner}'						)
				print(F'Weights that have been trained : {weights}'						)


# running the main() function
if __name__ == "__main__":
					main()
