From de695207dfd280a18c32209d578f2565061cdeee Mon Sep 17 00:00:00 2001 From: sakasegawa Date: Sun, 22 Nov 2026 04:14:32 +0900 Subject: [PATCH 1/3] Commit server_vad turns once silence_duration_ms has followed the speech, padding regions in the tools Transcription by regions took Silero VAD's padded regions, which give two regions closer than twice speech_pad_ms half the silence between them, so a stream knew a region's end only once that much silence had passed: with OpenAI's defaults an utterance was committed 600 ms after its speech rather than the 500 ms silence_duration_ms says, and a silence_duration_ms below twice prefix_padding_ms gave no sooner commit at all. The detection now finds the speech alone (speech_pad_ms 0), and RegionCut in tools/common pads it: speech_pad_ms before the speech, but not before the region before it ends, and as much after it, but no more than min_silence_duration_ms, so that a region's audio is all there once the silence that ends it has passed. Where max_speech_duration_s cut the speech and the speech after it starts within that silence, the region ends halfway to it if that comes first; a stream holds such a region until it knows which. The detection's longest region is max_speech_duration_s less the padding. The server's transcriptions, speech asr --vad and the assembly of utterances all cut with RegionCut, so a file and the same audio streamed keep giving the same regions and texts. speech vad keeps Silero VAD's own regions. Checked: server_realtime_smoke.py, speech_cli_smoke.py, server_smoke.py and server_diarization_smoke.py with Qwen3-ASR 0.6B Q8_0 and Silero VAD on an Apple M5 pass. The realtime smoke's new check, that a dump's utterances are all committed with 580 ms of audio after its last speech, fails on 0.11.0 and passes here; the CLI smoke now also compares a file and the same audio streamed with a longest region of 2 s, which cut the speech 12 times within speech and 5 times at a pause. Co-Authored-By: Claude Opus 5.5 --- checks/smoke/region_cut.py | 28 ++++ checks/smoke/server_realtime_smoke.py | 39 ++++-- checks/smoke/speech_cli_smoke.py | 124 +++++++++--------- ...s-deltas-the-text-two-readings-agree-on.md | 13 +- ...-realtime-with-the-session-in-the-tools.md | 8 +- ...-alone-in-the-tools-and-joins-the-texts.md | 16 ++- docs/cli.md | 6 +- docs/server.md | 12 +- measure/live_latency.py | 16 ++- tools/cli/asr.cpp | 11 +- tools/common/regions.cpp | 50 +++++++ tools/common/regions.h | 42 +++++- tools/common/utterances.cpp | 60 +++++---- tools/common/utterances.h | 39 +++--- tools/server/jobs.h | 8 +- tools/server/server.cpp | 4 +- 16 files changed, 334 insertions(+), 142 deletions(-) create mode 100644 checks/smoke/region_cut.py diff --git a/checks/smoke/region_cut.py b/checks/smoke/region_cut.py new file mode 100644 index 00000000..d0d8e911 --- /dev/null +++ b/checks/smoke/region_cut.py @@ -0,0 +1,28 @@ +"""The cut of transcription by regions, as tools/common/regions.cpp's RegionCut makes it, for the scripts that check or +measure it: `speech vad` with detection_flags() finds the speech alone, and padded() gives each stretch of speech the +audio the region keeps around it. It computes in the order RegionCut does, so that its seconds are the same doubles. +""" + + +def detection_flags(threshold, prefix_padding_ms, silence_duration_ms, max_speech_s): + """The flags of `speech vad` that find the speech of transcription by regions with these values of server_vad's + members and the longest region: no padding, and the longest region less the padding.""" + before, after = prefix_padding_ms / 1000, min(prefix_padding_ms, silence_duration_ms) / 1000 + return ["--threshold", repr(threshold), "--speech-pad-ms", "0", "--min-silence-duration-ms", str(silence_duration_ms), + "--max-speech-duration-s", repr(max_speech_s - before - after)] + + +def padded(speech, prefix_padding_ms, silence_duration_ms, length): + """The regions of `speech`, the (start, end) in seconds that `speech vad` with detection_flags() found in `length` + seconds of audio: prefix_padding_ms before each, but not before the region before it ends, and as much after it, but + no more than silence_duration_ms, or halfway to the speech after it where that starts within silence_duration_ms.""" + before, after = prefix_padding_ms / 1000, min(prefix_padding_ms, silence_duration_ms) / 1000 + silence = silence_duration_ms / 1000 + out, previous = [], 0.0 + for k, (start, end) in enumerate(speech): + last = end + after + if k + 1 < len(speech) and speech[k + 1][0] - end < silence: + last = min(last, end + (speech[k + 1][0] - end) / 2) + out.append((max(start - before, previous), min(last, length))) + previous = out[-1][1] + return out diff --git a/checks/smoke/server_realtime_smoke.py b/checks/smoke/server_realtime_smoke.py index 9de9a09f..16cd40a0 100644 --- a/checks/smoke/server_realtime_smoke.py +++ b/checks/smoke/server_realtime_smoke.py @@ -11,10 +11,11 @@ while its commit is transcribed, and the refusals of the upgrade: another model, another query member, another Origin and another Host. As someone speaks: deltas of a commit appended in real time before it is committed, and a reading under way stopped by the commit; with turn_detection server_vad, the dumps joined with silences and appended in pieces -of 20 ms cut into the regions that speech vad finds on the CPU, each with its speech_started and speech_stopped at the -region's bounds, its commit and its completed with the text of the region's samples sent as a WAV file, all of them -joined into the text of chunking_strategy with the same values; deltas of an utterance appended in real time before its -commit; a commit and a clear while speech is under way; minutes of silence held within the bound; server_vad's +of 20 ms cut into the regions of the speech that speech vad finds on the CPU, padded as transcription by regions pads +them (region_cut.py), each with its speech_started and speech_stopped at the region's bounds, its commit and its +completed with the text of the region's samples sent as a WAV file, all of them joined into the text of chunking_strategy +with the same values; each region committed once silence_duration_ms has followed its speech; deltas of an utterance +appended in real time before its commit; a commit and a clear while speech is under way; minutes of silence held within the bound; server_vad's refusals, on a server without a detection model too; and a detection flag given to the server (--threshold) as turn detection's default, before OpenAI's, with a session's own member kept. @@ -33,6 +34,7 @@ import tempfile import time +import region_cut from server_client import Server, expect_error from worker_client import joined_transcript, read_npy @@ -430,9 +432,10 @@ def kinds_of(events, item): raise SystemExit("no reading stopped when its buffer was committed: " + "".join(list(server.lines)[-5:])) print("realtime: a reading under way when its buffer was committed stopped, and the commit was recognized whole") -# server_vad: the dumps joined with silences of 1.5 s, appended in pieces of 20 ms, are cut into the regions speech vad -# finds in the same samples on the CPU, which the server's detection runs on too; each region is committed and -# recognized as its samples sent as a WAV file, and their texts join into what chunking_strategy gives the whole. +# server_vad: the dumps joined with silences of 1.5 s, appended in pieces of 20 ms, are cut into the regions of the speech +# speech vad finds in the same samples on the CPU, which the server's detection runs on too, padded as transcription by +# regions pads them; each region is committed and recognized as its samples sent as a WAV file, and their texts join into +# what chunking_strategy gives the whole. alls = [pcm24(read_npy(os.path.join(d, "audio.npy"))) for d in dumps] silence = b"\0" * 2 * 36000 joined = b"".join(p + silence for p in alls) @@ -440,9 +443,10 @@ def kinds_of(events, item): path = os.path.join(folder, "joined.wav") with open(path, "wb") as f: f.write(wav24(joined)) -detection = ["--threshold", "0.5", "--speech-pad-ms", "300", "--min-silence-duration-ms", "500", "--max-speech-duration-s", "10"] -regions = json.loads(subprocess.run([speech, "vad", vad, "--device", "cpu", "--threads", "1", "--format", "json", *detection, path], - capture_output=True, check=True).stdout)["regions"] +detection = region_cut.detection_flags(0.5, 300, 500, 10) +speech_found = json.loads(subprocess.run([speech, "vad", vad, "--device", "cpu", "--threads", "1", "--format", "json", *detection, path], + capture_output=True, check=True).stdout)["regions"] +regions = [{"start": s, "end": e} for s, e in region_cut.padded([(r["start"], r["end"]) for r in speech_found], 300, 500, len(joined) / 48000)] shutil.rmtree(folder) assert len(regions) >= len(alls), regions vws = server.websocket("/v1/realtime") @@ -480,7 +484,20 @@ def milliseconds(seconds): status, _, body = transcribe([("chunking_strategy", "auto")], [("file", "x.wav", wav24(joined))]) assert status == 200 and json.loads(body)["text"] == joined_transcript(parts, False)["text"], (body, parts) print(f"realtime server_vad: {len(items)} utterances of {len(joined) / 48000:.1f} s appended in pieces of 20 ms, each at the bounds of " - f"speech vad's region and completed with the text of its samples as a file, joined into chunking_strategy's text") + f"its region and completed with the text of its samples as a file, joined into chunking_strategy's text") +# A region is committed once silence_duration_ms of silence has followed its speech: the first dump's audio up to 580 ms +# after its last speech commits every region of it. The detection takes the 500 ms in its chunks of 32 ms, 512 ms and the +# chunk itself, and its resampler holds back 4.3 ms; Silero VAD's own padding would wait for 600 ms, and 640 ms of audio. +within = [r for r in speech_found if r["end"] < len(alls[0]) / 48000] +ows = server.websocket("/v1/realtime") +assert ows.event()["type"] == "session.created" +ows.send(session({"model": name}, {"type": "server_vad"})) +assert ows.event()["type"] == "session.updated" +appended(ows, joined[:2 * round((within[-1]["end"] + 0.58) * 24000)], 960) +events = settle(ows) +assert sum(e["type"] == "input_audio_buffer.committed" for e in events) == len(within), events +ows.close() +print(f"realtime server_vad: the {len(within)} utterances of the first dump committed with 580 ms of audio after its last speech") # Appended as fast as it is said, an utterance gets deltas after its speech started and before its commit. paced(vws, longest + silence) events = settle(vws) diff --git a/checks/smoke/speech_cli_smoke.py b/checks/smoke/speech_cli_smoke.py index a44313e5..e6edf0c2 100644 --- a/checks/smoke/speech_cli_smoke.py +++ b/checks/smoke/speech_cli_smoke.py @@ -27,9 +27,10 @@ languages; for a Nemotron 3.5 Transcribe dump of the model card's prompt for speaker tags, `speech asr --speakers` as a line per segment with its speaker and as JSON against the worker's end with speakers, and its refusal with --vad; and with --vad a detection model, -`speech asr --vad` on the dumps' audio joined with silences between them against the worker's ends of the regions that -`speech vad --split` writes, each of which holds the samples of its region, joined as transcription by regions joins -them (as JSON, with times where the model takes timestamps), an empty text for a file of silence, and the refusals of a +`speech asr --vad` on the dumps' audio joined with silences between them against the worker's ends of the regions of the +speech that `speech vad` finds, padded as transcription by regions pads them (region_cut.py), joined as transcription by +regions joins them (as JSON, with times where the model takes timestamps), and again with a longest region of 2 s, which +cuts the speech; an empty text for a file of silence, and the refusals of a model of another task for --vad and of a detection option the model does not take. For a detection model: `speech vad` on 32-bit float WAVE files of the dumps of reference/silero-vad/dump.py against the regions in each dump's regions.json, the official's, with the flags of each set of options, as text and as JSON; with --split a WAVE file of @@ -52,7 +53,7 @@ rate the model does not take, which leaves no file, a chunk shorter than its STFT and an odd byte on stdin; with --asr, `speech asr --enhance`, and the refusal of --enhance with a model of another task; and with --vad too, `speech asr --vad --enhance -`, whose utterances begin where those of `speech asr --vad -` begin and whose texts are those of `speech asr ---enhance` of each region `speech vad --split` writes. For a dialogue model, given a dump of reference/haru/dump.py: +--enhance` of each region of the speech `speech vad` finds, padded as transcription by regions pads it. For a dialogue model, given a dump of reference/haru/dump.py: `speech talk` hearing its user audio as a 16-bit WAVE file, speaking first, against the worker's frames of the same samples, seed and speak_first, into a file with its sizes set and to stdout, its text on stdout and with -o - on stderr; the refusals (exit 2) of no -o, of no AUDIO, of --live with AUDIO, of --live with -o, of --no-warmup without --live and of -o the file heard, @@ -77,6 +78,7 @@ import threading import time +import region_cut from worker_client import (MOST_CER, PARAGRAPH, Worker, cer, dump_requests, heard, joined_transcript, main_speaker, pcm16, read_npy, realtime_speakers, short, speakers_json, speaks_by_sentence) @@ -645,10 +647,9 @@ def wave_of(data, at): assert enhanced_text.endswith("\n"), enhanced_text print(f"asr --enhance: {enhanced_text.strip()!r}; --enhance of a recognition model: exit 2") if vad: - # The detection hears the audio as it arrives, so the stream's utterances are the regions `speech vad --split` - # writes, and each utterance is recognized as `speech asr --enhance` recognizes its region alone. - split = os.path.join(work, "regions") - shutil.rmtree(split, ignore_errors=True) + # The detection hears the audio as it arrives, so the stream's utterances are the regions of the speech `speech + # vad` finds in it, and each utterance is recognized as `speech asr --enhance` recognizes its region alone. + region_file = os.path.join(work, "region.wav") detection = ["--threshold", "0.5", "--speech-pad-ms", "300", "--min-silence-duration-ms", "500", "--max-speech-duration-s", "10"] for path, pcm, at in zip(files, pcms, rates): plain = run("asr", recognizer, "--vad", vad, "--format", "json", *detection, *options, "--rate", str(at), "-", input=pcm).stdout.decode() @@ -657,15 +658,20 @@ def wave_of(data, at): starts = [e["audio_start_ms"] for e in events if e["type"] == "input_audio_buffer.speech_started"] assert starts == [json.loads(line)["audio_start_ms"] for line in plain.splitlines() if json.loads(line)["type"] == "input_audio_buffer.speech_started"], "the detection heard enhanced audio" - # speech asr runs its detection on the CPU, and speech vad there gives the same regions. - run("vad", vad, "--split", split, "--device", "cpu", *detection, path) - regions = sorted(os.listdir(split)) + # speech asr runs its detection on the CPU, and speech vad there finds the same speech. + found = json.loads(run("vad", vad, "--format", "json", "--device", "cpu", *region_cut.detection_flags(0.5, 300, 500, 10), + path).stdout)["regions"] + regions = region_cut.padded([(r["start"], r["end"]) for r in found], 300, 500, len(pcm) / 2 / at) texts = [e["transcript"] for e in events if e["type"] == "conversation.item.input_audio_transcription.completed"] assert len(texts) == len(regions), (texts, regions) - for region, text in zip(regions, texts): - alone = run("asr", recognizer, "--enhance", model, *options, os.path.join(split, region)).stdout.decode().strip() - assert text == alone, (region, text, alone) - shutil.rmtree(split) + for (start, end), text in zip(regions, texts): + part = pcm[2 * round(start * at):2 * round(end * at)] + with open(region_file, "wb") as f: + f.write(b"RIFF" + struct.pack(" len(pcms), (names, regions) - w = Worker(speech, model, options) - parts = [] - for k, (name, region) in enumerate(zip(names, regions)): - with open(os.path.join(split, name), "rb") as f: - pcm = f.read()[44:] - first = round(region["start"] * rate) - assert pcm == joined[2 * first:2 * round(region["end"] * rate)], name - parts.append((first / rate, worker_end(f"region-{k}", pcm, **timed))) - w.close() - shutil.rmtree(split) - want = {"file": long, **joined_transcript(parts, bool(timed))} - got = json.loads(run("asr", model, "--vad", vad, "--format", "json", *detection, *(["--timestamps"] if timed else []), *options, long).stdout) - assert got == want, (got, want) - got = json.loads(run("asr", model, "--vad", vad, "--format", "json", *(["--timestamps"] if timed else []), *options, silence).stdout) - assert got == {"file": silence, "text": "", "stop": "complete", **({"segments": [], "tokens": []} if timed else {})}, got - print(f"asr --vad: {len(regions)} regions of {len(joined) / 2 / rate:.1f} s, the worker's ends of vad --split's files joined" - f"{' with their times' if timed else ''}; a file of silence gives an empty text") - # The same samples as PCM on stdin: OpenAI's events of each region in order, its start and end in milliseconds, and - # its completed with the worker's text, stop and languages of the region's samples. Read all at once, a region - # may get no delta, and any it gets come before its completed. - streamed = run("asr", model, "--vad", vad, "--format", "json", "--rate", str(rate), *detection, *options, "-", input=joined) - events = [json.loads(line) for line in streamed.stdout.decode().splitlines()] - items = list(dict.fromkeys(e["item_id"] for e in events)) - assert len(items) == len(regions), (len(items), regions) - def milliseconds(seconds): """Milliseconds rounded half away from zero, as C's llround() rounds them.""" whole = math.floor(seconds * 1000) return whole + (1 if seconds * 1000 - whole >= 0.5 else 0) - for item, region, (_, end) in zip(items, regions, parts): - mine = [e for e in events if e["item_id"] == item] - kinds = [e["type"].rsplit(".", 1)[1] for e in mine if not e["type"].endswith(".delta")] - assert kinds == ["speech_started", "speech_stopped", "committed", "completed"], kinds - first, last = round(region["start"] * rate), round(region["end"] * rate) - assert mine[0]["audio_start_ms"] == milliseconds(first / rate) and mine[1]["audio_end_ms"] == milliseconds(last / rate), (mine[:2], region) - assert all(e["delta"] for e in mine if e["type"].endswith(".delta")), mine - done = mine[-1] - assert done["transcript"] == end["text"] and done["stop"] == end["stop"], (done, end) - assert [x["code"] for x in done.get("languages", [])] == end.get("languages", []), (done, end) - assert done["usage"]["seconds"] == (last - first) / rate, (done, region) - print(f"asr --vad -: {len(items)} utterances, each speech_started and speech_stopped at its region's bounds, committed, and " - f"completed with the worker's text of the region") + # With a longest region of 8 s, and of 2 s, which cuts the speech at its pauses or within it, so that a region + # waits for the speech after it or for the silence before its padding is known. + counted = [] + for longest_region in (8, 2): + detection = ["--threshold", "0.5", "--speech-pad-ms", "300", "--min-silence-duration-ms", "500", "--max-speech-duration-s", str(longest_region)] + # speech asr runs its detection on the CPU, and speech vad there finds the same speech. + found = json.loads(run("vad", vad, "--format", "json", "--device", "cpu", *region_cut.detection_flags(0.5, 300, 500, longest_region), + long).stdout)["regions"] + regions = region_cut.padded([(r["start"], r["end"]) for r in found], 300, 500, len(joined) / 2 / rate) + assert len(regions) > (counted[-1] if counted else len(pcms)), (longest_region, regions) + counted.append(len(regions)) + w = Worker(speech, model, options) + parts = [] + for k, (start, end) in enumerate(regions): + first = round(start * rate) + parts.append((first / rate, worker_end(f"region-{k}", joined[2 * first:2 * round(end * rate)], **timed))) + w.close() + want = {"file": long, **joined_transcript(parts, bool(timed))} + got = json.loads(run("asr", model, "--vad", vad, "--format", "json", *detection, *(["--timestamps"] if timed else []), *options, long).stdout) + assert got == want, (longest_region, got, want) + # The same samples as PCM on stdin: OpenAI's events of each region in order, its start and end in milliseconds, + # and its completed with the worker's text, stop and languages of the region's samples. Read all at once, a + # region may get no delta, and any it gets come before its completed. + streamed = run("asr", model, "--vad", vad, "--format", "json", "--rate", str(rate), *detection, *options, "-", input=joined) + events = [json.loads(line) for line in streamed.stdout.decode().splitlines()] + items = list(dict.fromkeys(e["item_id"] for e in events)) + assert len(items) == len(regions), (longest_region, len(items), regions) + for item, (start, end_s), (_, end) in zip(items, regions, parts): + mine = [e for e in events if e["item_id"] == item] + kinds = [e["type"].rsplit(".", 1)[1] for e in mine if not e["type"].endswith(".delta")] + assert kinds == ["speech_started", "speech_stopped", "committed", "completed"], kinds + first, last = round(start * rate), round(end_s * rate) + assert mine[0]["audio_start_ms"] == milliseconds(first / rate) and mine[1]["audio_end_ms"] == milliseconds(last / rate), (mine[:2], start, end_s) + assert all(e["delta"] for e in mine if e["type"].endswith(".delta")), mine + done = mine[-1] + assert done["transcript"] == end["text"] and done["stop"] == end["stop"], (done, end) + assert [x["code"] for x in done.get("languages", [])] == end.get("languages", []), (done, end) + assert done["usage"]["seconds"] == (last - first) / rate, (done, start, end_s) + got = json.loads(run("asr", model, "--vad", vad, "--format", "json", *(["--timestamps"] if timed else []), *options, silence).stdout) + assert got == {"file": silence, "text": "", "stop": "complete", **({"segments": [], "tokens": []} if timed else {})}, got + print(f"asr --vad and asr --vad -: {counted[0]} and, with a longest region of 2 s, {counted[1]} regions of {len(joined) / 2 / rate:.1f} s, " + f"the worker's ends of the regions{' with their times' if timed else ''} joined from a file, and each utterance from stdin " + f"speech_started and speech_stopped at its region's bounds and completed with the worker's text; a file of silence gives an empty text") # Fed as fast as it is said, the first of the longest dump's utterances gets deltas before it is committed. longest = max(pcms, key=len) process = subprocess.Popen([speech, "asr", model, "--vad", vad, "--format", "json", "--rate", str(rate), *options, "-"], stdin=subprocess.PIPE, diff --git a/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md b/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md index f41c3691..78091eaf 100644 --- a/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md +++ b/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md @@ -14,7 +14,8 @@ The library recognizes a request's audio whole and gives its text once the recog as it arrives. The detection of audio given a piece at a time gives `speech_detect()`'s regions, each once it is certain ([the record of that detection](a-detection-of-audio-given-a-piece-at-a-time-gives-speech-detects-regions-each-once-it-is-certain.md)), and `speech_detection_speaking()` reports the region under way, and whether it is kept: until its speech has lasted -longer than `min_speech_duration_ms`, it is dropped if its speech ends that soon. Transcription by regions cuts a file with the options `region_options()` gives +longer than `min_speech_duration_ms`, it is dropped if its speech ends that soon. Transcription by regions cuts a file with the options `region_options()` gives, +the detection finding the speech alone and the tools padding it ([its record](transcription-by-regions-recognizes-each-region-where-someone-speaks-alone-in-the-tools-and-joins-the-texts.md)). Silero VAD's graphs are small (Apple M5, 2026-10-08): a minute of 16 kHz audio pushed in pieces of 20 ms takes 0.12 s @@ -26,10 +27,12 @@ on the CPU with one thread, 0.17 s with the performance cores and 0.52 s on Meta - **One assembly of utterances in `tools/common`**, for the command line and the server: it takes audio at the caller's rate, cuts it into utterances, recognizes each alone, one at a time on a thread of its own, and gives its events in order: speech started, speech stopped, committed, delta, completed or failed. With a detection, the - utterances are the detection's regions, with the options of transcription by regions, and each region's samples are - cut as transcription by regions cuts a file's, so a stream gets the regions and the texts that `speech asr --vad` gets - for the same audio. Without one, the caller commits, and an utterance is the audio taken since the last commit or - clear. + utterances are the regions of transcription by regions, the speech the detection finds padded as a file's, and each + region's samples are cut as transcription by regions cuts a file's, so a stream gets the regions and the texts that + `speech asr --vad` gets for the same audio. A region is committed once the silence that ends it has passed, or, where + `max_speech_duration_s` cut the speech itself, once the speech after it has begun or that silence has passed, since its + padding depends on which. Without a detection, the caller commits, and an utterance is the audio taken since the last + commit or clear. - **A delta carries the beginning that two readings in a row agree on**, beyond what the deltas sent: while an utterance goes on, its audio from its start is recognized again, and two readings in a row agree on the code points both begin with, back to the end of a word both have whole where the script puts spaces between words, and, where that is all of diff --git a/docs/adr/speech-serve-speaks-openais-realtime-transcription-over-a-websocket-at-v1-realtime-with-the-session-in-the-tools.md b/docs/adr/speech-serve-speaks-openais-realtime-transcription-over-a-websocket-at-v1-realtime-with-the-session-in-the-tools.md index ad94ce40..567c4aa8 100644 --- a/docs/adr/speech-serve-speaks-openais-realtime-transcription-over-a-websocket-at-v1-realtime-with-the-session-in-the-tools.md +++ b/docs/adr/speech-serve-speaks-openais-realtime-transcription-over-a-websocket-at-v1-realtime-with-the-session-in-the-tools.md @@ -37,10 +37,12 @@ while it goes on and recognizes it whole once committed on the recognition model held when it is committed, which it keeps, and in the turn it takes then among the requests on that model, so that a request that arrives after it runs after it, its audio resampled by the library as a file's is. A turn whose utterance never runs, because the session ended, is given up, so that the requests behind it go on. -- **`server_vad` cuts the utterances by the regions of the server's detection model**, with the options of transcription - by regions: `threshold`, `prefix_padding_ms` as `speech_pad_ms` and `silence_duration_ms` as +- **`server_vad` cuts the utterances by the regions of transcription by regions on the server's detection model**, with + its options: `threshold`, `prefix_padding_ms` as `speech_pad_ms` and `silence_duration_ms` as `min_silence_duration_ms`, defaulting to OpenAI's 0.5, 300 ms and 500 ms, and a longest region of 10 s. A - `turn_detection` given is the whole of it, a member left out taking its default. Each region gives `speech_started`, + `turn_detection` given is the whole of it, a member left out taking its default. The padding is the tools' own, so + that an utterance is committed once `silence_duration_ms` of silence has followed its speech, as OpenAI's reference + describes the turn. Each region gives `speech_started`, `speech_stopped` and `committed` of one item, in that order, with `audio_start_ms` and `audio_end_ms` the region's bounds from the start of the session's audio, so that the same audio gives the regions and texts of `chunking_strategy` with the same values. A server without a detection model answers `server_vad` with an error that says to give diff --git a/docs/adr/transcription-by-regions-recognizes-each-region-where-someone-speaks-alone-in-the-tools-and-joins-the-texts.md b/docs/adr/transcription-by-regions-recognizes-each-region-where-someone-speaks-alone-in-the-tools-and-joins-the-texts.md index b1023b37..22d614ea 100644 --- a/docs/adr/transcription-by-regions-recognizes-each-region-where-someone-speaks-alone-in-the-tools-and-joins-the-texts.md +++ b/docs/adr/transcription-by-regions-recognizes-each-region-where-someone-speaks-alone-in-the-tools-and-joins-the-texts.md @@ -32,6 +32,13 @@ without a separator, as qwen-asr does. `chunking_strategy` `"auto"` takes them all, and a `server_vad` object those of the members it leaves out. `speech asr --vad MODEL` takes the options of `speech vad` as flags of their names: those the detection model takes and the recognition model does not go to the detection, the others to every region's recognition. +- **The detection finds the speech alone, and the tools pad it as OpenAI describes a `server_vad` turn**, which ends + once `silence_duration_ms` of silence has followed its speech and keeps `prefix_padding_ms` before it. The detection + runs with `speech_pad_ms` 0, and a region keeps `speech_pad_ms` before its speech, but not before the region before it + ends, and as much after it, but no more than `min_silence_duration_ms`, so that its audio is all there once the + silence that ends it has passed. Where `max_speech_duration_s` cut the speech and the speech after it starts within + that silence, the region ends halfway to it if that comes first. The detection's longest region is + `max_speech_duration_s` less the padding, so that a region with its padding is no longer, as Silero VAD keeps it. - **The texts are joined with a space, unless either side is written without spaces or already has one**: Han, Hiragana and Katakana with their radicals, symbols, punctuation and full-width forms, the scripts the page's join leaves without a space. The space begins the next region's first segment and first token, so that the segments, and @@ -43,8 +50,9 @@ without a separator, as qwen-asr does. long region better, less than a shorter one. - **Audio in which no one speaks gives "" and recognizes nothing**, while the recognition options are still checked against the model, so that a request is refused the same way whatever its audio holds. -- **`speech vad --split DIR` writes each region as a 16-bit WAVE file**, cut as transcription by regions cuts it, so that - the regions it recognizes can be heard and given to other programs. +- **`speech vad --split DIR` writes each of its regions as a 16-bit WAVE file**, cut from the audio as transcription by + regions cuts a region, so that the regions can be heard and given to other programs. Its regions are Silero VAD's, + padded by Silero VAD's own rule. `measure/region_cap_compare.py` measured each longest region on 105.6 minutes of recordings joined from public test clips (Apple M5, Metal, 2026-10-08): FLEURS ja_jp test, one reading of each of its 321 sentences, in 21 recordings, and @@ -79,6 +87,10 @@ The alternatives were turned down: together at every pause, where a part of 1200 s ends once in twenty minutes. - Silero VAD's own defaults. They cut a sentence at every breath, and an OpenAI client that asks for `"auto"` or leaves a member of `server_vad` out expects OpenAI's values. +- Silero VAD's padding, with `prefix_padding_ms` as its `speech_pad_ms`, which pads both ends of a region and gives two + regions closer than twice it half the silence between them. A stream knows a region's end only once that much silence + has passed: 600 ms with OpenAI's defaults, where `silence_duration_ms` says 500, and a `silence_duration_ms` below + twice `prefix_padding_ms` gave no sooner turn at all. - 200 ms of silence for `chunking_strategy`, as `VadConfig` gives it, beside 500 ms for the Realtime API. The same audio would be cut into other regions by a file sent whole than by the same audio streamed, and by the command line. - No longest region, or 15 to 30 s. Regions of up to 27.7 s let reazonspeech-v2 drop three times as many FLEURS diff --git a/docs/cli.md b/docs/cli.md index 452215de..f28fad09 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -181,12 +181,14 @@ region: | Flag | Default | Meaning | |---|---|---| | `--threshold X` | 0.5 | the speech probability from which audio counts as speech | -| `--speech-pad-ms N` | 300 | the audio kept before and after each region | +| `--speech-pad-ms N` | 300 | the audio kept before each region's speech, and after it up to `--min-silence-duration-ms` | | `--min-silence-duration-ms N` | 500 | the silence that ends a region | | `--max-speech-duration-s S` | 10 | the longest region; a longer one is cut at its longest silence | | `--min-speech-duration-ms N` | 250 | the shortest region kept | -`speech vad --split` with the same flags writes the regions that `speech asr --vad` recognizes. +The padding after a region's speech is never longer than the silence that ends it, so that a region ends as soon as +that silence has passed, as `server_vad` ends a turn. `speech vad` pads its regions as Silero VAD does, so they can +differ from those of `speech asr --vad` where two lie close together or the silence is shorter than the padding. ### Speakers diff --git a/docs/server.md b/docs/server.md index c91b1ee1..42b381df 100644 --- a/docs/server.md +++ b/docs/server.md @@ -195,10 +195,11 @@ field per member: |---|---|---| | `chunking_strategy[type]` | | `server_vad`, required with the others | | `chunking_strategy[threshold]` | 0.5 | the speech probability from which audio counts as speech, 0 to 1 | -| `chunking_strategy[prefix_padding_ms]` | 300 | the audio kept before and after each region | +| `chunking_strategy[prefix_padding_ms]` | 300 | the audio kept before each region's speech, and after it up to `silence_duration_ms` | | `chunking_strategy[silence_duration_ms]` | 500 | the silence that ends a region | -A region is at most 10 s long, cut at its longest silence. A request with `chunking_strategy` to a server without a +A region is at most 10 s long, cut at its longest silence. A `silence_duration_ms` below about 200 ms cuts sentences at +their pauses, and a stretch of speech shorter than 250 ms between two such cuts is dropped. A request with `chunking_strategy` to a server without a detection model is a 400 that says to give it one: `speech serve reazonspeech-v2 silero-vad`. ```python @@ -314,11 +315,14 @@ texts as `chunking_strategy` with the same values. A server without a detection | Member | Default | Meaning | |---|---|---| | `threshold` | 0.5 | the speech probability from which audio counts as speech, 0 to 1 | -| `prefix_padding_ms` | 300 | the audio kept before and after each utterance | +| `prefix_padding_ms` | 300 | the audio kept before each utterance's speech, and after it up to `silence_duration_ms` | | `silence_duration_ms` | 500 | the silence that ends an utterance | An utterance is at most 10 s long, cut at its longest silence. `speech_started` comes about 0.26 s after the speech -begins, once it has lasted long enough to be kept, and the utterance is committed about 0.6 s after the speech ends. The buffer +begins, once it has lasted long enough to be kept, and the utterance is committed once `silence_duration_ms` of +silence has followed it, within the detection's 32 ms. A shorter `silence_duration_ms` gives the text sooner, and cuts +sentences at shorter pauses: below about 200 ms, an utterance ends at nearly every pause, and a stretch of speech shorter +than 250 ms between two of them is dropped. The buffer keeps only the utterance under way, or the last moments of silence, so a session can stay open through silence; a commit while `server_vad` runs transcribes it as an utterance, the one that `speech_started` named if speech is under way, and a clear drops it, and in both cases turn detection begins again on the audio that follows. diff --git a/measure/live_latency.py b/measure/live_latency.py index 3378b7eb..1596b661 100644 --- a/measure/live_latency.py +++ b/measure/live_latency.py @@ -28,8 +28,10 @@ - speech started and committed, from the start and from the end of speech; - whether it is cut: an utterance the detection cuts out of speech longer than its longest region (10 s) begins or ends inside the speech, at the cut, and is committed only once the stretch reaches that length, so its parts wait; -- whether the completed transcript is the text of the same samples, the region the server's detection cut found by - `speech vad` with server_vad's options, sent afterwards to /v1/audio/transcriptions of the same server. +- whether the completed transcript is the text of the same samples, the region the server's detection cut, sent + afterwards to /v1/audio/transcriptions of the same server: the region whose bounds are the item's among those of + `speech vad` with server_vad's options, padded either way a build may pad them, by Silero VAD's rule or by + transcription by regions' own (checks/smoke/region_cut.py). With --diarize, each server also holds the diarization model MODEL and each session asks for diarization with its defaults (session.audio.input.diarization {}), so that the server holds each completed transcript until the diarization @@ -79,6 +81,7 @@ import soxr sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "checks", "smoke")) +import region_cut # noqa: E402 from server_client import Server, WebSocket # noqa: E402 RATE = 24000 @@ -344,7 +347,8 @@ def utterances(events, started, reference, cut): if partial: at["first_partial"] = partial[0] done = first.get("completed") or first.get("failed") - region = [r for r in cut if milliseconds(r[0]) == first["speech_started"][1]["audio_start_ms"]] if "speech_started" in first else [] + region = [r for r in cut if milliseconds(r[0]) == first["speech_started"][1]["audio_start_ms"] and + ("speech_stopped" not in first or milliseconds(r[1]) == first["speech_stopped"][1]["audio_end_ms"])] if "speech_started" in first else [] rows.append({"item": item, "start": begin, "end": end, "heard": [r for r in reference if r[1] > begin and r[0] < end], "at": at, "failed": "failed" in first, "text": done[1].get("transcript") if done else None, "region": region[0] if region else None}) return rows @@ -430,15 +434,17 @@ def run(work, label, speech, model, vad, diarizer, serve, names, chunk_ms, round meta = json.load(f) path = os.path.join(work, "sessions", name + ".wav") cut_path = os.path.join(work, "cuts", label, name + ".json") + with open(path, "rb") as f: + pcm = f.read()[44:] if not os.path.exists(cut_path): os.makedirs(os.path.dirname(cut_path), exist_ok=True) cut = regions(speech, vad, [path], *SERVER_VAD)[0] + speech_only = regions(speech, vad, [path], *region_cut.detection_flags(0.5, 300, 500, 10))[0] + cut += [r for r in region_cut.padded(speech_only, 300, 500, len(pcm) / 2 / RATE) if r not in cut] with open(cut_path, "w") as f: json.dump(cut, f) with open(cut_path) as f: cut = json.load(f) - with open(path, "rb") as f: - pcm = f.read()[44:] language = meta["language"] if takes_language else None session = Session(server.port, info["name"], language, diarizer is not None) started = session.stream(pcm, RATE * chunk_ms // 1000) diff --git a/tools/cli/asr.cpp b/tools/cli/asr.cpp index 98bd80c1..7c989b17 100644 --- a/tools/cli/asr.cpp +++ b/tools/cli/asr.cpp @@ -44,10 +44,14 @@ std::string region_defaults() { return out; } -/** The detection model of --vad, and the request options that are its own: those it takes and the recognizer does not. */ +/** + * The detection model of --vad, the request options that are its own (those it takes and the recognizer does not), and + * the cut of transcription by regions they ask for. + */ struct Detection { Model model{nullptr, speech_model_free}; std::vector options; + std::optional cut; }; /** The diarization model of --diarize, and the request options that are its own. */ @@ -132,6 +136,7 @@ std::optional detection_of(const CommandLine & line, const std::optio (own ? d.options : recognition).push_back(o); } d.options = region_options(d.options); + d.cut.emplace(d.model.get(), d.options); options = recognition; return d; } @@ -279,8 +284,8 @@ int run_asr(const CommandLine & line, FILE * out) { rate = enhanced.rate; } if (detection) { - const Request request = detection_request(detection->model.get(), samples, rate, detection->options); - found = *detect_regions(request.get(), never); + const Request request = detection_request(detection->model.get(), samples, rate, detection->cut->detection()); + found = detection->cut->regions(*detect_regions(request.get(), never), (double) samples.size() / rate); regions = found.size(); transcript = *transcribe_regions(model.get(), samples, rate, found, options, timestamps, never, &parts); if (diarizer) { diff --git a/tools/common/regions.cpp b/tools/common/regions.cpp index 2f915e84..eae0a1f5 100644 --- a/tools/common/regions.cpp +++ b/tools/common/regions.cpp @@ -2,6 +2,10 @@ #include #include +#include +#include + +#include "failure.h" namespace { @@ -49,6 +53,52 @@ Request detection_request(speech_model * detector, const std::vector & sa return request; } +RegionCut::RegionCut(speech_model * detector, const std::vector & options) : detection_(options) { + apply_options(new_request(detector).get(), options); + const auto value = [&](speech_option option) -> const OptionValue & { + const auto last = std::find_if(options.rbegin(), options.rend(), [&](const RequestOption & o) { return o.option == option; }); + if (last == options.rend()) throw std::logic_error(std::string("a region cut without ") + speech_option_name(option)); + return last->value; + }; + const int64_t pad = std::get(value(SPEECH_OPT_SPEECH_PAD_MS)); + const int64_t silence = std::get(value(SPEECH_OPT_MIN_SILENCE_DURATION_MS)); + const double longest = std::get(value(SPEECH_OPT_MAX_SPEECH_DURATION_S)); + before_ = (double) pad / 1000; + after_ = (double) std::min(pad, silence) / 1000; + silence_ = (double) silence / 1000; + // Silero VAD keeps a region with its padding within max_speech_duration_s, which it shortens by twice its own padding. + const double speech = longest - before_ - after_; + if (!(speech > 0)) { + char message[256]; + std::snprintf(message, sizeof message, + "speech_pad_ms %lld keeps %g s around the speech of a region, which leaves it no room within max_speech_duration_s %g; " + "give less padding or a longer max_speech_duration_s", + (long long) pad, before_ + after_, longest); + throw Failure(speech_status_name(SPEECH_ERROR_INVALID_ARGUMENT), speech_option_name(SPEECH_OPT_SPEECH_PAD_MS), message); + } + for (RequestOption & o : detection_) { + if (o.option == SPEECH_OPT_SPEECH_PAD_MS) o.value = (int64_t) 0; + if (o.option == SPEECH_OPT_MAX_SPEECH_DURATION_S) o.value = speech; + } +} + +Region RegionCut::pad(const Region & speech, double from, std::optional next, double length) const { + double end = speech.end + after_; + if (next && *next - speech.end < silence_) end = std::min(end, speech.end + (*next - speech.end) / 2); + return {std::max(speech.start - before_, from), std::min(end, length)}; +} + +std::vector RegionCut::regions(const std::vector & speech, double length) const { + std::vector out; + double from = 0; + for (size_t i = 0; i < speech.size(); i++) { + const std::optional next = i + 1 < speech.size() ? std::optional(speech[i + 1].start) : std::nullopt; + out.push_back(pad(speech[i], from, next, length)); + from = out.back().end; + } + return out; +} + std::optional> detect_regions(speech_request * detection, Cancellation & cancellation) { if (check(cancellation.run(detection, [&] { return speech_detect(detection); })) == SPEECH_CANCELLED) return std::nullopt; const speech_result * result = speech_request_result(detection); diff --git a/tools/common/regions.h b/tools/common/regions.h index dde042e1..90b58418 100644 --- a/tools/common/regions.h +++ b/tools/common/regions.h @@ -24,7 +24,8 @@ struct VadMember { /** * The members of server_vad that speech.cpp takes: threshold as threshold, prefix_padding_ms, the audio kept before - * speech, as speech_pad_ms, and silence_duration_ms, the silence that ends speech, as min_silence_duration_ms. + * speech, as speech_pad_ms, and silence_duration_ms, the silence that ends speech, as min_silence_duration_ms. RegionCut + * keeps that padding around the speech itself. */ constexpr VadMember kServerVad[] = { {"threshold", SPEECH_OPT_THRESHOLD}, @@ -58,6 +59,45 @@ Request detection_request(speech_model * detector, const std::vector & sa /** The regions that a detection request set up by detection_request() finds, or nothing once it is cancelled. */ std::optional> detect_regions(speech_request * detection, Cancellation & cancellation); +/** + * How transcription by regions cuts audio, as OpenAI's server_vad describes its turns: a turn ends once + * silence_duration_ms of silence has followed its speech, and keeps prefix_padding_ms before the speech. The detection + * finds the speech alone, with speech_pad_ms 0, and each region keeps speech_pad_ms before its speech and as much after + * it, but no more than min_silence_duration_ms, so that the audio of a region is all there once the silence that ends it + * has passed. Silero VAD's own padding gives a region half the silence before the next one where that starts within + * twice speech_pad_ms, which a stream knows only once that much silence has passed: 600 ms with OpenAI's defaults, where + * silence_duration_ms says 500. + */ +class RegionCut { +public: + /** + * The cut that `options`, as region_options() completes them, ask of `detector`, which checks them as a request + * does; it throws a Failure where the padding leaves no room for speech within max_speech_duration_s. + */ + RegionCut(speech_model * detector, const std::vector & options); + + /** The detection's options: `options` with speech_pad_ms 0, and max_speech_duration_s less the padding. */ + const std::vector & detection() const { return detection_; } + /** The seconds kept before a region's speech and after it, and the silence that ends a region. */ + double before() const { return before_; } + double after() const { return after_; } + double silence() const { return silence_; } + + /** + * The region of `speech`, in audio of `length` seconds: from before() earlier, but not before `from`, the end of the + * region before it, to after() later, but not past `length`. Where the speech after it starts at `next` within the + * silence that ends a region, as where max_speech_duration_s cut the speech, the region ends after() later or halfway + * to `next`, whichever comes first. + */ + Region pad(const Region & speech, double from, std::optional next, double length) const; + /** The regions of `speech`, the speech that a detection with detection() found in `length` seconds of audio. */ + std::vector regions(const std::vector & speech, double length) const; + +private: + std::vector detection_; + double before_ = 0, after_ = 0, silence_ = 0; +}; + /** * Checks that `recognizer` is a model of speech recognition and takes `options`, before any region, so that audio without * regions refuses what audio with them would: the library's refusal throws a Failure, and another task unsupported. diff --git a/tools/common/utterances.cpp b/tools/common/utterances.cpp index 0b4af17b..cc0b96c3 100644 --- a/tools/common/utterances.cpp +++ b/tools/common/utterances.cpp @@ -1,10 +1,8 @@ #include "utterances.h" +#include #include #include -#include - -#include "regions.h" namespace utterances { @@ -33,29 +31,20 @@ double seconds_since(std::chrono::steady_clock::time_point t0) { } // namespace -Detection::Detection(speech_model * model, std::shared_ptr keep, std::vector options, int rate) - : model_(model), keep_(std::move(keep)), options_(std::move(options)), rate_(rate) { +Detection::Detection(speech_model * model, std::shared_ptr keep, const std::vector & options, int rate) + : model_(model), keep_(std::move(keep)), cut_(model, options), rate_(rate) { if (rate < kLowestRate) { throw Failure(speech_status_name(SPEECH_ERROR_INVALID_ARGUMENT), "audio", "audio at " + std::to_string(rate) + " Hz is below the " + std::to_string(kLowestRate) + " Hz that detecting speech as it arrives takes; resample it to " + std::to_string(kLowestRate) + " Hz or more"); } start(); - const ModelInfo info = model_info(model_); - const auto milliseconds = [&](speech_option option) { - for (const RequestOption & o : options_) { - if (o.option == option) return (double) std::get(o.value); - } - int64_t value = 0; - check(speech_model_info_option_default_int(info.get(), option, &value)); - return (double) value; - }; - reach_back_ = milliseconds(SPEECH_OPT_SPEECH_PAD_MS) / 1000 + kReachMargin; + reach_back_ = cut_.before() + kReachMargin; } void Detection::start() { const Request request = new_request(model_); - apply_options(request.get(), options_); + apply_options(request.get(), cut_.detection()); speech_detection * raw = nullptr; check(speech_detection_start(request.get(), rate_, &raw)); detection_.reset(raw); @@ -78,10 +67,10 @@ size_t Detection::region_count() const { return speech_detection_region_count(detection_.get()); } -std::pair Detection::region(size_t index) const { - double start = 0, end = 0; - check(speech_detection_region(detection_.get(), index, &start, &end)); - return {start, end}; +Region Detection::region(size_t index) const { + Region r; + check(speech_detection_region(detection_.get(), index, &r.start, &r.end)); + return r; } std::optional> Detection::speaking() const { @@ -133,6 +122,8 @@ void Assembly::detect(std::unique_ptr detection) { origin_ = heard_; pushed_ = 0; regions_ = 0; + held_.clear(); + from_ = 0; } void Assembly::manual() { @@ -242,11 +233,25 @@ double Assembly::heard() const { return (double) heard_ / rate_; } -void Assembly::take_regions() { +void Assembly::take_regions(bool ended) { + const RegionCut & cut = detection_->cut(); + const double length = (double) pushed_ / rate_; const auto at = [&](double seconds) { return origin_ + region_samples(Region{seconds, seconds}, rate_, pushed_).first; }; - for (const size_t count = detection_->region_count(); regions_ < count; regions_++) { - const std::pair region = detection_->region(regions_); - const uint64_t first = at(region.first), last = at(region.second); + for (const size_t count = detection_->region_count(); regions_ < count; regions_++) held_.push_back(detection_->region(regions_)); + const std::optional> speaking = detection_->speaking(); + // The detection gives a region that silence ended once that silence has passed, and one that max_speech_duration_s cut + // with the speech after it begun, or, where it cut the speech itself, before the speech after it has begun; such a + // region waits for that speech or for the silence, so that its padding is the one RegionCut gives the whole audio. + while (!held_.empty()) { + const Region speech = held_.front(); + std::optional next; + if (held_.size() > 1) next = held_[1].start; + else if (speaking) next = speaking->first; + if (!next && !ended && length - speech.end < cut.silence()) return; + const Region region = cut.pad(speech, from_, next, length); + held_.pop_front(); + from_ = region.end; + const uint64_t first = at(region.start), last = at(region.end); if (current_ && current_->start != first) drop_current(); if (!current_) current_ = Utterance{next_++, first, false, first, "", "", ""}; announce(*current_); @@ -257,7 +262,6 @@ void Assembly::take_regions() { send(stopped); commit_samples(current_->number, first, last); } - const std::optional> speaking = detection_->speaking(); if (!speaking) { if (current_) drop_current(); // The audio before what a region still to come may reach back to lies outside every region. @@ -265,7 +269,7 @@ void Assembly::take_regions() { if (heard_ - buffer_ > reach) keep_from(heard_ - reach); return; } - const uint64_t start = at(speaking->first); + const uint64_t start = at(std::max(speaking->first - cut.before(), from_)); if (current_ && current_->start != start) drop_current(); if (!current_) current_ = Utterance{next_++, start, false, start, "", "", ""}; keep_from(start); @@ -350,7 +354,7 @@ void Assembly::end_detection() { const auto t0 = std::chrono::steady_clock::now(); detection_->end(); detecting_ += seconds_since(t0); - take_regions(); + take_regions(true); detection_.reset(); } @@ -359,6 +363,8 @@ void Assembly::restart_detection() { origin_ = heard_; pushed_ = 0; regions_ = 0; + held_.clear(); + from_ = 0; } void Assembly::begin_manual_utterance() { diff --git a/tools/common/utterances.h b/tools/common/utterances.h index 987d48d2..2bd94dbd 100644 --- a/tools/common/utterances.h +++ b/tools/common/utterances.h @@ -14,15 +14,16 @@ #include "cancellation.h" #include "library.h" +#include "regions.h" #include "request-options.h" #include "speakers.h" #include "transcript.h" // Utterance assembly: audio that arrives a piece at a time, at a rate given when the assembly starts, cut into // utterances, each recognized alone, as transcription by regions recognizes a whole recording. With a detection, the -// utterances are the regions where someone speaks, which the detection gives sample for sample as speech_detect() gives -// them for the whole audio; without one, the caller commits each utterance, all the audio appended since the last -// commit. While an utterance goes on, its beginning is read again and again, and the beginning that two readings in a +// utterances are the regions of transcription by regions: the speech that the detection finds sample for sample as +// speech_detect() finds it in the whole audio, padded as RegionCut pads it; without one, the caller commits each +// utterance, all the audio appended since the last commit. While an utterance goes on, its beginning is read again and again, and the beginning that two readings in a // row agree on goes out as deltas, which only ever add text; once it is committed, it is recognized whole, and that // recognition, which may differ from the deltas, completes it. With a diarization, the completion waits until the // diarization has settled the utterance's audio, and carries the speakers within it, while the recognitions after it go @@ -108,19 +109,20 @@ class Enhancer { }; /** - * A detection of audio given a piece at a time (speech_detection), on a detection model that `keep` keeps until the - * detection is freed, with the request options it was started with. + * A detection of audio given a piece at a time (speech_detection) of the speech alone, on a detection model that `keep` + * keeps until the detection is freed, with the cut of transcription by regions that pads its regions. */ class Detection { public: /** - * Starts a detection of audio at `rate` with `options`, which the library checks; its refusal throws a Failure, and so - * does a rate below 8000 Hz, whose resampler holds back more audio than the assembly keeps for a region to come. + * Starts a detection of audio at `rate` with the cut that `options`, as region_options() completes them, ask for, + * which the library checks; its refusal throws a Failure, and so does a rate below 8000 Hz, whose resampler holds back + * more audio than the assembly keeps for a region to come. */ - Detection(speech_model * model, std::shared_ptr keep, std::vector options, int rate); + Detection(speech_model * model, std::shared_ptr keep, const std::vector & options, int rate); int rate() const { return rate_; } - const std::vector & options() const { return options_; } + const RegionCut & cut() const { return cut_; } /** What keeps the model, which tells the model a host holds now from the one the detection runs on. */ const void * model() const { return keep_.get(); } /** @@ -132,10 +134,10 @@ class Detection { void push(const float * samples, size_t n); void end(); size_t region_count() const; - /** The region at `index`, in seconds from the start of the detection's audio. */ - std::pair region(size_t index) const; + /** The speech of the region at `index`, in seconds from the start of the detection's audio. */ + Region region(size_t index) const; /** - * The start of the region begun and not given yet, and whether it is certain to be given, as + * The start of the speech of the region begun and not given yet, and whether it is certain to be given, as * speech_detection_speaking() gives them, or nothing. */ std::optional> speaking() const; @@ -147,7 +149,7 @@ class Detection { speech_model * model_; std::shared_ptr keep_; - std::vector options_; + RegionCut cut_; int rate_; double reach_back_ = 0; std::unique_ptr detection_{nullptr, speech_detection_free}; @@ -272,7 +274,8 @@ class Assembly { /** Sends the completions that wait, from the first, while each one's speakers are settled. */ void release(); // These run with the mutex held. - void take_regions(); + /** Commits the regions the detection has given, and follows the one begun; `ended` once the detection's audio has. */ + void take_regions(bool ended = false); void announce(Utterance & u); void send_agreed(Utterance & u); void commit_samples(uint64_t number, uint64_t first, uint64_t last); @@ -308,9 +311,15 @@ class Assembly { uint64_t heard_ = 0, buffer_ = 0; /** The samples of the utterances committed and not yet recognized. */ size_t committed_ = 0; - /** Where the detection's audio began, how much of it it took, and how many of its regions are committed. */ + /** Where the detection's audio began, how much of it it took, and how many of its regions it has given. */ uint64_t origin_ = 0, pushed_ = 0; size_t regions_ = 0; + /** + * The speech of the regions given and not yet committed, whose padding waits on whether speech starts again within + * the silence that ends a region, and the end of the last region committed, in seconds of the detection's audio. + */ + std::deque held_; + double from_ = 0; uint64_t next_ = 0; std::optional current_; std::deque finals_; diff --git a/tools/server/jobs.h b/tools/server/jobs.h index cc47801a..bced52a5 100644 --- a/tools/server/jobs.h +++ b/tools/server/jobs.h @@ -147,8 +147,12 @@ struct TranscriptionJob : Job { /** The length of the audio in seconds and its rate, for the log and verbose_json. */ double duration = 0; int sample_rate = 0; - /** With chunking_strategy: the detection model, kept as `served` is, and its request set up with the audio. */ + /** + * With chunking_strategy: the detection model, kept as `served` is, the cut its members ask for, and the detection + * request set up with the audio and the cut's options. + */ std::shared_ptr detector; + std::optional cut; Request detection{nullptr, speech_request_free}; /** With chunking_strategy: the model of `served`, the audio, the recognition options and whether they set timestamps. */ speech_model * recognizer = nullptr; @@ -292,7 +296,7 @@ inline void transcribe(const std::shared_ptr & job, Turns & tu } std::optional> regions = detect_regions(job->detection.get(), job->cancellation); if (!regions) return SPEECH_CANCELLED; - job->regions = std::move(*regions); + job->regions = job->cut->regions(*regions, (double) job->samples.size() / job->sample_rate); std::optional t = transcribe_regions(job->recognizer, job->samples, job->sample_rate, job->regions, job->options, job->timestamps, job->cancellation, job->diarization ? &job->parts : nullptr); if (!t) return SPEECH_CANCELLED; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 4c2fcb77..2644f4ca 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -231,8 +231,8 @@ class Server { res); if (!job->detector) return; try { - job->detection = detection_request(job->detector->get(), asked.samples, asked.sample_rate, - region_options(*asked.regions, job->detector->defaults())); + job->cut.emplace(job->detector->get(), region_options(*asked.regions, job->detector->defaults())); + job->detection = detection_request(job->detector->get(), asked.samples, asked.sample_rate, job->cut->detection()); } catch (const Failure & e) { ApiError error = openai::library_error(e); const std::string member = server_vad_member(e.option()); From 2ae293bc87af1435e269df3284d89387007c3ce0 Mon Sep 17 00:00:00 2001 From: sakasegawa Date: Sun, 22 Nov 2026 05:18:15 +0900 Subject: [PATCH 2/3] Hold a cut region until the speech after it is kept or dropped Where max_speech_duration_s cut the speech within it, the assembly padded the region by the start of the region under way even while that region was not yet kept. A stretch shorter than min_speech_duration_ms is then dropped, and the file, in which it is no region, pads the cut region by after() instead: streamed in pieces of 20 ms, a region cut at 3.616 s ended at 3.632 s, where the file ends it at 3.916 s. The region now waits until the speech after it is kept, dropped, or more than the silence away. Checked: the CLI smoke's new case, a region cut within its speech followed by 150 ms of speech and a second of silence, fed to speech asr - in pieces of 20 ms, fails without the fix and passes with it; speech_cli_smoke.py and server_realtime_smoke.py with Qwen3-ASR 0.6B and Silero VAD pass. Co-Authored-By: Claude Opus 5.5 --- checks/smoke/speech_cli_smoke.py | 42 +++++++++++++++++++++++++++++++- tools/common/utterances.cpp | 14 ++++++++--- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/checks/smoke/speech_cli_smoke.py b/checks/smoke/speech_cli_smoke.py index e6edf0c2..cd16a686 100644 --- a/checks/smoke/speech_cli_smoke.py +++ b/checks/smoke/speech_cli_smoke.py @@ -847,11 +847,51 @@ def milliseconds(seconds): assert done["transcript"] == end["text"] and done["stop"] == end["stop"], (done, end) assert [x["code"] for x in done.get("languages", [])] == end.get("languages", []), (done, end) assert done["usage"]["seconds"] == (last - first) / rate, (done, start, end_s) + # A region the longest region of 2 s cut within its speech, followed by 150 ms of that speech, too short to keep, and + # a second of silence: the stream waits until that speech is dropped and pads the region as the file does, where + # the region after it is none. + cuts = [r for k, r in enumerate(found) if k + 1 < len(found) and found[k + 1]["start"] - r["end"] < 0.05] + assert cuts, found + short = joined[:2 * round((cuts[0]["end"] + 0.15) * rate)] + b"\0" * 2 * rate + short_path = os.path.join(work, "speech-cli-smoke-cut.wav") + with open(short_path, "wb") as f: + f.write(b"RIFF" + struct.pack("> speaking = detection_->speaking(); // The detection gives a region that silence ended once that silence has passed, and one that max_speech_duration_s cut // with the speech after it begun, or, where it cut the speech itself, before the speech after it has begun; such a - // region waits for that speech or for the silence, so that its padding is the one RegionCut gives the whole audio. + // region waits for that speech to be kept or dropped, or for the silence, so that its padding is the one RegionCut + // gives the whole audio, in which the speech after it is a region's only where it was kept. while (!held_.empty()) { const Region speech = held_.front(); std::optional next; - if (held_.size() > 1) next = held_[1].start; - else if (speaking) next = speaking->first; - if (!next && !ended && length - speech.end < cut.silence()) return; + bool unsure = false; + if (held_.size() > 1) { + next = held_[1].start; + } else if (speaking && speaking->first - speech.end < cut.silence()) { + if (speaking->second) next = speaking->first; + else unsure = true; + } + if (!ended && (unsure || (!next && length - speech.end < cut.silence()))) return; const Region region = cut.pad(speech, from_, next, length); held_.pop_front(); from_ = region.end; From fe541fc80cf483b6d04715eca8aa193af42698a4 Mon Sep 17 00:00:00 2001 From: sakasegawa Date: Sun, 22 Nov 2026 05:18:15 +0900 Subject: [PATCH 3/3] Give the measured commit and completion times of the tools' padding measure/live_latency.py on an Apple M5 with FLEURS ja and en over /v1/realtime: the commit came 0.58 to 0.60 s after the speech ended in the median, where Silero VAD's padding gave 0.67 to 0.69 s, and the completed transcript 0.69 to 0.73 s with Qwen3-ASR 0.6B and 0.84 to 0.85 s with 1.7B, where it came 0.79 to 0.80 s and 0.96 to 1.00 s. Every completed transcript was the recognition of the same samples sent as a file. Co-Authored-By: Claude Opus 5.5 --- ...s-deltas-the-text-two-readings-agree-on.md | 21 ++++++++++++++----- docs/cli.md | 2 +- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md b/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md index 78091eaf..f89be8d1 100644 --- a/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md +++ b/docs/adr/live-transcription-cuts-utterances-by-the-detections-regions-and-sends-as-deltas-the-text-two-readings-agree-on.md @@ -94,13 +94,24 @@ program using the GPU at times), the times counted from where speech vad finds t |---|---|---| | speech started, after the speech begins | 0.25 to 0.26 s | 0.25 to 0.27 s | | first delta, after the speech begins | 0.68 to 1.53 s | 0.48 to 1.12 s | -| commit, after the speech ends | 0.60 s | 0.60 s | -| completed, after the speech ends | 0.69 to 1.15 s | 0.72 to 1.30 s | Two runs each, while another program synthesized speech on the GPU. The first delta waits for two readings to agree -past the mark or space before their end, about half a second of speech. The commit waits for the silence of `min_silence_duration_ms` and for what follows within twice -`speech_pad_ms`. The detection took 0.12 s per minute of 16 kHz audio and 0.15 s of 24 kHz alone, and 0.3 to 0.6 s -beside the readings, which take the GPU and the CPU it waits on. +past the mark or space before their end, about half a second of speech. The detection took 0.12 s per minute of 16 kHz +audio and 0.15 s of 24 kHz alone, and 0.3 to 0.6 s beside the readings, which take the GPU and the CPU it waits on. + +The commit comes once `min_silence_duration_ms` of silence has passed, within the detection's chunk of 32 ms and the +client's piece of audio. `measure/live_latency.py` on an Apple M5 (2026-11-22): FLEURS ja_jp and en_us test clips, two +sessions of five clips per language in each of two rounds, sent over `/v1/realtime` with `server_vad`'s defaults in +pieces of 100 ms as they would be said, Qwen3-ASR Q8_0 on Metal and Silero VAD on the CPU; the medians of the +utterances the detection did not cut, over Japanese and English, from the end of speech: + +| | Silero VAD's padding | the tools' padding | +|---|---|---| +| commit | 0.67 to 0.69 s | 0.58 to 0.60 s | +| completed, Qwen3-ASR 0.6B | 0.79 to 0.80 s | 0.69 to 0.73 s | +| completed, Qwen3-ASR 1.7B | 0.96 to 1.00 s | 0.84 to 0.85 s | + +Every completed transcript was the recognition of the same samples sent as a file afterwards. A beginning that two readings agree on and a later reading changes stays in the deltas until the completed event replaces it, and later readings add nothing to them; where the final text goes on from what they gave, one more delta diff --git a/docs/cli.md b/docs/cli.md index f28fad09..c2e98f0b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -234,7 +234,7 @@ speech asr qwen3-asr-0.6b --vad silero-vad --live --format json > events.jsonl `conversation.item.input_audio_transcription.delta`, text that adds to the end of what came before, and `conversation.item.input_audio_transcription.completed`, whose `transcript` is the whole text and replaces the deltas. - On an Apple M5, speech started comes 0.26 s after the speech begins, the first text 0.5 to 1.5 s after it, and the - final text 0.7 to 1.3 s after the speech ends. + final text 0.7 s (Qwen3-ASR 0.6B) to 0.85 s (1.7B) after the speech ends, in the median with the defaults. - stderr reports the microphone and its rate, and at the end the utterances and the time the detection took; `-v` also reports each utterance as it ends. A recognition that fails ends the run with exit 1, after the `failed` event in JSON. - With `--diarize`, the diarization hears the audio as it arrives, in its `low_latency` mode unless `--streaming-mode`