Spaces:
Build error
Build error
Add a simple "VAD" alternative - periodic VAD
Browse filesThis is a very simple alternative to using Silero Vad, where every
5 minutes (0:00 - 5:00, 5:00 - 10:00, etc.) is marked as a
"speech" segment, and whisper is then run on each
segment individually.
The upside is that all potential dialogue will be sent to
Whisper for transcribing, but it is also more likely to
get into an infinite sentence loop (although limited to each
5 minute segment).
Creating an artifical break every 5 minutes may also break
up a sentence accidentally, causing the sentence (or a word) to be
incorrectly transcribed.
Files changed (3)
- app.py+13-5
- tests/vad_test.pyAdded+66
- vad.py+119-58
14 unmodified lines1516171819202145 unmodified lines67686970717273747576777879808194 unmodified lines17617717817918018118214 unmodified linesfrom download import ExceededMaximumDuration, downloadUrlfrom utils import slugify, write_srt, write_vttfrom vad import VadTranscription# Limitations (set to -1 to disable)DEFAULT_INPUT_AUDIO_MAX_DURATION = 600 # seconds45 unmodified linesmodel = whisper.load_model(selectedModel)model_cache[selectedModel] = model# The resultsif (vad == 'silero-vad'):# Use Silero VADif (self.vad_model is None):self.vad_model = VadTranscription()result = self.vad_model.transcribe(source, lambda audio : model.transcribe(audio, language=selectedLanguage, task=task))else:# Default VADresult = model.transcribe(source, language=selectedLanguage, task=task)text = result["text"]94 unmodified linesgr.Audio(source="upload", type="filepath", label="Upload Audio"),gr.Audio(source="microphone", type="filepath", label="Microphone Input"),gr.Dropdown(choices=["transcribe", "translate"], label="Task"),gr.Dropdown(choices=["none", "silero-vad"], label="VAD"),], outputs=[gr.File(label="Download"),gr.Text(label="Transcription"),14 unmodified lines1516171819202145 unmodified lines676869707172737475767778798081828384858687888994 unmodified lines18418518618718818919014 unmodified linesfrom download import ExceededMaximumDuration, downloadUrlfrom utils import slugify, write_srt, write_vttfrom vad import VadPeriodicTranscription, VadSileroTranscription# Limitations (set to -1 to disable)DEFAULT_INPUT_AUDIO_MAX_DURATION = 600 # seconds45 unmodified linesmodel = whisper.load_model(selectedModel)model_cache[selectedModel] = model# Callable for processing an audio filewhisperCallable = lambda audio : model.transcribe(audio, language=selectedLanguage, task=task)# The resultsif (vad == 'silero-vad'):# Use Silero VADif (self.vad_model is None):self.vad_model = VadSileroTranscription()result = self.vad_model.transcribe(source, whisperCallable)elif (vad == 'periodic-vad'):# Very simple VAD - mark every 5 minutes as speech. This makes it less likely that Whisper enters an infinite loop, but# it may create a break in the middle of a sentence, causing some artifacts.periodic_vad = VadPeriodicTranscription(periodic_duration=60 * 5)result = periodic_vad.transcribe(source, whisperCallable)else:# Default VADresult = whisperCallable(source)text = result["text"]94 unmodified linesgr.Audio(source="upload", type="filepath", label="Upload Audio"),gr.Audio(source="microphone", type="filepath", label="Microphone Input"),gr.Dropdown(choices=["transcribe", "translate"], label="Task"),gr.Dropdown(choices=["none", "silero-vad", "periodic-vad"], label="VAD"),], outputs=[gr.File(label="Download"),gr.Text(label="Transcription"),
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import pprintimport unittestimport numpy as npimport sys
sys.path.append('../whisper-webui')
from vad import AbstractTranscription, VadSileroTranscription
class TestVad(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestVad, self).__init__(*args, **kwargs) self.transcribe_calls = []
def test_transcript(self): mock = MockVadTranscription()
self.transcribe_calls.clear() result = mock.transcribe("mock", lambda segment : self.transcribe_segments(segment))
self.assertListEqual(self.transcribe_calls, [ [30, 30], [100, 100] ])
self.assertListEqual(result['segments'], [{'end': 50.0, 'start': 40.0, 'text': 'Hello world'}, {'end': 120.0, 'start': 110.0, 'text': 'Hello world'}] )
def transcribe_segments(self, segment): self.transcribe_calls.append(segment.tolist())
# Dummy text return { 'text': "Hello world ", 'segments': [ { "start": 10.0, "end": 20.0, "text": "Hello world " } ], 'language': "" }
class MockVadTranscription(AbstractTranscription): def __init__(self): super().__init__()
def get_audio_segment(self, str, start_time: str = None, duration: str = None): start_time_seconds = float(start_time.removesuffix("s")) duration_seconds = float(duration.removesuffix("s"))
# For mocking, this just returns a simple numppy array return np.array([start_time_seconds, duration_seconds], dtype=np.float64)
def get_transcribe_timestamps(self, audio: str): result = []
result.append( { 'start': 30, 'end': 60 } ) result.append( { 'start': 100, 'end': 200 } ) return result
if __name__ == '__main__': unittest.main()1234561 unmodified line8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777810 unmodified lines8990919293949549 unmodified lines14514614714814915019 unmodified lines1701711721731741751761 unmodified line178179180181182183184185from collections import Counterfrom dis import disfrom typing import Any, Iterator, List, Dictfrom pprint import pprintimport torch1 unmodified lineimport ffmpegimport numpy as npSPEECH_TRESHOLD = 0.3MAX_SILENT_PERIOD = 10 # secondsSEGMENT_PADDING_LEFT = 1 # Start detected text segment earlySEGMENT_PADDING_RIGHT = 4 # End detected segments latedef load_audio(file: str, sample_rate: int = 16000,start_time: str = None, duration: str = None):"""Open an audio file and read as mono waveform, resampling as necessaryParameters----------file: strThe audio file to opensr: intThe sample rate to resample the audio if necessarystart_time: strThe start time, using the standard FFMPEG time duration syntax, or None to disable.duration: strThe duration, using the standard FFMPEG time duration syntax, or None to disable.Returns-------A NumPy array containing the audio waveform, in float32 dtype."""try:inputArgs = {'threads': 0}if (start_time is not None):inputArgs['ss'] = start_timeif (duration is not None):inputArgs['t'] = duration# This launches a subprocess to decode audio while down-mixing and resampling as necessary.# Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.out, _ = (ffmpeg.input(file, **inputArgs).output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sample_rate).run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True))except ffmpeg.Error as e:raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}")return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0class VadTranscription:def __init__(self):self.model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad')(self.get_speech_timestamps, _, _, _, _) = utilsdef transcribe(self, audio: str, whisperCallable):SAMPLING_RATE = 16000wav = load_audio(audio, sample_rate=SAMPLING_RATE)# get speech timestamps from full audio filesample_timestamps = self.get_speech_timestamps(wav, self.model, sampling_rate=SAMPLING_RATE, threshold=SPEECH_TRESHOLD)seconds_timestamps = self.convert_seconds(sample_timestamps, sampling_rate=SAMPLING_RATE)padded = self.pad_timestamps(seconds_timestamps, SEGMENT_PADDING_LEFT, SEGMENT_PADDING_RIGHT)merged = self.merge_timestamps(padded, MAX_SILENT_PERIOD)print("Timestamps:")pprint(merged)10 unmodified linessegment_start = segment['start']segment_duration = segment['end'] - segment_startsegment_audio = load_audio(audio, sample_rate=SAMPLING_RATE, start_time = str(segment_start) + "s", duration = str(segment_duration) + "s")print("Running whisper on " + str(segment_start) + ", duration: " + str(segment_duration))segment_result = whisperCallable(segment_audio)49 unmodified linesreturn resultdef merge_timestamps(self, timestamps: List[Dict[str, Any]], max_distance: float):result = []current_entry = None19 unmodified linesreturn resultdef convert_seconds(self, timestamps: List[Dict[str, Any]], sampling_rate: int):result = []for entry in timestamps:1 unmodified lineend = entry['end']result.append({'start': start / sampling_rate,'end': end / sampling_rate})return result12345671 unmodified line9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525310 unmodified lines6465666768697049 unmodified lines12012112212312412512612712819 unmodified lines1481491501511521531541 unmodified line156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246from abc import ABC, abstractmethodfrom collections import Counterfrom dis import disfrom typing import Any, Callable, Iterator, List, Dict, Unionfrom pprint import pprintimport torch1 unmodified lineimport ffmpegimport numpy as np# DefaultsSPEECH_TRESHOLD = 0.3MAX_SILENT_PERIOD = 10 # secondsSEGMENT_PADDING_LEFT = 1 # Start detected text segment earlySEGMENT_PADDING_RIGHT = 4 # End detected segments lateclass AbstractTranscription(ABC):def __init__(self, segment_padding_left: int = None, segment_padding_right = None, max_silent_period: int = None):self.sampling_rate = 16000self.segment_padding_left = segment_padding_leftself.segment_padding_right = segment_padding_rightself.max_silent_period = max_silent_perioddef get_audio_segment(self, str, start_time: str = None, duration: str = None):return load_audio(str, self.sampling_rate, start_time, duration)@abstractmethoddef get_transcribe_timestamps(self, audio: str):"""Get the start and end timestamps of the sections that should be transcribed by this VAD method.Parameters----------audio: strThe audio file.Returns-------A list of start and end timestamps, in fractional seconds."""returndef transcribe(self, audio: str, whisperCallable: Callable[[Union[str, np.ndarray, torch.Tensor]], dict[str, Union[dict, Any]]]):# get speech timestamps from full audio fileseconds_timestamps = self.get_transcribe_timestamps(audio)padded = self.pad_timestamps(seconds_timestamps, self.segment_padding_left, self.segment_padding_right)merged = self.merge_timestamps(padded, self.max_silent_period)print("Timestamps:")pprint(merged)10 unmodified linessegment_start = segment['start']segment_duration = segment['end'] - segment_startsegment_audio = self.get_audio_segment(audio, start_time = str(segment_start) + "s", duration = str(segment_duration) + "s")print("Running whisper on " + str(segment_start) + ", duration: " + str(segment_duration))segment_result = whisperCallable(segment_audio)49 unmodified linesreturn resultdef merge_timestamps(self, timestamps: List[Dict[str, Any]], max_distance: float):if max_distance is None:return timestampsresult = []current_entry = None19 unmodified linesreturn resultdef multiply_timestamps(self, timestamps: List[Dict[str, Any]], factor: float):result = []for entry in timestamps:1 unmodified lineend = entry['end']result.append({'start': start * factor,'end': end * factor})return resultclass VadSileroTranscription(AbstractTranscription):def __init__(self):super().__init__(SEGMENT_PADDING_LEFT, SEGMENT_PADDING_RIGHT, MAX_SILENT_PERIOD)self.model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad')(self.get_speech_timestamps, _, _, _, _) = utilsdef get_transcribe_timestamps(self, audio: str):wav = self.get_audio_segment(audio)sample_timestamps = self.get_speech_timestamps(wav, self.model, sampling_rate=self.sampling_rate, threshold=SPEECH_TRESHOLD)seconds_timestamps = self.multiply_timestamps(sample_timestamps, factor=1 / self.sampling_rate)return seconds_timestamps# A very simple VAD that just marks every N seconds as speechclass VadPeriodicTranscription(AbstractTranscription):def __init__(self, periodic_duration: int):super().__init__()self.periodic_duration = periodic_durationdef get_transcribe_timestamps(self, audio: str):# Get duration in secondsaudio_duration = float(ffmpeg.probe(audio)["format"]["duration"])result = []# Generate a timestamp every N secondsstart_timestamp = 0while (start_timestamp < audio_duration):end_timestamp = min(start_timestamp + self.periodic_duration, audio_duration)segment_duration = end_timestamp - start_timestamp# Minimum duration is 1 secondif (segment_duration >= 1):result.append( { 'start': start_timestamp, 'end': end_timestamp } )start_timestamp = end_timestampreturn resultdef load_audio(file: str, sample_rate: int = 16000,start_time: str = None, duration: str = None):"""Open an audio file and read as mono waveform, resampling as necessaryParameters----------file: strThe audio file to opensr: intThe sample rate to resample the audio if necessarystart_time: strThe start time, using the standard FFMPEG time duration syntax, or None to disable.duration: strThe duration, using the standard FFMPEG time duration syntax, or None to disable.Returns-------A NumPy array containing the audio waveform, in float32 dtype."""try:inputArgs = {'threads': 0}if (start_time is not None):inputArgs['ss'] = start_timeif (duration is not None):inputArgs['t'] = duration# This launches a subprocess to decode audio while down-mixing and resampling as necessary.# Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.out, _ = (ffmpeg.input(file, **inputArgs).output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sample_rate).run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True))except ffmpeg.Error as e:raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}")return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
app.py+13-5
tests/vad_test.pyAdded+66
vad.py+119-58