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..cd16a686 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) + # 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(" 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` 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..4e38e846 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,31 @@ 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 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; + 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; + 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 +268,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 +275,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 +360,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 +369,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());