






import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
	from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder







def 	SCREAMING_SNAKE_CASE							(					snake_case_   :				Any	,    snake_case_   :				Tuple	,    snake_case_   :				Union[str, Any]	,    snake_case_   :				Union[str, Any]=None	,    snake_case_   :				Optional[int]=None	,    snake_case_   :				List[str]=None	,    snake_case_   :				str=None	,    snake_case_   :				Any=None	,    ):





	if attention_mask is None:
		snake_case__					: Optional[Any]  =    input_ids.ne(config.pad_token_id  )
	if decoder_attention_mask is None:
		snake_case__					: List[str]  =    decoder_input_ids.ne(config.pad_token_id  )
	if head_mask is None:
		snake_case__					: Optional[Any]  =    torch.ones(config.encoder_layers	,    config.encoder_attention_heads	,    device=a__  )
	if decoder_head_mask is None:
		snake_case__					: List[Any]  =    torch.ones(config.decoder_layers	,    config.decoder_attention_heads	,    device=a__  )
	if cross_attn_head_mask is None:
		snake_case__					: Optional[Any]  =    torch.ones(config.decoder_layers	,    config.decoder_attention_heads	,    device=a__  )
	return {
	    "input_ids": input_ids,
	    "decoder_input_ids": decoder_input_ids,
	    "attention_mask": attention_mask,
	    "decoder_attention_mask": attention_mask,
	    "head_mask": head_mask,
	    "decoder_head_mask": decoder_head_mask,
	    "cross_attn_head_mask": cross_attn_head_mask,
	}



