





import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
						from transformers import SpeechaTextFeatureExtractor

_SCREAMING_SNAKE_CASE     :   Tuple      	=		random.Random()


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a=1.0   , __a=None   , __a=None   ):

	if rng is None:
		snake_case_		:			Dict											=	global_rng

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

	return values
@require_torch
@require_torchaudio
class SCREAMING_SNAKE_CASE_						(					unittest.TestCase					):






						def __init__(      self      :      Tuple		,   _A      :      Dict		,   _A      :      List[str]=7		,   _A      :      Optional[Any]=400		,   _A      :      Tuple=2000		,   _A      :      List[str]=24		,   _A      :      List[Any]=24		,   _A      :      Union[str, Any]=0.0		,   _A      :      Dict=16000		,   _A      :      Any=True		,   _A      :      int=True		,   )							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	parent
							snake_case_		:			str											=	batch_size
							snake_case_		:			Optional[Any]											=	min_seq_length
							snake_case_		:			List[Any]											=	max_seq_length
							snake_case_		:			Optional[int]											=	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
							snake_case_		:			str											=	feature_size
							snake_case_		:			str											=	num_mel_bins
							snake_case_		:			Tuple											=	padding_value
							snake_case_		:			Tuple											=	sampling_rate
							snake_case_		:			Optional[Any]											=	return_attention_mask
							snake_case_		:			Union[str, Any]											=	do_normalize






						def UpperCAmelCase_				(      self      :      Tuple	)							->    int:







							"""simple docstring"""


							return {
							    "feature_size": self.feature_size,
							    "num_mel_bins": self.num_mel_bins,
							    "padding_value": self.padding_value,
							    "sampling_rate": self.sampling_rate,
							    "return_attention_mask": self.return_attention_mask,
							    "do_normalize": self.do_normalize,
							}






						def UpperCAmelCase_				(      self      :      List[Any]		,   _A      :      Any=False		,   _A      :      Optional[int]=False	)							->    List[str]:







							"""simple docstring"""


							def _flatten(_A      :      Dict	):
								return list(itertools.chain(*__lowerCamelCase	)	)

							if equal_length:
								snake_case_		:			Tuple											=	[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_		:			Tuple											=	[
								    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_		:			Union[str, Any]											=	[np.asarray(__lowerCamelCase	) for x in speech_inputs]
							return speech_inputs
@require_torch
@require_torchaudio
class SCREAMING_SNAKE_CASE_						(					lowerCamelCase__       ,				unittest.TestCase					):
						__magic_name__:			Union[str, Any]       =       SpeechaTextFeatureExtractor if is_speech_available() else None






						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	SpeechaTextFeatureExtractionTester(self	)






						def UpperCAmelCase_				(      self      :      List[str]		,   _A      :      Any	)							->    int:







							"""simple docstring"""


							self.assertTrue(np.all(np.mean(__lowerCamelCase		,   axis=0	) < 1E-3	)	)
							self.assertTrue(np.all(np.abs(np.var(__lowerCamelCase		,   axis=0	) - 1	) < 1E-3	)	)






						def UpperCAmelCase_				(      self      :      Tuple	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							# create three inputs of length 800, 1000, and 1200
							snake_case_		:			Any											=	[floats_list((1, x)	)[0] for x in range(800		,   1400		,   200	)]
							snake_case_		:			Optional[Any]											=	[np.asarray(__lowerCamelCase	) for speech_input in speech_inputs]

							# Test feature size
							snake_case_		:			str											=	feature_extractor(__lowerCamelCase		,   padding=__lowerCamelCase		,   return_tensors='np'	).input_features
							self.assertTrue(input_features.ndim == 3	)
							self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size	)

							# Test not batched input
							snake_case_		:			Tuple											=	feature_extractor(speech_inputs[0]		,   return_tensors='np'	).input_features
							snake_case_		:			Tuple											=	feature_extractor(np_speech_inputs[0]		,   return_tensors='np'	).input_features
							self.assertTrue(np.allclose(__lowerCamelCase		,   __lowerCamelCase		,   atol=1E-3	)	)

							# Test batched
							snake_case_		:			Dict											=	feature_extractor(__lowerCamelCase		,   return_tensors='np'	).input_features
							snake_case_		:			Dict											=	feature_extractor(__lowerCamelCase		,   return_tensors='np'	).input_features
							for enc_seq_a, enc_seq_a in zip(__lowerCamelCase		,   __lowerCamelCase	):
								self.assertTrue(np.allclose(__lowerCamelCase		,   __lowerCamelCase		,   atol=1E-3	)	)

							# Test 2-D numpy arrays are batched.
							snake_case_		:			Optional[int]											=	[floats_list((1, x)	)[0] for x in (800, 800, 800)]
							snake_case_		:			Union[str, Any]											=	np.asarray(__lowerCamelCase	)
							snake_case_		:			Dict											=	feature_extractor(__lowerCamelCase		,   return_tensors='np'	).input_features
							snake_case_		:			Dict											=	feature_extractor(__lowerCamelCase		,   return_tensors='np'	).input_features
							for enc_seq_a, enc_seq_a in zip(__lowerCamelCase		,   __lowerCamelCase	):
								self.assertTrue(np.allclose(__lowerCamelCase		,   __lowerCamelCase		,   atol=1E-3	)	)






						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			Any											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							snake_case_		:			str											=	[floats_list((1, x)	)[0] for x in range(800		,   1400		,   200	)]

							snake_case_		:			List[Any]											=	['''longest''', '''max_length''', '''do_not_pad''']
							snake_case_		:			int											=	[None, 16, None]
							for max_length, padding in zip(__lowerCamelCase		,   __lowerCamelCase	):
								snake_case_		:			Optional[int]											=	feature_extractor(
								    __lowerCamelCase		,   padding=__lowerCamelCase		,   max_length=__lowerCamelCase		,   return_attention_mask=__lowerCamelCase	)
								snake_case_		:			Tuple											=	inputs.input_features
								snake_case_		:			Optional[Any]											=	inputs.attention_mask
								snake_case_		:			int											=	[np.sum(__lowerCamelCase	) for x in attention_mask]

								self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]	)
								self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]	)
								self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]	)






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







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							snake_case_		:			str											=	[floats_list((1, x)	)[0] for x in range(800		,   1400		,   200	)]

							snake_case_		:			str											=	['''longest''', '''max_length''', '''do_not_pad''']
							snake_case_		:			Optional[int]											=	[None, 16, None]
							for max_length, padding in zip(__lowerCamelCase		,   __lowerCamelCase	):
								snake_case_		:			Optional[Any]											=	feature_extractor(
								    __lowerCamelCase		,   max_length=__lowerCamelCase		,   padding=__lowerCamelCase		,   return_tensors='np'		,   return_attention_mask=__lowerCamelCase	)
								snake_case_		:			List[Any]											=	inputs.input_features
								snake_case_		:			Optional[int]											=	inputs.attention_mask
								snake_case_		:			Optional[Any]											=	[np.sum(__lowerCamelCase	) for x in attention_mask]

								self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]	)
								self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6	)
								self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]	)
								self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6	)
								self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]	)






						def UpperCAmelCase_				(      self      :      int	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							snake_case_		:			Optional[int]											=	[floats_list((1, x)	)[0] for x in range(800		,   1400		,   200	)]
							snake_case_		:			Union[str, Any]											=	feature_extractor(
							    __lowerCamelCase		,   padding='max_length'		,   max_length=4		,   truncation=__lowerCamelCase		,   return_tensors='np'		,   return_attention_mask=__lowerCamelCase		,   )
							snake_case_		:			Optional[Any]											=	inputs.input_features
							snake_case_		:			Any											=	inputs.attention_mask
							snake_case_		:			Dict											=	np.sum(attention_mask == 1		,   axis=1	)

							self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]	)
							self._check_zero_mean_unit_variance(input_features[1]	)
							self._check_zero_mean_unit_variance(input_features[2]	)






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







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							snake_case_		:			List[str]											=	[floats_list((1, x)	)[0] for x in range(800		,   1400		,   200	)]
							snake_case_		:			Dict											=	feature_extractor(
							    __lowerCamelCase		,   padding='longest'		,   max_length=4		,   truncation=__lowerCamelCase		,   return_tensors='np'		,   return_attention_mask=__lowerCamelCase		,   )
							snake_case_		:			Optional[Any]											=	inputs.input_features
							snake_case_		:			int											=	inputs.attention_mask
							snake_case_		:			Any											=	np.sum(attention_mask == 1		,   axis=1	)

							self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]	)
							self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]	)
							self._check_zero_mean_unit_variance(input_features[2]	)

							# make sure that if max_length < longest -> then pad to max_length
							self.assertEqual(input_features.shape		,   (3, 4, 24)	)

							snake_case_		:			List[Any]											=	[floats_list((1, x)	)[0] for x in range(800		,   1400		,   200	)]
							snake_case_		:			Any											=	feature_extractor(
							    __lowerCamelCase		,   padding='longest'		,   max_length=16		,   truncation=__lowerCamelCase		,   return_tensors='np'		,   return_attention_mask=__lowerCamelCase		,   )
							snake_case_		:			Union[str, Any]											=	inputs.input_features
							snake_case_		:			List[Any]											=	inputs.attention_mask
							snake_case_		:			str											=	np.sum(attention_mask == 1		,   axis=1	)

							self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]	)
							self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]	)
							self._check_zero_mean_unit_variance(input_features[2]	)

							# make sure that if max_length < longest -> then pad to max_length
							self.assertEqual(input_features.shape		,   (3, 6, 24)	)






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







							"""simple docstring"""


							import torch

							snake_case_		:			Dict											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							snake_case_		:			Union[str, Any]											=	np.random.rand(100		,   32	).astype(np.floataa	)
							snake_case_		:			Union[str, Any]											=	np_speech_inputs.tolist()

							for inputs in [py_speech_inputs, np_speech_inputs]:
								snake_case_		:			Tuple											=	feature_extractor.pad([{'input_features': inputs}]		,   return_tensors='np'	)
								self.assertTrue(np_processed.input_features.dtype == np.floataa	)
								snake_case_		:			Optional[Any]											=	feature_extractor.pad([{'input_features': inputs}]		,   return_tensors='pt'	)
								self.assertTrue(pt_processed.input_features.dtype == torch.floataa	)






						def UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      List[Any]	)							->    Dict:







							"""simple docstring"""


							from datasets import load_dataset

							snake_case_		:			str											=	load_dataset('hf-internal-testing/librispeech_asr_dummy'		,   'clean'		,   split='validation'	)
							# automatic decoding with librispeech
							snake_case_		:			Optional[Any]											=	ds.sort('id'	).select(range(__lowerCamelCase	)	)[:num_samples]['''audio''']

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






						def UpperCAmelCase_				(      self      :      Any	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	np.array([
							    -1.5_7_4_5, -1.7_7_1_3, -1.7_0_2_0, -1.6_0_6_9, -1.2_2_5_0, -1.1_1_0_5, -0.9_0_7_2, -0.8_2_4_1,
							    -1.2_3_1_0, -0.8_0_9_8, -0.3_3_2_0, -0.4_1_0_1, -0.7_9_8_5, -0.4_9_9_6, -0.8_2_1_3, -0.9_1_2_8,
							    -1.0_4_2_0, -1.1_2_8_6, -1.0_4_4_0, -0.7_9_9_9, -0.8_4_0_5, -1.2_2_7_5, -1.5_4_4_3, -1.4_6_2_5,
							]	)
							# fmt: on

							snake_case_		:			List[Any]											=	self._load_datasamples(1	)
							snake_case_		:			Optional[Any]											=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
							snake_case_		:			Optional[Any]											=	feature_extractor(__lowerCamelCase		,   return_tensors='pt'	).input_features
							self.assertEquals(input_features.shape		,   (1, 584, 24)	)
							self.assertTrue(np.allclose(input_features[0, 0, :30]		,   __lowerCamelCase		,   atol=1E-4	)	)








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE      	=		{
    """configuration_lxmert""": ["""LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LxmertConfig"""],
    """tokenization_lxmert""": ["""LxmertTokenizer"""],
}

try:
						if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		["""LxmertTokenizerFast"""]

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		[
						    """LxmertEncoder""",
						    """LxmertForPreTraining""",
						    """LxmertForQuestionAnswering""",
						    """LxmertModel""",
						    """LxmertPreTrainedModel""",
						    """LxmertVisualFeatureEncoder""",
						    """LxmertXLayer""",
						]

try:
						if not is_tf_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		[
						    """TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
						    """TFLxmertForPreTraining""",
						    """TFLxmertMainLayer""",
						    """TFLxmertModel""",
						    """TFLxmertPreTrainedModel""",
						    """TFLxmertVisualFeatureEncoder""",
						]


if TYPE_CHECKING:
						from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig
						from .tokenization_lxmert import LxmertTokenizer

						try:
												if not is_tokenizers_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_lxmert_fast import LxmertTokenizerFast

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_lxmert import (
												    LxmertEncoder,
												    LxmertForPreTraining,
												    LxmertForQuestionAnswering,
												    LxmertModel,
												    LxmertPreTrainedModel,
												    LxmertVisualFeatureEncoder,
												    LxmertXLayer,
												)

						try:
												if not is_tf_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_tf_lxmert import (
												    TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    TFLxmertForPreTraining,
												    TFLxmertMainLayer,
												    TFLxmertModel,
												    TFLxmertPreTrainedModel,
												    TFLxmertVisualFeatureEncoder,
												)

else:
						import sys

						_SCREAMING_SNAKE_CASE      	=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

