





import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


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
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


_UpperCamelCase							=      get_tests_dir('fixtures/dummy_feature_extractor_config.json')
_UpperCamelCase							=      get_tests_dir('fixtures/vocab.json')
_UpperCamelCase							=      get_tests_dir('fixtures')
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       List[str]	 =		["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]




				def 					__lowercase  (     self  :Dict			):
											__lowerCamelCase      :      str         =0




				def 					__lowercase  (     self  :List[Any]			):
											__lowerCamelCase      :      Tuple         =AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''			)
											self.assertIsInstance(__lowercase						,    __lowercase			)




				def 					__lowercase  (     self  :Tuple			):
											with tempfile.TemporaryDirectory() as tmpdirname:
																		__lowerCamelCase      :      str         =WavaVecaConfig()
																		__lowerCamelCase      :      Dict         =AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''			)

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

																		__lowerCamelCase      :      Dict         =AutoProcessor.from_pretrained(__lowercase			)

											self.assertIsInstance(__lowercase						,    __lowercase			)




				def 					__lowercase  (     self  :Union[str, Any]			):
											with tempfile.TemporaryDirectory() as tmpdirname:
																		# copy relevant files
																		copyfile(__lowercase						,    os.path.join(__lowercase						,    __lowercase			)			)
																		copyfile(__lowercase						,    os.path.join(__lowercase						,    '''vocab.json'''			)			)

																		__lowerCamelCase      :      List[str]         =AutoProcessor.from_pretrained(__lowercase			)

											self.assertIsInstance(__lowercase						,    __lowercase			)




				def 					__lowercase  (     self  :List[str]			):
											with tempfile.TemporaryDirectory() as tmpdirname:
																		__lowerCamelCase      :      Dict         =WavaVecaFeatureExtractor()
																		__lowerCamelCase      :      Union[str, Any]         =AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''			)

																		__lowerCamelCase      :      List[Any]         =WavaVecaProcessor(__lowercase						,    __lowercase			)

																		# save in new folder
																		processor.save_pretrained(__lowercase			)

																		# drop `processor_class` in tokenizer
																		with open(os.path.join(__lowercase						,    __lowercase			)						,    '''r'''			) as f:
																									__lowerCamelCase      :      int         =json.load(__lowercase			)
																									config_dict.pop('''processor_class'''			)

																		with open(os.path.join(__lowercase						,    __lowercase			)						,    '''w'''			) as f:
																									f.write(json.dumps(__lowercase			)			)

																		__lowerCamelCase      :      Union[str, Any]         =AutoProcessor.from_pretrained(__lowercase			)

											self.assertIsInstance(__lowercase						,    __lowercase			)




				def 					__lowercase  (     self  :Optional[int]			):
											with tempfile.TemporaryDirectory() as tmpdirname:
																		__lowerCamelCase      :      List[Any]         =WavaVecaFeatureExtractor()
																		__lowerCamelCase      :      Tuple         =AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''			)

																		__lowerCamelCase      :      int         =WavaVecaProcessor(__lowercase						,    __lowercase			)

																		# save in new folder
																		processor.save_pretrained(__lowercase			)

																		# drop `processor_class` in feature extractor
																		with open(os.path.join(__lowercase						,    __lowercase			)						,    '''r'''			) as f:
																									__lowerCamelCase      :      int         =json.load(__lowercase			)
																									config_dict.pop('''processor_class'''			)

																		with open(os.path.join(__lowercase						,    __lowercase			)						,    '''w'''			) as f:
																									f.write(json.dumps(__lowercase			)			)

																		__lowerCamelCase      :      List[Any]         =AutoProcessor.from_pretrained(__lowercase			)

											self.assertIsInstance(__lowercase						,    __lowercase			)




				def 					__lowercase  (     self  :List[Any]			):
											with tempfile.TemporaryDirectory() as tmpdirname:
																		__lowerCamelCase      :      int         =WavaVecaConfig(processor_class='''Wav2Vec2Processor'''			)
																		model_config.save_pretrained(__lowercase			)
																		# copy relevant files
																		copyfile(__lowercase						,    os.path.join(__lowercase						,    '''vocab.json'''			)			)
																		# create emtpy sample processor
																		with open(os.path.join(__lowercase						,    __lowercase			)						,    '''w'''			) as f:
																									f.write('''{}'''			)

																		__lowerCamelCase      :      Union[str, Any]         =AutoProcessor.from_pretrained(__lowercase			)

											self.assertIsInstance(__lowercase						,    __lowercase			)




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

											__lowerCamelCase      :      str         =AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''						,    trust_remote_code=__lowercase			)
											self.assertTrue(processor.special_attribute_present			)
											self.assertEqual(processor.__class__.__name__						,    '''NewProcessor'''			)

											__lowerCamelCase      :      List[Any]         =processor.feature_extractor
											self.assertTrue(feature_extractor.special_attribute_present			)
											self.assertEqual(feature_extractor.__class__.__name__						,    '''NewFeatureExtractor'''			)

											__lowerCamelCase      :      Optional[int]         =processor.tokenizer
											self.assertTrue(tokenizer.special_attribute_present			)
											if is_tokenizers_available():
																		self.assertEqual(tokenizer.__class__.__name__						,    '''NewTokenizerFast'''			)

																		# Test we can also load the slow version
																		__lowerCamelCase      :      Optional[int]         =AutoProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_processor'''						,    trust_remote_code=__lowercase						,    use_fast=__lowercase			)
																		__lowerCamelCase      :      Dict         =new_processor.tokenizer
																		self.assertTrue(new_tokenizer.special_attribute_present			)
																		self.assertEqual(new_tokenizer.__class__.__name__						,    '''NewTokenizer'''			)
											else:
																		self.assertEqual(tokenizer.__class__.__name__						,    '''NewTokenizer'''			)




				def 					__lowercase  (     self  :Union[str, Any]			):
											try:
																		AutoConfig.register('''custom'''						,    __lowercase			)
																		AutoFeatureExtractor.register(__lowercase						,    __lowercase			)
																		AutoTokenizer.register(__lowercase						,    slow_tokenizer_class=__lowercase			)
																		AutoProcessor.register(__lowercase						,    __lowercase			)
																		# Trying to register something existing in the Transformers library will raise an error
																		with self.assertRaises(__lowercase			):
																									AutoProcessor.register(__lowercase						,    __lowercase			)

																		# Now that the config is registered, it can be used as any other config with the auto-API
																		__lowerCamelCase      :      Optional[Any]         =CustomFeatureExtractor.from_pretrained(__lowercase			)

																		with tempfile.TemporaryDirectory() as tmp_dir:
																									__lowerCamelCase      :      Optional[Any]         =os.path.join(__lowercase						,    '''vocab.txt'''			)
																									with open(__lowercase						,    '''w'''						,    encoding='''utf-8'''			) as vocab_writer:
																																vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]			)			)
																									__lowerCamelCase      :      str         =CustomTokenizer(__lowercase			)

																		__lowerCamelCase      :      int         =CustomProcessor(__lowercase						,    __lowercase			)

																		with tempfile.TemporaryDirectory() as tmp_dir:
																									processor.save_pretrained(__lowercase			)
																									__lowerCamelCase      :      Optional[Any]         =AutoProcessor.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]
																		if CustomConfig in TOKENIZER_MAPPING._extra_content:
																									del TOKENIZER_MAPPING._extra_content[CustomConfig]
																		if CustomConfig in PROCESSOR_MAPPING._extra_content:
																									del PROCESSOR_MAPPING._extra_content[CustomConfig]




				def 					__lowercase  (     self  :List[str]			):
											class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
															"""simple docstring"""
															__snake_case   :       Dict	 =		False

											class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
															"""simple docstring"""
															__snake_case   :       Optional[int]	 =		False

											class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
															"""simple docstring"""
															__snake_case   :       List[str]	 =		"""AutoFeatureExtractor"""
															__snake_case   :       Optional[int]	 =		"""AutoTokenizer"""
															__snake_case   :       Union[str, Any]	 =		False

											try:
																		AutoConfig.register('''custom'''						,    __lowercase			)
																		AutoFeatureExtractor.register(__lowercase						,    __lowercase			)
																		AutoTokenizer.register(__lowercase						,    slow_tokenizer_class=__lowercase			)
																		AutoProcessor.register(__lowercase						,    __lowercase			)
																		# If remote code is not set, the default is to use local classes.
																		__lowerCamelCase      :      str         =AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''			)
																		self.assertEqual(processor.__class__.__name__						,    '''NewProcessor'''			)
																		self.assertFalse(processor.special_attribute_present			)
																		self.assertFalse(processor.feature_extractor.special_attribute_present			)
																		self.assertFalse(processor.tokenizer.special_attribute_present			)

																		# If remote code is disabled, we load the local ones.
																		__lowerCamelCase      :      str         =AutoProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_processor'''						,    trust_remote_code=__lowercase			)
																		self.assertEqual(processor.__class__.__name__						,    '''NewProcessor'''			)
																		self.assertFalse(processor.special_attribute_present			)
																		self.assertFalse(processor.feature_extractor.special_attribute_present			)
																		self.assertFalse(processor.tokenizer.special_attribute_present			)

																		# If remote is enabled, we load from the Hub.
																		__lowerCamelCase      :      str         =AutoProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_processor'''						,    trust_remote_code=__lowercase			)
																		self.assertEqual(processor.__class__.__name__						,    '''NewProcessor'''			)
																		self.assertTrue(processor.special_attribute_present			)
																		self.assertTrue(processor.feature_extractor.special_attribute_present			)
																		self.assertTrue(processor.tokenizer.special_attribute_present			)

											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]
																		if CustomConfig in TOKENIZER_MAPPING._extra_content:
																									del TOKENIZER_MAPPING._extra_content[CustomConfig]
																		if CustomConfig in PROCESSOR_MAPPING._extra_content:
																									del PROCESSOR_MAPPING._extra_content[CustomConfig]




				def 					__lowercase  (     self  :Dict			):
											__lowerCamelCase      :      Tuple         =AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert'''			)
											self.assertEqual(processor.__class__.__name__						,    '''BertTokenizerFast'''			)




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      List[Any]         =AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext'''			)
											self.assertEqual(processor.__class__.__name__						,    '''ConvNextImageProcessor'''			)

@is_staging_test
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       Dict	 =		["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]




				@classmethod
				def 					__lowercase  (     cls  :Dict			):
											__lowerCamelCase      :      Optional[int]         =TOKEN
											HfFolder.save_token(__lowercase			)




				@classmethod
				def 					__lowercase  (     cls  :int			):
											try:
																		delete_repo(token=cls._token						,    repo_id='''test-processor'''			)
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						,    repo_id='''valid_org/test-processor-org'''			)
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						,    repo_id='''test-dynamic-processor'''			)
											except HTTPError:
																		pass




				def 					__lowercase  (     self  :Optional[Any]			):
											__lowerCamelCase      :      Optional[int]         =WavaVecaProcessor.from_pretrained(__lowercase			)
											with tempfile.TemporaryDirectory() as tmp_dir:
																		processor.save_pretrained(
																		    os.path.join(__lowercase						,    '''test-processor'''			)						,    push_to_hub=__lowercase						,    use_auth_token=self._token			)

																		__lowerCamelCase      :      Any         =WavaVecaProcessor.from_pretrained(f'{USER}/test-processor'			)
																		for k, v in processor.feature_extractor.__dict__.items():
																									self.assertEqual(__lowercase						,    getattr(new_processor.feature_extractor						,    __lowercase			)			)
																		self.assertDictEqual(new_processor.tokenizer.get_vocab()						,    processor.tokenizer.get_vocab()			)




				def 					__lowercase  (     self  :Union[str, Any]			):
											__lowerCamelCase      :      Tuple         =WavaVecaProcessor.from_pretrained(__lowercase			)

											with tempfile.TemporaryDirectory() as tmp_dir:
																		processor.save_pretrained(
																		    os.path.join(__lowercase						,    '''test-processor-org'''			)						,    push_to_hub=__lowercase						,    use_auth_token=self._token						,    organization='''valid_org'''						,    )

																		__lowerCamelCase      :      List[str]         =WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org'''			)
																		for k, v in processor.feature_extractor.__dict__.items():
																									self.assertEqual(__lowercase						,    getattr(new_processor.feature_extractor						,    __lowercase			)			)
																		self.assertDictEqual(new_processor.tokenizer.get_vocab()						,    processor.tokenizer.get_vocab()			)




				def 					__lowercase  (     self  :List[Any]			):
											CustomFeatureExtractor.register_for_auto_class()
											CustomTokenizer.register_for_auto_class()
											CustomProcessor.register_for_auto_class()

											__lowerCamelCase      :      List[Any]         =CustomFeatureExtractor.from_pretrained(__lowercase			)

											with tempfile.TemporaryDirectory() as tmp_dir:
																		__lowerCamelCase      :      int         =os.path.join(__lowercase						,    '''vocab.txt'''			)
																		with open(__lowercase						,    '''w'''						,    encoding='''utf-8'''			) as vocab_writer:
																									vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]			)			)
																		__lowerCamelCase      :      List[Any]         =CustomTokenizer(__lowercase			)

											__lowerCamelCase      :      Optional[int]         =CustomProcessor(__lowercase						,    __lowercase			)

											with tempfile.TemporaryDirectory() as tmp_dir:
																		create_repo(f'{USER}/test-dynamic-processor'						,    token=self._token			)
																		__lowerCamelCase      :      int         =Repository(__lowercase						,    clone_from=f'{USER}/test-dynamic-processor'						,    token=self._token			)
																		processor.save_pretrained(__lowercase			)

																		# This has added the proper auto_map field to the feature extractor config
																		self.assertDictEqual(
																		    processor.feature_extractor.auto_map						,    {
																		        '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''',
																		        '''AutoProcessor''': '''custom_processing.CustomProcessor''',
																		    }						,    )

																		# This has added the proper auto_map field to the tokenizer config
																		with open(os.path.join(__lowercase						,    '''tokenizer_config.json'''			)			) as f:
																									__lowerCamelCase      :      Optional[int]         =json.load(__lowercase			)
																		self.assertDictEqual(
																		    tokenizer_config['''auto_map''']						,    {
																		        '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None],
																		        '''AutoProcessor''': '''custom_processing.CustomProcessor''',
																		    }						,    )

																		# The code has been copied from fixtures
																		self.assertTrue(os.path.isfile(os.path.join(__lowercase						,    '''custom_feature_extraction.py'''			)			)			)
																		self.assertTrue(os.path.isfile(os.path.join(__lowercase						,    '''custom_tokenization.py'''			)			)			)
																		self.assertTrue(os.path.isfile(os.path.join(__lowercase						,    '''custom_processing.py'''			)			)			)

																		repo.push_to_hub()

											__lowerCamelCase      :      Dict         =AutoProcessor.from_pretrained(f'{USER}/test-dynamic-processor'						,    trust_remote_code=__lowercase			)
											# Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
											self.assertEqual(new_processor.__class__.__name__						,    '''CustomProcessor'''			)











