





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_  :



					def __init__(		self     :     Union[str, Any]       ,      lowerCamelCase     :     Any       ,      lowerCamelCase     :     Optional[Any]=2       ,      lowerCamelCase     :     Union[str, Any]=32       ,      lowerCamelCase     :     Optional[Any]=16       ,      lowerCamelCase     :     Union[str, Any]=3       ,      lowerCamelCase     :     Optional[int]=True       ,      lowerCamelCase     :     Union[str, Any]=True       ,      lowerCamelCase     :     Union[str, Any]=32       ,      lowerCamelCase     :     Union[str, Any]=4       ,      lowerCamelCase     :     List[str]=[0, 1, 2, 3]       ,      lowerCamelCase     :     List[Any]=4       ,      lowerCamelCase     :     Any=37       ,      lowerCamelCase     :     List[Any]="gelu"       ,      lowerCamelCase     :     Any=0.1       ,      lowerCamelCase     :     List[str]=0.1       ,      lowerCamelCase     :     Tuple=0.02       ,      lowerCamelCase     :     Optional[int]=3       ,      lowerCamelCase     :     int=[1, 3_84, 24, 24]       ,      lowerCamelCase     :     int=True       ,      lowerCamelCase     :     Optional[Any]=None       ,      ):
							lowerCamelCase_	:     Dict 						=      parent
							lowerCamelCase_	:     int 						=      batch_size
							lowerCamelCase_	:     List[Any] 						=      image_size
							lowerCamelCase_	:     int 						=      patch_size
							lowerCamelCase_	:     List[str] 						=      num_channels
							lowerCamelCase_	:     int 						=      is_training
							lowerCamelCase_	:     int 						=      use_labels
							lowerCamelCase_	:     int 						=      hidden_size
							lowerCamelCase_	:     Tuple 						=      num_hidden_layers
							lowerCamelCase_	:     str 						=      backbone_out_indices
							lowerCamelCase_	:     str 						=      num_attention_heads
							lowerCamelCase_	:     Dict 						=      intermediate_size
							lowerCamelCase_	:     Tuple 						=      hidden_act
							lowerCamelCase_	:     str 						=      hidden_dropout_prob
							lowerCamelCase_	:     Tuple 						=      attention_probs_dropout_prob
							lowerCamelCase_	:     List[Any] 						=      initializer_range
							lowerCamelCase_	:     Tuple 						=      num_labels
							lowerCamelCase_	:     List[str] 						=      backbone_featmap_shape
							lowerCamelCase_	:     int 						=      scope
							lowerCamelCase_	:     Optional[int] 						=      is_hybrid
							# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
							lowerCamelCase_	:     Union[str, Any] 						=      (image_size // patch_size) ** 2
							lowerCamelCase_	:     List[str] 						=      num_patches + 1



					def   __a     (		self     :     Optional[Any]						):
							lowerCamelCase_	:     int 						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

							lowerCamelCase_	:     Dict 						=      None
							if self.use_labels:
									lowerCamelCase_	:     Union[str, Any] 						=      ids_tensor([self.batch_size, self.image_size, self.image_size]       ,      self.num_labels						)

							lowerCamelCase_	:     Union[str, Any] 						=      self.get_config()

							return config, pixel_values, labels



					def   __a     (		self     :     Optional[Any]						):
							lowerCamelCase_	:     Union[str, Any] 						=      {
							    'global_padding': 'same',
							    'layer_type': 'bottleneck',
							    'depths': [3, 4, 9],
							    'out_features': ['stage1', 'stage2', 'stage3'],
							    'embedding_dynamic_padding': True,
							    'hidden_sizes': [96, 1_92, 3_84, 7_68],
							    '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=UpperCamelCase__       ,      initializer_range=self.initializer_range       ,      is_hybrid=self.is_hybrid       ,      backbone_config=UpperCamelCase__       ,      backbone_featmap_shape=self.backbone_featmap_shape       ,      )



					def   __a     (		self     :     int       ,      lowerCamelCase     :     str       ,      lowerCamelCase     :     int       ,      lowerCamelCase     :     List[str]						):
							lowerCamelCase_	:     str 						=      DPTModel(config=UpperCamelCase__						)
							model.to(UpperCamelCase__						)
							model.eval()
							lowerCamelCase_	:     Any 						=      model(UpperCamelCase__						)
							self.parent.assertEqual(result.last_hidden_state.shape       ,      (self.batch_size, self.seq_length, self.hidden_size)						)



					def   __a     (		self     :     Tuple       ,      lowerCamelCase     :     List[str]       ,      lowerCamelCase     :     List[Any]       ,      lowerCamelCase     :     int						):
							lowerCamelCase_	:     Optional[Any] 						=      self.num_labels
							lowerCamelCase_	:     List[Any] 						=      DPTForDepthEstimation(UpperCamelCase__						)
							model.to(UpperCamelCase__						)
							model.eval()
							lowerCamelCase_	:     Dict 						=      model(UpperCamelCase__						)
							self.parent.assertEqual(result.predicted_depth.shape       ,      (self.batch_size, self.image_size, self.image_size)						)



					def   __a     (		self     :     Tuple       ,      lowerCamelCase     :     Optional[Any]       ,      lowerCamelCase     :     Union[str, Any]       ,      lowerCamelCase     :     int						):
							lowerCamelCase_	:     List[Any] 						=      self.num_labels
							lowerCamelCase_	:     Dict 						=      DPTForSemanticSegmentation(UpperCamelCase__						)
							model.to(UpperCamelCase__						)
							model.eval()
							lowerCamelCase_	:     List[str] 						=      model(UpperCamelCase__       ,      labels=UpperCamelCase__						)
							self.parent.assertEqual(
							    result.logits.shape       ,      (self.batch_size, self.num_labels, self.image_size, self.image_size)						)





					def   __a     (		self     :     Tuple						):
							lowerCamelCase_	:     List[str] 						=      self.prepare_config_and_inputs()
							lowerCamelCase_						,      lowerCamelCase_						,      lowerCamelCase_	:     List[Any] 						=      config_and_inputs
							lowerCamelCase_	:     Any 						=      {'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class 						UpperCamelCase_  (  _UpperCamelCase  ,     _UpperCamelCase  ,     unittest.TestCase							):
					_a      :						Dict						    =					(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
					_a      :						List[str]						    =					(
					    {
					        'depth-estimation': DPTForDepthEstimation,
					        'feature-extraction': DPTModel,
					        'image-segmentation': DPTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					_a      :						Optional[int]						    =					False
					_a      :						Optional[int]						    =					False
					_a      :						int						    =					False



					def   __a     (		self     :     List[Any]						):
							lowerCamelCase_	:     List[str] 						=      DPTModelTester(self						)
							lowerCamelCase_	:     Any 						=      ConfigTester(self       ,      config_class=UpperCamelCase__       ,      has_text_modality=UpperCamelCase__       ,      hidden_size=37						)



					def   __a     (		self     :     Tuple						):
							self.config_tester.run_common_tests()



					@unittest.skip(reason='DPT does not use inputs_embeds'						)
					def   __a     (		self     :     Union[str, Any]						):
							pass



					def   __a     (		self     :     Optional[Any]						):
							lowerCamelCase_						,      lowerCamelCase_	:     Tuple 						=      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowerCamelCase_	:     Optional[int] 						=      model_class(UpperCamelCase__						)
									self.assertIsInstance(model.get_input_embeddings()       ,      (nn.Module)						)
									lowerCamelCase_	:     Tuple 						=      model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(UpperCamelCase__       ,      nn.Linear						)						)



					def   __a     (		self     :     Union[str, Any]						):
							lowerCamelCase_						,      lowerCamelCase_	:     Tuple 						=      self.model_tester.prepare_config_and_inputs_for_common()

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

									lowerCamelCase_	:     List[Any] 						=      ['pixel_values']
									self.assertListEqual(arg_names[:1]       ,      UpperCamelCase__						)



					def   __a     (		self     :     str						):
							lowerCamelCase_	:     int 						=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCamelCase__						)



					def   __a     (		self     :     int						):
							lowerCamelCase_	:     List[str] 						=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_depth_estimation(*UpperCamelCase__						)



					def   __a     (		self     :     Any						):
							lowerCamelCase_	:     Optional[int] 						=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__						)



					def   __a     (		self     :     List[Any]						):
							for model_class in self.all_model_classes:
									if model_class.__name__ == "DPTForDepthEstimation":
											continue

									lowerCamelCase_						,      lowerCamelCase_	:     Dict 						=      self.model_tester.prepare_config_and_inputs_for_common()
									lowerCamelCase_	:     str 						=      True

									if model_class in get_values(UpperCamelCase__						):
											continue

									lowerCamelCase_	:     Dict 						=      model_class(UpperCamelCase__						)
									model.to(UpperCamelCase__						)
									model.train()
									lowerCamelCase_	:     Any 						=      self._prepare_for_class(UpperCamelCase__       ,      UpperCamelCase__       ,      return_labels=UpperCamelCase__						)
									lowerCamelCase_	:     int 						=      model(**UpperCamelCase__						).loss
									loss.backward()



					def   __a     (		self     :     Any						):
							for model_class in self.all_model_classes:
									if model_class.__name__ == "DPTForDepthEstimation":
											continue

									lowerCamelCase_						,      lowerCamelCase_	:     Union[str, Any] 						=      self.model_tester.prepare_config_and_inputs_for_common()
									lowerCamelCase_	:     str 						=      False
									lowerCamelCase_	:     Any 						=      True

									if model_class in get_values(UpperCamelCase__						) or not model_class.supports_gradient_checkpointing:
											continue
									lowerCamelCase_	:     str 						=      model_class(UpperCamelCase__						)
									model.to(UpperCamelCase__						)
									model.gradient_checkpointing_enable()
									model.train()
									lowerCamelCase_	:     Optional[Any] 						=      self._prepare_for_class(UpperCamelCase__       ,      UpperCamelCase__       ,      return_labels=UpperCamelCase__						)
									lowerCamelCase_	:     List[str] 						=      model(**UpperCamelCase__						).loss
									loss.backward()



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

							lowerCamelCase_	:     Dict 						=      _config_zero_init(UpperCamelCase__						)
							for model_class in self.all_model_classes:
									lowerCamelCase_	:     List[str] 						=      model_class(config=UpperCamelCase__						)
									# Skip the check for the backbone
									lowerCamelCase_	:     Dict 						=      []
									for name, module in model.named_modules():
											if module.__class__.__name__ == "DPTViTHybridEmbeddings":
													lowerCamelCase_	:     int 						=      [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   __a     (		self     :     Optional[int]						):
							pass



					@slow
					def   __a     (		self     :     Optional[Any]						):
							for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
									lowerCamelCase_	:     Optional[Any] 						=      DPTModel.from_pretrained(UpperCamelCase__						)
									self.assertIsNotNone(UpperCamelCase__						)





					def   __a     (		self     :     Any						):
							# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
							lowerCamelCase_						,      lowerCamelCase_	:     Dict 						=      self.model_tester.prepare_config_and_inputs_for_common()
							lowerCamelCase_	:     int 						=      'add'
							with self.assertRaises(UpperCamelCase__						):
									lowerCamelCase_	:     int 						=      DPTForDepthEstimation(UpperCamelCase__						)


def 		_SCREAMING_SNAKE_CASE     ( ):
		lowerCamelCase_	:     str 						=      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
		return image






@require_torch
@require_vision
@slow
class 						UpperCamelCase_  (  unittest.TestCase							):



					def   __a     (		self     :     int						):
							lowerCamelCase_	:     int 						=      DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas'						)
							lowerCamelCase_	:     List[Any] 						=      DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas'						).to(UpperCamelCase__						)

							lowerCamelCase_	:     str 						=      prepare_img()
							lowerCamelCase_	:     Tuple 						=      image_processor(images=UpperCamelCase__       ,      return_tensors='pt'						).to(UpperCamelCase__						)

							# forward pass
							with torch.no_grad():
									lowerCamelCase_	:     List[Any] 						=      model(**UpperCamelCase__						)
									lowerCamelCase_	:     List[Any] 						=      outputs.predicted_depth

							# verify the predicted depth
							lowerCamelCase_	:     List[str] 						=      torch.Size((1, 3_84, 3_84)						)
							self.assertEqual(predicted_depth.shape       ,      UpperCamelCase__						)

							lowerCamelCase_	:     Optional[int] 						=      torch.tensor(
							    [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]]						).to(UpperCamelCase__						)

							self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_00       ,      UpperCamelCase__       ,      atol=1E-4						)						)

'''simple docstring'''






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

_UpperCAmelCase    :     List[Any]         =       random.Random()





def  _SCREAMING_SNAKE_CASE		(      __snake_case							:			int   ,		__snake_case							:			Dict=1.0   ,		__snake_case							:			List[Any]=None   ,		__snake_case							:			List[str]=None				):
     if rng is None:
          _A    		=  global_rng

     _A    		=  []
     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 lowercase_       (		unittest.TestCase			):







   """simple docstring"""

   def __init__(      self      :			Tuple, UpperCamelCase__      :			Tuple, UpperCamelCase__      :			Union[str, Any]=7, UpperCamelCase__      :			List[str]=4_00, UpperCamelCase__      :			Any=20_00, UpperCamelCase__      :			int=10, UpperCamelCase__      :			Tuple=1_60, UpperCamelCase__      :			Tuple=8, UpperCamelCase__      :			List[str]=0.0, UpperCamelCase__      :			Optional[Any]=40_00, UpperCamelCase__      :			List[str]=False, UpperCamelCase__      :			List[Any]=True, )  ->			Dict:
        _A    		=  parent
        _A    		=  batch_size
        _A    		=  min_seq_length
        _A    		=  max_seq_length
        _A    		=  (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
        _A    		=  padding_value
        _A    		=  sampling_rate
        _A    		=  return_attention_mask
        _A    		=  do_normalize
        _A    		=  feature_size
        _A    		=  chunk_length
        _A    		=  hop_length
   def 	__UpperCAmelCase   (      self      :			Tuple     )  ->			Optional[Any]:
        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 	__UpperCAmelCase   (      self      :			Optional[Any], UpperCamelCase__      :			List[Any]=False, UpperCamelCase__      :			str=False     )  ->			Any:
        def _flatten(UpperCamelCase__      :			List[str]     ):
             return list(itertools.chain(*UpperCamelCase__     )     )

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







@require_torch
@require_torchaudio
class lowercase_       (		_UpperCamelCase    ,    unittest.TestCase			):







   """simple docstring"""

   __lowerCAmelCase         =   WhisperFeatureExtractor if is_speech_available() else None
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			Optional[Any]:
        _A    		=  WhisperFeatureExtractionTester(self     )
   def 	__UpperCAmelCase   (      self      :			List[Any]     )  ->			int:
        _A    		=  self.feature_extraction_class(**self.feat_extract_dict     )

        with tempfile.TemporaryDirectory() as tmpdirname:
             _A    		=  feat_extract_first.save_pretrained(UpperCamelCase__     )[0]
             check_json_file_has_correct_format(UpperCamelCase__     )
             _A    		=  self.feature_extraction_class.from_pretrained(UpperCamelCase__     )

        _A    		=  feat_extract_first.to_dict()
        _A    		=  feat_extract_second.to_dict()
        _A    		=  feat_extract_first.mel_filters
        _A    		=  feat_extract_second.mel_filters
        self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__     )     )
        self.assertEqual(UpperCamelCase__, UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			List[Any]:
        _A    		=  self.feature_extraction_class(**self.feat_extract_dict     )

        with tempfile.TemporaryDirectory() as tmpdirname:
             _A    		=  os.path.join(UpperCamelCase__, 'feat_extract.json'     )
             feat_extract_first.to_json_file(UpperCamelCase__     )
             _A    		=  self.feature_extraction_class.from_json_file(UpperCamelCase__     )

        _A    		=  feat_extract_first.to_dict()
        _A    		=  feat_extract_second.to_dict()
        _A    		=  feat_extract_first.mel_filters
        _A    		=  feat_extract_second.mel_filters
        self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__     )     )
        self.assertEqual(UpperCamelCase__, UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Union[str, Any]     )  ->			List[Any]:
        # Tests that all call wrap to encode_plus and batch_encode_plus
        _A    		=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
        # create three inputs of length 800, 1000, and 1200
        _A    		=  [floats_list((1, x)     )[0] for x in range(8_00, 14_00, 2_00     )]
        _A    		=  [np.asarray(UpperCamelCase__     ) for speech_input in speech_inputs]

        # Test feature size
        _A    		=  feature_extractor(UpperCamelCase__, 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
        _A    		=  feature_extractor(speech_inputs[0], return_tensors='np'     ).input_features
        _A    		=  feature_extractor(np_speech_inputs[0], return_tensors='np'     ).input_features
        self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__, atol=1e-3     )     )

        # Test batched
        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='np'     ).input_features
        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='np'     ).input_features
        for enc_seq_a, enc_seq_a in zip(UpperCamelCase__, UpperCamelCase__     ):
             self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__, atol=1e-3     )     )

        # Test 2-D numpy arrays are batched.
        _A    		=  [floats_list((1, x)     )[0] for x in (8_00, 8_00, 8_00)]
        _A    		=  np.asarray(UpperCamelCase__     )
        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='np'     ).input_features
        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='np'     ).input_features
        for enc_seq_a, enc_seq_a in zip(UpperCamelCase__, UpperCamelCase__     ):
             self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__, atol=1e-3     )     )

        # Test truncation required
        _A    		=  [floats_list((1, x)     )[0] for x in range(2_00, (feature_extractor.n_samples + 5_00), 2_00     )]
        _A    		=  [np.asarray(UpperCamelCase__     ) for speech_input in speech_inputs]

        _A    		=  [x[: feature_extractor.n_samples] for x in speech_inputs]
        _A    		=  [np.asarray(UpperCamelCase__     ) for speech_input in speech_inputs_truncated]

        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='np'     ).input_features
        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='np'     ).input_features
        for enc_seq_a, enc_seq_a in zip(UpperCamelCase__, UpperCamelCase__     ):
             self.assertTrue(np.allclose(UpperCamelCase__, UpperCamelCase__, atol=1e-3     )     )
   def 	__UpperCAmelCase   (      self      :			Any     )  ->			Any:
        import torch

        _A    		=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
        _A    		=  np.random.rand(1_00, 32     ).astype(np.floataa     )
        _A    		=  np_speech_inputs.tolist()

        for inputs in [py_speech_inputs, np_speech_inputs]:
             _A    		=  feature_extractor.pad([{'input_features': inputs}], return_tensors='np'     )
             self.assertTrue(np_processed.input_features.dtype == np.floataa     )
             _A    		=  feature_extractor.pad([{'input_features': inputs}], return_tensors='pt'     )
             self.assertTrue(pt_processed.input_features.dtype == torch.floataa     )
   def 	__UpperCAmelCase   (      self      :			int, UpperCamelCase__      :			int     )  ->			Optional[Any]:
        _A    		=  load_dataset('hf-internal-testing/librispeech_asr_dummy', 'clean', split='validation'     )
        # automatic decoding with librispeech
        _A    		=  ds.sort('id'     ).select(range(UpperCamelCase__     )     )[:num_samples]['audio']

        return [x["array"] for x in speech_samples]
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			List[Any]:
        # fmt: off
        _A    		=  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

        _A    		=  self._load_datasamples(1     )
        _A    		=  WhisperFeatureExtractor()
        _A    		=  feature_extractor(UpperCamelCase__, return_tensors='pt'     ).input_features
        self.assertEqual(input_features.shape, (1, 80, 30_00)     )
        self.assertTrue(torch.allclose(input_features[0, 0, :30], UpperCamelCase__, atol=1e-4     )     )

   def 	__UpperCAmelCase   (      self      :			int     )  ->			Any:
        _A    		=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
        _A    		=  self._load_datasamples(1     )[0]
        _A    		=  ((audio - audio.min()) / (audio.max() - audio.min())) * 6_55_35  # Rescale to [0, 65535] to show issue
        _A    		=  feat_extract.zero_mean_unit_var_norm([audio], attention_mask=UpperCamelCase__     )[0]

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



