Skip to content
Closed
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
20 changes: 10 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
name: CI
on: [push, pull_request]
jobs:
skeleton:
host:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Placeholder
run: echo "TODO: add build / test / lint jobs per module"







- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install ffmpeg (compressed uploads)
run: sudo apt-get update && sudo apt-get install -y ffmpeg
- name: Install host
run: pip install -r host/requirements.txt pytest
- name: Test host (no models needed; backends are faked)
run: python -m pytest -q host
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,13 @@ See `docs/subsystems/` for one doc per subsystem.

## Status

Empty skeleton. Docs layout follows yetone/magpie.
Phase 1 host runs locally on Apple silicon: dictation (accurate / fast speech model), clean-up, translation, and a
Voxt-style respond mode with live streamed answers and follow-ups. See `docs/subsystems/asr-pipeline.md` for latency.

```bash
python3 -m venv .venv && .venv/bin/pip install -r host/requirements.txt
host/workers/start_local.sh # local models + host; then open http://127.0.0.1:8765/demo
```

API: `docs/reference.md` · clients: `docs/integrating.md` · demo: `docs/demo.md`.
Docs layout follows yetone/magpie.
9 changes: 8 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,11 @@ ASR + 实时翻译。情感化 TTS 与全双工打断插话在后续阶段加入

## 状态

空骨架。文档目录结构参考 yetone/magpie。
首期 Host 已可在 Apple silicon 本地运行:听写(精确 / 快速两档识别模型)、整理、翻译,以及类似 Voxt 的应答模式(流式输出、可追问)。时延见 `docs/subsystems/asr-pipeline.md`。

```bash
python3 -m venv .venv && .venv/bin/pip install -r host/requirements.txt
host/workers/start_local.sh # 启动本地模型和 Host,然后打开 http://127.0.0.1:8765/demo
```

