File size: 2,726 Bytes
adabee1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | """Exercise real Whisper features without downloading or loading model weights."""
from pathlib import Path
import sys
import unittest
import numpy as np
import torch
from transformers import WhisperFeatureExtractor
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from asr_preprocessing import prepare_whisper_input
class WhisperWaveformPaddingTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.extractor = WhisperFeatureExtractor(feature_size=80)
def test_short_audio_uses_true_silence_floor_not_zero_mel_padding(self):
sample_rate = 16000
time = np.arange(sample_rate, dtype=np.float32) / sample_rate
wave = (0.1 * np.sin(2 * np.pi * 440 * time)).astype(np.float32)
fixed = prepare_whisper_input(self.extractor, wave)
explicit_wave_padding = np.pad(wave, (0, self.extractor.n_samples - len(wave)))
expected = self.extractor(explicit_wave_padding, sampling_rate=sample_rate,
return_tensors="pt", truncation=False, padding="do_not_pad")
torch.testing.assert_close(fixed.input_features, expected.input_features)
self.assertEqual(tuple(fixed.input_features.shape), (1, 80, 3000))
silence = fixed.input_features[:, :, 110:]
self.assertTrue(torch.all(silence < -0.1).item())
self.assertEqual(int(fixed.attention_mask.sum()), 100)
unpadded = self.extractor(wave, sampling_rate=sample_rate, return_tensors="pt",
truncation=False, padding="longest").input_features
old_mel_padding = torch.nn.functional.pad(unpadded, (0, 3000 - unpadded.shape[-1]))
self.assertFalse(torch.allclose(old_mel_padding, fixed.input_features))
def test_long_audio_retains_samples_and_features_after_thirty_seconds(self):
sample_rate = 16000
wave = np.zeros(35 * sample_rate, dtype=np.float32)
time = np.arange(3 * sample_rate, dtype=np.float32) / sample_rate
wave[32 * sample_rate:] = 0.1 * np.sin(2 * np.pi * 440 * time)
fixed = prepare_whisper_input(self.extractor, wave)
expected = self.extractor(wave, sampling_rate=sample_rate, return_tensors="pt",
truncation=False, padding="longest", return_attention_mask=True)
self.assertEqual(tuple(fixed.input_features.shape), (1, 80, 3500))
self.assertEqual(int(fixed.attention_mask.sum()), 3500)
torch.testing.assert_close(fixed.input_features, expected.input_features)
self.assertGreater(float(fixed.input_features[:, :, 3250:].max()),
float(fixed.input_features[:, :, :3000].max()))
if __name__ == "__main__":
unittest.main()
|