

import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
			from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import DPTImageProcessor






class _UpperCamelCase							:
			'''simple docstring'''







			def __init__(	self							:       Any					,					a							:       List[str]					,					a							:       List[Any]=2					,					a							:       Optional[Any]=32					,					a							:       List[Any]=16					,					a							:       Optional[Any]=3					,					a							:       List[str]=True					,					a							:       List[str]=True					,					a							:       Tuple=32					,					a							:       List[str]=4					,					a							:       str=[0, 1, 2, 3]					,					a							:       Tuple=4					,					a							:       int=37					,					a							:       Union[str, Any]="gelu"					,					a							:       int=0.1					,					a							:       List[str]=0.1					,					a							:       Tuple=0.02					,					a							:       Optional[int]=3					,					a							:       Any=[1, 384, 24, 24]					,					a							:       Union[str, Any]=True					,					a							:       Any=None					,					)							->				Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Any    =				parent
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				batch_size
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				image_size
				SCREAMING_SNAKE_CASE      :					Dict    =				patch_size
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				num_channels
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				is_training
				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				use_labels
				SCREAMING_SNAKE_CASE      :					int    =				hidden_size
				SCREAMING_SNAKE_CASE      :					List[str]    =				num_hidden_layers
				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				backbone_out_indices
				SCREAMING_SNAKE_CASE      :					List[str]    =				num_attention_heads
				SCREAMING_SNAKE_CASE      :					Dict    =				intermediate_size
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				hidden_act
				SCREAMING_SNAKE_CASE      :					int    =				hidden_dropout_prob
				SCREAMING_SNAKE_CASE      :					str    =				attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE      :					Tuple    =				initializer_range
				SCREAMING_SNAKE_CASE      :					List[str]    =				num_labels
				SCREAMING_SNAKE_CASE      :					List[Any]    =				backbone_featmap_shape
				SCREAMING_SNAKE_CASE      :					int    =				scope
				SCREAMING_SNAKE_CASE      :					List[str]    =				is_hybrid
				# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
				SCREAMING_SNAKE_CASE      :					List[Any]    =				(image_size // patch_size) ** 2
				SCREAMING_SNAKE_CASE      :					int    =				num_patches + 1
			def 							__UpperCamelCase       (	self							:       Tuple		)							->				Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Dict    =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

				SCREAMING_SNAKE_CASE      :					int    =				None
				if self.use_labels:
					SCREAMING_SNAKE_CASE      :					Tuple    =				ids_tensor([self.batch_size, self.image_size, self.image_size]					,					self.num_labels		)

				SCREAMING_SNAKE_CASE      :					List[str]    =				self.get_config()

				return config, pixel_values, labels
			def 							__UpperCamelCase       (	self							:       List[Any]		)							->				List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Tuple    =				{
				    "global_padding": "same",
				    "layer_type": "bottleneck",
				    "depths": [3, 4, 9],
				    "out_features": ["stage1", "stage2", "stage3"],
				    "embedding_dynamic_padding": True,
				    "hidden_sizes": [96, 192, 384, 768],
				    "num_groups": 2,
				}

				return DPTConfig(
				    image_size=self.image_size					,					patch_size=self.patch_size					,					num_channels=self.num_channels					,					hidden_size=self.hidden_size					,					num_hidden_layers=self.num_hidden_layers					,					backbone_out_indices=self.backbone_out_indices					,					num_attention_heads=self.num_attention_heads					,					intermediate_size=self.intermediate_size					,					hidden_act=self.hidden_act					,					hidden_dropout_prob=self.hidden_dropout_prob					,					attention_probs_dropout_prob=self.attention_probs_dropout_prob					,					is_decoder=a					,					initializer_range=self.initializer_range					,					is_hybrid=self.is_hybrid					,					backbone_config=a					,					backbone_featmap_shape=self.backbone_featmap_shape					,					)
			def 							__UpperCamelCase       (	self							:       Any					,					a							:       str					,					a							:       Union[str, Any]					,					a							:       List[str]		)							->				Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					int    =				DPTModel(config=a		)
				model.to(a		)
				model.eval()
				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				model(a		)
				self.parent.assertEqual(result.last_hidden_state.shape					,					(self.batch_size, self.seq_length, self.hidden_size)		)
			def 							__UpperCamelCase       (	self							:       str					,					a							:       Dict					,					a							:       Dict					,					a							:       int		)							->				Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					List[Any]    =				self.num_labels
				SCREAMING_SNAKE_CASE      :					List[Any]    =				DPTForDepthEstimation(a		)
				model.to(a		)
				model.eval()
				SCREAMING_SNAKE_CASE      :					Dict    =				model(a		)
				self.parent.assertEqual(result.predicted_depth.shape					,					(self.batch_size, self.image_size, self.image_size)		)
			def 							__UpperCamelCase       (	self							:       Union[str, Any]					,					a							:       Any					,					a							:       List[Any]					,					a							:       Union[str, Any]		)							->				Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					str    =				self.num_labels
				SCREAMING_SNAKE_CASE      :					str    =				DPTForSemanticSegmentation(a		)
				model.to(a		)
				model.eval()
				SCREAMING_SNAKE_CASE      :					List[str]    =				model(a					,					labels=a		)
				self.parent.assertEqual(
				    result.logits.shape					,					(self.batch_size, self.num_labels, self.image_size, self.image_size)		)






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

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Dict    =				self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					str    =				config_and_inputs
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				{"pixel_values": pixel_values}
				return config, inputs_dict






@require_torch
class _UpperCamelCase							(							__A							,		__A							,		unittest.TestCase      ):
			'''simple docstring'''







			lowerCamelCase__							=(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
			lowerCamelCase__							=(
			    {
			        'depth-estimation': DPTForDepthEstimation,
			        'feature-extraction': DPTModel,
			        'image-segmentation': DPTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			lowerCamelCase__							=False
			lowerCamelCase__							=False
			lowerCamelCase__							=False
			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				DPTModelTester(self		)
				SCREAMING_SNAKE_CASE      :					Tuple    =				ConfigTester(self					,					config_class=a					,					has_text_modality=a					,					hidden_size=37		)
			def 							__UpperCamelCase       (	self							:       Optional[int]		)							->				str:

				"""simple docstring"""

				self.config_tester.run_common_tests()
			@unittest.skip(reason="DPT does not use inputs_embeds"		)
			def 							__UpperCamelCase       (	self							:       Tuple		)							->				Dict:

				"""simple docstring"""

				pass
			def 							__UpperCamelCase       (	self							:       Dict		)							->				str:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Tuple    =				self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE      :					List[str]    =				model_class(a		)
					self.assertIsInstance(model.get_input_embeddings()					,					(nn.Module)		)
					SCREAMING_SNAKE_CASE      :					Any    =				model.get_output_embeddings()
					self.assertTrue(x is None or isinstance(a					,					nn.Linear		)		)
			def 							__UpperCamelCase       (	self							:       List[Any]		)							->				Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Optional[Any]    =				self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE      :					str    =				model_class(a		)
					SCREAMING_SNAKE_CASE      :					List[str]    =				inspect.signature(model.forward		)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				[*signature.parameters.keys()]

					SCREAMING_SNAKE_CASE      :					Dict    =				["pixel_values"]
					self.assertListEqual(arg_names[:1]					,					a		)
			def 							__UpperCamelCase       (	self							:       str		)							->				str:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					List[Any]    =				self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a		)
			def 							__UpperCamelCase       (	self							:       str		)							->				List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_depth_estimation(*a		)
			def 							__UpperCamelCase       (	self							:       int		)							->				List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*a		)
			def 							__UpperCamelCase       (	self							:       Union[str, Any]		)							->				List[str]:

				"""simple docstring"""

				for model_class in self.all_model_classes:
					if model_class.__name__ == "DPTForDepthEstimation":
						continue

					SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					List[str]    =				self.model_tester.prepare_config_and_inputs_for_common()
					SCREAMING_SNAKE_CASE      :					str    =				True

					if model_class in get_values(a		):
						continue

					SCREAMING_SNAKE_CASE      :					Tuple    =				model_class(a		)
					model.to(a		)
					model.train()
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				self._prepare_for_class(a					,					a					,					return_labels=a		)
					SCREAMING_SNAKE_CASE      :					Optional[int]    =				model(**a		).loss
					loss.backward()
			def 							__UpperCamelCase       (	self							:       List[Any]		)							->				Optional[int]:

				"""simple docstring"""

				for model_class in self.all_model_classes:
					if model_class.__name__ == "DPTForDepthEstimation":
						continue

					SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Any    =				self.model_tester.prepare_config_and_inputs_for_common()
					SCREAMING_SNAKE_CASE      :					List[Any]    =				False
					SCREAMING_SNAKE_CASE      :					Any    =				True

					if model_class in get_values(a		) or not model_class.supports_gradient_checkpointing:
						continue
					SCREAMING_SNAKE_CASE      :					Any    =				model_class(a		)
					model.to(a		)
					model.gradient_checkpointing_enable()
					model.train()
					SCREAMING_SNAKE_CASE      :					int    =				self._prepare_for_class(a					,					a					,					return_labels=a		)
					SCREAMING_SNAKE_CASE      :					List[str]    =				model(**a		).loss
					loss.backward()
			def 							__UpperCamelCase       (	self							:       Union[str, Any]		)							->				Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					int    =				self.model_tester.prepare_config_and_inputs_for_common()

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				_config_zero_init(a		)
				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE      :					List[Any]    =				model_class(config=a		)
					# Skip the check for the backbone
					SCREAMING_SNAKE_CASE      :					Any    =				[]
					for name, module in model.named_modules():
						if module.__class__.__name__ == "DPTViTHybridEmbeddings":
							SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				[F"{name}.{key}" for key in module.state_dict().keys()]
							break

					for name, param in model.named_parameters():
						if param.requires_grad:
							if name in backbone_params:
								continue
							self.assertIn(
							    ((param.data.mean() * 1e9).round() / 1e9).item()					,					[0.0, 1.0]					,					msg=F"Parameter {name} of model {model_class} seems not properly initialized"					,					)
			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."		)
			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				List[str]:

				"""simple docstring"""

				pass
			@slow
			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				List[str]:

				"""simple docstring"""

				for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
					SCREAMING_SNAKE_CASE      :					Any    =				DPTModel.from_pretrained(a		)
					self.assertIsNotNone(a		)






			def 							__UpperCamelCase       (	self							:       str		)							->				int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Tuple    =				self.model_tester.prepare_config_and_inputs_for_common()
				SCREAMING_SNAKE_CASE      :					List[Any]    =				"add"
				with self.assertRaises(a		):
					SCREAMING_SNAKE_CASE      :					List[str]    =				DPTForDepthEstimation(a		)

def        lowerCamelCase__       (    ):
	SCREAMING_SNAKE_CASE      :					List[Any]    =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
	return image






@require_torch
@require_vision
@slow
class _UpperCamelCase							(							unittest.TestCase      ):
			'''simple docstring'''







			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				str:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas"		)
				SCREAMING_SNAKE_CASE      :					str    =				DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas"		).to(a		)

				SCREAMING_SNAKE_CASE      :					Any    =				prepare_img()
				SCREAMING_SNAKE_CASE      :					str    =				image_processor(images=a					,					return_tensors="pt"		).to(a		)

				# forward pass
				with torch.no_grad():
					SCREAMING_SNAKE_CASE      :					Tuple    =				model(**a		)
					SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				outputs.predicted_depth

				# verify the predicted depth
				SCREAMING_SNAKE_CASE      :					Any    =				torch.Size((1, 384, 384)		)
				self.assertEqual(predicted_depth.shape					,					a		)

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				torch.tensor(
				    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]		).to(a		)

				self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100					,					a					,					atol=1e-4		)		)