class 				SCREAMING_SNAKE_CASE__		:





					"""simple docstring"""






					def __init__(   self	:    str				,						__A	:    Any				,						__A	:    Tuple=1_3				,						__A	:    List[Any]=7				,						__A	:    str=True				,						__A	:    int=False				,						__A	:    Optional[int]=9_9				,						__A	:    List[Any]=1_6				,						__A	:    Optional[int]=2				,						__A	:    Union[str, Any]=4				,						__A	:    Union[str, Any]=4				,						__A	:    List[str]="relu"				,						__A	:    List[Any]=0.1				,						__A	:    Union[str, Any]=0.1				,						__A	:    Optional[Any]=0.0				,						__A	:    Dict=0.0				,						__A	:    Dict=2_0				,						__A	:    List[str]=2				,						__A	:    Tuple=1				,						__A	:    Tuple=0				,						):
						snake_case__					: Any  =    parent
						snake_case__					: Any  =    batch_size
						snake_case__					: str  =    seq_length
						snake_case__					: str  =    is_training
						snake_case__					: List[str]  =    use_labels
						snake_case__					: Dict  =    vocab_size
						snake_case__					: List[Any]  =    hidden_size
						snake_case__					: Optional[Any]  =    num_hidden_layers
						snake_case__					: str  =    num_attention_heads
						snake_case__					: Optional[Any]  =    intermediate_size
						snake_case__					: Union[str, Any]  =    hidden_act
						snake_case__					: List[Any]  =    hidden_dropout_prob
						snake_case__					: Union[str, Any]  =    attention_probs_dropout_prob
						snake_case__					: Optional[Any]  =    encoder_layerdrop
						snake_case__					: Tuple  =    decoder_layerdrop
						snake_case__					: Optional[Any]  =    max_position_embeddings
						snake_case__					: List[Any]  =    eos_token_id
						snake_case__					: Optional[Any]  =    pad_token_id
						snake_case__					: Dict  =    bos_token_id



					def 			_lowercase	(   self	:    Optional[Any]			):
						snake_case__					: Tuple  =    ids_tensor([self.batch_size, self.seq_length]				,						self.vocab_size			)
						snake_case__					: Optional[Any]  =    self.eos_token_id  # Eos Token
						snake_case__					: List[Any]  =    ids_tensor([self.batch_size, self.seq_length]				,						self.vocab_size			)

						# we need to clamp the input ids here to avoid having pad token in between
						# this is because for M2M100 the position_ids are prepared such that
						# all pad tokens have pos id = 2 and rest are between 2..seq_length
						# and the seq_length here is seq_length - num_pad_tokens
						# but when using past, there is no way of knowing if the past input ids had
						# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
						# position_ids being off by num_pad_tokens in past input
						snake_case__					: Optional[int]  =    input_ids.clamp(self.pad_token_id + 1			)
						snake_case__					: str  =    decoder_input_ids.clamp(self.pad_token_id + 1			)

						snake_case__					: str  =    self.get_config()
						snake_case__					: int  =    prepare_mam_aaa_inputs_dict(_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE			)
						return config, inputs_dict



					def 			_lowercase	(   self	:    Optional[Any]			):
						return MaMaaaConfig(
						    vocab_size=self.vocab_size				,						d_model=self.hidden_size				,						encoder_layers=self.num_hidden_layers				,						decoder_layers=self.num_hidden_layers				,						encoder_attention_heads=self.num_attention_heads				,						decoder_attention_heads=self.num_attention_heads				,						encoder_ffn_dim=self.intermediate_size				,						decoder_ffn_dim=self.intermediate_size				,						dropout=self.hidden_dropout_prob				,						attention_dropout=self.attention_probs_dropout_prob				,						encoder_layerdrop=self.encoder_layerdrop				,						decoder_layerdrop=self.decoder_layerdrop				,						max_position_embeddings=self.max_position_embeddings				,						eos_token_id=self.eos_token_id				,						bos_token_id=self.bos_token_id				,						pad_token_id=self.pad_token_id				,						)



					def 			_lowercase	(   self	:    Tuple			):
						snake_case__,		snake_case__					: Dict  =    self.prepare_config_and_inputs()
						return config, inputs_dict



					def 			_lowercase	(   self	:    List[Any]				,						__A	:    str				,						__A	:    List[Any]			):
						snake_case__					: Optional[int]  =    MaMaaaModel(config=_SCREAMING_SNAKE_CASE			).get_decoder().to(_SCREAMING_SNAKE_CASE			).eval()
						snake_case__					: List[str]  =    inputs_dict["input_ids"]
						snake_case__					: Optional[Any]  =    inputs_dict["attention_mask"]
						snake_case__					: Any  =    inputs_dict["head_mask"]

						# first forward pass
						snake_case__					: Optional[Any]  =    model(_SCREAMING_SNAKE_CASE				,						attention_mask=_SCREAMING_SNAKE_CASE				,						head_mask=_SCREAMING_SNAKE_CASE				,						use_cache=_SCREAMING_SNAKE_CASE			)

						snake_case__,		snake_case__					: Dict  =    outputs.to_tuple()

						# create hypothetical multiple next token and extent to next_input_ids
						snake_case__					: Tuple  =    ids_tensor((self.batch_size, 3)				,						config.vocab_size			)
						snake_case__					: Optional[int]  =    ids_tensor((self.batch_size, 3)				,						2			)

						# append to next input_ids and
						snake_case__					: Dict  =    torch.cat([input_ids, next_tokens]				,						dim=-1			)
						snake_case__					: Optional[Any]  =    torch.cat([attention_mask, next_attn_mask]				,						dim=-1			)

						snake_case__					: Optional[int]  =    model(_SCREAMING_SNAKE_CASE				,						attention_mask=_SCREAMING_SNAKE_CASE			)["last_hidden_state"]
						snake_case__					: List[Any]  =    model(_SCREAMING_SNAKE_CASE				,						attention_mask=_SCREAMING_SNAKE_CASE				,						past_key_values=_SCREAMING_SNAKE_CASE			)[
						    "last_hidden_state"
						]

						# select random slice
						snake_case__					: Optional[int]  =    ids_tensor((1,)				,						output_from_past.shape[-1]			).item()
						snake_case__					: str  =    output_from_no_past[:, -3:, random_slice_idx].detach()
						snake_case__					: List[str]  =    output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]			)

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE				,						atol=1e-2			)			)






					def 			_lowercase	(   self	:    Tuple				,						__A	:    Union[str, Any]				,						__A	:    Dict			):
						snake_case__					: Tuple  =    MaMaaaModel(config=_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			).eval()
						snake_case__					: str  =    model(**_SCREAMING_SNAKE_CASE			)

						snake_case__					: Optional[int]  =    outputs.encoder_last_hidden_state
						snake_case__					: Tuple  =    outputs.last_hidden_state

						with tempfile.TemporaryDirectory() as tmpdirname:
							snake_case__					: Any  =    model.get_encoder()
							encoder.save_pretrained(_SCREAMING_SNAKE_CASE			)
							snake_case__					: Dict  =    MaMaaaEncoder.from_pretrained(_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			)

						snake_case__					: Optional[Any]  =    encoder(inputs_dict["input_ids"]				,						attention_mask=inputs_dict["attention_mask"]			)[
						    0
						]

						self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3			)

						with tempfile.TemporaryDirectory() as tmpdirname:
							snake_case__					: Optional[int]  =    model.get_decoder()
							decoder.save_pretrained(_SCREAMING_SNAKE_CASE			)
							snake_case__					: List[str]  =    MaMaaaDecoder.from_pretrained(_SCREAMING_SNAKE_CASE			).to(_SCREAMING_SNAKE_CASE			)

						snake_case__					: Any  =    decoder(
						    input_ids=inputs_dict["decoder_input_ids"]				,						attention_mask=inputs_dict["decoder_attention_mask"]				,						encoder_hidden_states=_SCREAMING_SNAKE_CASE				,						encoder_attention_mask=inputs_dict["attention_mask"]				,						)[0]

						self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3			)



