Skip to content

Effort free video editing!

Stop whisper repeating lines and misreading short utterances

WyattBlue524f8519cbf4
diff --git a/src/cmds/whisper.nim b/src/cmds/whisper.nim
index 8ef427c5..037d1fd5 100644
--- a/src/cmds/whisper.nim
+++ b/src/cmds/whisper.nim
@@ -143,6 +143,7 @@ proc main*(cArgs: seq[string]) =
input.close()
transcribe.run(readPacket, audioStream, model, language, translate, format,
- output, queue, threshold, prompt, threads, splitWords, isDebug)
+ output, queue, threshold, prompt, threads, splitWords, isDebug,
+ live = isMic)
if isMic:
stderr.writeLine("")
diff --git a/src/lib/pausecut.nim b/src/lib/pausecut.nim
index edc70fb6..ac86ea0f 100644
--- a/src/lib/pausecut.nim
+++ b/src/lib/pausecut.nim
@@ -1,3 +1,23 @@
+type Piece* = tuple[at: int, start: int64]
+ ## A stretch of a segment: its samples from index `at` on were read from
+ ## the source starting at sample `start`.
+
+func sourceSample*(pieces: openArray[Piece], at: int64): int64 =
+ ## The source sample that sample `at` of a segment was read from, for a
+ ## segment whose silences were dropped. `pieces` is ordered by `at`.
+ result = at
+ for p in pieces:
+ if p.at > at: break
+ result = p.start + (at - p.at)
+
+func piecesFrom*(pieces: openArray[Piece], cut: int): seq[Piece] =
+ ## The pieces of what is left of a segment once its first `cut` samples
+ ## are taken off.
+ result = @[(at: 0, start: sourceSample(pieces, cut))]
+ for p in pieces:
+ if p.at > cut:
+ result.add (at: p.at - cut, start: p.start)
+
func windowPeak(samples: openArray[float32], start, win: int): float32 =
for i in start ..< min(start + win, samples.len):
result = max(result, abs(samples[i]))
@@ -47,3 +67,9 @@ func quietestCut*(samples: openArray[float32], win: int,
bestScore = score
best = i
best * win + win div 2
+
+func gaveUp*(textLen: int, ms: int64): bool =
+ ## Whether a cue of `textLen` bytes lasting `ms` holds too little text for
+ ## its length to be speech that was followed: a model that loses its place
+ ## closes the rest of a segment with one cue.
+ ms >= 10_000 and textLen.int64 * 1000 < ms * 2
diff --git a/src/transcribe.nim b/src/transcribe.nim
index 197bb8d1..a4a89100 100644
--- a/src/transcribe.nim
+++ b/src/transcribe.nim
@@ -1,4 +1,4 @@
-import std/[json, os, strformat, strutils, typedthreads]
+import std/[json, os, sequtils, strformat, strutils, typedthreads]
import ./[av, ffmpeg, log]
import ./lib/[lang, pausecut, srttime]
@@ -32,6 +32,8 @@ void *ae_whisper_init(const char *model_path, int use_gpu, int verbose) {
return whisper_init_from_file_with_params(model_path, cp);
}
+#define AE_CARRY_TOKENS 64
+
// text is non-const char* to match Nim's cstring callback type (same TU now).
typedef void (*ae_seg_cb)(void *user, char *text, int64_t t0_ms, int64_t t1_ms);
@@ -50,11 +52,21 @@ int ae_whisper_run(void *ctx, const float *samples, int n_samples,
p.translate = translate != 0;
p.language = language;
p.n_threads = n_threads;
- // Carry the previous segment(s) as context. whisper keeps prior tokens in the
- // context's prompt_past (capped to ~recent), so reusing the same ctx across
- // calls conditions each utterance on the last — better continuity/spelling.
+ // Carry the previous segment's text as context: reusing the same ctx across
+ // calls conditions each utterance on the last, which keeps spelling and
+ // script (kanji vs. kana) consistent. Only its last sentence or two: given
+ // a full window of earlier transcript, the decoder starts copying lines
+ // from it on a fixed 2 s timestamp grid instead of following the audio.
p.no_context = false;
- p.initial_prompt = (initial_prompt && initial_prompt[0]) ? initial_prompt : NULL;
+ p.n_max_text_ctx = AE_CARRY_TOKENS;
+ if (initial_prompt && initial_prompt[0]) {
+ // The prompt gets its own room on top, in every call, instead of
+ // competing with the carried text for the same few tokens.
+ int n = whisper_tokenize((struct whisper_context *) ctx, initial_prompt, NULL, 0);
+ p.initial_prompt = initial_prompt;
+ p.carry_initial_prompt = true;
+ p.n_max_text_ctx += n < 0 ? -n : n;
+ }
if (max_len > 0) {
p.max_len = max_len;
p.token_timestamps = true;
@@ -220,25 +232,23 @@ const
PrerollMax = Rate div 5 # keep 0.2s of pre-speech audio so onsets aren't clipped
MinSpeech = Rate div 5 # ignore <0.2s blips (clicks, coughs)
CutSearch = Rate * 5 # how far back a full segment looks for a pause to end on
+ RepeatGapMs = 100 # a repeated cue this close to the last one continues it
+ RetryPadMs = 100 # silence put before a segment to decode it a second way
type OutCtx = object
f: File
format: string
splitWords: bool
index: int
- segStartMs: int64
-
-# Called by whisper_stream.c per text segment, on this (main) thread, so Nim GC
-# and File writes are safe.
-proc segCb(user: pointer, text: cstring, t0ms, t1ms: int64) {.cdecl.} =
- let oc = cast[ptr OutCtx](user)
- var s = ($text).strip(leading = true, trailing = true)
- s = s.replace("[BLANK_AUDIO]", "").strip()
- if s.len == 0: return
- if oc.splitWords and s in ["[", "]", "BLANK", "_", "AUDIO"]: return
-
- let startMs = oc.segStartMs + t0ms
- let endMs = oc.segStartMs + t1ms
+ pieces: seq[Piece] # where the segment being transcribed sits in the source
+ # A whisper decoder stuck on a line emits it again in back-to-back cues, so
+ # the latest cue is held back until the next one shows it isn't a repeat.
+ mergeRepeats: bool
+ held: bool
+ heldText: string
+ heldStartMs, heldEndMs: int64
+
+proc writeCue(oc: ptr OutCtx, s: string, startMs, endMs: int64) =
case oc.format
of "srt":
oc.index += 1
@@ -249,10 +259,43 @@ proc segCb(user: pointer, text: cstring, t0ms, t1ms: int64) {.cdecl.} =
oc.f.write(s & "\n")
oc.f.flushFile()
+proc flushHeld(oc: ptr OutCtx) =
+ if oc.held:
+ oc.held = false
+ writeCue(oc, oc.heldText, oc.heldStartMs, oc.heldEndMs)
+
+type Cue = tuple[text: string, t0ms, t1ms: int64]
+
+# Called per text segment on the thread that runs the model, so Nim GC is safe.
+proc segCb(user: pointer, text: cstring, t0ms, t1ms: int64) {.cdecl.} =
+ cast[ptr seq[Cue]](user)[].add ($text, t0ms, t1ms)
+
+proc emit(oc: ptr OutCtx, text: string, t0ms, t1ms: int64) =
+ var s = text.strip(leading = true, trailing = true)
+ s = s.replace("[BLANK_AUDIO]", "").strip()
+ if s.len == 0: return
+ if oc.splitWords and s in ["[", "]", "BLANK", "_", "AUDIO"]: return
+
+ # A cue that ends where a piece does ends with that piece's last sample,
+ # not at the start of the next piece, which is a dropped silence later.
+ let startMs = sourceSample(oc.pieces, t0ms * Rate div 1000) * 1000 div Rate
+ let endMs = max(startMs,
+ (sourceSample(oc.pieces, max(t1ms * Rate div 1000, 1) - 1) + 1) * 1000 div Rate)
+ if not oc.mergeRepeats:
+ writeCue(oc, s, startMs, endMs)
+ elif oc.held and s == oc.heldText and startMs - oc.heldEndMs <= RepeatGapMs:
+ oc.heldEndMs = max(oc.heldEndMs, endMs)
+ else:
+ flushHeld(oc)
+ oc.held = true
+ oc.heldText = s
+ oc.heldStartMs = startMs
+ oc.heldEndMs = endMs
+
type
Job = object
samples: seq[float32] # mono f32 @16k; len 0 is the end-of-stream sentinel
- startMs: int64
+ pieces: seq[Piece]
WorkerArgs = object
wctx: WhisperCtx
apple: bool
@@ -265,33 +308,55 @@ type
prompt: string
maxLen: cint
debug: bool
+ live: bool
const MaxPending = 16 # queued utterances before capture has to wait (back-pressure)
+proc runWhisper(a: ptr WorkerArgs, samples: seq[float32], cues: var seq[Cue]): cint =
+ ae_whisper_run(a.wctx, addr samples[0], samples.len.cint,
+ a.language.cstring, a.translate, a.threads, a.prompt.cstring,
+ a.maxLen, segCb, addr cues)
+
# Whisper runs here, off the capture thread, so a (multi-second) transcription
# never stalls av_read_frame and live mic audio isn't dropped. This thread alone
# drives the run-call sequence — preserving whisper's cross-call prompt context —
-# and owns every output write (via segCb); the capture thread only feeds it jobs.
+# and owns every output write (via emit); the capture thread only feeds it jobs.
proc whisperWorker(a: ptr WorkerArgs) {.thread.} =
while true:
var job = a.jobs[].recv()
if job.samples.len == 0: break
- a.oc.segStartMs = job.startMs
+ let startMs = sourceSample(job.pieces, 0) * 1000 div Rate
+ a.oc.pieces = move job.pieces
if a.debug:
- stderr.writeLine(&"transcribing {job.samples.len} samples at {job.startMs} ms")
+ stderr.writeLine(&"transcribing {job.samples.len} samples at {startMs} ms")
+ var cues: seq[Cue]
let rc =
if a.apple:
ae_speech_run(a.wctx, addr job.samples[0], job.samples.len.cint,
- a.maxLen, segCb, a.oc)
+ a.maxLen, segCb, addr cues)
elif a.parakeet:
ae_parakeet_run(a.wctx, addr job.samples[0], job.samples.len.cint,
- a.threads, a.maxLen, segCb, a.oc)
+ a.threads, a.maxLen, segCb, addr cues)
else:
- ae_whisper_run(a.wctx, addr job.samples[0], job.samples.len.cint,
- a.language.cstring, a.translate, a.threads, a.prompt.cstring,
- a.maxLen, segCb, a.oc)
+ a.runWhisper(job.samples, cues)
+ if not (a.apple or a.parakeet) and cues.anyIt(gaveUp(it.text.len, it.t1ms - it.t0ms)):
+ # Whether whisper follows a segment or drops most of it can turn on a
+ # few samples, so a second decode of slightly shifted audio often lands.
+ var padded = newSeq[float32](RetryPadMs * Rate div 1000)
+ padded.add job.samples
+ var again: seq[Cue]
+ if a.runWhisper(padded, again) == 0 and
+ not again.anyIt(gaveUp(it.text.len, it.t1ms - it.t0ms)):
+ if a.debug:
+ stderr.writeLine(&"decoded the segment at {startMs} ms a second time")
+ cues = again.mapIt((it.text, max(it.t0ms - RetryPadMs, 0),
+ max(it.t1ms - RetryPadMs, 0)))
+ for cue in cues:
+ emit(a.oc, cue.text, cue.t0ms, cue.t1ms)
if rc != 0:
- stderr.writeLine(&"transcription failed on segment at {job.startMs} ms; skipping")
+ stderr.writeLine(&"transcription failed on segment at {startMs} ms; skipping")
+ # Someone is watching a live transcript; don't sit on its latest line.
+ if a.live: flushHeld(a.oc)
type PacketSource* = proc(pkt: ptr AVPacket): cint {.gcsafe.}
## Fills `pkt` like av_read_frame: 0 on success, AVERROR_EAGAIN to retry,
@@ -305,11 +370,12 @@ proc fileSource*(fmtCtx: ptr AVFormatContext, stop: ptr bool): PacketSource =
proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
model, language: string, translate: bool, format, output: string,
queue: int, threshold: float32, prompt: string, threads: cint,
- splitWords, debug: bool, heardMs: ptr int64 = nil) =
+ splitWords, debug: bool, heardMs: ptr int64 = nil, live = false) =
## Read `audioStream`'s packets from `readPacket` (a file or the live mic)
## until it ends, transcribing each detected speech segment. Output goes to
## `output` ("-" = stdout). `heardMs`, if given, follows how much audio has
- ## been read, for a progress display.
+ ## been read, for a progress display. `live` writes each segment's text as
+ ## soon as it is transcribed.
let useApple = model == "apple"
let useParakeet = not useApple and isParakeetModel(model)
var language = language
@@ -398,7 +464,9 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
buildGraph(audioStream.codecpar.sample_rate, audioStream.codecpar.format,
addr audioStream.codecpar.ch_layout)
- var oc = OutCtx(f: outFile, format: format, splitWords: splitWords)
+ # Word cues repeat honestly ("had had"); only whisper loops on a line.
+ var oc = OutCtx(f: outFile, format: format, splitWords: splitWords,
+ mergeRepeats: not (useApple or useParakeet or splitWords))
let maxSeg = queue * Rate
var jobs: Channel[Job]
@@ -410,14 +478,19 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
var silenceRun = 0
var speechSamples = 0
var elapsed: int64 = 0 # total samples seen (real-time clock)
- var segStartSample: int64 = 0
+ var pieces: seq[Piece]
+ # A model handed one or two words has too little audio to recognize them or
+ # their language, so utterances are joined, minus the silence between them,
+ # until a segment is full. A live transcript can't wait for that.
+ let pack = not (live or useApple or useParakeet)
proc flushSeg() =
# Hand the utterance to the worker and keep capturing; blocks only if the
# queue is full (whisper falling behind real-time) — never silently drops.
if seg.len > 0 and speechSamples >= MinSpeech:
- jobs.send(Job(samples: move seg, startMs: (segStartSample * 1000) div Rate))
+ jobs.send(Job(samples: move seg, pieces: move pieces))
seg = newSeqOfCap[float32](maxSeg + Rate)
+ pieces = @[]
inSpeech = false
silenceRun = 0
speechSamples = 0
@@ -431,7 +504,7 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
WinSize, threshold)
let rest = seg[cut .. ^1]
let restSpeech = loudSamples(rest, WinSize, threshold)
- let restStart = segStartSample + cut
+ let restPieces = piecesFrom(pieces, cut)
let restSilence = min(silenceRun, rest.len)
seg.setLen(cut)
@@ -440,7 +513,7 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
seg.add(rest)
inSpeech = true
- segStartSample = restStart
+ pieces = restPieces
speechSamples = restSpeech
silenceRun = restSilence
@@ -456,7 +529,8 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
if peak >= threshold:
if not inSpeech:
inSpeech = true
- segStartSample = winStart - preroll.len # back-date to include preroll
+ # back-date to include preroll
+ pieces.add (at: seg.len, start: winStart - preroll.len)
if preroll.len > 0:
seg.add(preroll)
preroll.setLen(0)
@@ -467,7 +541,11 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
for i in 0 ..< L: seg.add(w[i]) # keep the natural trailing tail
silenceRun += L
if silenceRun >= SilenceGap:
- flushSeg()
+ if pack:
+ inSpeech = false
+ silenceRun = 0
+ else:
+ flushSeg()
else:
for i in 0 ..< L: preroll.add(w[i]) # rolling pre-speech buffer
if preroll.len > PrerollMax:
@@ -515,7 +593,7 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
oc: addr oc, jobs: addr jobs,
language: language, translate: (if translate: 1.cint else: 0.cint),
threads: threads, prompt: prompt,
- maxLen: (if splitWords: 1.cint else: 0.cint), debug: debug)
+ maxLen: (if splitWords: 1.cint else: 0.cint), debug: debug, live: live)
var worker: Thread[ptr WorkerArgs]
createThread(worker, whisperWorker, addr wargs)
@@ -553,6 +631,7 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
jobs.send(Job(samples: @[])) # sentinel
joinThread(worker)
jobs.close()
+ flushHeld(addr oc)
proc transcribeFile*(input, model, language: string, threads: int,
output: string, stop: ptr bool, heardMs: ptr int64 = nil) =