import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_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_speech_available():
	from transformers import WhisperFeatureExtractor

if is_torch_available():
	import torch

lowerCAmelCase_    =				random.Random()






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase=1.0 ,				_UpperCamelCase=None ,				_UpperCamelCase=None )		->						List[Any]:






				"""simple docstring"""


				if rng is None:
								snake_case_						:    str				=  global_rng

				snake_case_						:    Any				=  []
				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 					__lowerCAmelCase       (			unittest.TestCase     ):






			def __init__(self					,							__magic_name__					,							__magic_name__=7					,							__magic_name__=400					,							__magic_name__=2000					,							__magic_name__=10					,							__magic_name__=160					,							__magic_name__=8					,							__magic_name__=0.0					,							__magic_name__=4000					,							__magic_name__=False					,							__magic_name__=True					,							)     ->   List[str]:


							'''simple docstring'''



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






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


							'''simple docstring'''



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






			def 			lowerCamelCase  (self					,							__magic_name__=False					,							__magic_name__=False    )     ->   Optional[Any]:


							'''simple docstring'''



							def _flatten(__magic_name__    ):
											return list(itertools.chain(*__magic_name__    )    )

							if equal_length:
											snake_case_						:    int				=  [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_						:    int				=  [
											    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_						:    str				=  [np.asarray(__magic_name__    ) for x in speech_inputs]
							return speech_inputs




@require_torch
@require_torchaudio
class 					__lowerCAmelCase       (			_a,     unittest.TestCase     ):
			lowerCamelCase_     :     Optional[Any]       			=      WhisperFeatureExtractor if is_speech_available() else None






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


							'''simple docstring'''



							snake_case_						:    List[str]				=  WhisperFeatureExtractionTester(self    )






			def 			lowerCamelCase  (self    )     ->   List[str]:


							'''simple docstring'''



							snake_case_						:    str				=  self.feature_extraction_class(**self.feat_extract_dict    )

							with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_						:    Union[str, Any]				=  feat_extract_first.save_pretrained(__magic_name__    )[0]
											check_json_file_has_correct_format(__magic_name__    )
											snake_case_						:    List[Any]				=  self.feature_extraction_class.from_pretrained(__magic_name__    )

							snake_case_						:    Optional[int]				=  feat_extract_first.to_dict()
							snake_case_						:    Dict				=  feat_extract_second.to_dict()
							snake_case_						:    List[str]				=  feat_extract_first.mel_filters
							snake_case_						:    Union[str, Any]				=  feat_extract_second.mel_filters
							self.assertTrue(np.allclose(__magic_name__					,							__magic_name__    )    )
							self.assertEqual(__magic_name__					,							__magic_name__    )






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


							'''simple docstring'''



							snake_case_						:    Optional[int]				=  self.feature_extraction_class(**self.feat_extract_dict    )

							with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_						:    List[Any]				=  os.path.join(__magic_name__					,							'''feat_extract.json'''    )
											feat_extract_first.to_json_file(__magic_name__    )
											snake_case_						:    Optional[int]				=  self.feature_extraction_class.from_json_file(__magic_name__    )

							snake_case_						:    int				=  feat_extract_first.to_dict()
							snake_case_						:    Optional[int]				=  feat_extract_second.to_dict()
							snake_case_						:    Union[str, Any]				=  feat_extract_first.mel_filters
							snake_case_						:    str				=  feat_extract_second.mel_filters
							self.assertTrue(np.allclose(__magic_name__					,							__magic_name__    )    )
							self.assertEqual(__magic_name__					,							__magic_name__    )






			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							snake_case_						:    Optional[Any]				=  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_						:    str				=  [np.asarray(__magic_name__    ) for speech_input in speech_inputs]

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

							# Test not batched input
							snake_case_						:    Dict				=  feature_extractor(speech_inputs[0]					,							return_tensors='''np'''    ).input_features
							snake_case_						:    Optional[int]				=  feature_extractor(np_speech_inputs[0]					,							return_tensors='''np'''    ).input_features
							self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )

							# Test batched
							snake_case_						:    int				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							snake_case_						:    Union[str, Any]				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							for enc_seq_a, enc_seq_a in zip(__magic_name__					,							__magic_name__    ):
											self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )

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

							# Test truncation required
							snake_case_						:    Any				=  [floats_list((1, x)    )[0] for x in range(200					,							(feature_extractor.n_samples + 500)					,							200    )]
							snake_case_						:    Union[str, Any]				=  [np.asarray(__magic_name__    ) for speech_input in speech_inputs]

							snake_case_						:    Tuple				=  [x[: feature_extractor.n_samples] for x in speech_inputs]
							snake_case_						:    Optional[Any]				=  [np.asarray(__magic_name__    ) for speech_input in speech_inputs_truncated]

							snake_case_						:    Any				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							snake_case_						:    List[Any]				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							for enc_seq_a, enc_seq_a in zip(__magic_name__					,							__magic_name__    ):
											self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )






			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							import torch

							snake_case_						:    str				=  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_						:    Dict				=  np_speech_inputs.tolist()

							for inputs in [py_speech_inputs, np_speech_inputs]:
											snake_case_						:    Optional[Any]				=  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 			lowerCamelCase  (self					,							__magic_name__    )     ->   Dict:


							'''simple docstring'''



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

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






			def 			lowerCamelCase  (self    )     ->   str:


							'''simple docstring'''



							snake_case_						:    str				=  torch.tensor(
							    [
							        0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951,
							        0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678,
							        0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554,
							        -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854
							    ]    )
							# fmt: on

							snake_case_						:    List[Any]				=  self._load_datasamples(1    )
							snake_case_						:    Union[str, Any]				=  WhisperFeatureExtractor()
							snake_case_						:    Union[str, Any]				=  feature_extractor(__magic_name__					,							return_tensors='''pt'''    ).input_features
							self.assertEqual(input_features.shape					,							(1, 80, 3000)    )
							self.assertTrue(torch.allclose(input_features[0, 0, :30]					,							__magic_name__					,							atol=1e-4    )    )






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


							'''simple docstring'''



							snake_case_						:    Tuple				=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
							snake_case_						:    Optional[int]				=  self._load_datasamples(1    )[0]
							snake_case_						:    List[str]				=  ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535  # Rescale to [0, 65535] to show issue
							snake_case_						:    Optional[Any]				=  feat_extract.zero_mean_unit_var_norm([audio]					,							attention_mask=__magic_name__    )[0]

							self.assertTrue(np.all(np.mean(__magic_name__    ) < 1e-3    )    )
							self.assertTrue(np.all(np.abs(np.var(__magic_name__    ) - 1    ) < 1e-3    )    )