@require_torch
class 				SCREAMING_SNAKE_CASE__		(							UpperCamelCase_					,  UpperCamelCase_					,  UpperCamelCase_					,  unittest.TestCase		):





					"""simple docstring"""






					a_      =						(
					    (
					        MaMaaaModel,
					        MaMaaaForConditionalGeneration,
					    )
					    if is_torch_available()
					    else ()
					)
					a_      =						(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
					a_      =						(
					    {
					        'conversational': MaMaaaForConditionalGeneration,
					        'feature-extraction': MaMaaaModel,
					        'summarization': MaMaaaForConditionalGeneration,
					        'text2text-generation': MaMaaaForConditionalGeneration,
					        'translation': MaMaaaForConditionalGeneration,
					    }
					    if is_torch_available()
					    else {}
					)
					a_      =						True
					a_      =						True
					a_      =						False
					a_      =						False



					def 			_lowercase	(   self	:    Optional[Any]				,						__A	:    Dict				,						__A	:    Optional[int]				,						__A	:    List[str]				,						__A	:    Optional[Any]				,						__A	:    Optional[int]			):





						if pipeline_test_casse_name == "TranslationPipelineTests":
							# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
							# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
							return True

						return False



					def 			_lowercase	(   self	:    Dict			):
						snake_case__					: List[str]  =    MaMaaaModelTester(self			)
						snake_case__					: Union[str, Any]  =    ConfigTester(self				,						config_class=_SCREAMING_SNAKE_CASE			)



					def 			_lowercase	(   self	:    List[Any]			):
						self.config_tester.run_common_tests()



					def 			_lowercase	(   self	:    Any			):
						snake_case__,		snake_case__					: Optional[int]  =    self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
							snake_case__					: List[str]  =    model_class(_SCREAMING_SNAKE_CASE			)

							with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(_SCREAMING_SNAKE_CASE			)
								snake_case__,		snake_case__					: Tuple  =    model_class.from_pretrained(_SCREAMING_SNAKE_CASE				,						output_loading_info=_SCREAMING_SNAKE_CASE			)
							self.assertEqual(info["missing_keys"]				,						[]			)



					def 			_lowercase	(   self	:    str			):
						snake_case__					: Dict  =    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past_large_inputs(*_SCREAMING_SNAKE_CASE			)



					def 			_lowercase	(   self	:    Union[str, Any]			):
						snake_case__					: Optional[Any]  =    self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*_SCREAMING_SNAKE_CASE			)



					def 			_lowercase	(   self	:    Union[str, Any]			):
						snake_case__,		snake_case__					: int  =    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
							snake_case__					: Optional[int]  =    model_class(_SCREAMING_SNAKE_CASE			)
							model.to(_SCREAMING_SNAKE_CASE			)
							model.eval()

							snake_case__					: Any  =    copy.deepcopy(self._prepare_for_class(_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE			)			)

							if not self.is_encoder_decoder:
								snake_case__					: List[Any]  =    inputs["input_ids"]
								del inputs["input_ids"]
							else:
								snake_case__					: str  =    inputs["input_ids"]
								snake_case__					: str  =    inputs.get("decoder_input_ids"				,						_SCREAMING_SNAKE_CASE			)
								del inputs["input_ids"]
								inputs.pop("decoder_input_ids"				,						_SCREAMING_SNAKE_CASE			)

							snake_case__					: Optional[Any]  =    model.get_input_embeddings()
							if not self.is_encoder_decoder:
								snake_case__					: Dict  =    wte(_SCREAMING_SNAKE_CASE			)
							else:
								snake_case__					: Union[str, Any]  =    wte(_SCREAMING_SNAKE_CASE			)
								snake_case__					: Dict  =    wte(_SCREAMING_SNAKE_CASE			)

							with torch.no_grad():
								model(**_SCREAMING_SNAKE_CASE			)[0]






					def 			_lowercase	(   self	:    Union[str, Any]			):
						snake_case__,		snake_case__					: str  =    self.model_tester.prepare_config_and_inputs()
						snake_case__					: str  =    input_dict["input_ids"]
						snake_case__					: Tuple  =    input_ids.ne(1			).to(_SCREAMING_SNAKE_CASE			)
						snake_case__					: Tuple  =    MaMaaaForConditionalGeneration(_SCREAMING_SNAKE_CASE			).eval().to(_SCREAMING_SNAKE_CASE			)
						if torch_device == "cuda":
							model.half()
						model.generate(_SCREAMING_SNAKE_CASE				,						attention_mask=_SCREAMING_SNAKE_CASE			)
						model.generate(num_beams=4				,						do_sample=_SCREAMING_SNAKE_CASE				,						early_stopping=_SCREAMING_SNAKE_CASE				,						num_return_sequences=3			)







