


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							: Optional[int]      =   get_tests_dir('''fixtures''')
snake_case							: Tuple      =   get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
snake_case							: str      =   get_tests_dir('''fixtures/dummy-config.json''')







class  snake_case_     (unittest.TestCase   ):
					def 				lowerCamelCase__(   self     :List[Any]   )      ->					Union[str, Any]:
												a__    =  0
					def 				lowerCamelCase__(   self     :Any   )      ->					List[str]:
												a__    =  AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h'   )
												self.assertIsInstance(__snake_case    ,__snake_case   )
					def 				lowerCamelCase__(   self     :Dict   )      ->					str:
												a__    =  AutoFeatureExtractor.from_pretrained(__snake_case   )
												self.assertIsInstance(__snake_case    ,__snake_case   )
					def 				lowerCamelCase__(   self     :Union[str, Any]   )      ->					Optional[Any]:
												with tempfile.TemporaryDirectory() as tmpdirname:
																			a__    =  WavaVecaConfig()

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

																			config_dict.pop('feature_extractor_type'   )
																			a__    =  WavaVecaFeatureExtractor(**__snake_case   )

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

																			a__    =  AutoFeatureExtractor.from_pretrained(__snake_case   )

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

												self.assertIsInstance(__snake_case    ,__snake_case   )
					def 				lowerCamelCase__(   self     :Tuple   )      ->					Optional[Any]:
												a__    =  AutoFeatureExtractor.from_pretrained(__snake_case   )
												self.assertIsInstance(__snake_case    ,__snake_case   )
					def 				lowerCamelCase__(   self     :List[str]   )      ->					Tuple:
												with self.assertRaisesRegex(
												    __snake_case    ,'bert-base is not a local folder and is not a valid model identifier'   ):
																			a__    =  AutoFeatureExtractor.from_pretrained('bert-base'   )
					def 				lowerCamelCase__(   self     :List[str]   )      ->					Dict:
												with self.assertRaisesRegex(
												    __snake_case    ,R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'   ):
																			a__    =  AutoFeatureExtractor.from_pretrained(__snake_case    ,revision='aaaaaa'   )
					def 				lowerCamelCase__(   self     :Optional[Any]   )      ->					Optional[int]:
												with self.assertRaisesRegex(
												    __snake_case    ,'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'    ,):
																			a__    =  AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model'   )
					def 				lowerCamelCase__(   self     :Optional[int]   )      ->					str:
												# If remote code is not set, we will time out when asking whether to load the model.
												with self.assertRaises(__snake_case   ):
																			a__    =  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   ):
																			a__    =  AutoFeatureExtractor.from_pretrained(
																			    'hf-internal-testing/test_dynamic_feature_extractor'    ,trust_remote_code=__snake_case   )

												a__    =  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   )
																			a__    =  AutoFeatureExtractor.from_pretrained(__snake_case    ,trust_remote_code=__snake_case   )
												self.assertEqual(reloaded_feature_extractor.__class__.__name__    ,'NewFeatureExtractor'   )
					def 				lowerCamelCase__(   self     :Optional[Any]   )      ->					List[str]:
												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
																			a__    =  CustomFeatureExtractor.from_pretrained(__snake_case   )
																			with tempfile.TemporaryDirectory() as tmp_dir:
																										feature_extractor.save_pretrained(__snake_case   )
																										a__    =  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 				lowerCamelCase__(   self     :List[Any]   )      ->					Any:







												class  snake_case_     (lowerCamelCase_   ):
																	UpperCAmelCase__      :					Optional[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
																			a__    =  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.
																			a__    =  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
																			a__    =  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]








def 							__lowercase     (				__lowerCAmelCase							:       int     ):
							a__    =  generate_pascal_triangle(__lowerCAmelCase     )
							for row_idx in range(__lowerCAmelCase     ):
														# Print left spaces
														for _ in range(num_rows - row_idx - 1     ):
																					print(end=' '     )
														# Print row values
														for col_idx in range(row_idx + 1     ):
																					if col_idx != row_idx:
																												print(triangle[row_idx][col_idx]      ,					end=' '     )
																					else:
																												print(triangle[row_idx][col_idx]      ,					end=''     )
														print()






def 							__lowercase     (				__lowerCAmelCase							:       int     ):

							if not isinstance(__lowerCAmelCase      ,					__lowerCAmelCase     ):
														raise TypeError('The input value of \'num_rows\' should be \'int\''     )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'     )

							a__    =  []
							for current_row_idx in range(__lowerCAmelCase     ):
														a__    =  populate_current_row(__lowerCAmelCase      ,					__lowerCAmelCase     )
														triangle.append(__lowerCAmelCase     )
							return triangle






def 							__lowercase     (				__lowerCAmelCase							:       list[list[int]]      ,					__lowerCAmelCase							:       int     ):
							a__    =  [-1] * (current_row_idx + 1)
							# first and last elements of current row are equal to 1
							a__   ,      a__    =  1, 1
							for current_col_idx in range(1      ,					__lowerCAmelCase     ):
														calculate_current_element(
														    __lowerCAmelCase      ,					__lowerCAmelCase      ,					__lowerCAmelCase      ,					__lowerCAmelCase     )
							return current_row






def 							__lowercase     (				__lowerCAmelCase							:       list[list[int]]      ,					__lowerCAmelCase							:       list[int]      ,					__lowerCAmelCase							:       int      ,					__lowerCAmelCase							:       int      ,					):
							a__    =  triangle[current_row_idx - 1][current_col_idx - 1]
							a__    =  triangle[current_row_idx - 1][current_col_idx]
							a__    =  above_to_left_elt + above_to_right_elt






def 							__lowercase     (				__lowerCAmelCase							:       int     ):

							if not isinstance(__lowerCAmelCase      ,					__lowerCAmelCase     ):
														raise TypeError('The input value of \'num_rows\' should be \'int\''     )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    'The input value of \'num_rows\' should be greater than or equal to 0'     )

							a__    =  [[1]]

							for row_index in range(1      ,					__lowerCAmelCase     ):
														a__    =  [0] + result[-1] + [0]
														a__    =  row_index + 1
														# Calculate the number of distinct elements in a row
														a__    =  sum(divmod(__lowerCAmelCase      ,					2     )     )
														a__    =  [
														    temp_row[i - 1] + temp_row[i] for i in range(1      ,					distinct_elements + 1     )
														]
														a__    =  row_first_half[: (row_index + 1) // 2]
														row_second_half.reverse()
														a__    =  row_first_half + row_second_half
														result.append(__lowerCAmelCase     )

							return result






def 							__lowercase     (				):
							from collections.abc import Callable
							from timeit import timeit

							def benchmark_a_function(__lowerCAmelCase							:       Callable      ,					__lowerCAmelCase							:       int     ) -> None:
														a__    =  F'{func.__name__}({value})'
														a__    =  timeit(F'__main__.{call}'      ,					setup='import __main__'     )
														# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
														print(F'{call:38} -- {timing:.4f} seconds'     )

							for value in range(1_5     ):  # (1, 7, 14):
														for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
																					benchmark_a_function(__lowerCAmelCase      ,					__lowerCAmelCase     )
														print()


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						benchmark()




