
"""simple docstring"""





import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    FlaubertForMultipleChoice,
				    FlaubertForQuestionAnswering,
				    FlaubertForQuestionAnsweringSimple,
				    FlaubertForSequenceClassification,
				    FlaubertForTokenClassification,
				    FlaubertModel,
				    FlaubertWithLMHeadModel,
				)
				from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST






class        _UpperCAmelCase(       lowerCamelCase      ):



		def __init__(   self							,						__a							,						__a=13							,						__a=7							,						__a=True							,						__a=True							,						__a=True							,						__a=True							,						__a=True							,						__a=False							,						__a=False							,						__a=False							,						__a=2							,						__a=99							,						__a=0							,						__a=32							,						__a=5							,						__a=4							,						__a=0.1							,						__a=0.1							,						__a=5_12							,						__a=12							,						__a=2							,						__a=0.02							,						__a=3							,						__a=4							,						__a="last"							,						__a=None							,						__a=None							,						)			->			List[str]:






							'''simple docstring'''
							_UpperCamelCase									=    parent
							_UpperCamelCase									=    batch_size
							_UpperCamelCase									=    seq_length
							_UpperCamelCase									=    is_training
							_UpperCamelCase									=    use_input_lengths
							_UpperCamelCase									=    use_token_type_ids
							_UpperCamelCase									=    use_labels
							_UpperCamelCase									=    gelu_activation
							_UpperCamelCase									=    sinusoidal_embeddings
							_UpperCamelCase									=    causal
							_UpperCamelCase									=    asm
							_UpperCamelCase									=    n_langs
							_UpperCamelCase									=    vocab_size
							_UpperCamelCase									=    n_special
							_UpperCamelCase									=    hidden_size
							_UpperCamelCase									=    num_hidden_layers
							_UpperCamelCase									=    num_attention_heads
							_UpperCamelCase									=    hidden_dropout_prob
							_UpperCamelCase									=    attention_probs_dropout_prob
							_UpperCamelCase									=    max_position_embeddings
							_UpperCamelCase									=    type_vocab_size
							_UpperCamelCase									=    type_sequence_label_size
							_UpperCamelCase									=    initializer_range
							_UpperCamelCase									=    num_labels
							_UpperCamelCase									=    num_choices
							_UpperCamelCase									=    summary_type
							_UpperCamelCase									=    use_proj
							_UpperCamelCase									=    scope



		def 		UpperCAmelCase				(   self)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    ids_tensor([self.batch_size, self.seq_length]							,						self.vocab_size)
							_UpperCamelCase									=    random_attention_mask([self.batch_size, self.seq_length])

							_UpperCamelCase									=    None
							if self.use_input_lengths:
												_UpperCamelCase									=    (
												    ids_tensor([self.batch_size]							,						vocab_size=2) + self.seq_length - 2
												)  # small variation of seq_length

							_UpperCamelCase									=    None
							if self.use_token_type_ids:
												_UpperCamelCase									=    ids_tensor([self.batch_size, self.seq_length]							,						self.n_langs)

							_UpperCamelCase									=    None
							_UpperCamelCase									=    None
							_UpperCamelCase									=    None
							if self.use_labels:
												_UpperCamelCase									=    ids_tensor([self.batch_size]							,						self.type_sequence_label_size)
												_UpperCamelCase									=    ids_tensor([self.batch_size, self.seq_length]							,						self.num_labels)
												_UpperCamelCase									=    ids_tensor([self.batch_size]							,						2).float()
												_UpperCamelCase									=    ids_tensor([self.batch_size]							,						self.num_choices)

							_UpperCamelCase									=    self.get_config()

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_lengths,
							    sequence_labels,
							    token_labels,
							    is_impossible_labels,
							    choice_labels,
							    input_mask,
							)



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






							'''simple docstring'''
							return FlaubertConfig(
							    vocab_size=self.vocab_size							,						n_special=self.n_special							,						emb_dim=self.hidden_size							,						n_layers=self.num_hidden_layers							,						n_heads=self.num_attention_heads							,						dropout=self.hidden_dropout_prob							,						attention_dropout=self.attention_probs_dropout_prob							,						gelu_activation=self.gelu_activation							,						sinusoidal_embeddings=self.sinusoidal_embeddings							,						asm=self.asm							,						causal=self.causal							,						n_langs=self.n_langs							,						max_position_embeddings=self.max_position_embeddings							,						initializer_range=self.initializer_range							,						summary_type=self.summary_type							,						use_proj=self.use_proj							,						)



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertModel(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase									=    model(__a							,						lengths=__a							,						langs=__a)
							_UpperCamelCase									=    model(__a							,						langs=__a)
							_UpperCamelCase									=    model(__a)
							self.parent.assertEqual(result.last_hidden_state.shape							,						(self.batch_size, self.seq_length, self.hidden_size))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			List[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertWithLMHeadModel(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a							,						token_type_ids=__a							,						labels=__a)
							self.parent.assertEqual(result.loss.shape							,						())
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length, self.vocab_size))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertForQuestionAnsweringSimple(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a)

							_UpperCamelCase									=    model(__a							,						start_positions=__a							,						end_positions=__a)
							self.parent.assertEqual(result.start_logits.shape							,						(self.batch_size, self.seq_length))
							self.parent.assertEqual(result.end_logits.shape							,						(self.batch_size, self.seq_length))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Tuple:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertForQuestionAnswering(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a)

							_UpperCamelCase									=    model(
							    __a							,						start_positions=__a							,						end_positions=__a							,						cls_index=__a							,						is_impossible=__a							,						p_mask=__a							,						)

							_UpperCamelCase									=    model(
							    __a							,						start_positions=__a							,						end_positions=__a							,						cls_index=__a							,						is_impossible=__a							,						)

							((_UpperCamelCase)					,    )									=    result_with_labels.to_tuple()

							_UpperCamelCase									=    model(__a							,						start_positions=__a							,						end_positions=__a)

							((_UpperCamelCase)					,    )									=    result_with_labels.to_tuple()

							self.parent.assertEqual(result_with_labels.loss.shape							,						())
							self.parent.assertEqual(result.start_top_log_probs.shape							,						(self.batch_size, model.config.start_n_top))
							self.parent.assertEqual(result.start_top_index.shape							,						(self.batch_size, model.config.start_n_top))
							self.parent.assertEqual(
							    result.end_top_log_probs.shape							,						(self.batch_size, model.config.start_n_top * model.config.end_n_top))
							self.parent.assertEqual(
							    result.end_top_index.shape							,						(self.batch_size, model.config.start_n_top * model.config.end_n_top))
							self.parent.assertEqual(result.cls_logits.shape							,						(self.batch_size,))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertForSequenceClassification(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a)
							_UpperCamelCase									=    model(__a							,						labels=__a)

							self.parent.assertEqual(result.loss.shape							,						())
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.type_sequence_label_size))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			int:






							'''simple docstring'''
							_UpperCamelCase									=    self.num_labels
							_UpperCamelCase									=    FlaubertForTokenClassification(__a)
							model.to(__a)
							model.eval()

							_UpperCamelCase									=    model(__a							,						attention_mask=__a							,						labels=__a)
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.seq_length, self.num_labels))



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						__a							,						)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    self.num_choices
							_UpperCamelCase									=    FlaubertForMultipleChoice(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase									=    input_ids.unsqueeze(1).expand(-1							,						self.num_choices							,						-1).contiguous()
							_UpperCamelCase									=    token_type_ids.unsqueeze(1).expand(-1							,						self.num_choices							,						-1).contiguous()
							_UpperCamelCase									=    input_mask.unsqueeze(1).expand(-1							,						self.num_choices							,						-1).contiguous()
							_UpperCamelCase									=    model(
							    __a							,						attention_mask=__a							,						token_type_ids=__a							,						labels=__a							,						)
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, self.num_choices))




		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    
							)									=    config_and_inputs
							_UpperCamelCase									=    {
							    '''input_ids''': input_ids,
							    '''token_type_ids''': token_type_ids,
							    '''lengths''': input_lengths,
							    '''attention_mask''': input_mask,
							}
							return config, inputs_dict