接口:`docs/reference.md` · 客户端接入:`docs/integrating.md` · 演示:`docs/demo.md`。文档目录结构参考 yetone/magpie。
228 changes: 228 additions & 0 deletions client/demo/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Open Voice host demo</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; max-width: 860px; margin: 32px auto; padding: 0 16px; color: #1d2433; background: #f7f6f2; }
h1 { font-size: 26px; margin: 0 0 4px; } h2 { font-size: 18px; margin: 28px 0 8px; }
section { background: #fffefb; border: 1px solid #d9d6cc; border-radius: 12px; padding: 16px 20px; }
button { font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid #14213d; background: #14213d; color: #f7f6f2; cursor: pointer; }
button.rec { background: #a34e0e; border-color: #a34e0e; }
select, input, textarea { font: inherit; padding: 6px 8px; border: 1px solid #b9b5aa; border-radius: 6px; }
textarea { width: 100%; box-sizing: border-box; }
.out { white-space: pre-wrap; margin-top: 10px; } .raw { color: #5b6475; } .meta { color: #5b6475; font-size: 14px; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.entry { border-top: 1px solid #e3e0d6; padding-top: 8px; margin-top: 8px; }
.turn { margin-top: 10px; white-space: pre-wrap; } .turn.you { color: #5b6475; } .turn.bot { color: #1d2433; }
.turn.note { color: #a34e0e; font-size: 14px; } .turn .meta { display: block; }
</style>
</head>
<body>
<h1>Open Voice host demo</h1>
<p class="meta" id="health">Checking backends…</p>

<h2>Speak → text (dictate or translate)</h2>
<section>
<div class="row">
<label>Mode <select id="mode"><option value="polish">Dictate (clean up)</option><option value="transcribe">Transcribe only</option><option value="translate">Translate</option><option value="respond">Respond (assistant)</option></select></label>
<label>Into <select id="target"></select></label>
<label id="speedBox" hidden>Speech model <select id="speed"><option value="accurate">Accurate (full)</option><option value="fast">Fast (4-bit)</option></select></label>
<button id="rec">Hold to talk</button>
<button id="free">Start hands-free</button>
<span class="meta" id="freeState"></span>
</div>
<textarea id="selected" rows="2" placeholder="Optional for Respond: text to work on (like selecting text in an app), e.g. an email to reply to" hidden></textarea>
<div class="out" id="dictOut" aria-live="polite"></div>
<div id="convo" hidden>
<div id="thread" aria-live="polite"></div>
<div class="row" style="margin-top:12px">
<input id="followText" placeholder="Type a follow-up, or just speak again" size="46" aria-label="Follow-up">
<button id="followSend">Send</button>
<button id="newConvo">New conversation</button>
</div>
</div>
</section>

<h2>Text → translation</h2>
<section>
<textarea id="src" rows="3">我们明天下午三点开会,记得带上 WorkSwarm 的 demo。</textarea>
<div class="row"><label>Into <select id="target2"></select></label><button id="tr">Translate</button></div>
<div class="out" id="trOut" aria-live="polite"></div>
</section>



<script>
const $ = id => document.getElementById(id);
const fail = async r => { const j = await r.json().catch(() => ({})); return (j.error && j.error.message) || r.statusText; };

fetch("/v1/capabilities").then(r => r.json()).then(c => {
$("target").add(new Option("same as me", ""));
for (const sel of [$("target"), $("target2")]) {
for (const code of c.output_languages || []) sel.add(new Option(code, code, false, code === "en"));
}
$("speedBox").hidden = !(c.speeds || []).includes("fast");
});
fetch("/v1/health").then(r => r.json()).then(h => {
$("health").textContent = "Backends: " + Object.entries(h.backends).map(([k, v]) => `${k} ${v.ok ? "ok" : "DOWN"}`).join(" · ");
});

// Hold-to-talk with the browser's own echo cancellation and noise suppression.
let recorder, chunks = [];
async function start() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } });
recorder = new MediaRecorder(stream); chunks = [];
recorder.ondataavailable = e => chunks.push(e.data);
recorder.onstop = () => { stream.getTracks().forEach(t => t.stop()); send(new Blob(chunks, { type: recorder.mimeType })); };
recorder.start(); $("rec").classList.add("rec"); $("rec").textContent = "Listening… release to send";
}
function stop() { if (recorder && recorder.state === "recording") recorder.stop(); $("rec").classList.remove("rec"); $("rec").textContent = "Hold to talk"; }
// Respond mode: a conversation. Answers stream in as the model writes them; every turn is a follow-up
// until "New conversation" (the earlier turns travel with each request as `history`).
let history = [];
function turn(cls, label, text) {
const d = document.createElement("div"); d.className = "turn " + cls;
if (label) d.append(Object.assign(document.createElement("b"), { textContent: label + ": " }));
const span = document.createElement("span"); span.textContent = text || ""; d.append(span);
$("thread").append(d); return span;
}
async function streamTurn(url, init, typed) {
const t0 = performance.now(), selected = $("selected").value.trim();
let first = null, out = null, note = null, you = typed ? turn("you", "You", typed) : null;
const r = await fetch(url, init);
if (!r.ok) { turn("note", "", "Error: " + await fail(r)); return; }
const reader = r.body.getReader(), dec = new TextDecoder(); let buf = "";
for (;;) {
const { value, done } = await reader.read(); if (done) break;
buf += dec.decode(value, { stream: true });
for (let i; (i = buf.indexOf("\n\n")) >= 0; buf = buf.slice(i + 2)) {
const block = buf.slice(0, i), kind = /^event: (.*)$/m.exec(block)[1], data = JSON.parse(/^data: (.*)$/m.exec(block)[1]);
if (kind === "transcript") you = turn("you", "You", data.raw);
else if (kind === "tool") (note = note || turn("note", "", "")).textContent = `Looking up ${data.name.replace("_", " ")}: ${Object.values(data.arguments).join(", ")}…`;
else if (kind === "delta") { if (!out) { first = Math.round(performance.now() - t0); out = turn("bot", "OpenVoice", ""); } out.textContent += data.text; }
else if (kind === "error") turn("note", "", "Error: " + data.message);
else if (kind === "final") {
if (!out) out = turn("bot", "OpenVoice", data.text || "(no answer)");
const total = Math.round(performance.now() - t0), tools = (data.tool_calls || []).map(t => `${t.name} ${t.ms} ms`).join(", ");
out.parentElement.append(Object.assign(document.createElement("span"), { className: "meta",
textContent: `first words after ${first ?? total} ms · done in ${total} ms` + (tools ? ` · ${tools}` : "") }));
const asked = data.raw || typed;
history.push({ role: "user", content: selected && history.length === 0 ? `Request: ${asked}\n\nSelected text:\n${selected}` : asked });
history.push({ role: "assistant", content: data.text || "" });
history = history.slice(-20);
}
}
}
}
function respondOptions() {
const o = { mode: "respond", history };
if ($("target").value) o.output_language = $("target").value;
if (!history.length && $("selected").value.trim()) o.context = { selected_text: $("selected").value.trim() };
return o;
}
$("followSend").onclick = () => {
const text = $("followText").value.trim(); if (!text) return; $("followText").value = "";
const body = { text, ...respondOptions() }; delete body.mode;
streamTurn("/v1/respond?stream=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }, text);
};
$("followText").addEventListener("keydown", e => { if (e.key === "Enter") $("followSend").click(); });
$("newConvo").onclick = () => { history = []; $("thread").innerHTML = ""; };

async function send(blob, box = $("dictOut")) {
if ($("mode").value === "respond") {
const opts = respondOptions(); if (!$("speedBox").hidden) opts.speed = $("speed").value;
const form = new FormData(); form.append("audio", blob, "speech.wav"); form.append("options", JSON.stringify(opts));
if (box !== $("dictOut")) box.remove(); // hands-free placeholder: the thread shows the turn instead
return streamTurn("/v1/dictate?stream=1", { method: "POST", body: form });
}
const mode = $("mode").value, opts = { mode };
if (!$("speedBox").hidden) opts.speed = $("speed").value;
if (mode === "translate") opts.output_language = $("target").value || "en";
if (mode === "respond") {
if ($("target").value) opts.output_language = $("target").value;
if ($("selected").value.trim()) opts.context = { selected_text: $("selected").value.trim() };
}
const form = new FormData(); form.append("audio", blob, "speech.webm"); form.append("options", JSON.stringify(opts));
box.textContent = "Working…";
const t0 = performance.now(), r = await fetch("/v1/dictate", { method: "POST", body: form });
if (!r.ok) { box.textContent = "Error: " + await fail(r); return; }
const j = await r.json(), ms = Math.round(performance.now() - t0);
box.innerHTML = "";
box.append(Object.assign(document.createElement("div"), { textContent: j.text }),
Object.assign(document.createElement("div"), { className: "raw", textContent: "heard: " + j.raw }),
Object.assign(document.createElement("div"), { className: "meta", textContent: `${ms} ms round trip · ${JSON.stringify(j.timings_ms)}`
+ (j.tool_calls && j.tool_calls.length ? " · tools: " + j.tool_calls.map(t => `${t.name}(${Object.values(t.arguments).join(", ")}) ${t.ms} ms`).join(", ") : "")
+ (j.warnings.length ? " · " + j.warnings.join(", ") : "") }));
}
// Hands-free: the mic stays open. Speech start and end are detected from the level, and each utterance is
// sent while listening continues. Results are added in order, newest last.
let free = null, chain = Promise.resolve();
function wavBlob(chunks, rate) {
const n = chunks.reduce((s, c) => s + c.length, 0), out = new DataView(new ArrayBuffer(44 + n * 2));
const str = (o, t) => [...t].forEach((ch, i) => out.setUint8(o + i, ch.charCodeAt(0)));
str(0, "RIFF"); out.setUint32(4, 36 + n * 2, true); str(8, "WAVEfmt "); out.setUint32(16, 16, true);
out.setUint16(20, 1, true); out.setUint16(22, 1, true); out.setUint32(24, rate, true); out.setUint32(28, rate * 2, true);
out.setUint16(32, 2, true); out.setUint16(34, 16, true); str(36, "data"); out.setUint32(40, n * 2, true);
let o = 44; for (const c of chunks) for (const v of c) { out.setInt16(o, Math.max(-1, Math.min(1, v)) * 32767, true); o += 2; }
return new Blob([out], { type: "audio/wav" });
}
async function startFree(stream) {
stream = stream || await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, channelCount: 1 } });
const ctx = new AudioContext(), src = ctx.createMediaStreamSource(stream);
// shortcut: ScriptProcessor is deprecated but still runs in Chrome and Safari; move to an AudioWorklet if it is removed.
const node = ctx.createScriptProcessor(4096, 1, 1), block = 4096 / ctx.sampleRate;
let noise = 0.005, pre = [], speech = [], loud = 0, quiet = 0, active = false;
node.onaudioprocess = e => {
const x = new Float32Array(e.inputBuffer.getChannelData(0));
const rms = Math.sqrt(x.reduce((s, v) => s + v * v, 0) / x.length), threshold = Math.max(0.015, noise * 3);
if (!active) {
if (rms < threshold) noise = 0.95 * noise + 0.05 * rms; // learn the room's background level
pre.push(x); if (pre.length > 3) pre.shift(); // ~0.25 s kept so the first word is not clipped
loud = rms > threshold ? loud + 1 : 0;
if (loud >= 2) { active = true; speech = pre; pre = []; quiet = 0; $("freeState").textContent = "Hearing you…"; }
return;
}
speech.push(x); quiet = rms > threshold ? 0 : quiet + 1;
if (quiet * block < 0.8 && speech.length * block < 30) return; // utterance ends after 0.8 s of quiet (30 s max)
active = false; loud = 0; $("freeState").textContent = "Listening…";
if ((speech.length - quiet) * block < 0.35) return; // a click or cough, not speech
const blob = wavBlob(speech, ctx.sampleRate), box = document.createElement("div");
box.className = "entry"; $("dictOut").append(box);
chain = chain.then(() => send(blob, box)); // one request at a time keeps the order
};
src.connect(node); node.connect(ctx.destination); // a ScriptProcessor only runs while connected
free = { stream, ctx };
$("dictOut").innerHTML = ""; $("free").textContent = "Stop hands-free"; $("free").classList.add("rec");
$("freeState").textContent = "Listening…";
}
function stopFree() {
free.stream.getTracks().forEach(t => t.stop()); free.ctx.close(); free = null;
$("free").textContent = "Start hands-free"; $("free").classList.remove("rec"); $("freeState").textContent = "";
}
$("free").onclick = () => free ? stopFree() : startFree();
$("mode").onchange = () => {
const respond = $("mode").value === "respond";
$("selected").hidden = $("convo").hidden = !respond; $("dictOut").hidden = respond;
$("target").value = respond ? "" : ($("target").value || "en"); // respond: answer in my language unless I pick one
};

for (const [down, up] of [["mousedown", "mouseup"], ["touchstart", "touchend"]]) {
$("rec").addEventListener(down, e => { e.preventDefault(); start(); });
$("rec").addEventListener(up, stop);
}
$("rec").addEventListener("keydown", e => { if (e.key === " " && !e.repeat) { e.preventDefault(); start(); } });
$("rec").addEventListener("keyup", e => { if (e.key === " ") stop(); });

$("tr").onclick = async () => {
$("trOut").textContent = "Working…";
const r = await fetch("/v1/translate", { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: $("src").value, output_language: $("target2").value, dictionary: [{ term: "WorkSwarm" }] }) });
const j = await r.json();
$("trOut").textContent = r.ok ? `${j.text}\n(${j.timings_ms.total} ms, ${j.models.mt})` : "Error: " + j.error.message;
};


