Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions openless-all/app/scripts/local-asr-lifecycle-contract.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)\(/);
Expand Down
4 changes: 3 additions & 1 deletion openless-all/app/src-tauri/src/asr/local/experimental.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down Expand Up @@ -98,6 +114,7 @@ impl Runtime {
models: Arc<ExperimentalAsrService>,
generation: u64,
partials: Arc<dyn TextStreamSink>,
context: Option<String>,
) -> Result<Arc<dyn TranscriptionSession>, BackendError> {
let expected_runtime = self.generation.load(Ordering::Acquire);
install::refresh_worker(&directory).await?;
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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<std::ffi::OsString> {
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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
Loading