@require_torch
class        _UpperCAmelCase(       lowerCamelCase ,	lowerCamelCase ,	unittest.TestCase      ):
		lowercase__         = (
		    (
		        FlaubertModel,
		        FlaubertWithLMHeadModel,
		        FlaubertForQuestionAnswering,
		        FlaubertForQuestionAnsweringSimple,
		        FlaubertForSequenceClassification,
		        FlaubertForTokenClassification,
		        FlaubertForMultipleChoice,
		    )
		    if is_torch_available()
		    else ()
		)
		lowercase__         = (
		    {
		        'feature-extraction': FlaubertModel,
		        'fill-mask': FlaubertWithLMHeadModel,
		        'question-answering': FlaubertForQuestionAnsweringSimple,
		        'text-classification': FlaubertForSequenceClassification,
		        'token-classification': FlaubertForTokenClassification,
		        'zero-shot': FlaubertForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a							,						__a							,						__a)			->			Optional[Any]:






							'''simple docstring'''
							if (
							    pipeline_test_casse_name == "QAPipelineTests"
							    and tokenizer_name is not None
							    and not tokenizer_name.endswith('''Fast''')
							):
												# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
												# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
												# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
												return True

							return False



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a=False)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    super()._prepare_for_class(__a							,						__a							,						return_labels=__a)

							if return_labels:
												if model_class.__name__ == "FlaubertForQuestionAnswering":
																	_UpperCamelCase									=    torch.zeros(
																	    self.model_tester.batch_size							,						dtype=torch.long							,						device=__a)
																	_UpperCamelCase									=    torch.zeros(
																	    self.model_tester.batch_size							,						dtype=torch.long							,						device=__a)

							return inputs_dict



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






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertModelTester(self)
							_UpperCamelCase									=    ConfigTester(self							,						config_class=__a							,						emb_dim=37)



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							self.config_tester.run_common_tests()



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_model(*__a)



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_lm_head(*__a)



		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_simple_qa(*__a)



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_qa(*__a)



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_sequence_classif(*__a)



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_token_classif(*__a)



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_multiple_choice(*__a)



		@slow
		def 		UpperCAmelCase				(   self)			->			Union[str, Any]:






							'''simple docstring'''
							for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_UpperCamelCase									=    FlaubertModel.from_pretrained(__a)
												self.assertIsNotNone(__a)




		@slow
		@require_torch_gpu
		def 		UpperCAmelCase				(   self)			->			Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
												# FlauBertForMultipleChoice behaves incorrectly in JIT environments.
												if model_class == FlaubertForMultipleChoice:
																	return

												_UpperCamelCase									=    True
												_UpperCamelCase									=    model_class(config=__a)

												_UpperCamelCase									=    self._prepare_for_class(__a							,						__a)
												_UpperCamelCase									=    torch.jit.trace(
												    __a							,						(inputs_dict['''input_ids'''].to('''cpu'''), inputs_dict['''attention_mask'''].to('''cpu''')))

												with tempfile.TemporaryDirectory() as tmp:
																	torch.jit.save(__a							,						os.path.join(__a							,						'''traced_model.pt'''))
																	_UpperCamelCase									=    torch.jit.load(os.path.join(__a							,						'''traced_model.pt''')							,						map_location=__a)
																	loaded(inputs_dict['''input_ids'''].to(__a)							,						inputs_dict['''attention_mask'''].to(__a))