def 	SCREAMING_SNAKE_CASE							(					snake_case_   :				Union[str, Any]  ):
	return torch.tensor(a__	,    dtype=torch.long	,    device=a__  )


__lowerCamelCase   :     Optional[int] 		= 1e-4





@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 				SCREAMING_SNAKE_CASE__		(							unittest.TestCase		):





					"""simple docstring"""






					@cached_property
					def 			_lowercase	(   self	:    str			):
						return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"			)



					def 			_lowercase	(   self	:    Tuple			):
						snake_case__					: Tuple  =    MaMaaaModel.from_pretrained("facebook/m2m100_418M"			).to(_SCREAMING_SNAKE_CASE			)
						snake_case__					: Dict  =    _long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]			)
						snake_case__					: Any  =    _long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]			)
						snake_case__					: Tuple  =    prepare_mam_aaa_inputs_dict(model.config				,						_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE			)
						with torch.no_grad():
							snake_case__					: List[Any]  =    model(**_SCREAMING_SNAKE_CASE			)[0]
						snake_case__					: List[str]  =    torch.Size((1, 1_1, 1_0_2_4)			)
						self.assertEqual(output.shape				,						_SCREAMING_SNAKE_CASE			)
						# change to expected output here
						snake_case__					: List[Any]  =    torch.tensor(
						    [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]]				,						device=_SCREAMING_SNAKE_CASE			)
						self.assertTrue(torch.allclose(output[:, :3, :3]				,						_SCREAMING_SNAKE_CASE				,						atol=_SCREAMING_SNAKE_CASE			)			)



					def 			_lowercase	(   self	:    Union[str, Any]			):
						snake_case__					: Any  =    MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"			).to(_SCREAMING_SNAKE_CASE			)

						# change to intended input
						snake_case__					: List[str]  =    _long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]			)
						snake_case__					: Union[str, Any]  =    _long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]			)
						snake_case__					: Union[str, Any]  =    prepare_mam_aaa_inputs_dict(model.config				,						_SCREAMING_SNAKE_CASE				,						_SCREAMING_SNAKE_CASE			)
						with torch.no_grad():
							snake_case__					: Dict  =    model(**_SCREAMING_SNAKE_CASE			)[0]
						snake_case__					: Optional[int]  =    torch.Size((1, 1_1, model.config.vocab_size)			)
						self.assertEqual(output.shape				,						_SCREAMING_SNAKE_CASE			)
						# change to expected output here
						snake_case__					: List[str]  =    torch.tensor(
						    [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]]				,						device=_SCREAMING_SNAKE_CASE			)
						self.assertTrue(torch.allclose(output[:, :3, :3]				,						_SCREAMING_SNAKE_CASE				,						atol=_SCREAMING_SNAKE_CASE			)			)






					def 			_lowercase	(   self	:    Dict			):
						snake_case__					: int  =    MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"			).to(_SCREAMING_SNAKE_CASE			)
						snake_case__					: List[Any]  =    MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"				,						src_lang="fr"				,						tgt_lang="en"			)

						snake_case__					: Any  =    [
						    "L\'affaire NSA souligne l\'absence totale de débat sur le renseignement",
						    "Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.",
						    "Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"
						    " Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"
						    " l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.",
						]

						# The below article tests that we don't add any hypotheses outside of the top n_beams
						snake_case__					: List[str]  =    tokenizer(_SCREAMING_SNAKE_CASE				,						padding=_SCREAMING_SNAKE_CASE				,						return_tensors="pt"			)

						snake_case__					: List[Any]  =    model.generate(
						    input_ids=dct["input_ids"].to(_SCREAMING_SNAKE_CASE			)				,						attention_mask=dct["attention_mask"].to(_SCREAMING_SNAKE_CASE			)				,						num_beams=5				,						forced_bos_token_id=tokenizer.get_lang_id("en"			)				,						)

						snake_case__					: Union[str, Any]  =    [
						    "The NSA case highlights the total absence of intelligence debate",
						    "I think there are two levels of response from the French government.",
						    "When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."
						    " Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"
						    " communications in France.",
						]

						snake_case__					: int  =    tokenizer.batch_decode(
						    hypotheses_batch.tolist()				,						clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE				,						skip_special_tokens=_SCREAMING_SNAKE_CASE			)
						assert generated == expected_en