</script>
</body>
</html>
33 changes: 33 additions & 0 deletions docs/demo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Demo run sheet (phase 1)

Everything runs on one Mac: no cloud, no GPU server. About 6 minutes.

## Before (10 min ahead)

1. Run `OPENVOICE_TOOLS=1 host/workers/start_local.sh`.
- It starts or confirms both speech models, the LLM and the host, then prints health. Every backend should say `ok`.
- `OPENVOICE_TOOLS=1` allows the weather and Wikipedia lookups for step 5. Leave it out to keep everything on the device.
2. Open **http://127.0.0.1:8765/demo** in Chrome and allow the microphone. Dictate one sentence and press *Translate* once, to warm the models: the first call is slower.
3. Close memory-heavy apps. Phase 1 needs about 11 GB; when memory is tight, the first request after idle can take seconds.

## The story

| # | Show | Say | Backup |
|---|---|---|---|
| 1 | Architecture: client → host (sessions, router) → local model workers | One API for every client; every model is local and swappable by config | – |
| 2 | **Dictation**: *Dictate*, hold to talk: "Um, so tomorrow we review the demo at three, then lunch" | Clean text in about 0.3 s; fillers removed, and clean sentences skip the LLM entirely | *Transcribe only* |
| 3 | **Hands-free**: *Start hands-free*, then just talk; pause between sentences | No button: each sentence is detected and sent while it keeps listening | Hold to talk |
| 4 | **Speed switch**: *Speech model → Fast (4-bit)*, same sentence | About 215 ms instead of about 320 ms; slightly more errors on mixed Chinese-English | Stay on *Accurate* |
| 5 | **Mixed language and translation**: "我们明天 meeting 改到三点半", then mode *Translate* into `en` | Mixed speech is the hard case (8% error vs 24% for Whisper on 320 clips); translation adds about 0.2 s | *Text → translation* box |
| 6 | **Respond**: mode *Respond*: "How's the weather in Toronto? Answer in Chinese." Then paste an email into the selected-text box: "Reply to this, I'll be ten minutes late" | It answers and writes, live, word by word; looks up weather on its own when tools are on | "What is the capital of Japan?" |
| 7 | **Follow-up**: say or type "Now shorter" or "And tomorrow?" | Follow-ups start in about 0.1 s: the conversation is cached on the model server | Type it in the box |

## Limits to mention if asked

- Text appears after you stop speaking; there is no live partial transcript while speaking yet.
- Hands-free uses a simple level-based detector: noise can trigger it, and a long pause splits a sentence.
- Speech output (TTS) and full-duplex are later phases.

## After

Run `pkill -f "vllm serve"; pkill -f "python -m host.sessions"`.
Loading