From 18caeb0348a778d9a815b3821f77192c37345160 Mon Sep 17 00:00:00 2001 From: chenyue42 Date: Thu, 26 Nov 2026 20:22:36 -0600 Subject: [PATCH] =?UTF-8?q?feat(textstream):=20=E8=AF=8D=E5=85=B8=E7=83=AD?= =?UTF-8?q?=E8=AF=8D=E8=BF=9B=E5=85=A5=20TextStream=20=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已启用的词典词条作为 Qwen3-ASR 的 context 参与 TextStream 识别, 在语音识别这一步就把专有名词写对,而不是只靠 LLM 润色去补。 - 沿用会话冻结的 asr.prompt,经环境变量 OPENLESS_TEXTSTREAM_CONTEXT 交给 worker,再传给 init_streaming(context=...)。 - worker 把 "A, B." 转成 mlx-qwen3-asr 文档要求的空格分隔:逗号列表会 诱使解码器在正常语句中续写词表。去掉尖括号,避免词条被分词成控制 token。 - 没有人声的窗口会让解码器把 context 当作转写输出,并残留在强制前缀里 吞掉之后的语音。检测连续 4 个及以上、顺序与词典一致的词条,从所有快照 中去掉并重启流;触发的那块音频在新流里再解码一次。 - 带 context 时被标成 None 的语言不再沿用到后续窗口。 - 把已发布的 worker 加入 PREVIOUS_WORKERS,已安装用户可直接升级脚本。 不带词典时行为与之前一致。 Co-Authored-By: Claude Fable 5.2 --- .../local-asr-lifecycle-contract.test.mjs | 13 ++ .../src-tauri/src/asr/local/experimental.rs | 4 +- .../src/asr/local/experimental/textstream.rs | 42 ++++++ .../local/experimental/textstream/install.rs | 13 ++ .../experimental/textstream/test_worker.py | 118 +++++++++++++++-- .../local/experimental/textstream/worker.py | 122 ++++++++++++++++-- 6 files changed, 287 insertions(+), 25 deletions(-) diff --git a/openless-all/app/scripts/local-asr-lifecycle-contract.test.mjs b/openless-all/app/scripts/local-asr-lifecycle-contract.test.mjs index 277aa9522..2425cedba 100644 --- a/openless-all/app/scripts/local-asr-lifecycle-contract.test.mjs +++ b/openless-all/app/scripts/local-asr-lifecycle-contract.test.mjs @@ -24,6 +24,19 @@ assert.match(verification, /meta\.ctime_nsec\(\)/); assert.match(verification, /before != after/); assert.match(native, /with_local_startup_spawner/); assert.match(worker, /TextStreamChunk\s*\{\s*text: finalized \+ draft\.as_str\(\),\s*offset: 0/); +// Dictionary hotwords reach TextStream as the session's frozen ASR prompt, set on +// the worker's environment right before spawn; argv is readable by every account. +assert.match( + read('src-tauri/src/asr/local/experimental.rs'), + /let hotwords = context\.asr\.prompt\.clone\(\);[^]*?\.textstream\s*\.start\([^)]*, hotwords\)/, +); +assert.match(worker, /apply_context\(&mut command, context\.as_deref\(\)\);\s*let mut child = command\.spawn\(\)/); +// Rust and the Python worker each name the variable; they must agree. +const script = read('src-tauri/src/asr/local/experimental/textstream/worker.py'); +for (const source of [worker, script]) { + assert.match(source, /CONTEXT_ENV(?:: &str)? = "OPENLESS_TEXTSTREAM_CONTEXT"/); +} +assert.match(script, /context = " "\.join\(phrases\)[^]*?init_streaming\(\s*context=context,/); const core = read('crates/openless-core/src/local_asr_service.rs'); const activate = core.match(/ fn activate\([^]*?(?=\n fn )/)[0]; assert.doesNotMatch(activate, /\.(?:prepare|preload|preload_lease|download_native_model)\(/); diff --git a/openless-all/app/src-tauri/src/asr/local/experimental.rs b/openless-all/app/src-tauri/src/asr/local/experimental.rs index 16d0013e2..796aec536 100644 --- a/openless-all/app/src-tauri/src/asr/local/experimental.rs +++ b/openless-all/app/src-tauri/src/asr/local/experimental.rs @@ -337,9 +337,11 @@ impl TranscriptionEngine for ExperimentalTranscriptionEngine { let (directory, generation) = models.lease(model)?; #[cfg(all(target_os = "macos", target_arch = "aarch64"))] if model == Model::TextStream { + // The session's frozen dictionary hotwords; selection flows clear them. + let hotwords = context.asr.prompt.clone(); return runtime .textstream - .start(directory, models, generation, _partials) + .start(directory, models, generation, _partials, hotwords) .await; } runtime.prepare(model, directory.clone()).await?; diff --git a/openless-all/app/src-tauri/src/asr/local/experimental/textstream.rs b/openless-all/app/src-tauri/src/asr/local/experimental/textstream.rs index e9faa4e87..9ee6e7705 100644 --- a/openless-all/app/src-tauri/src/asr/local/experimental/textstream.rs +++ b/openless-all/app/src-tauri/src/asr/local/experimental/textstream.rs @@ -32,6 +32,22 @@ use tokio::sync::oneshot; pub use install::{install, installed}; const MAX_LINE: u64 = protocol::MAX_EVENT_BYTES as u64; const MAX_QUEUED_BYTES: usize = 32_000 * 600; // Ten-minute capture/retranscribe cap; no dropped speech. +const CONTEXT_ENV: &str = "OPENLESS_TEXTSTREAM_CONTEXT"; + +/// Hand the session's frozen dictionary hotwords to the worker, which feeds them +/// to Qwen3-ASR as recognition context. Every local account can read argv through +/// `ps`, the environment only this user; an unusable hint is dropped, never a +/// start failure. +fn apply_context(command: &mut Command, context: Option<&str>) { + match context + .map(str::trim) + .filter(|context| !context.is_empty() && !context.contains('\0')) + { + Some(context) => command.env(CONTEXT_ENV, context), + // Do not inherit a stale value from the application's own environment. + None => command.env_remove(CONTEXT_ENV), + }; +} fn error(message: impl std::fmt::Display) -> BackendError { BackendError::new(BackendErrorCode::Provider, message.to_string()) } @@ -98,6 +114,7 @@ impl Runtime { models: Arc, generation: u64, partials: Arc, + context: Option, ) -> Result, BackendError> { let expected_runtime = self.generation.load(Ordering::Acquire); install::refresh_worker(&directory).await?; @@ -157,6 +174,7 @@ impl Runtime { .stdout(Stdio::piped()) .stderr(Stdio::null()) .process_group(0); + apply_context(&mut command, context.as_deref()); let mut child = command.spawn().map_err(error)?; let stdin = child.stdin.take().expect("worker stdin"); let stdout = child.stdout.take().expect("worker stdout"); @@ -480,6 +498,30 @@ mod tests { assert!(cancelled.is_empty()); } + #[test] + fn dictionary_context_travels_by_environment_and_never_as_a_stale_value() { + fn sent(context: Option<&str>) -> Option { + let mut command = Command::new("/usr/bin/true"); + apply_context(&mut command, context); + assert!( + command.get_args().next().is_none(), + "vocabulary must stay out of argv" + ); + let (_, value) = command + .get_envs() + .find(|(name, _)| name.to_str() == Some(CONTEXT_ENV)) + .expect("set or explicitly removed, never inherited"); + value.map(Into::into) + } + assert_eq!( + sent(Some(" OpenLess, 李梓涵. ")), + Some("OpenLess, 李梓涵.".into()) + ); + for unusable in [None, Some(" "), Some("Open\0Less")] { + assert_eq!(sent(unusable), None); + } + } + #[test] fn startup_cancellation_kills_only_the_owned_process() { let child = Command::new("/bin/sleep") diff --git a/openless-all/app/src-tauri/src/asr/local/experimental/textstream/install.rs b/openless-all/app/src-tauri/src/asr/local/experimental/textstream/install.rs index 6955b25b3..e203cfb0d 100644 --- a/openless-all/app/src-tauri/src/asr/local/experimental/textstream/install.rs +++ b/openless-all/app/src-tauri/src/asr/local/experimental/textstream/install.rs @@ -49,6 +49,9 @@ fn current_worker_installed(directory: &Path) -> bool { && std::fs::read_to_string(script(directory)).is_ok_and(|s| s == WORKER) } +/// `(environment hash, worker.py SHA-256)` of every worker a release has shipped +/// against the current `requirements.lock`. When `worker.py` changes, add the +/// outgoing pair, or existing installations stop counting as installed. const PREVIOUS_WORKERS: &[(&str, &str)] = &[ ( "f585f75ca2d669b48f75a40fe6a7213f9948ac84ce3c5c9378f2b84dfe77a243", @@ -58,6 +61,16 @@ const PREVIOUS_WORKERS: &[(&str, &str)] = &[ "64e7ec7b3c3557bea2314d8a99564cf7cfb0402ff1cea586fc3c5366ef5e543b", "f08166fc2a375a42f9c86bcc75ded43e1bc8b742c4fba4289db4002a6bc464dc", ), + // v2.0.2-Beta.1 to Beta.3. + ( + "6815c8a1b0d0a1ff1bef18f0d67d33314c6c8ff1b014bc8fe30cee1c2ed22754", + "36c1f568c9f7ed246ce951637d057bfaa862d436bc0a71e0c9e509e4d0c277a0", + ), + // v2.0.2-Beta.4 to v2.0.3-Beta.3: the last worker without dictionary hotwords. + ( + "2b057586461d02fb9350cdc1c9fb8def7b64f7471b1cc74538885fd086c73da5", + "da7d78a407857e0ade872d4b041451736ed044e4a609652934f3b30039555515", + ), ]; /// A known managed worker can be upgraded at recording start without reinstalling diff --git a/openless-all/app/src-tauri/src/asr/local/experimental/textstream/test_worker.py b/openless-all/app/src-tauri/src/asr/local/experimental/textstream/test_worker.py index df9ce4efe..d5c586b78 100644 --- a/openless-all/app/src-tauri/src/asr/local/experimental/textstream/test_worker.py +++ b/openless-all/app/src-tauri/src/asr/local/experimental/textstream/test_worker.py @@ -25,7 +25,7 @@ class FakeAudio(list): @property def data(self): - return bytearray(len(self) * 4) + return bytes([any(self)]) # One flag per frame: does it hold speech? def astype(self, _dtype): return self @@ -50,13 +50,40 @@ def init_streaming(self, **kwargs): def feed_audio(self, _audio, _state): self.calls.append(("feed",)) - return SimpleNamespace(stable_text="你好", text="你好世") + return SimpleNamespace(stable_text="你好", text="你好世", language="Chinese") def finish_streaming(self, _state): self.calls.append(("finish",)) return SimpleNamespace(stable_text="你好,世界。", text="你好,世界。") +class RecitingSession(FakeSession): + """Like Qwen3-ASR: a window without speech is transcribed as the context, and + the stream that did so keeps it as its prefix. One script per stream.""" + + scripts: ClassVar[list[list[str]]] = [] + + def init_streaming(self, **kwargs): + self.calls.append(("init", kwargs)) + recited = kwargs["context"].capitalize() + index = sum(call[0] == "init" for call in self.calls) - 1 + script = [text.format(recited=recited) for text in self.scripts[index]] + return SimpleNamespace( + stable_text="", text="", language="unknown", script=iter(script) + ) + + def feed_audio(self, _audio, state): + self.calls.append(("feed", state.language)) + state.text = state.stable_text = next(state.script) + state.language = "None" + return state + + def finish_streaming(self, state): + self.calls.append(("finish",)) + state.text = state.stable_text = next(state.script) + return state + + class WorkerTests(unittest.TestCase): def test_import_does_not_initialize_inference_or_capture(self): self.assertNotIn("mlx.core", sys.modules) @@ -147,12 +174,11 @@ def test_draft_is_revisable_and_final_comes_from_decoder(self): ) self.assertNotEqual(snapshots.sequence, 0) - def run_fake(self, finish=True, gpu_available=True): + def run_fake(self, finish=True, gpu_available=True, session=FakeSession, blocks="S"): + """`blocks`: two-second PCM blocks, `S` with speech and `s` silent.""" FakeSession.calls = [] - request = { - "type": "audio", - "pcm": base64.b64encode(b"\x01\x00" * 32000).decode(), - } + pcm = b"".join((b"\x01\x00" if b == "S" else b"\x00\x00") * 32000 for b in blocks) + request = {"type": "audio", "pcm": base64.b64encode(pcm).decode()} lines = json.dumps(request) + "\n" + ('{"type":"finish"}\n' if finish else "") output = io.StringIO() mlx_core = SimpleNamespace( @@ -179,13 +205,15 @@ def run_fake(self, finish=True, gpu_available=True): "mlx": SimpleNamespace(__path__=[], core=mlx_core), "mlx.core": mlx_core, "numpy": SimpleNamespace( - frombuffer=lambda raw, dtype: FakeAudio([0] * (len(raw) // 2)), + frombuffer=lambda raw, dtype: FakeAudio(memoryview(raw).cast("h")), float32=object(), ascontiguousarray=lambda audio: audio, ), - "mlx_qwen3_asr": SimpleNamespace(Session=FakeSession), + "mlx_qwen3_asr": SimpleNamespace(Session=session), "silero_vad_lite": SimpleNamespace( - SileroVAD=lambda _rate: SimpleNamespace(process=lambda _frame: 1.0) + SileroVAD=lambda _rate: SimpleNamespace( + process=lambda frame: float(frame[0]) + ) ), } with tempfile.TemporaryDirectory() as root: @@ -229,6 +257,76 @@ def test_feed_produces_draft_before_finish_and_final_is_refined(self): init = next(call for call in FakeSession.calls if call[0] == "init") self.assertIsNone(init[1]["language"], "do not hard-code English") + PROMPT = "ghostty, OpenLess, 李梓涵, RLWE, NTT." + + def recite(self, scripts, blocks): + RecitingSession.scripts = scripts + with patch.dict(os.environ, {worker.CONTEXT_ENV: self.PROMPT}): + events = self.run_fake(session=RecitingSession, blocks=blocks) + # stdout events are what SSE republishes. + self.assertNotIn("李梓涵", json.dumps(events, ensure_ascii=False)) + count = lambda kind: sum(call[0] == kind for call in FakeSession.calls) + return [e["finalized"] + e["draft"] for e in events[1:]], count("init"), count("feed") + + def test_dictionary_reaches_the_decoder_as_space_separated_terms(self): + # OpenLess freezes "A, B."; a comma list makes the decoder continue it, and + # `<...>` would be tokenized as control tokens. + prompt = " OpenLess, 李梓涵, LWEs-to-RLWE packing, <|audio_pad|>.\n" + with patch.dict(os.environ, {worker.CONTEXT_ENV: prompt}): + self.run_fake() + init = next(call for call in FakeSession.calls if call[0] == "init") + self.assertEqual( + init[1]["context"], "OpenLess 李梓涵 LWEs-to-RLWE packing |audio_pad|" + ) + + def test_no_dictionary_keeps_the_upstream_empty_context(self): + for environment in ({}, {worker.CONTEXT_ENV: " \n"}): + with patch.dict(os.environ, environment, clear=True): + self.run_fake() + init = [call for call in FakeSession.calls if call[0] == "init"] + self.assertEqual([call[1]["context"] for call in init], [""]) + + def test_a_recited_dictionary_restarts_the_decoder_and_never_reaches_the_user(self): + # Speech; a silent window that is recited, also when decoded on its own; + # silence that waits for speech; speech whose final decode recites again. + scripts = [["你好。", "你好。{recited}。"], ["{recited}"], ["世界", "世界。{recited}"]] + texts, streams, decoded = self.recite(scripts, "SSsS") + self.assertEqual(texts, ["你好。", "你好。", "你好。世界", "你好。世界。"]) + self.assertEqual((streams, decoded), (3, 4)) + + def test_speech_beginning_in_a_recited_block_is_decoded_again(self): + scripts = [["你好。", "你好。{recited}。"], ["世", "世界", "世界。"]] + texts, streams, decoded = self.recite(scripts, "SSS") + self.assertEqual(texts, ["你好。", "你好。世", "你好。世界", "你好。世界。"]) + self.assertEqual((streams, decoded), (2, 4)) + + def test_only_phrases_in_dictionary_order_count_as_recitation(self): + recited = worker.recitation( + ["New York Stock Exchange", "OpenLess", "AI", "is", "the", "best"] + ) + for spoken in ( + "I work at the New York Stock Exchange.", # One phrase of four words. + "OpenLess AI is fine", # Fewer than RECITED_PHRASES in a row. + "I said Kai is the best player.", # Inside an ordinary word. + "best, the, is, AI", # A list the speaker dictated in another order. + ): + self.assertEqual(recited.sub("", spoken), spoken) + for recitation in ("OpenLess AI is the best.", "Openless, AI,is the best"): + self.assertEqual(recited.sub("", f"for today. {recitation} Hello"), "for today. Hello") + self.assertIsNone(worker.recitation(["ghostty", "OpenLess", "李梓涵"])) + + def test_a_none_language_guess_is_not_kept_for_later_windows(self): + self.recite([["一", "二", "三", "四"]], "SSS") + seen = [call[1] for call in FakeSession.calls if call[0] == "feed"] + self.assertEqual(seen, ["unknown"] * 3) + + def test_utterances_join_by_script(self): + join = worker.join_utterances + self.assertEqual(join("for today.", "Hello."), "for today. Hello.") + self.assertEqual(join("项目进度。", "Hello."), "项目进度。Hello.") + self.assertEqual(join("안녕하세요", "반갑습니다."), "안녕하세요 반갑습니다.") + self.assertEqual(join("", "今天"), "今天") + def test_missing_metal_never_silently_starts_cpu_inference(self) -> None: with self.assertRaisesRegex(RuntimeError, "Metal GPU"): self.run_fake(gpu_available=False) diff --git a/openless-all/app/src-tauri/src/asr/local/experimental/textstream/worker.py b/openless-all/app/src-tauri/src/asr/local/experimental/textstream/worker.py index 3369e6233..7a7ae1eb1 100644 --- a/openless-all/app/src-tauri/src/asr/local/experimental/textstream/worker.py +++ b/openless-all/app/src-tauri/src/asr/local/experimental/textstream/worker.py @@ -16,6 +16,7 @@ import math import os import queue +import re import sys import threading import time @@ -25,6 +26,61 @@ MAX_LINE = 1_000_000 MAX_AUDIO_BYTES = 32_000 * 600 +CONTEXT_ENV = "OPENLESS_TEXTSTREAM_CONTEXT" +RECITED_PHRASES = 4 +_CONTROL_MARKUP = str.maketrans("", "", "<>") + + +def hotword_phrases() -> list[str]: + """Dictionary phrases OpenLess froze for this recording; empty when unused. + + OpenLess joins them as "A, B." and already bounds the text. Angle brackets + would be tokenized as control tokens such as `<|audio_pad|>` and break the + prompt, so they never reach the tokenizer. + """ + text = os.environ.get(CONTEXT_ENV, "").strip().removesuffix(".") + phrases = ( + " ".join(phrase.translate(_CONTROL_MARKUP).replace(",", " ").split()) + for phrase in text.split(", ") + ) + return [phrase for phrase in phrases if phrase] + + + +def recitation(phrases: list[str]) -> re.Pattern | None: + """Match the context transcribed back instead of speech. + + For a window without speech the decoder writes out its system prompt: several + dictionary phrases in a row, in dictionary order. Speech does not come out + that way. Sentence starts are capitalised and separators may vary. + """ + terms = [r"\s+".join(map(re.escape, phrase.split())) for phrase in phrases] + runs = [ + r"[\s,,、]*".join(terms[start:end]) + for end in range(len(terms), RECITED_PHRASES - 1, -1) + for start in range(end - RECITED_PHRASES + 1) + ] + if not runs: + return None + runs.sort(key=len, reverse=True) + return re.compile( + "(? str: + """Chinese and Japanese join directly; spaced scripts, Korean included, get a space.""" + if not done or not text: + return done or text + + def spaceless(character: str) -> bool: + code = ord(character) + hangul = 0x3130 <= code <= 0x318F or 0xAC00 <= code <= 0xD7AF + return code >= 0x2E80 and not hangul + + joiner = "" if spaceless(done[-1]) or spaceless(text[0]) else " " + return done + joiner + text def metal_memory_limits(memory_bytes: int, recommended_bytes: int) -> tuple[int, int]: @@ -270,15 +326,25 @@ def emit(event): from silero_vad_lite import SileroVAD session = Session(model=str(model_dir)) - state = session.init_streaming( - chunk_size_sec=2.0, - max_context_sec=30.0, - sample_rate=16000, - unfixed_chunk_num=2, - unfixed_token_num=5, - language=None, - finalization_mode="accuracy", - ) + phrases = hotword_phrases() + # Qwen3-ASR documents space-separated terms; a comma list invites the + # decoder to continue it in the middle of ordinary speech. + context = " ".join(phrases) + recited = recitation(phrases) + + def new_stream(): + return session.init_streaming( + context=context, + chunk_size_sec=2.0, + max_context_sec=30.0, + sample_rate=16000, + unfixed_chunk_num=2, + unfixed_token_num=5, + language=None, + finalization_mode="accuracy", + ) + + state = new_stream() vad = SileroVAD(16000) mx.clear_cache() budget.checkpoint() @@ -287,9 +353,23 @@ def emit(event): pending = bytearray() total = 0 heard_speech = False + done = "" # Transcript from before the decoder was last restarted. + + def spoken(text: str) -> str: + text = recited.sub("", text).strip() if recited else text + return join_utterances(done, text) + + def decode(audio, stream): + stream = session.feed_audio(audio, stream) + if stream.language == "None": + # With context, a chunk with little speech can be labelled "None"; + # kept, it is forced on every later window and joins them with + # spaces. + stream.language = "unknown" + return stream def feed(raw): - nonlocal state, heard_speech + nonlocal state, heard_speech, done audio = np.frombuffer(raw, dtype="