Effort free video editing!
End a full transcription segment at a pause
WyattBlue730ff866f1e4
diff --git a/src/cli.nim b/src/cli.nimindex 3ec34aa7..ed4ad519 100644--- a/src/cli.nim+++ b/src/cli.nim@@ -115,7 +115,7 @@ const whisperOptions*: seq[OptDef] = @[OptDef(names: "-tr, --translate", kind: Flag, datum: coTranslate,help: "Translate from source language to english"),OptDef(names: "--queue", datum: coQueue, metavar: "SECS",- help: "The maximum size in seconds of a single transcribed segment (default 30)"),+ help: "The maximum size in seconds of a single transcribed segment (default 30, or 120 with parakeet models)"),OptDef(names: "--prompt", datum: coPrompt, metavar: "TEXT",help: "Bias transcription toward given vocabulary/spelling (e.g. names, jargon)"),OptDef(names: "--threads", datum: coThreads, metavar: "N",diff --git a/src/cmds/whisper.nim b/src/cmds/whisper.nimindex 77f41c9d..ac046f99 100644--- a/src/cmds/whisper.nim+++ b/src/cmds/whisper.nim@@ -27,7 +27,8 @@ proc main*(cArgs: seq[string]) =var format = "text"var formatExplicit = falsevar output = "-"- var queue: int = 30+ var queue: int = 0+ var queueExplicit = falsevar prompt: string = ""var threads: cint = 4var threshold: float32 = 0.04@@ -53,6 +54,7 @@ proc main*(cArgs: seq[string]) =try: parseInt(key)except ValueError: error &"Invalid --queue: {key}")+ queueExplicit = trueof coPrompt:prompt = keyof coThreads:@@ -92,6 +94,8 @@ proc main*(cArgs: seq[string]) =# Install early so Ctrl-C is graceful even during the (slow) model load.setControlCHook(onCtrlC)+ if not queueExplicit:+ queue = defaultQueue(model)if queue < 1 or queue > 86400:error &"Invalid queue value: {queue}"if output != "-" and not formatExplicit:diff --git a/src/lib/pausecut.nim b/src/lib/pausecut.nimnew file mode 100644index 00000000..edc70fb6--- /dev/null+++ b/src/lib/pausecut.nim@@ -0,0 +1,49 @@+func windowPeak(samples: openArray[float32], start, win: int): float32 =+ for i in start ..< min(start + win, samples.len):+ result = max(result, abs(samples[i]))++func loudSamples*(samples: openArray[float32], win: int,+ threshold: float32): int =+ ## How many samples lie in `win`-sized windows that peak at `threshold` or+ ## above.+ var start = 0+ while start < samples.len:+ if windowPeak(samples, start, win) >= threshold:+ result += min(win, samples.len - start)+ start += win++func quietestCut*(samples: openArray[float32], win: int,+ threshold: float32): int =+ ## The index to split `samples` at so the cut does the least harm to speech:+ ## the middle of the longest pause, or of the quietest stretch when nothing+ ## falls below `threshold`. The latest candidate wins a tie.+ let n = samples.len div win+ if n == 0:+ return samples.len++ var peaks = newSeq[float32](n)+ for i in 0 ..< n:+ peaks[i] = windowPeak(samples, i * win, win)++ var pauseStart = 0+ var pauseLen = 0+ var run = 0+ for i in 0 ..< n:+ run = (if peaks[i] < threshold: run + 1 else: 0)+ if run > 0 and run >= pauseLen:+ pauseLen = run+ pauseStart = i - run + 1+ if pauseLen > 0:+ # Mid-pause leaves each side some silence around its speech.+ return pauseStart * win + pauseLen * win div 2++ # Rank a window by its neighbors too, so a lone dip between two loud+ # windows (a zero crossing, not a lull) loses to a wider one.+ var best = 0+ var bestScore = float32.high+ for i in 0 ..< n:+ let score = max(peaks[i], max(peaks[max(i - 1, 0)], peaks[min(i + 1, n - 1)]))+ if score <= bestScore:+ bestScore = score+ best = i+ best * win + win div 2diff --git a/src/transcribe.nim b/src/transcribe.nimindex 2799d454..197bb8d1 100644--- a/src/transcribe.nim+++ b/src/transcribe.nim@@ -1,6 +1,6 @@import std/[json, os, strformat, strutils, typedthreads]import ./[av, ffmpeg, log]-import ./lib/[lang, srttime]+import ./lib/[lang, pausecut, srttime]typeWhisperCtx = pointer@@ -195,6 +195,12 @@ proc whisperLanguage*(language: string): string =func isParakeetModel*(model: string): bool ="parakeet" in model.extractFilename.toLowerAscii+func defaultQueue*(model: string): int =+ ## The longest segment, in seconds, to hand `model` at once. Whisper reads+ ## 30 second windows; parakeet's encoder takes the whole segment, and fewer+ ## segments mean fewer cuts through running speech.+ if isParakeetModel(model): 120 else: 30+# Apple SpeechAnalyzer backend (src/ae_speech.swift), selected with model "apple".when defined(appleSpeech):proc ae_speech_init(locale: cstring): WhisperCtx {.importc, cdecl.}@@ -213,6 +219,7 @@ constSilenceGap = Rate div 2 # 0.5s of trailing silence ends an utterancePrerollMax = Rate div 5 # keep 0.2s of pre-speech audio so onsets aren't clippedMinSpeech = Rate div 5 # ignore <0.2s blips (clicks, coughs)+ CutSearch = Rate * 5 # how far back a full segment looks for a pause to end ontype OutCtx = objectf: File@@ -415,6 +422,28 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,silenceRun = 0speechSamples = 0+ proc cutSeg() =+ # A segment that fills up mid-speech ends at its last pause, not its last+ # sample: a model given half a word invents the rest. The audio after the+ # pause opens the next segment.+ let spanStart = seg.len - min(CutSearch, maxSeg div 2)+ let cut = spanStart + quietestCut(seg.toOpenArray(spanStart, seg.high),+ WinSize, threshold)+ let rest = seg[cut .. ^1]+ let restSpeech = loudSamples(rest, WinSize, threshold)+ let restStart = segStartSample + cut+ let restSilence = min(silenceRun, rest.len)++ seg.setLen(cut)+ speechSamples = max(speechSamples - restSpeech, 0)+ flushSeg()++ seg.add(rest)+ inSpeech = true+ segStartSample = restStart+ speechSamples = restSpeech+ silenceRun = restSilence+proc gateWindow(w: ptr UncheckedArray[float32], L: int) =var peak: float32 = 0for i in 0 ..< L:@@ -445,7 +474,7 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,preroll = preroll[preroll.len - PrerollMax .. ^1]if inSpeech and seg.len >= maxSeg:- flushSeg()+ cutSeg()proc gateFrame(fr: ptr AVFrame) =let n = fr.nb_samples.int@@ -536,6 +565,7 @@ proc transcribeFile*(input, model, language: string, threads: int,if container.audio.len == 0: error "No audio stream found"let lang = if model != "apple" and isParakeetModel(model): "auto" else: languagerun(fileSource(container.formatContext, stop), container.audio[0], model, lang,- translate = false, format = "srt", output = output, queue = 30,+ translate = false, format = "srt", output = output,+ queue = defaultQueue(model),threshold = 0.04, prompt = "", threads = threads.cint, splitWords = true,debug = false, heardMs = heardMs)