import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

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

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / '''utils'''))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase__    :Optional[Any]       =				get_tests_dir('''fixtures''')

class 						__a (							unittest.TestCase     ):
		def       UpperCAmelCase__							(     self		)					->			Any:




									"""simple docstring"""





									_UpperCAmelCase											=     mock.Mock()
									_UpperCAmelCase											=     500
									_UpperCAmelCase											=     {}
									_UpperCAmelCase											=     HTTPError
									_UpperCAmelCase											=     {}

									# Download this model to make sure it's in the cache.
									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2'		)
									# Under the mock environment we get a 500 error when trying to reach the model.
									with mock.patch('requests.Session.request'     ,       return_value=_SCREAMING_SNAKE_CASE		) as mock_head:
																_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2'		)
																# This check we did call the fake head request
																mock_head.assert_called()






		def       UpperCAmelCase__							(     self		)					->			Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained(
									    'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json'		)



@is_staging_test
class 						__a (							unittest.TestCase     ):
		@classmethod
		def       UpperCAmelCase__							(     cls		)					->			Tuple:




									"""simple docstring"""





									_UpperCAmelCase											=     TOKEN
									HfFolder.save_token(_SCREAMING_SNAKE_CASE		)
		@classmethod
		def       UpperCAmelCase__							(     cls		)					->			Tuple:




									"""simple docstring"""





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

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

									try:
																delete_repo(token=cls._token     ,       repo_id='test-dynamic-feature-extractor'		)
									except HTTPError:
																pass
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained(_SCREAMING_SNAKE_CASE		)
									feature_extractor.push_to_hub('test-feature-extractor'     ,       use_auth_token=self._token		)

									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained(f'''{USER}/test-feature-extractor'''		)
									for k, v in feature_extractor.__dict__.items():
																self.assertEqual(_SCREAMING_SNAKE_CASE     ,       getattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)		)

									# Reset repo
									delete_repo(token=self._token     ,       repo_id='test-feature-extractor'		)

									# Push to hub via save_pretrained
									with tempfile.TemporaryDirectory() as tmp_dir:
																feature_extractor.save_pretrained(
																    _SCREAMING_SNAKE_CASE     ,       repo_id='test-feature-extractor'     ,       push_to_hub=_SCREAMING_SNAKE_CASE     ,       use_auth_token=self._token		)

									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained(f'''{USER}/test-feature-extractor'''		)
									for k, v in feature_extractor.__dict__.items():
																self.assertEqual(_SCREAMING_SNAKE_CASE     ,       getattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)		)
		def       UpperCAmelCase__							(     self		)					->			Optional[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained(_SCREAMING_SNAKE_CASE		)
									feature_extractor.push_to_hub('valid_org/test-feature-extractor'     ,       use_auth_token=self._token		)

									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor'		)
									for k, v in feature_extractor.__dict__.items():
																self.assertEqual(_SCREAMING_SNAKE_CASE     ,       getattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)		)

									# Reset repo
									delete_repo(token=self._token     ,       repo_id='valid_org/test-feature-extractor'		)

									# Push to hub via save_pretrained
									with tempfile.TemporaryDirectory() as tmp_dir:
																feature_extractor.save_pretrained(
																    _SCREAMING_SNAKE_CASE     ,       repo_id='valid_org/test-feature-extractor-org'     ,       push_to_hub=_SCREAMING_SNAKE_CASE     ,       use_auth_token=self._token		)

									_UpperCAmelCase											=     WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org'		)
									for k, v in feature_extractor.__dict__.items():
																self.assertEqual(_SCREAMING_SNAKE_CASE     ,       getattr(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)		)






		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





									CustomFeatureExtractor.register_for_auto_class()
									_UpperCAmelCase											=     CustomFeatureExtractor.from_pretrained(_SCREAMING_SNAKE_CASE		)

									feature_extractor.push_to_hub('test-dynamic-feature-extractor'     ,       use_auth_token=self._token		)

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

									_UpperCAmelCase											=     AutoFeatureExtractor.from_pretrained(
									    f'''{USER}/test-dynamic-feature-extractor'''     ,       trust_remote_code=_SCREAMING_SNAKE_CASE		)
									# Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
									self.assertEqual(new_feature_extractor.__class__.__name__     ,       'CustomFeatureExtractor'		)