"""simple docstring"""





from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :Optional[Any]						,    __lowercase  :Collection[float] | None = None			):
											if components is None:
																		__lowerCamelCase      :      str         =[]
											__lowerCamelCase      :      int         =list(__lowercase			)




				def __len__(     self  :Union[str, Any]			):
											return len(self.__components			)




				def __str__(     self  :List[Any]			):
											return "(" + ",".join(map(__lowercase						,    self.__components			)			) + ")"




				def __add__(     self  :Union[str, Any]						,    __lowercase  :Vector			):
											__lowerCamelCase      :      Tuple         =len(self			)
											if size == len(__lowercase			):
																		__lowerCamelCase      :      int         =[self.__components[i] + other.component(__lowercase			) for i in range(__lowercase			)]
																		return Vector(__lowercase			)
											else:
																		raise Exception('''must have the same size'''			)




				def __sub__(     self  :int						,    __lowercase  :Vector			):
											__lowerCamelCase      :      int         =len(self			)
											if size == len(__lowercase			):
																		__lowerCamelCase      :      Union[str, Any]         =[self.__components[i] - other.component(__lowercase			) for i in range(__lowercase			)]
																		return Vector(__lowercase			)
											else:  # error case
																		raise Exception('''must have the same size'''			)




				@overload
				def __mul__(     self  :List[str]						,    __lowercase  :float			):
											...




				@overload
				def __mul__(     self  :Union[str, Any]						,    __lowercase  :Vector			):
											...




				def __mul__(     self  :List[Any]						,    __lowercase  :float | Vector			):
											if isinstance(__lowercase						,    (float, int)			):
																		__lowerCamelCase      :      Optional[int]         =[c * other for c in self.__components]
																		return Vector(__lowercase			)
											elif isinstance(__lowercase						,    __lowercase			) and len(self			) == len(__lowercase			):
																		__lowerCamelCase      :      Dict         =len(self			)
																		__lowerCamelCase      :      Union[str, Any]         =[self.__components[i] * other.component(__lowercase			) for i in range(__lowercase			)]
																		return sum(__lowercase			)
											else:  # error case
																		raise Exception('''invalid operand!'''			)




				def 					__lowercase  (     self  :Optional[Any]			):
											return Vector(self.__components			)




				def 					__lowercase  (     self  :Union[str, Any]						,    __lowercase  :int			):
											if isinstance(__lowercase						,    __lowercase			) and -len(self.__components			) <= i < len(self.__components			):
																		return self.__components[i]
											else:
																		raise Exception('''index out of range'''			)




				def 					__lowercase  (     self  :int						,    __lowercase  :int						,    __lowercase  :float			):
											assert -len(self.__components			) <= pos < len(self.__components			)
											__lowerCamelCase      :      int         =value




				def 					__lowercase  (     self  :Union[str, Any]			):
											if len(self.__components			) == 0:
																		raise Exception('''Vector is empty'''			)
											__lowerCamelCase      :      Tuple         =[c**2 for c in self.__components]
											return math.sqrt(sum(__lowercase			)			)




				def 					__lowercase  (     self  :Any						,    __lowercase  :Vector						,    __lowercase  :bool = False			):
											__lowerCamelCase      :      Tuple         =self * other
											__lowerCamelCase      :      str         =self.euclidean_length() * other.euclidean_length()
											if deg:
																		return math.degrees(math.acos(num / den			)			)
											else:
																		return math.acos(num / den			)



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							assert isinstance(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )
							return Vector([0] * dimension   )



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							assert isinstance(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   ) and (isinstance(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   ))
							__lowerCamelCase      :      List[Any]         =[0] * dimension
							__lowerCamelCase      :      Union[str, Any]         =1
							return Vector(SCREAMING_SNAKE_CASE   )



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							float    ,						SCREAMING_SNAKE_CASE       :							Vector    ,						SCREAMING_SNAKE_CASE       :							Vector   ):


							'''simple docstring'''







							assert (
							    isinstance(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )
							    and isinstance(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )
							    and (isinstance(SCREAMING_SNAKE_CASE    ,						(int, float)   ))
							)
							return x * scalar + y



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							random.seed(SCREAMING_SNAKE_CASE   )
							__lowerCamelCase      :      Optional[int]         =[random.randint(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   ) for _ in range(SCREAMING_SNAKE_CASE   )]
							return Vector(SCREAMING_SNAKE_CASE   )
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :Tuple						,    __lowercase  :list[list[float]]						,    __lowercase  :int						,    __lowercase  :int			):
											__lowerCamelCase      :      Optional[Any]         =matrix
											__lowerCamelCase      :      int         =w
											__lowerCamelCase      :      str         =h




				def __str__(     self  :Optional[Any]			):
											__lowerCamelCase      :      Optional[int]         =''''''
											for i in range(self.__height			):
																		ans += "|"
																		for j in range(self.__width			):
																									if j < self.__width - 1:
																																ans += str(self.__matrix[i][j]			) + ","
																									else:
																																ans += str(self.__matrix[i][j]			) + "|\n"
											return ans




				def __add__(     self  :Any						,    __lowercase  :Matrix			):
											if self.__width == other.width() and self.__height == other.height():
																		__lowerCamelCase      :      Optional[int]         =[]
																		for i in range(self.__height			):
																									__lowerCamelCase      :      Optional[int]         =[
																									    self.__matrix[i][j] + other.component(__lowercase						,    __lowercase			)
																									    for j in range(self.__width			)
																									]
																									matrix.append(__lowercase			)
																		return Matrix(__lowercase						,    self.__width						,    self.__height			)
											else:
																		raise Exception('''matrix must have the same dimension!'''			)




				def __sub__(     self  :Tuple						,    __lowercase  :Matrix			):
											if self.__width == other.width() and self.__height == other.height():
																		__lowerCamelCase      :      List[str]         =[]
																		for i in range(self.__height			):
																									__lowerCamelCase      :      Dict         =[
																									    self.__matrix[i][j] - other.component(__lowercase						,    __lowercase			)
																									    for j in range(self.__width			)
																									]
																									matrix.append(__lowercase			)
																		return Matrix(__lowercase						,    self.__width						,    self.__height			)
											else:
																		raise Exception('''matrices must have the same dimension!'''			)




				@overload
				def __mul__(     self  :List[Any]						,    __lowercase  :float			):
											...




				@overload
				def __mul__(     self  :List[Any]						,    __lowercase  :Vector			):
											...




				def __mul__(     self  :Union[str, Any]						,    __lowercase  :float | Vector			):
											if isinstance(__lowercase						,    __lowercase			):  # matrix-vector
																		if len(__lowercase			) == self.__width:
																									__lowerCamelCase      :      int         =zero_vector(self.__height			)
																									for i in range(self.__height			):
																																__lowerCamelCase      :      Union[str, Any]         =[
																																    self.__matrix[i][j] * other.component(__lowercase			)
																																    for j in range(self.__width			)
																																]
																																ans.change_component(__lowercase						,    sum(__lowercase			)			)
																									return ans
																		else:
																									raise Exception(
																									    '''vector must have the same size as the '''
																									    '''number of columns of the matrix!'''			)
											elif isinstance(__lowercase						,    (int, float)			):  # matrix-scalar
																		__lowerCamelCase      :      Optional[Any]         =[
																		    [self.__matrix[i][j] * other for j in range(self.__width			)]
																		    for i in range(self.__height			)
																		]
																		return Matrix(__lowercase						,    self.__width						,    self.__height			)
											return None




				def 					__lowercase  (     self  :Union[str, Any]			):
											return self.__height




				def 					__lowercase  (     self  :Tuple			):
											return self.__width




				def 					__lowercase  (     self  :Any						,    __lowercase  :int						,    __lowercase  :int			):
											if 0 <= x < self.__height and 0 <= y < self.__width:
																		return self.__matrix[x][y]
											else:
																		raise Exception('''change_component: indices out of bounds'''			)




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :int						,    __lowercase  :int						,    __lowercase  :float			):
											if 0 <= x < self.__height and 0 <= y < self.__width:
																		__lowerCamelCase      :      int         =value
											else:
																		raise Exception('''change_component: indices out of bounds'''			)




				def 					__lowercase  (     self  :List[Any]						,    __lowercase  :int						,    __lowercase  :int			):
											if self.__height != self.__width:
																		raise Exception('''Matrix is not square'''			)
											__lowerCamelCase      :      Union[str, Any]         =self.__matrix[:x] + self.__matrix[x + 1 :]
											for i in range(len(__lowercase			)			):
																		__lowerCamelCase      :      Optional[int]         =minor[i][:y] + minor[i][y + 1 :]
											return Matrix(__lowercase						,    self.__width - 1						,    self.__height - 1			).determinant()




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :int						,    __lowercase  :int			):
											if self.__height != self.__width:
																		raise Exception('''Matrix is not square'''			)
											if 0 <= x < self.__height and 0 <= y < self.__width:
																		return (-1) ** (x + y) * self.minor(__lowercase						,    __lowercase			)
											else:
																		raise Exception('''Indices out of bounds'''			)




				def 					__lowercase  (     self  :Optional[Any]			):
											if self.__height != self.__width:
																		raise Exception('''Matrix is not square'''			)
											if self.__height < 1:
																		raise Exception('''Matrix has no element'''			)
											elif self.__height == 1:
																		return self.__matrix[0][0]
											elif self.__height == 2:
																		return (
																		    self.__matrix[0][0] * self.__matrix[1][1]
																		    - self.__matrix[0][1] * self.__matrix[1][0]
																		)
											else:
																		__lowerCamelCase      :      int         =[
																		    self.__matrix[0][y] * self.cofactor(0						,    __lowercase			) for y in range(self.__width			)
																		]
																		return sum(__lowercase			)



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							__lowerCamelCase      :      list[list[float]]         =[[0] * n for _ in range(SCREAMING_SNAKE_CASE   )]
							return Matrix(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							random.seed(SCREAMING_SNAKE_CASE   )
							__lowerCamelCase      :      list[list[float]]         =[
							    [random.randint(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   ) for _ in range(SCREAMING_SNAKE_CASE   )] for _ in range(SCREAMING_SNAKE_CASE   )
							]
							return Matrix(SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE   )