@require_torch
class        _UpperCAmelCase(       unittest.TestCase      ):



		@slow
		def 		UpperCAmelCase				(   self)			->			List[str]:






							'''simple docstring'''
							_UpperCamelCase									=    FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''')
							_UpperCamelCase									=    torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
							with torch.no_grad():
												_UpperCamelCase									=    model(__a)[0]
							_UpperCamelCase									=    torch.Size((1, 11, 7_68))
							self.assertEqual(output.shape							,						__a)
							_UpperCamelCase									=    torch.tensor(
							    [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]])

							self.assertTrue(torch.allclose(output[:, :3, :3]							,						__a							,						atol=1e-4))











'''simple docstring'''

import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
	import torch

if is_datasets_available():
	from datasets import load_dataset

a							   =				random.Random()







def a_     (    __UpperCAmelCase				,							__UpperCAmelCase=1.0				,							__UpperCAmelCase=None				,							__UpperCAmelCase=None					)				->					List[str]:





			"""simple docstring"""







			if rng is None:
						snake_case:    Dict      							=global_rng

			snake_case:    Tuple      							=[]
			for batch_idx in range(shape[0]					):
						values.append([]					)
						for _ in range(shape[1]					):
									values[-1].append(rng.random() * scale					)

			return values






class 						a_		(     unittest.TestCase    ):


							def __init__(				self   :						int      ,						a_   :						Any      ,						a_   :						str=7      ,						a_   :						Tuple=4_0_0      ,						a_   :						List[Any]=2_0_0_0      ,						a_   :						str=2_0_4_8      ,						a_   :						List[str]=1_2_8      ,						a_   :						int=1      ,						a_   :						Tuple=5_1_2      ,						a_   :						Dict=3_0      ,						a_   :						Optional[int]=4_4_1_0_0      ,						)			->					Union[str, Any]:
										snake_case:    Union[str, Any]      							=parent
										snake_case:    Optional[Any]      							=batch_size
										snake_case:    Union[str, Any]      							=min_seq_length
										snake_case:    List[str]      							=max_seq_length
										snake_case:    str      							=(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
										snake_case:    int      							=spectrogram_length
										snake_case:    List[str]      							=feature_size
										snake_case:    Dict      							=num_audio_channels
										snake_case:    int      							=hop_length
										snake_case:    List[Any]      							=chunk_length
										snake_case:    Optional[Any]      							=sampling_rate


							def    UpperCamelCase     (				self   :						Any			)			->					Dict:
										return {
										    "spectrogram_length": self.spectrogram_length,
										    "feature_size": self.feature_size,
										    "num_audio_channels": self.num_audio_channels,
										    "hop_length": self.hop_length,
										    "chunk_length": self.chunk_length,
										    "sampling_rate": self.sampling_rate,
										}




							def    UpperCamelCase     (				self   :						Tuple      ,						a_   :						Optional[Any]=False      ,						a_   :						Tuple=False			)			->					Optional[int]:
										def _flatten(a_   :						Dict			):
													return list(itertools.chain(*a_			)			)

										if equal_length:
													snake_case:    Union[str, Any]      							=[floats_list((self.max_seq_length, self.feature_size)			) for _ in range(self.batch_size			)]
										else:
													# make sure that inputs increase in size
													snake_case:    Union[str, Any]      							=[
													    floats_list((x, self.feature_size)			)
													    for x in range(self.min_seq_length      ,						self.max_seq_length      ,						self.seq_length_diff			)
													]
										if numpify:
													snake_case:    Any      							=[np.asarray(a_			) for x in speech_inputs]
										return speech_inputs






@require_torch
@require_torchaudio
class 						a_		(     snake_case    ,   unittest.TestCase    ):
							UpperCAmelCase			:		Optional[Any]        =				TvltFeatureExtractor


							def    UpperCamelCase     (				self   :						int			)			->					int:
										snake_case:    Union[str, Any]      							=TvltFeatureExtractionTester(self			)


							def    UpperCamelCase     (				self   :						Optional[Any]			)			->					str:
										snake_case:    int      							=self.feature_extraction_class(**self.feat_extract_dict			)
										self.assertTrue(hasattr(a_      ,						'spectrogram_length'			)			)
										self.assertTrue(hasattr(a_      ,						'feature_size'			)			)
										self.assertTrue(hasattr(a_      ,						'num_audio_channels'			)			)
										self.assertTrue(hasattr(a_      ,						'hop_length'			)			)
										self.assertTrue(hasattr(a_      ,						'chunk_length'			)			)
										self.assertTrue(hasattr(a_      ,						'sampling_rate'			)			)


							def    UpperCamelCase     (				self   :						Tuple			)			->					Optional[int]:
										snake_case:    Tuple      							=self.feature_extraction_class(**self.feat_extract_dict			)

										with tempfile.TemporaryDirectory() as tmpdirname:
													snake_case:    Optional[Any]      							=feat_extract_first.save_pretrained(a_			)[0]
													check_json_file_has_correct_format(a_			)
													snake_case:    str      							=self.feature_extraction_class.from_pretrained(a_			)

										snake_case:    Optional[int]      							=feat_extract_first.to_dict()
										snake_case:    List[str]      							=feat_extract_second.to_dict()
										snake_case:    Optional[int]      							=dict_first.pop('mel_filters'			)
										snake_case:    List[Any]      							=dict_second.pop('mel_filters'			)
										self.assertTrue(np.allclose(a_      ,						a_			)			)
										self.assertEqual(a_      ,						a_			)


							def    UpperCamelCase     (				self   :						str			)			->					str:
										snake_case:    Any      							=self.feature_extraction_class(**self.feat_extract_dict			)

										with tempfile.TemporaryDirectory() as tmpdirname:
													snake_case:    int      							=os.path.join(a_      ,						'feat_extract.json'			)
													feat_extract_first.to_json_file(a_			)
													snake_case:    Union[str, Any]      							=self.feature_extraction_class.from_json_file(a_			)

										snake_case:    Optional[Any]      							=feat_extract_first.to_dict()
										snake_case:    Optional[Any]      							=feat_extract_second.to_dict()
										snake_case:    Union[str, Any]      							=dict_first.pop('mel_filters'			)
										snake_case:    Union[str, Any]      							=dict_second.pop('mel_filters'			)
										self.assertTrue(np.allclose(a_      ,						a_			)			)
										self.assertEqual(a_      ,						a_			)


							def    UpperCamelCase     (				self   :						Union[str, Any]			)			->					List[str]:
										# Initialize feature_extractor
										snake_case:    Tuple      							=self.feature_extraction_class(**self.feat_extract_dict			)

										# create three inputs of length 800, 1000, and 1200
										snake_case:    Any      							=[floats_list((1, x)			)[0] for x in range(8_0_0      ,						1_4_0_0      ,						2_0_0			)]
										snake_case:    Optional[Any]      							=[np.asarray(a_			) for speech_input in speech_inputs]

										# Test not batched input
										snake_case:    List[Any]      							=feature_extractor(np_speech_inputs[0]      ,						return_tensors='np'      ,						sampling_rate=4_4_1_0_0			).audio_values

										self.assertTrue(encoded_audios.ndim == 4			)
										self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size			)
										self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length			)
										self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels			)

										# Test batched
										snake_case:    Any      							=feature_extractor(a_      ,						return_tensors='np'      ,						sampling_rate=4_4_1_0_0			).audio_values

										self.assertTrue(encoded_audios.ndim == 4			)
										self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size			)
										self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length			)
										self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels			)

										# Test audio masking
										snake_case:    Optional[Any]      							=feature_extractor(
										    a_      ,						return_tensors='np'      ,						sampling_rate=4_4_1_0_0      ,						mask_audio=a_			).audio_values

										self.assertTrue(encoded_audios.ndim == 4			)
										self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size			)
										self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length			)
										self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels			)

										# Test 2-D numpy arrays are batched.
										snake_case:    List[Any]      							=[floats_list((1, x)			)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
										snake_case:    List[str]      							=np.asarray(a_			)
										snake_case:    str      							=feature_extractor(a_      ,						return_tensors='np'      ,						sampling_rate=4_4_1_0_0			).audio_values
										self.assertTrue(encoded_audios.ndim == 4			)
										self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size			)
										self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length			)
										self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels			)


							def    UpperCamelCase     (				self   :						Any      ,						a_   :						str			)			->					Union[str, Any]:
										snake_case:    Dict      							=load_dataset('hf-internal-testing/librispeech_asr_dummy'      ,						'clean'      ,						split='validation'			)
										# automatic decoding with librispeech
										snake_case:    Optional[int]      							=ds.sort('id'			).select(range(a_			)			)[:num_samples]['audio']

										return [x["array"] for x in speech_samples]




							def    UpperCamelCase     (				self   :						Optional[Any]			)			->					Optional[int]:
										snake_case:    Tuple      							=self._load_datasamples(1			)
										snake_case:    Any      							=TvltFeatureExtractor()
										snake_case:    Any      							=feature_extractor(a_      ,						return_tensors='pt'			).audio_values

										self.assertEquals(audio_values.shape      ,						(1, 1, 1_9_2, 1_2_8)			)

										snake_case:    int      							=torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]]			)
										self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]      ,						a_      ,						atol=1E-4			)			)




