diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94a2d6a..c92b987 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore index bb69967..d49cf61 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ build/ # local models / audio / secrets *.gguf *.onnx +!host/sessions/models/silero_vad_16k_op15.onnx *.bin *.wav *.mp3 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..0f72142 --- /dev/null +++ b/NOTICE @@ -0,0 +1,26 @@ +OpenVoice +Copyright 2026 ThinkFlowLab +Licensed under the Apache License 2.0 (LICENSE). + +Third-party material in this repository +--------------------------------------- + +Clean-up prompt (host/sessions/prompts/cleanup.txt) + Adapted from VoxtNew, Copyright 2026 ActNow and the SGLang-Omni Team, Apache License 2.0. + Details, pinned source and upstream notices: host/sessions/prompts/NOTICE and host/sessions/prompts/LICENSE-Voxt. + +Silero VAD (host/sessions/models/silero_vad_16k_op15.onnx), bundled + snakers4/silero-vad, commit 446da2ad95fc90d67a3b12e12ea3f5410b9b3ec4, MIT License + (host/sessions/models/LICENSE-silero-vad). Provenance and SHA-256: host/sessions/models/README.md. + +ASCEND transcript excerpts (a few words quoted in host/eval/README.md) + ASCEND, Lovenia et al., LREC 2022 (CAiRE/ASCEND on Hugging Face), CC BY-SA 4.0. + +Optional models, not bundled (downloaded by the user, see host/README.md) +--------------------------------------------------------------------------- + +CAM++ speaker embeddings: 3dspeaker_speech_campplus_sv_zh_en_16k-common_advanced.onnx from the + k2-fsa/sherpa-onnx release "speaker-recongition-models" (3D-Speaker CAM++), Apache License 2.0. +Nemotron-3-Diarization (Q8 GGUF): nvidia/Nemotron-3-Diarization on Hugging Face, revision + 52a432672732425e4c19765b9fec9b5810e6f4ba, OpenMDW License 1.1. +NeMo-Speech.cpp 0.3.1 (C library that runs it): NVIDIA/NeMo-Speech.cpp release v0.3.1, Apache License 2.0. diff --git a/client/demo/index.html b/client/demo/index.html new file mode 100644 index 0000000..e7b5aa1 --- /dev/null +++ b/client/demo/index.html @@ -0,0 +1,315 @@ + + + + +OpenVoice host demo + + + +

OpenVoice host demo

+

Checking backends…

+ +

Speak → text (dictate or translate)

+
+
+ + + + + + + + + +
+ + +
+ +
+ +

Text → translation

+
+ +
+
+
+ + + + + + + + diff --git a/docs/demo.md b/docs/demo.md new file mode 100644 index 0000000..dd20bfb --- /dev/null +++ b/docs/demo.md @@ -0,0 +1,32 @@ +# 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: the host hears each sentence end, shows live text while you speak, and 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 + +- Hands-free uses Silero VAD on the host: typing and room noise do not trigger it, and live text appears while you speak. A pause longer than about half a second ends the sentence. +- Speech output (TTS) and full-duplex are later phases. + +## After + +Run `pkill -f "vllm serve"; pkill -f "python -m host.sessions"`. diff --git a/docs/integrating.md b/docs/integrating.md index 27cc4cc..253fe14 100644 --- a/docs/integrating.md +++ b/docs/integrating.md @@ -1,5 +1,77 @@ # Integrating OpenVoice -状态:待编写(TBD)。 +How a client (desktop input method, phone app, web page) talks to the Personal Host. The full API is in [reference.md](reference.md); `client/demo/index.html` is a working example of everything below. -如何接入 OpenVoice:作为 PC 端语音输入法、SDK 或服务调用;配置与鉴权方式。 +## Start the host + +```bash +python3 -m venv .venv && .venv/bin/pip install -r host/requirements.txt +host/workers/start_local.sh # local models (see subsystems/model-workers.md) + host on 127.0.0.1:8765 +``` + +Open `http://127.0.0.1:8765/demo` to try it. On loopback no token is needed, except for pages served from another origin (they get `403 forbidden_origin`, so no other web page can drive the host). On any other address the host refuses to start without `OPENVOICE_TOKEN`, and clients send `Authorization: Bearer `. + +## The four modes + +One request carries one recording: WAV, 16 kHz, mono, PCM16 is fastest; other formats go through ffmpeg. It goes to `POST /v1/dictate` as multipart with `audio` and an `options` JSON: + +| What the user wants | `options` | `text` in the result | +|---|---|---| +| Dictation | `{"mode": "polish"}` | what they said, without fillers | +| Exact words | `{"mode": "transcribe"}` | what the recognizer heard | +| Spoken translation | `{"mode": "translate", "output_language": "zh"}` | the translation (`raw` keeps the original) | +| Ask or rewrite | `{"mode": "respond", "output_language"?: "zh", "context"?: {"selected_text": "..."}}` | the answer or rewritten text | + +- **Speed:** add `"speed": "fast"` for the 4-bit speech model (about 100 ms faster, slightly more errors on mixed Chinese-English). `GET /v1/capabilities` lists the speeds this host serves. +- **Never lose speech:** if clean-up or translation fails, `text` falls back to `raw` with a warning. If recognition fails, keep the recording and retry with the same `request_id`. + +## Live answers and follow-ups (respond mode) + +- **Stream:** add `?stream=1` and read `text/event-stream`. The events are `transcript` (what was heard), `tool` (a lookup started), `delta` (`{text}`, append it) and `final` (the whole result). Show `delta` text as it arrives. Answers start about 0.55 s after the user stops speaking. +- **Follow-ups:** keep the conversation on the client and send it as `"history": [{"role": "user", "content": ...}, {"role": "assistant", "content": ...}]` (up to 20 turns). The host is stateless, and the model server's cache makes follow-ups start in about 0.1 s. +- **Typed requests:** `POST /v1/respond` with JSON `{text, history?, output_language?, context?}`. It supports `?stream=1` too. + +Minimal browser loop (from the demo page): + +```js +const r = await fetch("/v1/respond?stream=1", { method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ text, history }) }); +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 === "delta") output.textContent += data.text; + if (kind === "final") history.push({ role: "user", content: text }, { role: "assistant", content: data.text }); + } +} +``` + +## Tools: MCP servers + +Give respond mode tools by listing MCP servers in a JSON file (the `mcpServers` format other MCP clients use) and starting the host with `OPENVOICE_MCP=host/mcp.example.json`. The example server (`host/mcp_servers/mac.py`) offers these tools, all on this Mac: +- read-only: the time, your Shortcuts +- actions: run a Shortcut, open a link, add a reminder + +Actions ask before they run. A streaming client gets a `confirm` event with the tool and its arguments. Show it with Yes and No buttons, then answer with `POST /v1/confirm`. In a listening session the user can also just say "yes" or "no". The demo page does both. + +Measured on an M1 Max, with live speech: +- the confirmation appears about 1.2–1.5 s after the user stops speaking +- a spoken "no" is understood about 0.2 s after it ends +- 8 of 8 tool-choice cases picked the right tool, or no tool for ordinary questions (`host/eval`) + +## Hands-free capture + +Open a listening session (`GET /v1/listen`, see reference.md) and stream the microphone as 16 kHz PCM16. The host finds each utterance with a voice-activity model and sends live `partial` text while the user speaks. It processes each utterance in the session's mode; in respond mode it remembers the conversation. The client only captures audio and renders events, so desktop, phone and web behave the same. `client/demo/index.html` shows it in about 60 lines (`AudioContext({sampleRate: 16000})`, then Int16 frames over the WebSocket). + +Measured on an M1 Max, with live speech at real-time pace: +- 1.5 s of key clicks and 1.5 s of loud noise started nothing +- the end of speech was detected about 0.5 s after the speaker stopped +- the final text arrived 0.46 s (5 s sentence) to 0.84 s (8 s sentence) later + +## Who is speaking (optional) + +With `sherpa-onnx` installed and `OPENVOICE_SPEAKER_MODEL` pointing at the CAM++ model, `GET /v1/capabilities` shows `listen.speakers: true`. Send `"speakers": true` in the listen `start` message and each `transcript` and `final` carries `speaker: {id, name?, score}`. Voices are `S1`, `S2`, … within a session. + +To show names, enrol a person once: `POST /v1/speakers` with `name`, `consent=true` and about 15 s of them talking. The demo page has an "Enrol a voice" panel that does this. The voiceprint stays on the host's computer and can be deleted with `DELETE /v1/speakers/{id}`. Use labels for display and notes only, never to allow an action. See reference.md. diff --git a/docs/openapi.yaml b/docs/openapi.yaml new file mode 100644 index 0000000..de3856e --- /dev/null +++ b/docs/openapi.yaml @@ -0,0 +1,330 @@ +openapi: 3.1.0 +info: + title: OpenVoice gateway + version: 0.1.0 + description: > + HTTP part of the OpenVoice gateway contract v0. Prose, principles and the + WebSocket stream (/v1/dictate/stream) are in contract.md. +servers: + - url: http://127.0.0.1:8765 + description: Local gateway on the same Mac +security: + - bearer: [] + - {} +paths: + /v1/health: + get: + summary: Gateway and backend status + responses: + "200": + description: Status + content: + application/json: + schema: { $ref: "#/components/schemas/Health" } + /v1/capabilities: + get: + summary: What this gateway supports + responses: + "200": + description: Capabilities + content: + application/json: + schema: { $ref: "#/components/schemas/Capabilities" } + /v1/translate: + post: + summary: Translate typed or selected text + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [text, output_language] + properties: + text: { type: string, maxLength: 8000 } + output_language: { type: string } + dictionary: { type: array, maxItems: 500, items: { $ref: "#/components/schemas/DictTerm" } } + request_id: { type: string, maxLength: 64 } + responses: + "200": + description: Translation + content: + application/json: + schema: + type: object + properties: + request_id: { type: string } + source: { type: string } + text: { type: string } + output_language: { type: string } + timings_ms: { type: object } + "400": { $ref: "#/components/responses/Error" } + "502": { $ref: "#/components/responses/Error" } + /v1/confirm: + post: + summary: Answer a `confirm` event (an MCP action waiting for the user) + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [id, approve] + properties: + id: { type: string } + approve: { type: boolean } + responses: + "200": { description: Answer delivered; the action runs or is declined } + "404": { description: No action is waiting for that id (answered already or timed out) } + /v1/speakers: + get: + summary: List enrolled voices (names only, never voiceprints) + responses: + "200": + description: Enrolled voices + content: + application/json: + schema: + type: object + required: [model, speakers] + properties: + model: { type: string } + speakers: + type: array + items: { $ref: "#/components/schemas/Speaker" } + "400": { description: "unsupported_option: speaker labels are unavailable" } + "409": { description: "enrolment_failed: the store belongs to another speaker model" } + post: + summary: Enrol a voice from about 15 s of one person talking (needs their consent) + description: > + Keeps only the speech and needs 10 s of it. Stores one voiceprint on this computer + and discards the audio. Enrolling a name again replaces it. + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [name, consent, audio] + properties: + name: { type: string, minLength: 1, maxLength: 64 } + consent: { type: string, enum: ["true"], description: The person being enrolled agrees } + audio: { type: string, format: binary } + responses: + "200": + description: Enrolled + content: + application/json: + schema: { $ref: "#/components/schemas/Speaker" } + "400": { description: "bad_request, too_little_speech or unsupported_option" } + "409": { description: "enrolment_failed: the store belongs to another speaker model" } + /v1/speakers/{id}: + delete: + summary: Delete one enrolled voice + parameters: + - { name: id, in: path, required: true, schema: { type: string } } + responses: + "200": + description: Deleted + content: + application/json: + schema: + type: object + properties: + id: { type: string } + deleted: { type: boolean } + "404": { description: No voice with that id } + "409": { description: "enrolment_failed: the store belongs to another speaker model" } + /v1/respond: + post: + summary: Typed request or follow-up in respond mode (add ?stream=1 for server-sent events) + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [text] + properties: + text: { type: string, maxLength: 8000 } + output_language: { type: string } + history: { type: array, maxItems: 20, items: { $ref: "#/components/schemas/Turn" } } + context: { $ref: "#/components/schemas/AppContext" } + request_id: { type: string, maxLength: 64 } + responses: + "200": + description: Result, or text/event-stream with ?stream=1 + content: + application/json: + schema: { $ref: "#/components/schemas/DictateResult" } + "400": { $ref: "#/components/responses/Error" } + /v1/dictate: + post: + summary: Recognise one recording, then clean up, translate or respond (add ?stream=1 for server-sent events) + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [audio] + properties: + audio: + type: string + format: binary + description: WAV PCM16 16 kHz mono preferred; any ffmpeg-decodable format accepted. + options: + type: string + description: DictateOptions as a JSON string. + contentMediaType: application/json + contentSchema: { $ref: "#/components/schemas/DictateOptions" } + encoding: + options: { contentType: application/json } + responses: + "200": + description: Result (also for empty audio, with empty text) + content: + application/json: + schema: { $ref: "#/components/schemas/DictateResult" } + "400": { $ref: "#/components/responses/Error" } + "401": { $ref: "#/components/responses/Error" } + "413": { $ref: "#/components/responses/Error" } + "415": { $ref: "#/components/responses/Error" } + "429": { $ref: "#/components/responses/Error" } + "500": { $ref: "#/components/responses/Error" } + "502": { $ref: "#/components/responses/Error" } + "503": { $ref: "#/components/responses/Error" } +components: + securitySchemes: + bearer: { type: http, scheme: bearer } + responses: + Error: + description: Error + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + schemas: + DictateOptions: + type: object + additionalProperties: false + properties: + request_id: { type: string, maxLength: 64 } + mode: { type: string, enum: [transcribe, polish, translate, respond], default: polish } + language: { type: string, default: auto, description: "BCP-47 hint or 'auto'" } + output_language: { type: string, description: "Required for translate, optional for respond, rejected otherwise" } + speed: { type: string, enum: [accurate, fast], default: accurate } + history: + type: array + maxItems: 20 + items: { $ref: "#/components/schemas/Turn" } + clean_up: { type: boolean, default: true, description: "translate: drop um, uh, ah, er, hmm, 呃, 嗯 and resolve spoken self-corrections (2 p.m. No, 3 p.m.) before translating" } + style: { type: string, enum: [as_is, casual, neutral, formal], default: neutral } + instructions: { type: string, maxLength: 2000 } + dictionary: + type: array + maxItems: 500 + items: { $ref: "#/components/schemas/DictTerm" } + context: { $ref: "#/components/schemas/AppContext" } + Turn: + type: object + required: [role, content] + additionalProperties: false + properties: + role: { type: string, enum: [user, assistant] } + content: { type: string, maxLength: 8000 } + DictTerm: + type: object + required: [term] + additionalProperties: false + properties: + term: { type: string, maxLength: 100 } + aliases: + type: array + maxItems: 10 + items: { type: string, maxLength: 100 } + AppContext: + type: object + additionalProperties: false + properties: + app_id: { type: string } + app_name: { type: string } + field_kind: { type: string, enum: [chat, email, document, code, search, terminal, other] } + text_before: { type: string, maxLength: 2000 } + selected_text: { type: string, maxLength: 8000 } + url_host: { type: string } + DictateResult: + type: object + required: [request_id, text, raw, mode, warnings, timings_ms, models] + properties: + request_id: { type: string } + text: { type: string } + raw: { type: string } + language: { type: string } + mode: { type: string, enum: [transcribe, polish, translate, respond] } + tool_calls: + type: array + items: { type: object, properties: { name: { type: string }, arguments: { type: object }, ms: { type: integer } } } + warnings: + type: array + items: + type: string + enum: [polish_failed, polish_not_needed, translate_failed, respond_failed, polish_skipped_empty, dictionary_truncated, context_truncated, language_uncertain] + timings_ms: + type: object + properties: + decode: { type: integer } + asr: { type: integer } + polish: { type: integer } + total: { type: integer } + models: + type: object + properties: + asr: { type: string } + llm: { type: string } + Health: + type: object + required: [status, version] + properties: + status: { type: string, enum: [ok, degraded, down] } + version: { type: string } + backends: + type: object + additionalProperties: + type: object + properties: + ok: { type: boolean } + model: { type: string } + Capabilities: + type: object + required: [contract, modes, streaming, max_audio_seconds] + properties: + contract: { type: string } + modes: { type: array, items: { type: string } } + languages: { type: array, items: { type: string } } + streaming: + type: object + properties: + available: { type: boolean } + partials: { type: boolean } + max_audio_seconds: { type: integer } + max_dictionary_terms: { type: integer } + audio_formats: { type: array, items: { type: string } } + Speaker: + type: object + required: [id, name] + properties: + id: { type: string } + name: { type: string } + Error: + type: object + required: [error] + properties: + error: + type: object + required: [code, message, retryable] + properties: + code: + type: string + enum: [bad_request, unsupported_option, unauthorized, forbidden_origin, audio_too_long, bad_audio, rate_limited, asr_failed, backend_unavailable, internal] + message: { type: string } + retryable: { type: boolean } diff --git a/docs/reference.md b/docs/reference.md index 0b6ee62..d436727 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1,5 +1,266 @@ -# Reference +# Reference: the OpenVoice host API (contract 0.6) -状态:待编写(TBD)。 +This is the only interface between OpenVoice clients (desktop input method, phone, web) and the Personal Host. Clients never call model servers directly. The host's voice-session service (`host/sessions`) sits in front of local model workers (`host/workers`), chosen by the provider router (`host/router`). It may run on the same Mac (`http://127.0.0.1:`) or on a GPU server; apps cannot tell the difference. -配置 / CLI / API 参考:Host 配置项、会话接口、任务接口、路由策略。 +Machine-readable form of the HTTP part: [`openapi.yaml`](openapi.yaml). The WebSocket part is specified below only. + +## Principles + +1. **Never lose what the user said.** If polishing fails, the host still returns the raw transcript (`text = raw`, plus a warning). If recognition fails, it returns an error, and the app keeps the audio for retry. +2. **Thin apps.** Prompts, the dictionary merge and model choice live in the host. Apps send audio plus context and insert `text`. +3. **Context is opt-in.** Every context field is optional. Apps send only what the user allowed (for example, no surrounding text unless the user turned it on). +4. **No storage by default.** The host keeps no audio or text after the response. Logs hold ids, sizes, timings and error codes, never content. +5. **Versioned and additive.** All paths start with `/v1`. New fields may appear in v0.x; clients ignore unknown fields. A breaking change means `/v2`. + +## Auth + +`Authorization: Bearer ` is required whenever the host listens on anything other than `127.0.0.1`. On localhost a token is optional. A missing or wrong token gets `401 unauthorized`. + +Without a token, the host serves only this machine's own pages: a request whose `Origin` is not the host's own address, or whose `Host` is not `127.0.0.1`, `localhost` or `[::1]`, gets `403 forbidden_origin` (HTTP and WebSocket). This stops any web page the user opens from driving the host, and DNS rebinding. Native apps send no `Origin` and are not affected. A client served from another origin (a dev server, a webview with its own scheme) sets `OPENVOICE_TOKEN` on the host and sends the token. + +## Audio + +- Preferred: WAV, PCM signed 16-bit little-endian, 16 kHz, mono. +- Also accepted on `POST /v1/dictate`: any format ffmpeg decodes (m4a/AAC, webm/opus, mp3). The host converts it. +- Streaming accepts raw `pcm_s16le` 16 kHz mono only. +- Limits: `max_audio_seconds` from `/v1/capabilities` (default 600). Longer audio gets `413 audio_too_long`. + +## Shared objects + +### `DictateOptions` + +| Field | Type | Default | Meaning | +|---|---|---|---| +| `request_id` | string (≤ 64) | generated | Client-generated id. Repeating a finished id within 10 minutes returns the same result (safe retry). | +| `mode` | `"transcribe"` \| `"polish"` \| `"translate"` \| `"respond"` | `"polish"` | `transcribe` = recognition only. `polish` = recognition, then LLM clean-up (fillers, false starts, self-corrections such as "2 p.m. No, 3 p.m." → "3 p.m.", punctuation, formatting). `translate` (since 0.3) = recognition, then translation of the **raw** transcript into `output_language`; `raw` keeps what was said. Reserved for later: `"rewrite"`, `"command"`. | +| `language` | string | `"auto"` | BCP-47 hint (`en`, `zh`, `zh-Hant`, `yue`, ...) or `auto`. Mixed Chinese-English is normal and needs no flag. | +| `output_language` | string | none | Required for `translate`, rejected for other modes (`400 unsupported_option`). One of `capabilities.output_languages` (`en`, `zh`, `zh-Hant`, `yue`, `ja`, `ko`, `fr`, `de`, `es`, …). | +| `clean_up` | boolean | `true` | For `translate`: drop hesitations (`um`, `uh`, `ah`, `er`, `hmm`, `呃`, `嗯`) before translating, so the translation has none. Words that may mean something (`you know`, `那个`, repeats) stay. A spoken self-correction ("at 2 p.m. No, 3 p.m.", "John. Sorry, I mean Jake", "两点的会。不对,三点") is resolved by the clean-up model first, so only "3 p.m." is translated; that one extra call (~0.2–0.3 s) happens only when such a cue is heard. `false` translates every word; `raw` always keeps them. Ignored by other modes (`polish` always resolves self-corrections). | +| `style` | `"as_is"` \| `"casual"` \| `"neutral"` \| `"formal"` | `"neutral"` | Tone for `polish`. `as_is` keeps the wording and only fixes fillers and punctuation. | +| `instructions` | string (≤ 2000) | none | The user's own rule for this app or for all apps ("use British spelling", "bullets for lists"). Added to the polish prompt. | +| `dictionary` | `DictTerm[]` (≤ 500) | `[]` | Names and jargon. Sent to the speech model as context where it supports that, and always to the LLM. | +| `context` | `AppContext` | none | Where the text will go. | + +`DictTerm`: `{ "term": "WorkSwarm", "aliases": ["work swarm", "works for"] }`. `term` is the spelling to output. `aliases` are known mishearings the LLM may map to it. + +`AppContext`: + +| Field | Type | Meaning | +|---|---|---| +| `app_id` | string | Bundle id or package name (`com.tinyspeck.slackmacgap`, `com.android.chrome`). | +| `app_name` | string | Display name. | +| `field_kind` | `"chat"` \| `"email"` \| `"document"` \| `"code"` \| `"search"` \| `"terminal"` \| `"other"` | The app's best guess of the target field. | +| `text_before` | string (≤ 2000) | Text before the cursor. Opt-in only. | +| `selected_text` | string (≤ 8000) | Current selection. Opt-in only. | +| `url_host` | string | For browsers: host only, never the full URL. | + +### `DictateResult` + +```json +{ + "request_id": "01JF...", + "text": "Can we move the WorkSwarm sync to 3 pm?", + "raw": "um can we move the work swarm sync to three pm", + "language": "en", + "mode": "polish", + "warnings": [], + "timings_ms": { "decode": 4, "asr": 210, "polish": 380, "total": 601 }, + "models": { "asr": "Qwen/Qwen3-ASR-1.7B", "llm": "Qwen/Qwen3-4B-Instruct-2507" } +} +``` + +- `text` is what the app inserts. `raw` is the recognizer's output, kept for history and retry. +- `warnings` values: `polish_failed` (`text` equals `raw`), `polish_not_needed` (the transcript had no fillers, repeats or dictionary aliases, so the clean-up model was skipped and `text` equals `raw`), `translate_failed` (`text` equals `raw`), `respond_failed` (no answer; `text` is empty), `polish_skipped_empty`, `dictionary_truncated`, `context_truncated`, `language_uncertain`. +- `timings_ms` is measured on the host. Apps add their own upload and insert times for end-to-end numbers. +- An empty recording gives `200` with `text: ""` and `raw: ""`, never an error. + +### Errors + +Every non-2xx response has this body: + +```json +{ "error": { "code": "backend_unavailable", "message": "ASR backend did not answer in 10 s", "retryable": true } } +``` + +| HTTP | `code` | `retryable` | When | +|---|---|---|---| +| 400 | `bad_request` | no | Malformed JSON or missing audio. | +| 400 | `unsupported_option` | no | A reserved mode or option this host does not implement. | +| 401 | `unauthorized` | no | Token missing or wrong. | +| 403 | `forbidden_origin` | no | No token, and the request came from another web page (see Auth). | +| 413 | `audio_too_long` | no | Over `max_audio_seconds`. | +| 415 | `bad_audio` | no | Cannot decode. | +| 429 | `rate_limited` | yes | Too many concurrent sessions. `Retry-After` header set. | +| 502 | `asr_failed` | yes | The speech model returned an error. | +| 503 | `backend_unavailable` | yes | The speech model is not reachable or still loading. | +| 502 | `mt_failed` | yes | `/v1/translate`: the translation model gave no usable output. | +| 500 | `internal` | yes | Anything else. | + +The LLM never causes an error response; its failures become `warnings: ["polish_failed"]`. + +## HTTP endpoints + +### `GET /v1/health` + +`200 {"status": "ok" | "degraded" | "down", "version": "0.1.0", "backends": {"asr": {"ok": true, "model": "..."}, "llm": {"ok": false, "model": "..."}}}`. `degraded` means ASR works but LLM does not, so `polish` falls back to raw text. + +### `GET /v1/capabilities` + +```json +{ + "contract": "0.6", + "modes": ["transcribe", "polish", "translate", "respond"], + "listen": {"available": true, "vad": "silero", "vad_models": ["silero", "level"], + "speakers": true, "speaker_model": "nemotron-3-diarization-q8_0"}, + "speeds": ["accurate", "fast"], + "output_languages": ["ar", "bn", "cs", "de", "en", "es", "fa", "fr", "gu", "he", "hi", "id", "it", "ja", "km", "ko", + "mr", "ms", "my", "nl", "pl", "pt", "ru", "ta", "te", "th", "tl", "tr", "uk", "ur", "vi", "yue", + "zh", "zh-Hans", "zh-Hant"], + "tools": {"enabled": false, "mcp": ["create_reminder", "list_shortcuts", "now", "open_url", "run_shortcut"]}, + "languages": ["auto", "en", "zh"], + "streaming": {"available": true, "partials": false}, + "max_audio_seconds": 600, + "max_dictionary_terms": 500, + "audio_formats": ["wav", "pcm_s16le", "m4a", "webm", "mp3"] +} +``` + +This is a host with the fast model, Nemotron speaker labels and the example MCP servers (`host/mcp.example.json`). `speeds` is `["accurate"]` without a fast model; `listen.speakers` is `false` and `speaker_model` `null` without a speaker model; `tools.mcp` is empty without `OPENVOICE_MCP`. + +Apps read this at start and hide what is not available. + +### `POST /v1/dictate` + +`multipart/form-data` with two parts: +- `audio`: the recording (file). +- `options`: `DictateOptions` as a JSON string (optional; defaults apply). + +Response: `200 DictateResult`, or an error as above. This is the whole MVP: record until the hotkey is released, send, insert `text`. + +### Respond mode, streaming and follow-ups (since 0.4) + +- **`mode: "respond"`** on `/v1/dictate`: the spoken request is answered or carried out, or the selected text is rewritten. + - With tools enabled (`OPENVOICE_TOOLS=1` on the host, off by default because the query leaves the device), the model may call `get_weather` (wttr.in) and `web_search` (Wikipedia API; set `OPENVOICE_CONTACT` to a project URL or email, as Wikimedia's robot policy asks). `GET /v1/capabilities` reports `tools.enabled`. + - With MCP servers configured (`OPENVOICE_MCP`, see below), their tools are offered too. + - Options: `output_language` (optional reply language) and `context.selected_text` (text the request is about). + - The result adds `tool_calls: [{name, arguments, ms, approved?}]`; `approved` is present for actions that needed confirmation. If no answer is produced, `text` is empty and the warning is `respond_failed`. +- **`history`:** a list of `{role: "user"|"assistant", content}`, up to 20 turns. It carries the earlier conversation, so a request can be a follow-up ("now in Chinese", "shorter"). +- **`POST /v1/respond`:** a typed request or follow-up. JSON body `{text, history?, output_language?, context?, request_id?}`. Same result shape as `/v1/dictate`. +- **Streaming:** add `?stream=1` to `/v1/dictate` or `/v1/respond`. The response is `text/event-stream` with these events, in order: + - `transcript` `{raw, language}`: speech only, right after recognition + - `confirm` `{id, name, label, arguments, timeout_s}`: an action waits for the user (see below) + - `tool` `{name, arguments}`: when a lookup or action starts + - `delta` `{text}`: pieces of the answer as they are written + - `final` ``: the same object as the non-streaming response + - In respond mode, `final.text` is what to insert and can differ slightly from the joined `delta`s: an intro line such as "Sure, here's a reply:" and Markdown line-break spaces are removed. Show the `delta`s as a live preview, then replace them with `final.text`. + + On failure the last event is `error` `{code, message, retryable}`. Every mode streams; only respond produces `delta` events. + +### MCP tools and confirmations (since 0.6) + +- **Servers:** `OPENVOICE_MCP` names a JSON file in the common `mcpServers` format: stdio `{"command", "args", "env"?, "cwd"?}` or streamable HTTP `{"url", "headers"?}`. See `host/mcp.example.json` and the example server `host/mcp_servers/mac.py`. A server that fails to start is skipped with a warning. + - Tools keep their own names; when two servers share a name, the later one is called `server__tool`. + - `GET /v1/capabilities` lists them in `tools.mcp`. +- **Which tools ask first:** a tool runs straight away if it declares `readOnlyHint`. Any other tool sends a `confirm` event and waits. + - Per server, `"confirm": "always"` or `"never"` overrides this. +- **Answering:** + - `POST /v1/confirm` with `{"id", "approve": true|false}`. + - In a listening session, `{"type": "confirm", "id", "approve"}`, or simply say yes or no. + - No answer within `timeout_s` (60 s) counts as no. A declined action does not run, and the model says so. +- **Without a stream** (plain `POST /v1/respond` or `/v1/dictate`), nobody can be asked, so actions are declined. Read-only tools still run. + +### `POST /v1/translate` (since 0.3) + +Translate typed, pasted or selected text. JSON body `{"text": "...", "output_language": "en", "dictionary": [DictTerm], "request_id": "..."}` (text ≤ 8000 characters). Returns `{"request_id", "source", "text", "output_language", "warnings", "timings_ms", "models"}`. Dictionary terms are kept as spelled. If the model gives no usable translation, the response is `502 mt_failed` (retryable): there is no recording to keep here. + +## WebSocket: `GET /v1/listen` (hands-free session, since 0.5) + +The client streams the microphone; the host finds utterances, shows live text, and processes each one. + +**Client → host:** +1. `{"type": "start", "options": DictateOptions, "audio": {"encoding": "pcm_s16le", "sample_rate": 16000, "channels": 1}, "vad"?: {"model": "silero", "end_silence_ms": 512, "partials": true}, "speakers"?: true}`. `end_silence_ms` must be 200–2000; raise it (800–1200) if pauses such as "uh … " split a sentence. `model` is `silero` (default) or `level`, the old loudness detector, kept for comparison; `capabilities.listen.vad_models` lists them. `speakers` turns on speaker labels (below); it is off by default. +2. Binary PCM frames of any length, continuously, silence included. +3. `{"type": "reset"}` forgets the conversation (respond mode). + - `{"type": "confirm", "id": "...", "approve": true}` answers a `confirm` event. Speaking works too: while an action waits, the next utterance is transcribed and checked for a yes or no (yes, okay, 好的, no, cancel, 算了…). The host sends it as `transcript` `{raw, answer: "yes"|"no"}`. Anything else declines the action and is handled as a new request. +4. `{"type": "stop"}` ends the session after the last utterance is processed. + +**Host → client:** every event has `utterance` (1, 2, …). +- `ready` +- `speech_start` +- `partial` `{text}`: live transcript while speaking, from the fast speech model when one is configured +- `speech_end`, or `speech_dropped` (under ~0.2 s of speech: clicks, coughs) +- then the usual `transcript`, `tool`, `delta`, `final` `{result}` or `error` +- `done` after `stop` + +**How utterances are found:** voice activity comes from Silero VAD (MIT, bundled, CPU) on 32 ms chunks: +- speech starts after ~96 ms of speech; ~256 ms of audio from before the start is kept +- it ends after `end_silence_ms` of quiet, or 30 s +- noise, music and key clicks do not start an utterance +- with `"model": "level"` a chunk counts as speech when it is 3× louder than the learned room level, so steady noise (hiss, a beep) does start one: in a test, 2 s of hiss became an empty utterance with `level` and nothing with `silero` + +In respond mode the session keeps the conversation (20 turns), so each utterance is a follow-up. `history` in `start` seeds it. + +**Speaker labels** (opt-in, when `GET /v1/capabilities` shows `listen.speakers: true`): `transcript` and `final` get `"speaker": {"id": "S1", "name"?: "Ali", "score": 0.83, "also"?: ["S2"]}`. `listen.speaker_model` names the labeller in use. +- `id` is the session's label for the voice (`S1`, `S2`, …). +- **Nemotron-3-Diarization** (preferred when set up): every 32 ms of the session's audio goes into one streaming diarizer, and a sentence takes the speaker who talked most during it. `score` is that speaker's share of the talk; `also` lists anyone else who spoke over them (≥ 0.3 s and 15% of the sentence). Up to 8 speakers per session, no enrolled names. Needs `OPENVOICE_DIAR_LIB` (the `libnemo_speech_asr_c` library from NeMo-Speech.cpp) and `OPENVOICE_DIAR_MODEL` (the Q8 GGUF, SHA-256 checked); neither is bundled, see "Speaker labels (optional download)" in `host/README.md`. On an M1 Max: no added wait (median speech end → transcript 480 ms vs 525 ms without labels), 48/48 labels right on a two-voice test, about 20% of one CPU core while listening. +- **CAM++** (fallback): one voiceprint per sentence. `name` is added when the voice matches an enrolled one; `score` is the cosine similarity to the matched voice (threshold 0.35), not a probability. Needs the optional `sherpa-onnx` package and the CAM++ model at `OPENVOICE_SPEAKER_MODEL` (SHA-256 checked); neither is bundled, see `host/README.md`. This path is not run in CI (no `sherpa-onnx` there); the tests use a fake embedder. +- With neither, `speakers: true` gets `400 unsupported_option`. +- The field is left out when labelling is late (45 ms for CAM++, 1.5 s for Nemotron) or fails; the utterance carries on without it. +- In respond mode the model is told who spoke: each request it sees starts with `[Speaker S1]` (or the name), so it keeps track of who said what. `raw` and `text` stay untagged. +- Labels are a hint for display, notes and the conversation. They never authorise an action. + +### Voice enrolment: `/v1/speakers` (needs speaker labels) + +Enrolment lets CAM++ labels show a person's name (Nemotron labels don't use it). All three routes need auth and return `400 unsupported_option` when CAM++ is not set up. + +- `POST /v1/speakers`, multipart: `name` (1–64 characters, no control characters; spaces around it are trimmed), `consent` = `true`, and `audio` (any format `/v1/dictate` takes, up to 60 s). + - `consent: true` states that the person being enrolled agrees. Without it the request is `400 bad_request`. + - The host keeps only the speech (Silero VAD) and needs 10 s of it, from one person; otherwise `400 too_little_speech`. Recording about 15 s is enough. + - It stores one voiceprint, the mean of four 2.5 s embeddings, then discards the audio. Enrolling a name again replaces it. + - Returns `{"id": "Ali", "name": "Ali"}`. Today the id is the name. +- `GET /v1/speakers` returns `{"model": "...", "speakers": [{"id", "name"}]}`. Voiceprints are never returned. +- `DELETE /v1/speakers/{id}` returns `{"id", "deleted": true}`, or `404 not_found`. +- A store written for another speaker model is refused with `409 enrolment_failed`; delete the file and enrol again. + +**Privacy.** A voiceprint is biometric data. +- It stays on the host's computer, in `OPENVOICE_SPEAKERS` (default `~/.openvoice/speakers.json`). The folder is 0700 and the file 0600; it is never sent anywhere. +- Deleting an enrolment, or the file, removes it for new sessions. A running session keeps its copy until it ends. +- Enrol only people who agree, and treat labels as advisory: two people can sound alike (in T20 tests, 3 of 208 other speakers' turns got the enrolled name). + +## WebSocket: `GET /v1/dictate/stream` + +For live text while speaking, and to start recognition before the user stops. Auth uses the same bearer header, or `?token=` for clients that cannot set headers (browsers). + +Client → server: + +1. Text frame `{"type": "start", "options": DictateOptions, "audio": {"encoding": "pcm_s16le", "sample_rate": 16000, "channels": 1}}`. +2. Binary frames: raw PCM, 20–200 ms each, in order. +3. Text frame `{"type": "stop"}` when the user stops, or `{"type": "cancel"}` to drop everything. + +Server → client: + +- `{"type": "ready", "request_id": "..."}` after `start`. +- `{"type": "partial", "text": "can we move the", "stable_chars": 12}`: the live transcript (raw, not polished). The first `stable_chars` characters will not change. Only sent when `capabilities.streaming.partials` is true. +- `{"type": "final", "result": DictateResult}` after `stop`, then the server closes with code 1000. +- `{"type": "error", "error": {...}}`, then close with code 1011 (server) or 1008 (auth or policy). +- `{"type": "cancelled"}` after `cancel`, then close with code 1000. + +Rules: +- If no audio arrives for 30 s, the server sends `error` with `bad_request` and closes. +- If the connection drops before `final`, the result is lost. The app must keep its own copy of the audio and retry with `POST /v1/dictate` using the same `request_id`. +- A host whose backend cannot stream still accepts this endpoint. It buffers audio and sends only `final`. + +## How the host uses vLLM-Omni (informative, may change) + +- **Speech:** vLLM serving Qwen3-ASR (`vllm serve Qwen/Qwen3-ASR-1.7B`). It is called through `/v1/audio/transcriptions` or `/v1/chat/completions` with `input_audio`; T1 and T2 decide which one is faster and more reliable. Dictionary terms go into the ASR context prompt (Qwen3-ASR accepts context text). +- **Polish:** any OpenAI-compatible `/v1/chat/completions`: a local vllm-metal server, vLLM on a GPU, or a hosted API. +- **Streaming partials:** either repeated recognition of the growing buffer, or the backend's realtime endpoint where it exists. This is an internal choice behind the same WebSocket. +- **Local Mac:** the same host runs against vllm-metal on `127.0.0.1`. + +## Out of scope for phase 1 (reserved) + +- Speech output (TTS) and full-duplex conversation: later phases (`docs/subsystems/tts-director.md`, `full-duplex.md`). + +- Actions and task execution (`mode: "command"`). Later these will go through MCP tools on the device; the host returns a proposed tool call, and the app confirms and runs it. +- Translate and rewrite modes. +- User accounts, sync and history on the server. diff --git a/docs/results/T20.md b/docs/results/T20.md new file mode 100644 index 0000000..e4ed6e6 --- /dev/null +++ b/docs/results/T20.md @@ -0,0 +1,164 @@ +# T20 · Who is speaking? +Use bilingual CAM++ for opt-in live speaker labels on the M1 Max. It labeled 76/80 held-out utterances correctly anonymously and named 78/80 after ten seconds of enrolment per person. +It took 19 ms median / 20 ms p90 with a 228 MiB peak process RSS. For recordings, choose Nemotron-3-Diarization Q8. Its pooled DER was 11.08% on the three test excerpts. + +## What the Mac measured + +Two fresh local processes used the same CPU runtime, four ONNX threads, and the central 2.5 s of each finished utterance at most. Names were scored against the original speaker IDs. Anonymous labels used optimal one-to-one cluster mapping within each session. Enrolment used four consecutive 2.5 s vectors averaged per speaker. A grid of cosine thresholds from 0.20 to 0.80 in 0.05 increments maximized the sum of anonymous mapped hits and enrolled exact-name hits on development only, choosing the lower threshold on ties. Anonymous centroids update on assignment. Enrolled references stay fixed. + +| Model | Matched / 80 anonymous | Exact names / 80 | Threshold | Warm label p50 / p90 | Cold load + first embedding | Peak process RSS | +|---|---:|---:|---:|---:|---:|---:| +| CAM++ advanced | 76 (95.0%) | 78 (97.5%) | 0.35 | 19.0 / 19.5 ms | 235 ms | 228 MiB | +| ERes2NetV2 | 77 (96.2%) | 77 (96.2%) | 0.50 | 101.2 / 105.0 ms | 186 ms | 362 MiB | + +The 168 warm timings include development and held-out utterances. They cover PCM preprocessing, extraction and centroid assignment. Cold timing begins at extractor creation in a fresh Python process with NumPy/SciPy already imported. RSS is the process high-water mark, including the evaluation harness, runtime, and recording VAD. Timings reflect the Mac's workload at measurement. ERes2NetV2 had the highest anonymous accuracy by one utterance but exceeded the live latency budget. [Raw CAM++ results](../../spikes/t20_speakers/results/cam.json) · [Raw ERes2NetV2 results](../../spikes/t20_speakers/results/eres.json) + +| Held-out session | Turns | CAM++ anonymous / named correct | ERes2NetV2 anonymous / named correct | +|---|---:|---:|---:| +| English · AMI | 32 | 32 / 32 | 31 / 31 | +| Mandarin · AliMeeting | 32 | 30 / 32 | 32 / 32 | +| Mixed · ASCEND | 16 | 14 / 14 | 14 / 14 | + +| Across three held-out sessions | True speakers split across labels | Output labels merging multiple people | +|---|---:|---:| +| CAM++ anonymous | 2/10 | 1/11 | +| CAM++ enrolled | 1/10 | 0/11 | +| ERes2NetV2 anonymous | 2/10 | 0/12 | +| ERes2NetV2 enrolled | 2/10 | 0/12 | + +**Host timing.** An in-process WebSocket replay used the real Silero VAD, real CAM++ and an immediate mocked ASR response. Twenty-four held-out clips ran in paired sessions with labels off/on in alternating order. All 24 labeled runs returned a speaker. Added time between the host sending `speech_end` and sending the first `final` was **18.9 ms median, 20.0 ms p90, 21.2 ms maximum**. This isolates the addition to the host path. Physical capture, network latency and contention with live ASR requests were outside this replay. [Measured values](../../spikes/t20_speakers/results/host.json) + +**Ignoring other speakers.** With just one person enrolled at a time, CAM++ recognized 78/80 target turns and incorrectly named 3/208 non-target turns. The same held-out people and audio were reused across these comparisons. For notes, a client can display the name. For access control or automatic exclusion, these errors can attribute someone else's speech or drop the enrolled person's speech. + +## Recording accuracy + +Both embedding baselines took raw continuous audio through the host's Silero VAD and endpointer, then assigned one speaker per turn. A ±0.25 s collar around every reference boundary was excluded. Overlap elsewhere counts in the reference speaker-seconds. Miss, false alarm and confusion percentages share that denominator. The synthetic mixed turns have 400 ms gaps, shorter than the host’s 512 ms endpoint silence. Several speakers can therefore land in a single host turn. + +| Recording | Model | Miss % | False alarm % | Confusion % | DER % | +|---|---|---:|---:|---:|---:| +| AMI | CAM++ | 17.7 | 0.0 | 0.9 | 18.6 | +| AliMeeting | CAM++ | 8.8 | 3.6 | 10.2 | 22.6 | +| ASCEND | CAM++ | 1.5 | 0.0 | 40.3 | 41.8 | +| AMI | ERes2NetV2 | 17.7 | 0.0 | 1.1 | 18.8 | +| AliMeeting | ERes2NetV2 | 8.8 | 3.6 | 10.5 | 22.9 | +| ASCEND | ERes2NetV2 | 1.5 | 0.0 | 40.3 | 41.8 | + +### Dedicated recording model on the M1 Max + +NVIDIA Nemotron-3-Diarization Q8_0, official native arm64 CPU runtime 0.3.1, default postprocessing, `v3-offline` buffered preset. No enrolment or known speaker count. Each held-out input ran in a fresh CLI process. Wall time includes process startup, model initialization, WAV I/O, inference and RTTM output. Peak is that process's macOS maximum resident memory, decimal MB. The first two files are real meetings, the last is a constructed sequence of code-switch clips with pauses. DER uses the same `error_times` function as the live backends, including overlapped speech, per-recording optimal speaker assignment and a 0.25 s forgiveness region **on each side** of each reference boundary. + +| Test recording | Audio s | Scored reference speaker-s | Miss % | FA % | Confusion % | DER % | Wall s | Peak MB | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| AMI TS3003b | 120.00 | 86.21 | 13.40 | 0.48 | 0.08 | 13.97 | 1.354 | 199.84 | +| AliMeeting R8002_M8003_MS803 | 120.00 | 75.27 | 5.24 | 0.39 | 2.07 | 7.70 | 1.343 | 194.63 | +| ASCEND test | 62.87 | 48.47 | 0.81 | 0.00 | 10.38 | 11.18 | 0.662 | 175.21 | +| Pooled speaker-time | 302.87 | 209.95 | 7.57 | 0.34 | 3.17 | 11.08 | 3.359 total | 199.84 max | + +In a separate fresh process the native model constructor returned in 4.0 ms. Whole-process time for load-and-destroy was 0.14 s with a 15.56 MB peak. This measures creation of the native handle, with the OS file cache uncontrolled. First-inference costs are included in the meeting wall times. No local eight-speaker run or long-meeting accuracy measurement. [Model card](https://huggingface.co/nvidia/Nemotron-3-Diarization) · [Pinned CPU release](https://github.com/NVIDIA/NeMo-Speech.cpp/releases/tag/v0.3.1) · [CLI preset definition](https://github.com/NVIDIA/NeMo-Speech.cpp/blob/v0.3.1/docs/cli.md#diarize-audio) + +From the repo root after preparing the recording manifest, use a temporary directory and one downloaded model at a time: + +```sh +nemo_tmp=$(mktemp -d) +cpu_pkg=nemo-speech-0.3.1-macos-aarch64-cpu +curl -fLsS --retry 2 -o "$nemo_tmp/cli.tar.gz" "https://github.com/NVIDIA/NeMo-Speech.cpp/releases/download/v0.3.1/$cpu_pkg.tar.gz" +(cd "$nemo_tmp" && echo 'd829fedaf29a397c7ce2ff86761c465323efdeab1c61851e2b249cf8e8f85122 cli.tar.gz' | shasum -a 256 -c - && tar -xzf cli.tar.gz) +curl -fLsS --retry 2 -o "$nemo_tmp/model.gguf" https://huggingface.co/nvidia/Nemotron-3-Diarization/resolve/52a432672732425e4c19765b9fec9b5810e6f4ba/Nemotron-3-Diarization.q8_0.gguf +(cd "$nemo_tmp" && echo '08456d9e22cd9a323c0364d98375f3746d6e68507ebb705cd46438c534c7a3a1 model.gguf' | shasum -a 256 -c -) +python -m spikes.t20_speakers.recording_model /tmp/t20-data/recordings.jsonl "$nemo_tmp/$cpu_pkg/bin/nemo-speech" "$nemo_tmp/model.gguf" +rm "$nemo_tmp/model.gguf" +``` + +## Host and API proposal for Claude + +The prototype adds `listen.speakers` to capabilities and accepts a boolean `speakers` on the initial `/v1/listen` message. It defaults off. Setting it on without the optional runtime and checkpoint returns `unsupported_option`. Anonymous centroids live only for the lifetime of that session. A new session starts fresh. The hands-free demo shows the opt-in checkbox when available and prefixes each completed utterance with its name or session ID. + +On success the host adds the same top-level field to `transcript` and `final`, for example `"speaker":{"id":"S1","name":"Ali","score":0.83}`. Anonymous labels omit `name`. The score is cosine similarity to the chosen previous reference, with zero for the first observation of a new anonymous speaker. It is not a probability of identity. Extraction overlaps recognition. The transcript waits up to 45 ms for outstanding work. If work overruns, fails, or the worker is busy, both events omit the optional field and the utterance proceeds. The opt-in session loads the model before announcing ready. Labeling supports attribution for clients. It does not authorize actions, filter out bystanders, or inject names into the LLM prompt. + +**Update (3 Dec): implemented.** Ali approved the HTTP enrolment API below. It is in the host as `POST`/`GET`/`DELETE /v1/speakers`, with the demo page panel; see `docs/reference.md`. Two differences from this proposal: the id is the enrolled name, and the store keeps the T20 method (mean of four 2.5 s embeddings over 10 s of speech). + +**Proposed enrolment API, pending Ali and Claude.** Enrolment requires affirmative opt-in from the person being enrolled. The proposed authenticated `POST /v1/speakers` accepts a name and approximately ten seconds of solo speech, validates the audio, stores a model-bound normalized reference locally, discards the submitted audio, and returns an opaque enrolment ID. `GET /v1/speakers` lists IDs and names without returning templates. `DELETE /v1/speakers/{id}` removes one enrolment. Deleting the local file removes all templates for subsequent sessions. Existing sessions must end to release any in-memory copy. The prototype supplies an explicit local enrolment command. No HTTP enrolment route is registered. No host contract version change is included. + +## Speaker evaluation data + +The script uses a fixed, session- and identity-disjoint local development/holdout partition. These labels refer to this spike. AMI and AliMeeting sessions both come from their respective official test sets. ASCEND uses its upstream validation and test sets. Each person contributes a separate 10.2 s enrollment and eight held-out utterances. Development has 11 speakers / 88 utterances, and test has 10 speakers / 80 utterances. The total is 168 scored utterances. Enrollment and trials use different source intervals/clips. Enrollment is same-session for the real meetings, so cross-session recognition remains unmeasured. + +| Split | Session | Live speakers | DER excerpt | Wall-clock overlap | +|---|---|---:|---|---:| +| Development | AMI ES2004a | 4 | 0–120 s, 3 active in excerpt | 3.69 s | +| Development | AliMeeting R8002_M8002_MS802 | 4 | 0–120 s, 4 active | 24.59 s | +| Development | ASCEND | 3 | 115.43 s constructed, with 400 ms pauses | 0 s | +| Holdout | AMI TS3003b | 4 | 480–600 s, 4 active | 4.64 s | +| Holdout | AliMeeting R8002_M8003_MS803 | 4 | 60–180 s, 4 active | 6.02 s | +| Holdout | ASCEND | 2 | 62.87 s constructed, with 400 ms pauses | 0 s | + +AMI uses the corpus mix-headset signal, with the BUTSpeechFIT “only_words” RTTM. AliMeeting uses channel zero of the actual far-field microphone array and speaker/timestamps from the Argmax representation. For both, the recording window is the first 120 s window on a 60 s grid containing at least one second of uninterrupted reference overlap. Original silence and all overlapping labels are preserved. Intervals are clipped and offset to the start of the excerpt. The AMI reference counts speech words and omits nonlexical vocalizations. The live meeting trials use annotated single-speaker stretches outside the recording excerpt. They cover the meeting timeline and are capped at 6 s. Thus these are oracle-segmented single-speaker utterances, not an end-to-end VAD benchmark. + +ASCEND requires the official mixed-language flag, Latin letters and Han characters in the transcript, and an original clip duration of 1.2–8 s. The speaker key is original_speaker_id, verified against the original filename. The development set uses IDs 7, 12 and 20. The holdout uses IDs 3 and 17. The composite uses ordered round-robin turns, no simultaneous speech, and references mark clip boundaries and the added silence rather than hand-timed within-clip activity. It should be reported separately from natural-meeting DER. All original source keys/intervals are retained locally in manifest.jsonl; no speaker recordings need to enter the repository. + +AMI Consortium releases AMI under [CC BY 4.0](https://groups.inf.ed.ac.uk/ami/corpus/license.shtml). Sources are the [mix-headset mirror](https://huggingface.co/datasets/FluidInference/ami-corpus-mirror) and [BUTSpeechFIT reference annotations](https://github.com/BUTSpeechFIT/AMI-diarization-setup). Yu et al. release [AliMeeting on OpenSLR](https://openslr.org/119/) under CC BY-SA 4.0. The [Argmax mirror](https://huggingface.co/datasets/argmaxinc/ali-meetings) declares the same license. Lovenia et al. release [ASCEND](https://huggingface.co/datasets/CAiRE/ASCEND) under CC BY-SA 4.0. The script pins revisions, selects and trims local derivatives and does not redistribute audio. + +Reproduce with ffmpeg and curl on PATH: `uv run --python 3.12 --with pyarrow==26.0.1 python spikes/t20_speakers/prepare_data.py --output /tmp/t20-data`. Downloads total about 1.3 GB. Add `--cache /tmp/t20-data/source` to retain source downloads between runs. Local result paths are absolute. Verification checked every live WAV for mono PCM16 at 16 kHz, every enrollment WAV for exactly 10.2 s, and reference overlap on all four natural excerpts. This small, balanced subset is suitable for a local comparison, not a full-corpus estimate. No personal recordings were used. + +## Shortlist + +MB and GB below are decimal file sizes unless noted. Model files occupy additional memory at inference. EER measures verification on pairs of clips. DER measures missed, spurious and incorrectly attributed speaker time in a recording. A single embedding has no standalone DER on AMI, AliMeeting, AISHELL-4 or VoxConverse. None of the cited model cards measures accuracy on within-utterance Mandarin–English code-switches. + +| Candidate and use | Files and runtime | Weight license and download | Online labels and enrolment | Published results | +|---|---|---|---|---| +| CAM++ Chinese/English advanced, live | 28.28 MB ONNX, CPU | “Apache License 2.0”, public | Embed each completed utterance. Match to local named enrolment vectors or anonymous centroids. | CN-Celeb Test EER 5.98%, VoxCeleb-O 1.16%. Chinese and English training. [Original card](https://modelscope.cn/models/iic/speech_campplus_sv_zh_en_16k-common_advanced) · [ONNX releases](https://github.com/k2-fsa/sherpa-onnx/releases/tag/speaker-recongition-models) | +| ERes2NetV2 Chinese common, live | 71.44 MB ONNX, CPU | “Apache License 2.0”, public | Same utterance and enrolment interface. | CN-Celeb Test EER 3.81%. This Chinese-trained checkpoint has no verified VoxCeleb result. [Original card](https://modelscope.cn/models/iic/speech_eres2netv2_sv_zh-cn_16k-common) · [ONNX releases](https://github.com/k2-fsa/sherpa-onnx/releases/tag/speaker-recongition-models) | +| WeSpeaker VoxCeleb ResNet34-LM, alternate live baseline | 26.53 MB publisher ONNX, CPU | “cc-by-4.0”, public. Credit WeSpeaker and identify changes if redistributed. | Utterance embedding and enrolment matching as above. English-tagged VoxCeleb2 training. | VoxCeleb1 O/E/H **cleaned** EER 0.797/0.937/1.695% with LM and no AS-Norm. With AS-Norm, 0.723/0.867/1.532%; this requires cohort normalization. CN-Celeb unverified for these weights. [Card](https://huggingface.co/Wespeaker/wespeaker-voxceleb-resnet34-LM) · [Files](https://huggingface.co/Wespeaker/wespeaker-voxceleb-resnet34-LM/tree/main) | +| sherpa-onnx, offline meeting baseline | CPU ONNX segmentation + embedding + clustering. pyannote segmentation FP32 5.7 MiB or INT8 1.5 MiB (upstream rounded sizes), plus the selected embedding. | Original segmentation “mit”, gated on HF. Sherpa distributes an attributed conversion publicly. CAM++ embedding uses its own Apache-2.0 terms. | Whole-file anonymous turns, including overlap. A separate embedding match would supply names. | No verified DER on the four requested sets for this exact pairing. Do not transfer pyannote full-pipeline DER to this configuration. [Segmentation card](https://huggingface.co/pyannote/segmentation-3.0) · [Conversion and inference](https://k2-fsa.github.io/sherpa/onnx/speaker-diarization/models.html) | +| pyannote Community-1, offline meeting reference | PyTorch CPU by default. About 32.8 MB for segmentation, embedding and PLDA files together, plus runtime. | “cc-by-4.0”, gated. Requires accepting terms, then runs offline from local files. | Anonymous meeting turns, overlap and configurable speaker-count bounds. Use regular diarization when scoring overlap. Names require a separate match. | See table below. [Card and results](https://huggingface.co/pyannote/speaker-diarization-community-1) · [Files](https://huggingface.co/api/models/pyannote/speaker-diarization-community-1?blobs=true) | +| NVIDIA Nemotron-3-Diarization, newer recording candidate | 100M parameters, 198.68 MB NeMo checkpoint. Publisher also lists a 107.01 MB Q8 GGUF. | “openmdw-1.1”, public. Retain required notices when redistributing. | Anonymous activity for up to eight concurrent speaker slots, no named enrolment in the card. Streaming input buffer 80 ms minimum, 320 ms lowest recommended, before compute. Fit to the host's end-of-utterance budget depends on scheduling and needs measurement. | See table below. Its training includes VoxConverse dev and test. [Card, configuration and results](https://huggingface.co/nvidia/Nemotron-3-Diarization) · [Files](https://huggingface.co/nvidia/Nemotron-3-Diarization/tree/main) | + +Sherpa states “Please check the license of your selected model.” Its Apache-2.0 runtime does not relicense weights. For CAM++ and ERes2NetV2, the original publisher explicitly identifies the weight license above. Their published EERs describe those original checkpoints. Neither conversion has independent EER validation here. Keep model copyright, license and change notices with redistributed assets. [Sherpa license note](https://k2-fsa.github.io/sherpa/onnx/speaker-identification/apk.html) · [Apache-2.0 redistribution terms](https://www.apache.org/licenses/LICENSE-2.0) + +### Published full-pipeline DER (%) + +| Evaluation, overlap scored | AMI | AliMeeting | AISHELL-4 | VoxConverse | +|---|---:|---:|---:|---:| +| pyannote 3.1, zero collar | IHM 18.8 / SDM 22.7 | Channel 1 24.5 | 12.2 | v0.3 11.2 | +| Community-1, same card and scoring | IHM 17.0 / SDM 19.9 | Channel 1 20.3 | 11.7 | v0.3 11.2 | +| Sortformer v2.1 re-scored in Nemotron card, 1.04 s buffer, forced-aligned labels, zero collar | MHM 16.36 / SDM 21.73 | Near 12.47 / far 15.58 | Unverified | Unverified | +| Nemotron-3, same card, labels and 1.04 s buffer | MHM 9.48 / SDM 12.80 | Near 6.59 / far 10.80 | Unverified | Unverified | + +Compare rows within each pair. NVIDIA uses forced-aligned reference boundaries. A local evaluation with a 0.25 s collar uses yet another protocol. The authors’ independently published Sortformer v2.1 launch scores also differ from their later re-scoring, so the table uses the paired results on the later card. [pyannote benchmark](https://huggingface.co/pyannote/speaker-diarization-community-1#benchmark) · [NVIDIA benchmark and scoring notes](https://huggingface.co/nvidia/Nemotron-3-Diarization) · [Sortformer launch card](https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2.1) + +## Other runtimes and alternatives considered + +| Candidate | Evidence and trade-off | +|---|---| +| SpeechBrain ECAPA-TDNN | “apache-2.0”, public, PyTorch. The embedding checkpoint alone is 83.32 MB. Supports enrolment; VoxCeleb1-test cleaned EER 0.80%. No verified CN-Celeb or mixed-speech result for these weights. [Card](https://huggingface.co/speechbrain/spkrec-ecapa-voxceleb) · [Files](https://huggingface.co/speechbrain/spkrec-ecapa-voxceleb/tree/main) | +| NVIDIA TitaNet-Large | “cc-by-4.0”, public, 23M parameters, 101.62 MB NeMo package and sherpa conversion available. Supports embeddings for enrolment. VoxCeleb1 cleaned EER 0.66%. Oracle-VAD AMI DER (lapel/mix-headset) 2.03/1.73% with known speaker count, 2.03/1.89% with unknown count. This evaluation supplies the speech boundaries. CN-Celeb, AliMeeting, AISHELL-4 and VoxConverse results unverified for this setup. [Card](https://huggingface.co/nvidia/speakerverification_en_titanet_large) · [Files](https://huggingface.co/nvidia/speakerverification_en_titanet_large/tree/main) | +| NVIDIA Sortformer v1 / streaming v2.1 | Four speaker slots. Offline v1 weights use “cc-by-nc-4.0”. Streaming v2.1 uses “NVIDIA Open Model License”, 471 MB NeMo package. Its launch card lists 1.04 s low-latency input buffering. Nemotron above addresses eight-speaker recordings. [V1 card](https://huggingface.co/nvidia/diar_sortformer_4spk-v1) · [v2.1 card](https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2.1) | +| DiariZen / Reverb v1 | DiariZen's MIT code ships weights under “CC BY-NC 4.0”. Sherpa identifies the alternative Reverb segmentation weights as “non-commercial”. These terms exclude a generally redistributable commercial product. [DiariZen weight license](https://github.com/BUTSpeechFIT/DiariZen/blob/main/MODEL_LICENSE) · [Reverb card](https://huggingface.co/Revai/reverb-diarization-v1) · [Sherpa conversion notes](https://k2-fsa.github.io/sherpa/onnx/speaker-diarization/models.html#sherpa-onnx-reverb-diarization-v1) | +| FunASR speaker component | Its Paraformer pipeline combines a VAD, ASR, punctuation and CAM++. The existing listen path already provides ASR and VAD. Importing the entire pipeline would duplicate both. The shortlisted model is the specifically licensed bilingual checkpoint. [FunASR](https://github.com/modelscope/FunASR) · [Bilingual checkpoint](https://modelscope.cn/models/iic/speech_campplus_sv_zh_en_16k-common_advanced) | +| MOSS-Transcribe-Diarize | Mandarin/English joint timestamped speaker transcription, “apache-2.0”, 0.9B parameters, 1.81 GB published weight file before runtime. vLLM supports diarized segments. First-party meeting benchmarks use CER/cpCER; these cannot establish time-based DER. An optimized Mac deployment would need independent memory/latency and identity-continuity tests. [Card](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) · [Files](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize/tree/main) · [vLLM API](https://docs.vllm.ai/en/latest/serving/online_serving/speech_to_text/) | +| Qwen and vLLM alternatives | The installed Qwen3-ASR-1.7B card documents ASR and language output. ASLP's Qwen3-Omni-based Speaker-Reasoner explicitly produces attributed text, but its released weights total 63.44 GB and its card calls for a custom vLLM branch; downstream weight license unverified. Microsoft VibeVoice-ASR-HF (“mit”) supports speaker-attributed segments via vLLM but has 16.66 GB of weights. Both exceed the extra live memory allowance in published form. vLLM is a serving runtime; diarized output depends on the checkpoint. [Qwen3-ASR card](https://huggingface.co/Qwen/Qwen3-ASR-1.7B) · [Speaker-Reasoner](https://huggingface.co/ASLP-lab/Speaker-Reasoner) · [VibeVoice files](https://huggingface.co/microsoft/VibeVoice-ASR-HF/tree/main) · [vLLM supported models](https://docs.vllm.ai/en/latest/serving/online_serving/speech_to_text/) | + +## Reproduce + +From the repository root, create an isolated arm64 Python 3.12 environment. The optional CPU speaker dependency is installed only where requested. No server or listening port is needed to reproduce the measurements. + +```bash +uv venv --python 3.12 /tmp/t20-env +source /tmp/t20-env/bin/activate +uv pip install -r host/requirements.txt sherpa-onnx==2.0.3 scipy pytest pyarrow==26.0.1 +python spikes/t20_speakers/prepare_data.py --output /tmp/t20-data +release=https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models +mkdir -p /tmp/t20-models +for model in 3dspeaker_speech_campplus_sv_zh_en_16k-common_advanced 3dspeaker_speech_eres2netv2_sv_zh-cn_16k-common; do + curl -fL "$release/$model.onnx" -o "/tmp/t20-models/$model.onnx" || exit 1 + python -m spikes.t20_speakers.benchmark /tmp/t20-data "/tmp/t20-models/$model.onnx" "/tmp/$model.json" || exit 1 + rm "/tmp/t20-models/$model.onnx" +done +python -m pytest -q host +``` + +For the live prototype, download just the winning checkpoint and set `OPENVOICE_SPEAKER_MODEL` to its path in the host environment. The loader verifies its SHA-256. Run `python -m spikes.t20_speakers.check_host /tmp/t20-data` with the model path set to repeat the paired timing and single-enrollee trials. For named attribution, create a private file with `python -m spikes.t20_speakers.enroll /private/path/voices.json 'Ali=/private/path/consenting-voice.wav'`, then set `OPENVOICE_SPEAKERS` to that JSON path. The helper accepts multiple name/WAV arguments in one invocation and refuses to overwrite an existing file. The file contains biometric templates and should stay outside synced folders and the repository. Template matching works locally without a server or account. + +## Scope of evidence + +This is a small, balanced comparison using real public speech, with constructed mixed-language conversations. Eight-person meetings, long meetings, overlapping code-switching, recognition across days and devices, whispered speech, and live microphone trials with Ali remain untested. Enrolment and evaluation clips from a given meeting share its acoustics. The enrolled-name experiment included all speakers present. The single-enrollee check estimates false accepts only for the other speakers in these three sessions. Stranger and replay performance remain unknown. Keep speaker labels advisory for meeting notes and respond-mode clients. No model binaries, audio, names of enrolled users, or voiceprints are included in the PR. diff --git a/docs/subsystems/asr-pipeline.md b/docs/subsystems/asr-pipeline.md index 8c9defe..5f08010 100644 --- a/docs/subsystems/asr-pipeline.md +++ b/docs/subsystems/asr-pipeline.md @@ -1,5 +1,25 @@ # ASR Pipeline -状态:待编写(TBD)。 +状态:首期已实现(phase 1 implemented) -首期:ASR 链路。识别、整理、上屏三段;对标 Chatterfly 的级联 ASR + LLM,关注整理段时延。 +Recognize → clean up → insert, a cascaded ASR → LLM pipeline, with the clean-up stage kept off the critical path whenever possible. Measured on an M1 Max (32 GB), warm, through the host: + +| Mode | Median | p90 | +|---|---:|---:| +| Dictation, accurate (Qwen3-ASR-1.7B) | ~320 ms | ~660 ms | +| Dictation, fast (4-bit decoder) | ~215 ms | ~510 ms | + +1. **Recognize:** Qwen3-ASR-1.7B, accurate or fast route. Accuracy on 320 real clips (ASCEND): + - accurate: English WER 17.7%, Mandarin CER 6.6%, mixed MER 7.98% + - fast: mixed MER 8.86% + - Whisper large-v3, for comparison: mixed MER 24.3% +2. **Clean-up gate** (`prompts.needs_polish`): Qwen3-ASR already punctuates. The LLM runs only when the transcript has: + - fillers (um, uh, ah, 呃, 嗯, 那个, a clause-initial 就是) + - a repeated word or phrase ("I I", 专业专业, 我这个,我这个) + - a dictionary alias, or a style or instructions setting + + That is about 30% of utterances. The rest skip about 190 ms and come back with the warning `polish_not_needed`. Most edits the gate skips were unwanted anyway (dropping 但是, translating "opportunity" to 机会). +3. **Clean-up:** Qwen3-4B-Instruct (4-bit) with `prompts/cleanup.txt` (adapted from a third-party Apache-2.0 prompt, see `prompts/NOTICE`). A guard (`prompts.accepted`) rejects edits that answer a dictated question or drift too far; the result then falls back to the transcript. +4. **Insert:** the client types or pastes `text`. + +Tried without gain on this hardware: n-gram speculative decoding for clean-up (drafts were accepted but not faster to verify). Prompt prefix caching is already on. diff --git a/docs/subsystems/model-workers.md b/docs/subsystems/model-workers.md index 2b37e66..5593dc7 100644 --- a/docs/subsystems/model-workers.md +++ b/docs/subsystems/model-workers.md @@ -1,5 +1,17 @@ # Model Workers -状态:待编写(TBD)。 +状态:首期已实现(phase 1 implemented)· `host/workers/` -本地模型 workers:识别(ASR)、文本模型、合成(TTS);长文本下的音色一致性。 +Local model servers with OpenAI-compatible APIs. On a Mac they are vLLM with the [vllm-metal](https://github.com/vllm-project/vllm-metal) plugin (MLX); on a GPU server, vLLM. `host/workers/start_local.sh` starts them and the host. + +| Port | Model | Role | Memory (M1 Max) | +|---|---|---|---:| +| 8100 | Qwen/Qwen3-ASR-1.7B | speech, accurate | 4.7 GB | +| 8103 | the same with a 4-bit decoder (`quantize_asr.py`) | speech, fast | 2.4 GB | +| 8101 | mlx-community/Qwen3-4B-Instruct-2507-4bit | clean-up, translation, respond (tool calling: `--enable-auto-tool-choice --tool-call-parser hermes`) | 3.7 GB | +| 8102 | optional, e.g. mlx-community/Hy-MT2-7B-4bit (`MT_MODEL=...`) | translation | 5.4 GB | + +- **Setup:** `git clone https://github.com/vllm-project/vllm-metal && cd vllm-metal && ./install.sh` (macOS 15+, Apple silicon). The script expects it under `$OPENVOICE_WORK` (default `~/openvoice-work`); override with `VLLM=/bin`. +- **ASR memory cap:** `mlx_cache_profile/sitecustomize.py` limits MLX's reusable-buffer cache to 128 MiB in the ASR processes only. Peak memory fell from 12 GB to 5.9 GB, with identical transcripts on 320 clips. +- **Fast ASR:** the community `mlx-community/Qwen3-ASR-1.7B-4bit` build does not load on vllm-metal (its audio-encoder weights are in a different layout). `quantize_asr.py` quantizes only the decoder of the official checkpoint and keeps the layout the server expects; the start script runs it once. +- **Memory matters more than any single optimisation:** with other large models loaded, requests after idle took 6–10 s while macOS paged weights back in. Phase 1 alone peaks near 11 GB. diff --git a/docs/subsystems/provider-router.md b/docs/subsystems/provider-router.md index f820dd1..40effb6 100644 --- a/docs/subsystems/provider-router.md +++ b/docs/subsystems/provider-router.md @@ -1,5 +1,14 @@ # Provider Router -状态:待编写(TBD)。 +状态:首期最小实现(phase 1, minimal)· `host/router/` -模型路由:按语言、能力、隐私策略选择本地模型或云端模型;派活前做能力校验。 +Phase 1 routes each stage to one local server, read from the environment so a model can be swapped without code changes: + +| Stage | Settings | Default | +|---|---|---| +| `asr` | `OPENVOICE_ASR_URL`, `OPENVOICE_ASR_MODEL` | `http://127.0.0.1:8100`, Qwen/Qwen3-ASR-1.7B | +| `asr_fast` (optional; `speed: "fast"`) | `OPENVOICE_ASR_FAST_URL`, `OPENVOICE_ASR_FAST_MODEL` | none | +| `llm` (clean-up, respond) | `OPENVOICE_LLM_URL`, `OPENVOICE_LLM_MODEL` | `http://127.0.0.1:8101`, Qwen/Qwen3-4B-Instruct-2507 | +| `mt` (translation) | `OPENVOICE_MT_URL`, `OPENVOICE_MT_MODEL` | the `llm` route | + +Every route is local; no cloud provider is wired in phase 1. Language-, capability- and privacy-based routing (and per-stage cloud opt-in, cloud-provider.md) build on this table. diff --git a/docs/subsystems/translation.md b/docs/subsystems/translation.md index 6cd8fca..b371d7f 100644 --- a/docs/subsystems/translation.md +++ b/docs/subsystems/translation.md @@ -1,5 +1,15 @@ # Translation -状态:待编写(TBD)。 +状态:首期已实现(phase 1 implemented) -首期:实时翻译。口语实时转准确书面外语;多语言交流场景。 +- **Spoken:** `mode: "translate"` with `output_language` (35 languages; see `GET /v1/capabilities`). The **raw** transcript is translated, because cleaning it with the LLM first risked answering or changing the language. Only hesitations (um, uh, ah, er, hmm, 呃, 嗯) are dropped first, by a fixed rule with no model and no added time. A spoken self-correction ("2 p.m. No, 3 p.m.", "不对,三点") is the exception: a correction word anywhere, with or without punctuation ("no", "sorry", "I mean", "actually", "wait", "make it", "rather", "不对", "不是", "哦不", "说错"…), sends the sentence through the clean-up model and its guard first (~0.2–0.3 s more), so only the corrected version is translated. `"clean_up": false` turns both off. `raw` keeps what was said. About 0.2 s after recognition with Qwen3-4B. +- **Typed or selected text:** `POST /v1/translate`. +- **Model:** the clean-up LLM by default, so there is no extra memory. Any OpenAI-compatible translation model can be routed in with `OPENVOICE_MT_URL` / `OPENVOICE_MT_MODEL`; the prompt is Hy-MT2's documented one, with its terminology form for dictionary terms. On 30 real transcripts (zh, mixed → en; en → zh): + +| Model, on the Mac (4-bit) | Median | Extra memory | Notes | +|---|---:|---:|---| +| Qwen3-4B-Instruct (default) | 192 ms | 0 | Literal; one meaning error (蛙泳 → "freestyle") | +| Hy-MT2-1.8B | 181 ms | 2.5 GB | Sometimes adds words | +| Hy-MT2-7B | 376 ms | 5.4 GB | Best zh → en; may finish unfinished fragments | + +- **Failure:** `text = raw` plus the warning `translate_failed` (speech), or `502 mt_failed` (`/v1/translate`). diff --git a/docs/subsystems/voice-sessions.md b/docs/subsystems/voice-sessions.md index 74f2649..2cf77a2 100644 --- a/docs/subsystems/voice-sessions.md +++ b/docs/subsystems/voice-sessions.md @@ -1,5 +1,17 @@ # Voice Sessions -状态:待编写(TBD)。 +状态:首期已实现(phase 1 implemented)· `host/sessions/` -语音会话:采集、打断、返回结果;会话生命周期与状态机。 +One request = one voice session: capture (on the client) → recognize → clean up, translate or respond → return. Sessions are stateless on the host: a respond-mode conversation is carried by the client as `history`. API: [../reference.md](../reference.md). + +| Step | Where | Notes | +|---|---|---| +| Capture | client | Hold-to-talk (one recording), or hands-free: a listening session (`/v1/listen`) where the host runs Silero VAD (`vad.py`), sends live partials and processes each utterance | +| Decode | `app.decode` | 16 kHz mono PCM16 WAV is read directly (no ffmpeg, about 35 ms saved); other formats go through ffmpeg (pipe only, bounded by `OPENVOICE_MAX_AUDIO_SECONDS`) | +| Recognize | ASR worker | Accurate or fast route, per request (`speed`); see provider-router.md | +| Post-process | `app.process` | `transcribe` / `polish` (asr-pipeline.md) / `translate` (translation.md) / `respond` | +| Return | `/v1/dictate` | JSON, or server-sent events with `?stream=1` (`transcript`, `tool`, `delta`, `final`) | + +- **Limits:** `OPENVOICE_MAX_SESSIONS` concurrent sessions (429 above it), and the audio length cap. Results are kept 10 minutes by `request_id`, so a client can retry safely after a dropped connection. +- **Respond mode:** the LLM answers the request. With `context.selected_text` it works on that text (rewrite, reply, explain). The answer is streamed. Tools (`host/sessions/tools.py`: weather, Wikipedia) are offered only with `OPENVOICE_TOOLS=1`, because their queries leave the device. Answers are plain text, since they are typed into other apps. +- **Interrupt:** a client cancels by closing the stream. `/v1/dictate/stream` (WebSocket) also accepts `{"type": "cancel"}`. diff --git a/host/README.md b/host/README.md index aa06a62..fef55e9 100644 --- a/host/README.md +++ b/host/README.md @@ -2,10 +2,41 @@ Local Personal Host: the core of OpenVoice. -- `sessions/` — voice sessions: capture / interrupt / return results -- `jobs/` — durable jobs: queue / resume / cancel +## What runs today + +```bash +python3 -m venv .venv && .venv/bin/pip install -r host/requirements.txt +host/workers/start_local.sh # local models + the host on 127.0.0.1:8765 (the host alone: python -m host.sessions) +``` + +Then open `http://127.0.0.1:8765/demo`. The host (`sessions/`) serves: + +- **Dictation** (`POST /v1/dictate`, `WS /v1/dictate/stream`): transcribe, polish (clean-up), translate, respond. +- **Respond mode:** streamed answers, follow-ups, optional tools (`OPENVOICE_TOOLS=1`) and MCP servers (`OPENVOICE_MCP`), with confirmation before any action. +- **Hands-free listening** (`WS /v1/listen`): Silero VAD (bundled) finds each sentence. +- **Speaker labels** (optional, see below) and voice enrolment (`/v1/speakers`). + +The API is in `docs/reference.md`; how a client uses it is in `docs/integrating.md`. Tests: `python -m pytest -q host` (fake model servers, no downloads). + +## Speaker labels (optional download) + +Neither labeller is bundled or installed by `requirements.txt`, so on a fresh clone labels are off +(`GET /v1/capabilities` shows `listen.speakers: false`). Set up one of them: + +**Nemotron-3-Diarization (preferred: stable labels for a whole session, shows overlap)** +1. The C library: the macOS arm64 CPU package of [NeMo-Speech.cpp v0.3.1](https://github.com/NVIDIA/NeMo-Speech.cpp/releases/tag/v0.3.1) (Apache-2.0). Set `OPENVOICE_DIAR_LIB` to its `lib/libnemo_speech_asr_c.2.dylib`. +2. The model: `Nemotron-3-Diarization.q8_0.gguf` from [nvidia/Nemotron-3-Diarization](https://huggingface.co/nvidia/Nemotron-3-Diarization) (OpenMDW-1.1), revision `52a432672732425e4c19765b9fec9b5810e6f4ba`. Set `OPENVOICE_DIAR_MODEL` to its path. The host checks its SHA-256. + +**CAM++ (fallback: per-sentence voiceprints, enrolled names)** +1. `pip install sherpa-onnx==2.0.3`. +2. `3dspeaker_speech_campplus_sv_zh_en_16k-common_advanced.onnx` from the sherpa-onnx [speaker-recongition-models](https://github.com/k2-fsa/sherpa-onnx/releases/tag/speaker-recongition-models) release (Apache-2.0). Set `OPENVOICE_SPEAKER_MODEL` to its path. The host checks its SHA-256. +3. Not run in CI: the tests use a fake embedder, and the real path was checked by hand only (`docs/results/T20.md`). + +## Layout + +- `sessions/` — voice sessions: dictation, listening, respond mode, speaker labels (the running host) +- `workers/` — local model workers: start script, ASR quantisation, MLX cache limit +- `mcp_servers/` — example MCP servers for respond-mode actions +- `eval/` — clean-up and respond quality checks - `router/` — provider router: language / capability / privacy policy -- `devices/` — device registry: pairing / grants / revocation -- `workers/` — local model workers: recognition / text model / synthesis -- `storage/` — host-owned storage: SQLite memory / job state / audio files -- `cloud/` — optional cloud provider, per-stage opt-in +- `jobs/`, `devices/`, `storage/`, `cloud/` — planned (durable jobs, device pairing, host storage, optional cloud), not built yet diff --git a/host/__init__.py b/host/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/host/eval/README.md b/host/eval/README.md new file mode 100644 index 0000000..3a0a8bc --- /dev/null +++ b/host/eval/README.md @@ -0,0 +1,90 @@ +# Answer quality + +`python -m host.eval.quality --model --host ` runs [cases.jsonl](cases.jsonl) and prints each failure with its reason: +- **Clean-up (polish), 22 dictations.** English and Chinese with fillers, stutters, negations, numbers, unfinished sentences, questions or commands that must not be answered, and spoken self-corrections (p17–p22: four to resolve, two look-alikes to keep). Each case lists what must be gone and what must stay. +- **Respond, 24 requests.** Questions, writing, rewriting selected text, Chinese, mixed Chinese-English, and requests for another output language. The checks look for Markdown, a preamble, quotes, the wrong language, a missing expected answer, a missing numbered list, an over-long answer, and an echo of the selected text. + +Clean-up calls the LLM with the host's own gate, prompt and guard. Respond goes through `/v1/respond`. The checks are heuristics: read the failures before trusting the counts. `--rescore run.jsonl` re-checks a saved run with the current checks. + +## Quality pass, 3 Dec 2026 + +Model: Qwen3-4B-Instruct-2507, 4-bit, on vllm-metal (M1 Max), temperature 0. Before is the backend-phase1 prompts (PR #2). Both runs are scored with the same checks. + +| | Before | After | +|---|---:|---:| +| Clean-up, 16 cases | 10 pass | 16 pass | +| Respond, 24 cases | 20 pass | 23 pass (the one flag is a check error, see below) | +| Respond time, median / p90 | 228 / 581 ms | 177 / 462 ms | + +What was wrong, and the fix: +- **Clean-up translated English into Chinese.** "Uh, remind me to call Sarah tomorrow at 9." came back as "提醒我明天九点打给 Sarah。". The guard caught it and inserted the raw text, so fillers stayed in. This happened in 5 of 16 cases. **Fix:** the host now tells the model the transcript's language: Chinese if it has at least as many Han characters as English words, otherwise English. A Chinese-language rule leads the policy and two examples were added. "Hmm" joined the filler list. +- **The guard rejected good question edits** that dropped "hmm" or a stutter ("the, uh, the train"). **Fix:** it now ignores those when it compares a question before and after. +- **Respond answered a mixed request in the wrong language,** with an intro. "我们明天的 meeting 要 reschedule 吗?帮我写个回复说改到周五。" got "当然可以,以下是…" and an English reply. **Fix:** mixed Chinese-English requests default to Chinese. An intro line that ends in a colon before a drafted message is removed in code (`prompts.tidy`), along with quotes around the draft. + - A prompt rule alone did not stop the intro. + - A few-shot example made the model copy the example into unrelated replies, so it was dropped. +- **Lists ended lines with two spaces** (Markdown line breaks). The final text drops them. + +**Held-out check.** These are the 30 real ASCEND transcripts from the T9 evaluation, not used for tuning. The clean-up model runs on 9; the gate skips the rest. + +| | Old prompt | New prompt | +|---|---:|---:| +| Guard rejections | 0 | 0 | +| Output language changed | 1 | 0 | + +- The old prompt also changed "western 还有 eastern" to "western 还是 eastern" ("and" became "or"). The new prompt keeps it. +- One filler 那个 is still left in 00007 and 00485. + +**Limits:** +- The 16 + 24 cases were written for this pass and used for tuning. Only the 30 held-out transcripts are independent. +- r11 is flagged "preamble" because the drafted reply itself starts with 好的 ("好的,我们把会议改到周五…"). That is correct output; the check is too coarse. + +## MCP tools, 3 Dec 2026 + +The tool-choice cases (`t01`–`t08`) run only when the host offers the example MCP server's tools (`OPENVOICE_MCP=host/mcp.example.json`). Each case checks which tool was called and key arguments, for example a reminder due at `15:00` for "明天下午三点". Actions are declined in these runs because a plain request cannot confirm, so nothing on the Mac changes. + +First run: 6 of 8. These are the problems found and fixed: + +| Case | What went wrong | Fix | +|---|---|---| +| t01 "What time is it?" | The model guessed 14:30 instead of calling the clock tool | The prompt says the time of day is unknown without a tool (the date is given) | +| t04 "Open youtube.com for me." | The call came out as text, `open_url("https://www.youtube.com")` | Tools keep their own names (it was `mac__open_url`). A reply that is exactly a call to an offered tool is run as that call (`prompts.text_call`) | +| t08 (no tool expected) | "已创建提醒" was added: an action claimed but never called | Rule: say something was done only when a tool result says so | +| r13 (`output_language: zh`) | Answered in English once tool schemas were attached | The output language is repeated in the user turn | + +After the fixes: tools 8/8, respond 24/24, clean-up 16/16. + +**Approve path, live.** "Remind me to check the OpenVoice test tomorrow at 10." was approved through `/v1/confirm`. Reminders then had "Check OpenVoice test", due Friday 4 Dec 2026 at 10:00, and the tool took 1.2 s. +- The model's reply repeated the request instead of confirming it. +- A successful action's result now reads "Done. … Tell the user in one short sentence what was done." +- Replayed for four actions, the replies became confirmations in the request's language: "A reminder … has been set.", "已为您设置提醒:明天下午三点交报告。", "Opened YouTube for you.", "Your New Shortcut 3 has been executed successfully." + +**Live mic test, 3 Dec.** "Remind me to stretch in ten minutes", said right after "What time is it?", got "A reminder to stretch has been created for 13:18." No tool was called, so nothing was asked and nothing was created. Separately, English relative times were guessed wrong ("in ten minutes" at 13:08 became 08:00). + +Fixes: +- The action rule moved to the very end of the system prompt. Repeating it in the user turn also worked, but it flipped two Chinese answers to English. +- `create_reminder` takes `in_minutes`, and the server computes the time. + +New cases t09 (with that history) and t10 (in an hour). Result: tools 10/10, respond 24/24, clean-up 16/16. Five multi-turn conversations, in English and Chinese, all asked before acting. + +## Self-corrections, 4 Dec 2026 + +Same model and settings. Spoken self-corrections ("Book me a meeting at 2 p.m. No, 3 p.m.") used to skip the model in `polish` (no filler, so the gate called them clean) and were translated with both times. + +**How it works now** (`prompts.corrected`, `prompts.accepted`, `cleanup.txt`): +- **Gate:** a correction word anywhere, with or without punctuation ("no", "sorry", "I mean", "actually", "wait", "make it", "rather", 不对, 不是, 哦不, 说错, 我是说…), sends the sentence to the clean-up model. A look-alike costs one call (~0.2 s); the model is told to change nothing when nothing is replaced. +- **Prompt:** keep only the corrected version, in long sentences and without punctuation too; examples in English and Chinese (repeated 不对, 哦不, no punctuation). +- **Guard:** a correction may remove a lot (your "七点…不对,不对,不对,不对…八点钟" keeps 18 of 40 characters) but may add almost nothing. Two edits are always refused, and the words as spoken are kept: one that drops every negation ("not the 3 p.m. one" → "the 3 p.m. slot"), and one that only drops "sorry", "actually", "no" or "wait" while replacing nothing. + +**Results:** + +| Set | First version | Now | +|---|---:|---:| +| 22 short variants (phrasings, no punctuation, Chinese) | 11 | 20 | +| 11 long sentences, English and Chinese, incl. Ali's recording | – | 10 | +| 12 long look-alikes that must stay as said | – | 12 | +| 13 spoken clips (macOS voices), polish and translate | 13 | 13 | +| This eval: clean-up / respond / tools | 22 / 24 / 10 | 21 / 24 / 10 | + +- **Still missed:** "两点,啊不对,三点开会" and "改到下周一,哦不,改到下周二" (the model left them as said), and "2 p.m. Not 2, 3 p.m." (the model was right, but the negation rule refuses any edit that drops "not"). +- **p22 is flagged** because the model dropped "Actually," and the guard refused it; the words as spoken were inserted, which is the intended result. +- Probe scripts: the 33 sentences are in the session scratchpad (`probe.py`, `probe2.py`), not in the repo. diff --git a/host/eval/__init__.py b/host/eval/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/host/eval/cases.jsonl b/host/eval/cases.jsonl new file mode 100644 index 0000000..0c810de --- /dev/null +++ b/host/eval/cases.jsonl @@ -0,0 +1,56 @@ +{"id": "p01", "kind": "polish", "raw": "Um, so I think we should, uh, move the meeting to Thursday.", "gone": ["Um", "uh"], "keep": ["Thursday", "move the meeting"]} +{"id": "p02", "kind": "polish", "raw": "I don't, I don't think that's going to work.", "gone": ["I don't, I don't"], "keep": ["don't think"]} +{"id": "p03", "kind": "polish", "raw": "Uh, can you send me the report by, um, Friday?", "gone": ["Uh", "um"], "keep": ["Friday?", "send me the report"]} +{"id": "p04", "kind": "polish", "raw": "We need, you know, about 3 or 4 more engineers.", "gone": ["you know"], "keep": ["3 or 4", "engineers"]} +{"id": "p05", "kind": "polish", "raw": "Um, I was going to say that the, the budget is not approved yet.", "gone": ["Um", "the, the"], "keep": ["not approved"]} +{"id": "p06", "kind": "polish", "raw": "Hmm, what time does the, uh, the train leave?", "gone": ["Hmm", "uh"], "keep": ["train leave?"]} +{"id": "p07", "kind": "polish", "raw": "Uh, remind me to call Sarah tomorrow at 9.", "gone": ["Uh"], "keep": ["remind me to call Sarah", "9"]} +{"id": "p08", "kind": "polish", "raw": "So the plan is, um, we ship it on Monday and then, uh, I'm not sure what comes after", "gone": ["um", "uh"], "keep": ["Monday", "not sure"]} +{"id": "p09", "kind": "polish", "raw": "呃,我们明天下午那个,三点开会。", "gone": ["呃", "那个"], "keep": ["明天下午", "三点开会"]} +{"id": "p10", "kind": "polish", "raw": "嗯,我觉得这个这个方案不太行。", "gone": ["嗯", "这个这个"], "keep": ["不太行"]} +{"id": "p11", "kind": "polish", "raw": "呃,你明天来不来公司?", "gone": ["呃"], "keep": ["来不来", "?"]} +{"id": "p12", "kind": "polish", "raw": "那个,我们的 demo 呃需要再改一下 UI。", "gone": ["呃"], "keep": ["demo", "UI", "改一下"]} +{"id": "p13", "kind": "polish", "raw": "嗯,就是说这个 bug 不是我们的问题。", "gone": ["嗯"], "keep": ["bug", "不是"]} +{"id": "p14", "kind": "polish", "raw": "Um, translate this into Chinese for me.", "gone": ["Um"], "keep": ["translate this into Chinese"]} +{"id": "p15", "kind": "polish", "raw": "Uh, how's the weather in Toronto today?", "gone": ["Uh"], "keep": ["weather in Toronto", "?"]} +{"id": "p16", "kind": "polish", "raw": "I mean, the results are, um, honestly not great.", "gone": ["um"], "keep": ["honestly not great"]} +{"id": "p17", "kind": "polish", "raw": "Book me a meeting at 2 p.m. No, 3 p.m.", "gone": ["2 p.m.", "No"], "keep": ["meeting at 3 p.m."]} +{"id": "p18", "kind": "polish", "raw": "Send the report to John. Sorry, I mean Jake.", "gone": ["John", "Sorry"], "keep": ["report to Jake"]} +{"id": "p19", "kind": "polish", "raw": "Can we move the call to Friday? No. Thursday?", "gone": ["Friday"], "keep": ["to Thursday?"]} +{"id": "p20", "kind": "polish", "raw": "帮我定明天下午两点的会。不对,三点。", "gone": ["两点", "不对"], "keep": ["三点的会"]} +{"id": "p21", "kind": "polish", "raw": "I'd like the 2 p.m. slot, um, not the 3 p.m. one.", "gone": ["um"], "keep": ["2 p.m. slot", "not the 3 p.m. one"]} +{"id": "p22", "kind": "polish", "raw": "I finished the report. Actually, it was easier than I thought.", "keep": ["finished the report", "Actually, it was easier"]} +{"id": "r01", "kind": "respond", "text": "What is the capital of Japan?", "lang": "en", "expect": ["Tokyo"]} +{"id": "r02", "kind": "respond", "text": "How many days are in a leap year?", "lang": "en", "expect": ["366"]} +{"id": "r03", "kind": "respond", "text": "Give me three tips for a good presentation.", "lang": "en", "list": true} +{"id": "r04", "kind": "respond", "text": "Write a short message to my team saying the meeting is moved to 3 pm.", "lang": "en", "expect": ["3"]} +{"id": "r05", "kind": "respond", "text": "Explain what an API is in one sentence.", "lang": "en", "max_chars": 300} +{"id": "r06", "kind": "respond", "text": "What is the capital of Japan? Answer in Chinese.", "lang": "zh", "expect": ["东京"]} +{"id": "r07", "kind": "respond", "text": "日本的首都是哪里?", "lang": "zh", "expect": ["东京"]} +{"id": "r08", "kind": "respond", "text": "帮我写一句话告诉同事我会晚到十分钟。", "lang": "zh", "expect": ["十分钟", "10分钟", "10 分钟"]} +{"id": "r09", "kind": "respond", "text": "给我三个学习英语的建议。", "lang": "zh", "list": true} +{"id": "r10", "kind": "respond", "text": "帮我用英文写一句:明天的会议取消了。", "lang": "en", "expect": ["cancel"]} +{"id": "r11", "kind": "respond", "text": "我们明天的 meeting 要 reschedule 吗?帮我写个回复说改到周五。", "lang": "zh", "expect": ["周五", "星期五"]} +{"id": "r12", "kind": "respond", "text": "Say good morning.", "output_language": "zh", "lang": "zh", "expect": ["早"]} +{"id": "r13", "kind": "respond", "text": "Tell me a fun fact about octopuses.", "output_language": "zh", "lang": "zh", "expect": ["章鱼", "八爪鱼"]} +{"id": "r14", "kind": "respond", "text": "Reply to this, I'll be ten minutes late.", "selected": "Hi Ali, are we still on for the 2 pm sync today? — Mei", "lang": "en", "expect": ["10", "ten"], "no_echo": "are we still on"} +{"id": "r15", "kind": "respond", "text": "Make this shorter.", "selected": "I wanted to reach out to let you know that unfortunately I will not be able to attend the meeting that was scheduled for tomorrow afternoon because of a conflict.", "lang": "en", "max_chars": 140} +{"id": "r16", "kind": "respond", "text": "Translate this into Chinese.", "selected": "The deadline has been moved to next Monday.", "lang": "zh", "expect": ["周一", "星期一"], "max_chars": 60} +{"id": "r17", "kind": "respond", "text": "Fix the grammar.", "selected": "He don't know where the files is.", "lang": "en", "expect": ["doesn't know", "does not know"], "max_chars": 80} +{"id": "r18", "kind": "respond", "text": "把这段改得更礼貌一点。", "selected": "你把文件发给我,快点。", "lang": "zh", "expect": ["请", "麻烦", "可以", "能否", "谢谢"]} +{"id": "r19", "kind": "respond", "text": "Make it more formal.", "selected": "hey, can't make it tmrw, sorry!", "lang": "en", "max_chars": 300} +{"id": "r20", "kind": "respond", "text": "What's 15% of 80?", "lang": "en", "expect": ["12"]} +{"id": "r21", "kind": "respond", "text": "List the steps to make tea.", "lang": "en", "list": true} +{"id": "r22", "kind": "respond", "text": "嗯,那个,你能告诉我一年有几个月吗?", "lang": "zh", "expect": ["12", "十二"]} +{"id": "r23", "kind": "respond", "text": "Um, what's the opposite of hot?", "lang": "en", "expect": ["cold", "Cold"]} +{"id": "r24", "kind": "respond", "text": "Who wrote Romeo and Juliet? 用中文回答。", "lang": "zh", "expect": ["莎士比亚"]} +{"id": "t01", "kind": "respond", "text": "What time is it?", "tool": "now"} +{"id": "t02", "kind": "respond", "text": "Remind me to call Sarah tomorrow at 9.", "tool": "create_reminder", "args_has": ["Sarah", "09:00"]} +{"id": "t03", "kind": "respond", "text": "提醒我明天下午三点交报告。", "tool": "create_reminder", "args_has": ["报告", "15:00"]} +{"id": "t04", "kind": "respond", "text": "Open youtube.com for me.", "tool": "open_url", "args_has": ["youtube.com"]} +{"id": "t05", "kind": "respond", "text": "Which shortcuts do I have?", "tool": "list_shortcuts"} +{"id": "t06", "kind": "respond", "text": "Run my shortcut called New Shortcut 3.", "tool": "run_shortcut", "args_has": ["New Shortcut 3"]} +{"id": "t07", "kind": "respond", "text": "What is the capital of France?", "tool": null, "needs": "now"} +{"id": "t08", "kind": "respond", "text": "帮我写一句话告诉同事我会晚到十分钟。", "tool": null, "needs": "now"} +{"id": "t09", "kind": "respond", "text": "Remind me to stretch in ten minutes.", "history": [{"role": "user", "content": "What time is it?"}, {"role": "assistant", "content": "The time is 13:08 EST on Thursday, 03 December 2026."}], "tool": "create_reminder", "args_has": ["\"in_minutes\": 10"]} +{"id": "t10", "kind": "respond", "text": "Set a reminder to drink water in an hour.", "tool": "create_reminder", "args_has": ["\"in_minutes\": 60"]} diff --git a/host/eval/quality.py b/host/eval/quality.py new file mode 100644 index 0000000..d7b06ac --- /dev/null +++ b/host/eval/quality.py @@ -0,0 +1,136 @@ +"""Answer-quality check for clean-up (polish) and respond, on typed transcripts so speech recognition is held fixed. + +python -m host.eval.quality --llm http://127.0.0.1:8101 --model --host http://127.0.0.1:8765 --out run.jsonl + +Polish runs the host's own gate, prompt and guard against the LLM; respond goes through the host's /v1/respond. +Every check is automatic and listed per case; read the failures, the checks are heuristics. +""" +import argparse +import json +import re +from pathlib import Path + +import httpx + +from host.sessions import prompts +from host.sessions.options import Options + +CASES = Path(__file__).with_name("cases.jsonl") +FILLER = re.compile(r"\b(?:um+|uh+|hmm+|erm+)\b|[呃嗯]", re.I) +MARKDOWN = re.compile(r"\*|^#+\s|^\s*[-•]\s", re.M) +PREAMBLE = re.compile(r"^(?:sure|certainly|of course|okay|ok|here(?:'s| is| are)|absolutely|great question|好的|当然|没问题|以下是)", re.I) +LIST = re.compile(r"^\s*(?:\d+[.)、]|[一二三四五]、)", re.M) + + +def han(s): + return sum("一" <= c <= "鿿" for c in s) / max(1, len(re.sub(r"\s", "", s))) + + +def polish(client, args, case): + opts = Options() + raw = case["raw"] + text, path = raw, "skipped" + if prompts.needs_polish(raw, opts): + r = client.post(args.llm + "/v1/chat/completions", json={ + "model": args.model, "messages": prompts.messages(raw, opts), "temperature": 0}) + r.raise_for_status() + choice = r.json()["choices"][0] + candidate = choice["message"]["content"] + ok = choice.get("finish_reason", "stop") == "stop" and prompts.accepted(raw, candidate, opts.dictionary) + text, path = (candidate.strip(), "model") if ok else (raw, "fallback") + fails = [f"left: {g}" for g in case.get("gone", []) if g in text] + fails += [f"lost: {k}" for k in case.get("keep", []) if k.casefold() not in text.casefold()] + if path == "fallback": + fails.append("guard rejected the edit") + if (han(raw) > 0.3) != (han(text) > 0.3): + fails.append("language changed") + return dict(id=case["id"], kind="polish", input=raw, output=text, path=path, fails=fails) + + +def check_respond(case, text): + fails = [] + if re.search(r"[ \t]\n", text): + fails.append("trailing spaces") + if not text: + fails.append("empty") + if MARKDOWN.search(text): + fails.append("markdown") + if PREAMBLE.search(text): + fails.append("preamble") + if text[:1] in "\"'“「" : + fails.append("quoted") + if case["lang"] == "zh" and han(text) < 0.3 or case["lang"] == "en" and han(text) > 0.05: + fails.append(f"not in {case['lang']}") + if case.get("expect") and not any(e.casefold() in text.casefold() for e in case["expect"]): + fails.append(f"missing one of {case['expect']}") + if case.get("list") and len(LIST.findall(text)) < 2: + fails.append("no numbered list") + if case.get("max_chars") and len(text) > case["max_chars"]: + fails.append(f"over {case['max_chars']} chars") + if case.get("no_echo") and case["no_echo"].casefold() in text.casefold(): + fails.append("echoed the selected text") + return fails + + +def respond(client, args, case): + body = dict(text=case["text"]) + if case.get("output_language"): + body["output_language"] = case["output_language"] + if case.get("selected"): + body["context"] = dict(selected_text=case["selected"]) + if case.get("history"): + body["history"] = case["history"] + r = client.post(args.host + "/v1/respond", json=body) + r.raise_for_status() + out = r.json() + text = out["text"] + if "tool" in case: # tool choice only: actions are declined here (no way to confirm), so the text is not checked + used = {c["name"]: json.dumps(c["arguments"], ensure_ascii=False) for c in out.get("tool_calls", [])} + fails = [] if (case["tool"] in used if case["tool"] else not used) else [f"called {sorted(used) or 'nothing'}"] + fails += [f"arguments lack {a}" for a in case.get("args_has", []) if a not in used.get(case["tool"], "")] + text = f"{text} [tools: {used}]" + else: + fails = check_respond(case, text) + return dict(id=case["id"], kind="tools" if "tool" in case else "respond", input=case["text"], output=text, + ms=out.get("timings_ms", {}).get("respond"), fails=fails) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--llm", default="http://127.0.0.1:8101") + parser.add_argument("--model", default="Qwen/Qwen3-4B-Instruct-2507") + parser.add_argument("--host", default="http://127.0.0.1:8765") + parser.add_argument("--out", type=Path) + parser.add_argument("--rescore", type=Path, help="re-check the respond rows of an earlier run with the current checks") + args = parser.parse_args() + if args.rescore: + cases = {c["id"]: c for c in map(json.loads, CASES.read_text(encoding="utf-8").splitlines())} + rows = [json.loads(line) for line in args.rescore.read_text(encoding="utf-8").splitlines()] + for r in rows: + if r["kind"] == "respond": + r["fails"] = check_respond(cases[r["id"]], r["output"]) + return report(rows, args.out) + rows = [] + with httpx.Client(timeout=60, trust_env=False) as client: + offered = client.get(args.host + "/v1/capabilities").json()["tools"].get("mcp", []) + for case in map(json.loads, CASES.read_text(encoding="utf-8").splitlines()): + if "tool" in case and (case["tool"] or case["needs"]) not in offered: + continue # tool-choice cases need the example MCP server (host/mcp.example.json) + rows.append((polish if case["kind"] == "polish" else respond)(client, args, case)) + row = rows[-1] + print(f"{row['id']} {'ok ' if not row['fails'] else 'FAIL'} {row['output'][:90]!r} {'; '.join(row['fails'])}") + report(rows, args.out) + + +def report(rows, out): + for kind in ("polish", "respond", "tools"): + part = [r for r in rows if r["kind"] == kind] + if not part: + continue + print(f"{kind}: {sum(not r['fails'] for r in part)}/{len(part)} pass") + if out: + out.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/host/mcp.example.json b/host/mcp.example.json new file mode 100644 index 0000000..a924649 --- /dev/null +++ b/host/mcp.example.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "mac": { + "command": "python", + "args": ["-m", "host.mcp_servers.mac"] + } + } +} diff --git a/host/mcp_servers/__init__.py b/host/mcp_servers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/host/mcp_servers/mac.py b/host/mcp_servers/mac.py new file mode 100644 index 0000000..411aae5 --- /dev/null +++ b/host/mcp_servers/mac.py @@ -0,0 +1,115 @@ +"""Example MCP server with a few macOS actions, for respond mode: python -m host.mcp_servers.mac (stdio). + +Everything runs on this Mac through its own apps (Shortcuts, Reminders, `open`); nothing goes to the network. +Tools that change something leave readOnlyHint unset, so the host asks the user before running them. +Creating a reminder makes macOS ask once for permission to control Reminders. +""" +import subprocess +from datetime import datetime, timedelta + +from mcp.server.fastmcp import FastMCP +from mcp.types import ToolAnnotations + +mcp = FastMCP("mac") +READ = ToolAnnotations(readOnlyHint=True) +ACT = ToolAnnotations(readOnlyHint=False, destructiveHint=False) + +REMINDER = """on run argv + set d to missing value + if (count of argv) > 1 then + set d to current date + set day of d to 1 + set year of d to (item 2 of argv as integer) + set month of d to (item 3 of argv as integer) + set day of d to (item 4 of argv as integer) + set hours of d to (item 5 of argv as integer) + set minutes of d to (item 6 of argv as integer) + set seconds of d to 0 + end if + tell application "Reminders" + if d is missing value then + make new reminder with properties {name:(item 1 of argv)} + else + make new reminder with properties {name:(item 1 of argv), remind me date:d} + end if + end tell +end run""" + + +def run(*cmd, timeout=30): + done = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) + if done.returncode: + raise RuntimeError((done.stderr or done.stdout).strip()[:300] or f"{cmd[0]} failed") + return done.stdout.strip() + + +@mcp.tool(annotations=READ) +def now() -> str: + """The local date, weekday and time on this Mac.""" + return datetime.now().astimezone().strftime("%A %d %B %Y, %H:%M %Z") + + +@mcp.tool(annotations=READ) +def list_shortcuts() -> str: + """Names of the user's Apple Shortcuts.""" + return run("shortcuts", "list") or "No shortcuts." + + +@mcp.tool(annotations=ACT) +def run_shortcut(name: str, text_input: str = "") -> str: + """Run one of the user's Apple Shortcuts by its exact name, optionally with text input. Returns its output.""" + cmd = ["shortcuts", "run", name] + if text_input: + cmd += ["--input-path", "-"] + out = subprocess.run(cmd, input=text_input, capture_output=True, text=True, timeout=120) + if out.returncode: + raise RuntimeError(out.stderr.strip()[:300] or "shortcut failed") + return out.stdout.strip() or f"Ran {name}." + return run(*cmd, timeout=120) or f"Ran {name}." + + +@mcp.tool(annotations=ACT) +def open_url(url: str) -> str: + """Open a web page in the default browser.""" + if not url.startswith(("https://", "http://")): + raise ValueError("Only http and https links can be opened.") + run("open", url) + return f"Opened {url}." + + +def parse_due(due, now=None): + """A full local date-time, or a bare time ("15:00", "3 pm") meaning its next occurrence: the 4B model sends both.""" + text, now = due.strip().replace("T", " "), now or datetime.now() + try: + return datetime.fromisoformat(text[:16]) + except ValueError: + pass + for fmt in ("%H:%M", "%I:%M %p", "%I:%M%p", "%I %p", "%I%p"): + try: + t = datetime.strptime(text.upper(), fmt) + except ValueError: + continue + when = now.replace(hour=t.hour, minute=t.minute, second=0, microsecond=0) + return when if when > now else when + timedelta(days=1) + raise ValueError(f"Could not read the time {due!r}; use YYYY-MM-DD HH:MM.") + + +@mcp.tool(annotations=ACT) +def create_reminder(title: str, due: str = "", in_minutes: int = 0) -> str: + """Add a reminder to the Reminders app. For "in ten minutes" or "in an hour" set in_minutes (10, 60). + For a clock time set due: local date and time as YYYY-MM-DD HH:MM. Leave both empty for no alert.""" + args = [title] + when = None + if in_minutes: # relative times are computed here: the 4B model guessed 08:00 for "in ten minutes" at 13:08 + when = datetime.now() + timedelta(minutes=int(in_minutes)) + due = when.strftime("%Y-%m-%d %H:%M") + elif due: + when = parse_due(due) + if when: + args += [str(v) for v in (when.year, when.month, when.day, when.hour, when.minute)] + run("osascript", "-e", REMINDER, *args) + return f"Reminder added: {title}" + (f", {due}" if due else "") + "." + + +if __name__ == "__main__": + mcp.run() diff --git a/host/requirements.txt b/host/requirements.txt new file mode 100644 index 0000000..925c9ca --- /dev/null +++ b/host/requirements.txt @@ -0,0 +1,9 @@ +fastapi>=0.115,<1 +httpx>=0.28,<1 +python-multipart>=0.0.20,<1 +uvicorn[standard]>=0.34,<1 +numpy>=1.26,<3 +onnxruntime>=1.20,<2 +mcp>=1.9,<2 +# shortcut: fastapi 0.165 calls get_logger(name, version, provider), which opentelemetry-api 1.46 rejects; lift when fastapi is fixed +opentelemetry-api<1.46 diff --git a/host/router/.gitkeep b/host/router/.gitkeep deleted file mode 100644 index 8b13789..0000000 --- a/host/router/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/host/router/__init__.py b/host/router/__init__.py new file mode 100644 index 0000000..8b819a3 --- /dev/null +++ b/host/router/__init__.py @@ -0,0 +1,33 @@ +"""Provider router: which local model serves each stage of a request. + +Phase 1 routes by stage and requested speed; every route is a local OpenAI-compatible server (vllm-metal on a Mac, +vLLM on a GPU). Configured by environment variables, so a model can be swapped without code changes. +""" +import os +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Route: + url: str + model: str + + +def load(): + """Stage -> Route from the environment. Optional stages appear only when configured.""" + env = os.environ.get + routes = { + "asr": Route(env("OPENVOICE_ASR_URL", "http://127.0.0.1:8100").rstrip("/"), env("OPENVOICE_ASR_MODEL", "Qwen/Qwen3-ASR-1.7B")), + "llm": Route(env("OPENVOICE_LLM_URL", "http://127.0.0.1:8101").rstrip("/"), env("OPENVOICE_LLM_MODEL", "Qwen/Qwen3-4B-Instruct-2507")), + } + # Faster speech model, chosen per request with speed="fast" (Qwen3-ASR with a 4-bit decoder). + if env("OPENVOICE_ASR_FAST_URL"): + routes["asr_fast"] = Route(env("OPENVOICE_ASR_FAST_URL").rstrip("/"), env("OPENVOICE_ASR_FAST_MODEL", "Qwen3-ASR-1.7B-4bit")) + # Translation model (e.g. a Hy-MT2 build); defaults to the clean-up LLM, so one LLM covers every stage. + routes["mt"] = Route(env("OPENVOICE_MT_URL", routes["llm"].url).rstrip("/"), env("OPENVOICE_MT_MODEL", routes["llm"].model)) + return routes + + +def asr_for(routes, speed): + """The speech route for a request; None when it asks for a speed this host does not serve.""" + return routes["asr_fast" if speed == "fast" else "asr"] if speed != "fast" or "asr_fast" in routes else None diff --git a/host/sessions/.gitkeep b/host/sessions/.gitkeep deleted file mode 100644 index 8b13789..0000000 --- a/host/sessions/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/host/sessions/__init__.py b/host/sessions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/host/sessions/__main__.py b/host/sessions/__main__.py new file mode 100644 index 0000000..8af0d75 --- /dev/null +++ b/host/sessions/__main__.py @@ -0,0 +1,9 @@ +import os + +import uvicorn + +from .app import create_app + +if __name__ == "__main__": + uvicorn.run(create_app(), host=os.getenv("OPENVOICE_HOST", "127.0.0.1"), + port=int(os.getenv("OPENVOICE_PORT", "8765")), access_log=False, log_level="warning") diff --git a/host/sessions/app.py b/host/sessions/app.py new file mode 100644 index 0000000..f8515d2 --- /dev/null +++ b/host/sessions/app.py @@ -0,0 +1,874 @@ +import asyncio +import hmac +import io +import json +import os +import time +import unicodedata +import uuid +import wave +from contextlib import AsyncExitStack, asynccontextmanager, contextmanager + +import httpx +from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect +from fastapi.responses import JSONResponse, Response, StreamingResponse +from starlette.datastructures import UploadFile +from starlette.exceptions import HTTPException + +from .. import router +from . import prompts, tools +from pathlib import Path + +from .options import Options, RespondRequest, TranslateRequest, Turn +from . import diarizer, speakers, vad as vad_module +from .mcp_tools import MCPTools + + +class Fault(Exception): + def __init__(self, status, code, message): + self.status = status + self.detail = dict(code=code, message=message, retryable=status >= 500 or status == 429) + + +DEMO = Path(__file__).resolve().parents[2] / "client" / "demo" / "index.html" + + +def invalid(): + return Fault(400, "bad_request", "Invalid request or options.") + + +def options(data): + if isinstance(data, dict) and data.get("mode", "polish") not in ("polish", "transcribe", "translate", "respond"): + raise Fault(400, "unsupported_option", "Unsupported mode.") + try: + opts = Options.model_validate(data) + except ValueError: + raise invalid() from None + if (opts.mode == "translate" and not opts.output_language) or ( + opts.output_language and (opts.mode not in ("translate", "respond") or opts.output_language not in prompts.LANGUAGES)): + raise Fault(400, "unsupported_option", "translate needs a supported output_language; respond may take one; other modes none.") + if not opts.request_id: + opts.request_id = uuid.uuid4().hex + return opts + + +def wav(pcm): + out = io.BytesIO() + with wave.open(out, "wb") as stream: + stream.setparams((1, 2, 16000, 0, "NONE", "")) + stream.writeframes(pcm) + return out.getvalue() + + +async def decode(source, seconds): + # Fast path: the contract's preferred format (PCM16, 16 kHz, mono WAV) needs no ffmpeg (~35 ms saved). + cap = seconds * 32000 + 65536 + data = await source.read(cap + 1) + try: + with wave.open(io.BytesIO(data)) as stream: + if stream.getparams()[:3] == (1, 2, 16000) and stream.getcomptype() == "NONE": + pcm = stream.readframes(stream.getnframes()) + if len(data) > cap or len(pcm) > seconds * 32000: + raise Fault(413, "audio_too_long", "Audio exceeds the configured duration.") + return pcm + except (wave.Error, EOFError): + pass + await source.seek(0) + # Only pipe input is permitted, including for nested FFmpeg protocols. + proc = await asyncio.create_subprocess_exec( + "ffmpeg", "-nostdin", "-v", "error", "-xerror", "-protocol_whitelist", "pipe", + "-i", "pipe:0", "-map", "0:a:0", "-t", str(seconds + 1), "-ac", "1", "-ar", + "16000", "-f", "s16le", "pipe:1", stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL) + async def feed(): + try: + while chunk := await source.read(65536): + proc.stdin.write(chunk) + await proc.stdin.drain() + except (BrokenPipeError, ConnectionResetError): + pass + finally: + proc.stdin.close() + + writer = asyncio.create_task(feed()) + try: + async with asyncio.timeout(max(30, seconds)): + pcm = await proc.stdout.read() + await proc.wait() + await writer + except TimeoutError: + raise Fault(415, "bad_audio", "Audio decoding timed out.") from None + finally: + if proc.returncode is None: + proc.kill() + await proc.stdout.read() + await proc.wait() + writer.cancel() + await asyncio.gather(writer, return_exceptions=True) + if len(pcm) > seconds * 32000: + raise Fault(413, "audio_too_long", "Audio exceeds the configured duration.") + if proc.returncode: + raise Fault(415, "bad_audio", "Cannot decode audio.") + return pcm + + +def spoken_by(text, speaker, tag="Speaker"): + """A turn as the model sees it in a labelled session: "[Speaker Ali] I like pizza", and its reply "[To Ali] ...". + With "Ali: ..." the model wrote lines for the other speaker and believed them; without the [To ...] tags on its own + replies it sometimes answered "I prefer sushi" as if it were the speaker.""" + return f"[{tag} {speaker.get('name') or speaker['id']}] {text}" if speaker else text + + +def create_app(transport=None, vad_factory=None, mcp=None, speaker_factory=None, speaker_embedder=None): + """vad_factory: makes one voice-activity scorer per listening session (tests inject a fake). + speaker_embedder: PCM -> voiceprint for voice enrolment (tests inject a fake; default: the speaker model). + mcp: MCP tools to offer in respond mode; by default the servers listed in the OPENVOICE_MCP file.""" + vad_factory = vad_factory or vad_module.SileroVAD + host = os.getenv("OPENVOICE_HOST", "127.0.0.1") + token = os.getenv("OPENVOICE_TOKEN", "") + if host != "127.0.0.1" and not token: + raise ValueError("Set OPENVOICE_TOKEN for a non-loopback listener.") + routes = router.load() + urls = {k: r.url for k, r in routes.items()} + models = {k: r.model for k, r in routes.items()} + # Respond-mode tools send their query off the device: opt-in only (Local First, AGENTS.md). + tools_on = os.getenv("OPENVOICE_TOOLS") == "1" + limit = int(os.getenv("OPENVOICE_MAX_AUDIO_SECONDS", "600")) + capacity = int(os.getenv("OPENVOICE_MAX_SESSIONS", "4")) + if min(limit, capacity) < 1: + raise ValueError("Duration and session limits must be positive.") + cache, pending = {}, {} + speaker_jobs = set() # Threads can finish after a client disconnects. + active = 0 + mcp_tools = mcp or MCPTools() + confirmations = {} # confirm id -> Future[bool], while an action waits for the user + + @asynccontextmanager + async def lifespan(app): + async with httpx.AsyncClient(transport=transport, timeout=60, trust_env=False) as client, AsyncExitStack() as stack: + app.state.client = client + if mcp is None and os.getenv("OPENVOICE_MCP"): + await mcp_tools.start(os.environ["OPENVOICE_MCP"], stack) + yield + cache.clear() + + app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) + + def auth(conn, query=False): + header = conn.headers.get("authorization", "") + supplied = header[7:] if header[:7].lower() == "bearer " else "" + if query and not supplied: + supplied = conn.query_params.get("token", "") + local = conn.scope.get("server", (None,))[0] == "127.0.0.1" + if (token and not hmac.compare_digest(supplied.encode(), token.encode())) or (not token and not local): + raise Fault(401, "unauthorized", "Bearer token required.") + # Without a token, only this host's own pages may call it: any web page the user opens can reach + # 127.0.0.1, and a rebound DNS name (evil.example -> 127.0.0.1) would look same-origin. + host, origin = conn.headers.get("host", ""), conn.headers.get("origin") + if not token and (host.rsplit(":", 1)[0] not in ("127.0.0.1", "localhost", "[::1]") + or origin is not None and origin.split("://", 1)[-1] != host): + raise Fault(403, "forbidden_origin", "Requests from other web pages need the host's token.") + + @contextmanager + def slot(): + nonlocal active + if active >= capacity: + raise Fault(429, "rate_limited", "Too many active sessions.") + active += 1 + try: + yield + finally: + active -= 1 + + @app.exception_handler(Fault) + async def failure(request, exc): + return JSONResponse({"error": exc.detail}, status_code=exc.status, + headers={"Retry-After": "1"} if exc.status == 429 else {}) + + @app.exception_handler(Exception) + async def internal(request, exc): + return JSONResponse({"error": Fault(500, "internal", "Host error.").detail}, status_code=500) + + @app.get("/demo") + async def demo(request: Request): + auth(request) # same rule as the API: open on 127.0.0.1, token elsewhere + return Response(DEMO.read_bytes(), media_type="text/html") + + @app.get("/v1/health") + async def health(request: Request): + auth(request) + async def probe(k): + try: + response = await app.state.client.get(urls[k] + "/v1/models", timeout=3) + response.raise_for_status() + return any(row["id"] == models[k] for row in response.json()["data"]) + except (httpx.HTTPError, KeyError, TypeError, ValueError): + return False + asr, llm = await asyncio.gather(probe("asr"), probe("llm")) + backends = {k: dict(ok=ok, model=models[k]) for k, ok in (("asr", asr), ("llm", llm))} + if "asr_fast" in urls: + backends["asr_fast"] = dict(ok=await probe("asr_fast"), model=models["asr_fast"]) + if (urls["mt"], models["mt"]) != (urls["llm"], models["llm"]): + backends["mt"] = dict(ok=await probe("mt"), model=models["mt"]) + return dict(status=("down" if not asr else "ok" if llm else "degraded"), version="0.1.0", backends=backends) + + @app.get("/v1/capabilities") + async def capabilities(request: Request): + auth(request) + return dict(contract="0.6", modes=["transcribe", "polish", "translate", "respond"], + listen=dict(available=vad_module.MODEL.is_file(), vad="silero", vad_models=["silero", "level"], + speakers=speaker_factory is not None or diarizer.available() or speakers.available(), + speaker_model=(diarizer.MODEL_ID if diarizer.available() else speakers.MODEL_ID + if speakers.available() else None)), + speeds=["accurate", "fast"] if "asr_fast" in urls else ["accurate"], + output_languages=sorted(prompts.LANGUAGES), tools=dict(enabled=tools_on, mcp=sorted(mcp_tools.tools)), languages=["auto", "en", "zh"], + streaming=dict(available=True, partials=False), max_audio_seconds=limit, + max_dictionary_terms=500, audio_formats=["wav", "pcm_s16le", "m4a", "webm", "mp3"]) + + async def translate(text, target, dictionary): + """Returns (translation, None) or (None, warning). Never raises for model trouble: callers keep the source.""" + try: + r = await app.state.client.post(urls["mt"] + "/v1/chat/completions", json={ + "model": models["mt"], "messages": prompts.translation(text, target, dictionary), + "temperature": 0, "max_tokens": 1024}) + r.raise_for_status() + choice = r.json()["choices"][0] + candidate = choice["message"]["content"] + if choice.get("finish_reason", "stop") != "stop" or not prompts.translated(text, candidate): + raise ValueError + return candidate.strip(), None + except (httpx.HTTPError, ValueError, IndexError, KeyError, TypeError): + return None, "translate_failed" + + async def respond(raw, opts, emit=None, speakers=False): + """Answers the spoken request (or rewrites the selected text), calling tools when it needs to. + The model is streamed: each piece of the answer is passed to `emit("delta", ...)` as it is written. + Returns (text or None, tool calls made).""" + can_ask, emit = emit is not None, emit or (lambda kind, data: asyncio.sleep(0)) + specs = (tools.SPECS if tools_on else []) + mcp_tools.specs + offered = {t["function"]["name"] for t in specs} + messages, calls = prompts.respond(raw, opts, actions=bool(mcp_tools.specs), speakers=speakers), [] + try: + for turn in range(3): # at most two tool rounds, then a final answer without tools + text, shown, pending, last = "", 0, {}, turn == 2 + async with app.state.client.stream("POST", urls["llm"] + "/v1/chat/completions", json={ + "model": models["llm"], "messages": messages, "temperature": 0, "max_tokens": 400, + "stream": True, **({"tools": specs} if specs and not last else {})}) as r: + r.raise_for_status() + async for line in r.aiter_lines(): + if not line.startswith("data: ") or line == "data: [DONE]": + continue + delta = json.loads(line[6:])["choices"][0].get("delta") or {} + if delta.get("content"): + # shortcut: drops Markdown bold the model still emits sometimes; a "*" split across pieces can slip through. + delta["content"] = delta["content"].replace("**", "") + text += delta["content"] + visible = prompts.untag(text) if speakers else text + if visible.strip() and len(visible) > shown: # hold back leading whitespace a tool call might follow + await emit("delta", dict(text=visible[shown:])) + shown = len(visible) + for part in delta.get("tool_calls") or []: + call = pending.setdefault(part.get("index", 0), dict(id="", name="", arguments="")) + call["id"] = part.get("id") or call["id"] + call["name"] += (part.get("function") or {}).get("name") or "" + call["arguments"] += (part.get("function") or {}).get("arguments") or "" + if last: + pending = {} + written = not last and not pending and prompts.text_call(text, {t["function"]["name"]: t["function"]["parameters"] for t in specs}) + if written: + pending, text = {0: dict(id="call-from-text", name=written[0], arguments=json.dumps(written[1]))}, "" + if not pending: + return prompts.tidy(prompts.untag(text) if speakers else text) or None, calls # deltas were a preview; final text is what to insert + messages.append({"role": "assistant", "content": text, "tool_calls": [ + {"id": c["id"], "type": "function", "function": {"name": c["name"], "arguments": c["arguments"]}} + for c in pending.values()]}) + for c in pending.values(): + try: + args = json.loads(c["arguments"] or "{}") + except ValueError: + args = {} + if c["name"] not in offered: # e.g. web_search written by the model with OPENVOICE_TOOLS unset + messages.append({"role": "tool", "tool_call_id": c["id"], + "content": f"There is no {c['name']} tool. Answer without it."}) + continue + approved = None + if c["name"] in mcp_tools and mcp_tools.needs_confirm(c["name"]): + approved = can_ask and await ask(emit, c["name"], args) + if approved is False: + result = ("The user declined this action; it was not done. Say so in a few words." if can_ask else + "Not done: this action needs the user's confirmation, which this request cannot ask " + "for. Tell the user to ask again in a live session.") + calls.append(dict(name=c["name"], arguments=args, ms=0, approved=False)) + messages.append({"role": "tool", "tool_call_id": c["id"], "content": result}) + continue + await emit("tool", dict(name=c["name"], arguments=args)) + t = time.monotonic() + result = await (mcp_tools.call(c["name"], args) if c["name"] in mcp_tools + else tools.run(app.state.client, c["name"], args)) + calls.append(dict(name=c["name"], arguments=args, ms=round((time.monotonic()-t)*1000), + **({} if approved is None else dict(approved=True)))) + messages.append({"role": "tool", "tool_call_id": c["id"], "content": result}) + except (httpx.HTTPError, ValueError, IndexError, KeyError, TypeError): + pass + return None, calls + + async def ask(emit, name, args, wait=60): + """Sends a `confirm` event and waits for POST /v1/confirm, a listen-session reply, or the timeout (= no).""" + cid = uuid.uuid4().hex + confirmations[cid] = answer = asyncio.get_running_loop().create_future() + try: + await emit("confirm", dict(id=cid, name=name, label=mcp_tools.label(name), arguments=args, timeout_s=wait)) + return await asyncio.wait_for(answer, wait) + except TimeoutError: + return False + finally: + confirmations.pop(cid, None) + + def resolve(cid, approve): + answer = confirmations.get(cid) + if answer is None or answer.done(): + return False + answer.set_result(bool(approve)) + return True + + async def clean(raw, opts): + """The clean-up model's edit of `raw`, or None when it fails or the guard rejects it.""" + try: + r = await app.state.client.post(urls["llm"] + "/v1/chat/completions", json={ + "model": models["llm"], "messages": prompts.messages(raw, opts), "temperature": 0}) + r.raise_for_status() + choice = r.json()["choices"][0] + candidate = choice["message"]["content"] + if choice.get("finish_reason", "stop") != "stop" or not prompts.accepted(raw, candidate, opts.dictionary): + return None + return candidate.strip() + except (httpx.HTTPError, ValueError, IndexError, KeyError, TypeError): + return None + + async def process(opts, pcm, start, decode_ms, emit=None, speaker=None): + """speaker: in a labelled listen session, returns this utterance's speaker label (or None) once the + transcript is out, so the model is told who is talking.""" + if opts.speed == "fast" and "asr_fast" not in urls: + raise Fault(400, "unsupported_option", "This host has no fast speech model.") + warnings, extra = [], {} + raw, text, language = "", "", opts.language + timings = dict(decode=decode_ms, asr=0, polish=0) + asr = "asr_fast" if opts.speed == "fast" else "asr" + used = {"asr": models[asr]} + if pcm and pcm.count(0) != len(pcm): + t = time.monotonic() + data = {"model": models[asr]} + if opts.language != "auto": + data["language"] = opts.language + if opts.dictionary: + data["prompt"] = ", ".join(item.term for item in opts.dictionary) + try: + r = await app.state.client.post(urls[asr] + "/v1/audio/transcriptions", data=data, + files={"file": ("audio.wav", wav(pcm), "audio/wav")}) + if r.status_code == 503: + raise Fault(503, "backend_unavailable", "Recognizer is unavailable.") + r.raise_for_status() + body = r.json() + raw = body["text"] + if not isinstance(raw, str): + raise ValueError + if "" in raw and raw.startswith("language "): + prefix, raw = raw.split("", 1) + language = {"English": "en", "Chinese": "zh"}.get(prefix[9:].strip(), language) + raw = raw.strip() + if isinstance(body.get("language"), str): + language = body["language"] + except httpx.RequestError: + raise Fault(503, "backend_unavailable", "Recognizer could not be reached.") from None + except (httpx.HTTPStatusError, ValueError, KeyError, TypeError): + raise Fault(502, "asr_failed", "Recognizer returned an invalid response.") from None + timings["asr"] = round((time.monotonic()-t)*1000) + if emit: + await emit("transcript", dict(raw=raw.strip(), language=language)) + if language == "auto": + warnings.append("language_uncertain") + text = raw + if opts.mode == "polish" and raw and not prompts.needs_polish(raw, opts): + warnings.append("polish_not_needed") # nothing for the model to fix: skip ~190 ms + elif opts.mode == "polish" and raw: + t = time.monotonic() + used["llm"] = models["llm"] + text = await clean(raw, opts) or raw + if text is raw: + warnings.append("polish_failed") + timings["polish"] = round((time.monotonic()-t)*1000) + elif opts.mode == "polish": + warnings.append("polish_skipped_empty") + if opts.mode == "respond" and raw: + t = time.monotonic() + used["llm"] = models["llm"] + text, calls = await respond(spoken_by(raw, speaker and speaker()), opts, emit, speakers=speaker is not None) + if text is None: + text = "" + warnings.append("respond_failed") + timings["respond"] = round((time.monotonic()-t)*1000) + extra["tool_calls"] = calls + if opts.mode == "translate" and raw: + # Translate the raw transcript, fillers aside: LLM polishing first risks answering or changing the language (T9). + t = time.monotonic() + used["mt"] = models["mt"] + source = prompts.unfill(raw) if opts.clean_up else raw + if opts.clean_up and prompts.corrected(source): # "2 p.m. No, 3 p.m.": translate only what was meant + used["llm"] = models["llm"] + source = await clean(source, opts) or source + translation, problem = await translate(source, opts.output_language, opts.dictionary) + text = translation or raw + if problem: + warnings.append(problem) + timings["translate"] = round((time.monotonic()-t)*1000) + timings["total"] = round((time.monotonic()-start)*1000) + return dict(request_id=opts.request_id, mode=opts.mode, raw=raw, text=text, language=language, + warnings=warnings, timings_ms=timings, models=used, **extra) + + async def finish(opts, audio, start): + key = opts.request_id + if key in cache: + return cache[key] + if key in pending: + await pending[key].wait() + return await finish(opts, audio, start) + done = pending[key] = asyncio.Event() + try: + t = time.monotonic() + if isinstance(audio, bytearray): + pcm = bytes(audio) + elif audio.size == 0: + pcm = b"" + else: + pcm = await decode(audio, limit) + result = await process(opts, pcm, start, round((time.monotonic()-t)*1000)) + cache[key] = result + asyncio.get_running_loop().call_later(600, cache.pop, key, None) + return result + finally: + pending.pop(key) + done.set() + + @app.post("/v1/translate") + async def translate_text(request: Request): + auth(request) + start = time.monotonic() + with slot(): + try: + req = TranslateRequest.model_validate_json(await request.body()) + except ValueError: + raise invalid() from None + if req.output_language not in prompts.LANGUAGES: + raise Fault(400, "unsupported_option", "Unsupported output_language.") + translation, problem = await translate(req.text, req.output_language, req.dictionary) + if problem: + raise Fault(502, "mt_failed", "The translation model returned no usable translation.") + ms = round((time.monotonic()-start)*1000) + return dict(request_id=req.request_id or uuid.uuid4().hex, source=req.text, text=translation, + output_language=req.output_language, warnings=[], timings_ms=dict(translate=ms, total=ms), + models=dict(mt=models["mt"])) + + def sse(work): + """Run `work(emit)` and stream its events as server-sent events; the last one is `final` or `error`.""" + async def events(): + queue = asyncio.Queue() + async def emit(kind, data): + await queue.put((kind, data)) + async def run(): + try: + with slot(): + await emit("final", await work(emit)) + except Fault as fault: + await emit("error", fault.detail) + except Exception: + await emit("error", Fault(500, "internal", "Host error.").detail) + task = asyncio.create_task(run()) + try: + while True: + kind, data = await queue.get() + yield f"event: {kind}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n" + if kind in ("final", "error"): + break + finally: + task.cancel() + return StreamingResponse(events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"}) + + @app.post("/v1/dictate") + async def dictate(request: Request, stream: bool = False): + auth(request) + start = time.monotonic() + if stream: + # The upload closes when the form does, so decode it now; recognition and the answer stream. + try: + with slot(): # the decode (ffmpeg, up to the audio limit) counts against the session limit too + async with request.form(max_files=1, max_fields=1) as form: + audio = form.get("audio") + if not isinstance(audio, UploadFile): + raise invalid() + opts = options(json.loads(form.get("options", "{}"))) + t = time.monotonic() + pcm = b"" if audio.size == 0 else await decode(audio, limit) + except (ValueError, TypeError, HTTPException): + raise invalid() from None + decode_ms = round((time.monotonic()-t)*1000) + return sse(lambda emit: process(opts, pcm, start, decode_ms, emit)) + with slot(): + try: + async with request.form(max_files=1, max_fields=1) as form: + audio = form.get("audio") + if not isinstance(audio, UploadFile): + raise invalid() + opts = options(json.loads(form.get("options", "{}"))) + return await finish(opts, audio, start) + except (ValueError, TypeError, HTTPException): + raise invalid() from None + + @app.post("/v1/respond") + async def respond_text(request: Request, stream: bool = False): + """Typed request or follow-up in respond mode: same answers and tools as speech, without audio.""" + auth(request) + try: + req = RespondRequest.model_validate_json(await request.body()) + except ValueError: + raise invalid() from None + opts = options(dict(mode="respond", request_id=req.request_id, output_language=req.output_language, + history=[t.model_dump() for t in req.history], context=req.context.model_dump())) + async def work(emit=None): + start = time.monotonic() + text, calls = await respond(req.text, opts, emit) + return dict(request_id=opts.request_id, mode="respond", raw=req.text, text=text or "", + warnings=[] if text else ["respond_failed"], tool_calls=calls, + timings_ms=dict(respond=round((time.monotonic()-start)*1000)), models=dict(llm=models["llm"])) + if stream: + return sse(work) + with slot(): + return await work() + + store_lock = asyncio.Lock() + + def speakers_on(): + if speaker_factory is None and speaker_embedder is None and not speakers.available(): + raise Fault(400, "unsupported_option", "Speaker labels are unavailable.") + + @app.post("/v1/speakers") + async def enrol(request: Request): + """Enrol a voice by name: about 10 s of the person's own speech, with their consent. Only the voiceprint is + kept (in the local store); the audio is discarded. Labels are advisory and never authorise anything.""" + auth(request) + speakers_on() + try: + async with request.form(max_files=1, max_fields=2) as form: + audio, name = form.get("audio"), str(form.get("name", "")).strip() + if not isinstance(audio, UploadFile) or form.get("consent") != "true": + raise invalid() + if not 1 <= len(name) <= 64 or any(unicodedata.category(c)[0] == "C" for c in name): + raise invalid() + pcm = await decode(audio, 60) + except (ValueError, TypeError, HTTPException): + raise invalid() from None + vad, size = vad_factory(), vad_module.CHUNK_BYTES + speech = b"".join(c for c in (pcm[i:i + size] for i in range(0, len(pcm) - size + 1, size)) if vad(c) >= 0.35) + if len(speech) < speakers.ENROL_BYTES: + raise Fault(400, "too_little_speech", "Need about 10 s of speech from one person; record a little longer.") + embed = speaker_embedder or speakers.load_embedder() + try: + vector = await asyncio.to_thread(speakers.enrol_vector, embed, speech) + async with store_lock: + voices = speakers.read_store() + voices[name] = vector.tolist() # re-enrolling a name replaces it + speakers.write_store(voices) + except ValueError as exc: + raise Fault(409 if "another speaker model" in str(exc) else 400, "enrolment_failed", str(exc)) from None + return dict(id=name, name=name) + + @app.get("/v1/speakers") + async def enrolled(request: Request): + auth(request) + speakers_on() + try: + names = list(speakers.read_store()) + except ValueError as exc: + raise Fault(409, "enrolment_failed", str(exc)) from None + return dict(model=speakers.MODEL_ID, speakers=[dict(id=n, name=n) for n in names]) + + @app.delete("/v1/speakers/{speaker_id:path}") # names may hold "/"; a voiceprint must always be deletable + async def unenrol(request: Request, speaker_id: str): + auth(request) + speakers_on() + async with store_lock: + try: + voices = speakers.read_store() + except ValueError as exc: + raise Fault(409, "enrolment_failed", str(exc)) from None + if voices.pop(speaker_id, None) is None: + raise Fault(404, "not_found", "No voice is enrolled under that id.") + speakers.write_store(voices) + return dict(id=speaker_id, deleted=True) + + @app.post("/v1/confirm") + async def confirm(request: Request): + """Answer to a `confirm` event: {"id": ..., "approve": true|false}.""" + auth(request) + try: + body = json.loads(await request.body()) + cid, approve = body["id"], body["approve"] + if not isinstance(cid, str) or not isinstance(approve, bool): + raise ValueError + except (ValueError, KeyError, TypeError): + raise invalid() from None + if not resolve(cid, approve): + raise Fault(404, "not_found", "No action is waiting for that id.") + return dict(id=cid, approve=approve) + + @app.websocket("/v1/dictate/stream") + async def stream(ws: WebSocket): + await ws.accept() + try: + auth(ws, query=True) + with slot(): + async with asyncio.timeout(30): + first = await ws.receive() + if first["type"] == "websocket.disconnect": + return + msg = json.loads(first.get("text") or "null") + if not isinstance(msg, dict) or msg.get("type") != "start" or msg.get("audio") != dict( + encoding="pcm_s16le", sample_rate=16000, channels=1): + raise invalid() + opts = options(msg.get("options", {})) + await ws.send_json(dict(type="ready", request_id=opts.request_id)) + pcm = bytearray() + while True: + frame = await asyncio.wait_for(ws.receive(), timeout=30) + if frame["type"] == "websocket.disconnect": + return + chunk = frame.get("bytes") + if chunk is not None: + if not 640 <= len(chunk) <= 6400 or len(chunk) % 2: + raise invalid() + if len(pcm) + len(chunk) > limit * 32000: + raise Fault(413, "audio_too_long", "Audio exceeds the configured duration.") + pcm.extend(chunk) + continue + msg = json.loads(frame.get("text") or "null") + if msg == {"type": "cancel"}: + await ws.send_json(dict(type="cancelled")) + elif msg == {"type": "stop"}: + result = await finish(opts, pcm, time.monotonic()) + await ws.send_json(dict(type="final", result=result)) + else: + raise invalid() + await ws.close() + return + except WebSocketDisconnect: + return + except Exception as exc: + await ws_fail(ws, exc) + + @app.websocket("/v1/listen") + async def listen(ws: WebSocket): + """Hands-free session: the client streams the microphone; the host finds utterances with a VAD model, + sends live partial text while the user speaks, and processes each utterance in the chosen mode. + In respond mode the session keeps the conversation, so each utterance is a follow-up.""" + await ws.accept() + lock, queue, tasks, closers = asyncio.Lock(), asyncio.Queue(), [], [] + + waiting = [None] # id of the action this session was last asked to confirm + + async def send(event): + if event.get("type") == "confirm": + waiting[0] = event["id"] + async with lock: + await ws.send_json(event) + + try: + auth(ws, query=True) + with slot(): + async with asyncio.timeout(30): + first = await ws.receive() + if first["type"] == "websocket.disconnect": + return + msg = json.loads(first.get("text") or "null") + if not isinstance(msg, dict) or msg.get("type") != "start" or msg.get("audio") != dict( + encoding="pcm_s16le", sample_rate=16000, channels=1): + raise invalid() + opts = options(msg.get("options", {})) + tuning = msg.get("vad") or {} + end_ms = tuning.get("end_silence_ms", 512) + if not isinstance(end_ms, int) or not 200 <= end_ms <= 2000: + raise invalid() + partials = tuning.get("partials", True) is not False + if tuning.get("model", "silero") not in ("silero", "level"): + raise invalid() + vad = vad_module.LevelVAD() if tuning.get("model") == "level" else vad_factory() + seg = vad_module.Segmenter(end_chunks=max(1, end_ms // 32)) + enabled = msg.get("speakers", False) + if not isinstance(enabled, bool): + raise invalid() + speaker_session = None + if enabled: + if speaker_factory is None and not (diarizer.available() or speakers.available()): + raise Fault(400, "unsupported_option", "Speaker labels are unavailable.") + # The streaming diarizer when installed (stable labels for whole meetings, overlap); else CAM++. + factory = speaker_factory or (lambda: diarizer.DiarSession(diarizer.load()) if diarizer.available() + else speakers.SpeakerSession(speakers.load_embedder())) + speaker_session = await asyncio.to_thread(factory) + if hasattr(speaker_session, "close"): + closers.append(speaker_session.close) + streaming = hasattr(speaker_session, "feed") # hears all audio; labels by time span + fed = 0 # 32 ms pieces this session has heard + previous_job = None + + def start_label(pcm, trailing_s=end_ms / 1000): + nonlocal previous_job + if (speaker_session is None or len(speaker_jobs) >= capacity + or (not streaming and previous_job is not None and not previous_job.done())): + return None + end = fed * vad_module.CHUNK_BYTES / 32000 + span = (end - len(pcm) / 32000, end - trailing_s) # trailing_s: the silence that ended it + def label(): + try: + return {"speaker": speaker_session.label(pcm, span) if streaming else speaker_session.label(pcm)} + except Exception: + return {} # Optional labelling must never discard a transcript. + previous_job = asyncio.get_running_loop().run_in_executor(None, label) + speaker_jobs.add(previous_job) + previous_job.add_done_callback(speaker_jobs.discard) + return previous_job + + async def speaker_fields(job): + if job is not None: + done, _ = await asyncio.wait([job], timeout=getattr(speaker_session, "wait_s", 0) + 0.045) + if done: + return job.result() + return {} + + history = list(opts.history) + partial_route = dict(speed="fast") if "asr_fast" in urls else {} + await send(dict(type="ready", request_id=opts.request_id)) + + async def utterances(): + while (item := await queue.get()) is not None: + n, pcm, job = item + fields = {} + start = time.monotonic() + async def emit(kind, data, n=n): + if kind == "transcript": + fields.update(await speaker_fields(job)) + data.update(fields) + await send(dict(type=kind, utterance=n, **data)) + u = opts.model_copy(update=dict(history=history[-20:], request_id=f"{opts.request_id}-{n}")) + try: + result = await process(u, pcm, start, 0, emit, + speaker=(lambda: fields.get("speaker")) if speaker_session else None) + except Fault as fault: + await send(dict(type="error", utterance=n, error=fault.detail)) + continue + await send(dict(type="final", utterance=n, result=result, **fields)) + if opts.mode == "respond" and result["raw"] and result["text"]: + history.extend([Turn(role="user", content=spoken_by(result["raw"], fields.get("speaker"))[:8000]), + Turn(role="assistant", content=spoken_by(result["text"], fields.get("speaker"), "To")[:8000])]) + + async def reply(n, pcm, job): + """An utterance while an action waits: a yes or no answers it; anything else declines it and + is processed as a new request.""" + p = opts.model_copy(update=dict(mode="transcribe", output_language="", **partial_route)) + try: + heard = (await process(p, pcm, time.monotonic(), 0))["raw"] + except Fault: + heard = "" + said = prompts.yes_or_no(heard) + resolve(waiting[0], said is True) + if said is None: + await queue.put((n, pcm, job)) + else: + await send(dict(type="transcript", utterance=n, raw=heard, answer="yes" if said else "no", + **await speaker_fields(job))) + + async def partial(n, pcm): + p = opts.model_copy(update=dict(mode="transcribe", output_language="", **partial_route)) + try: + result = await process(p, pcm, time.monotonic(), 0) + if result["raw"] and seg.active and current[0] == n: + await send(dict(type="partial", utterance=n, text=result["raw"])) + except Fault: + pass # a missed partial is harmless; the final transcript follows + + worker = asyncio.create_task(utterances()) + tasks.append(worker) + buf, current, last_partial, partial_task = bytearray(), [0], 0, None + while True: + frame = await asyncio.wait_for(ws.receive(), timeout=30) + if frame["type"] == "websocket.disconnect": + return + chunk = frame.get("bytes") + if chunk is None: + msg = json.loads(frame.get("text") or "null") + if isinstance(msg, dict) and msg.get("type") == "confirm": + resolve(msg.get("id"), msg.get("approve") is True) + continue + if msg == {"type": "reset"}: + history.clear() + await send(dict(type="reset")) + continue + if msg != {"type": "stop"}: + raise invalid() + event = seg.flush() + if event and event[0] == "end": + await send(dict(type="speech_end", utterance=current[0])) + await queue.put((current[0], event[1], start_label(event[1], 0))) + await queue.put(None) + await worker + await send(dict(type="done")) + await ws.close() + return + if len(chunk) % 2 or len(chunk) > 64000: + raise invalid() + buf.extend(chunk) + while len(buf) >= vad_module.CHUNK_BYTES: + piece = bytes(buf[:vad_module.CHUNK_BYTES]) + del buf[:vad_module.CHUNK_BYTES] + if streaming: + speaker_session.feed(piece) + fed += 1 + event = seg.feed(piece, vad(piece)) + if event and event[0] == "start": + current[0] += 1 + last_partial = 0 + await send(dict(type="speech_start", utterance=current[0])) + elif event and event[0] in ("end", "drop"): + if partial_task: + partial_task.cancel() + await send(dict(type="speech_end" if event[0] == "end" else "speech_dropped", utterance=current[0])) + if event[0] == "end" and waiting[0] in confirmations: + tasks.append(asyncio.create_task(reply(current[0], event[1], start_label(event[1])))) + elif event[0] == "end": + await queue.put((current[0], event[1], start_label(event[1]))) + elif seg.active and partials: + heard = len(seg.audio()) + if heard - last_partial >= 19200 and not (partial_task and not partial_task.done()): + last_partial = heard # about every 0.6 s of new speech, one at a time + partial_task = asyncio.create_task(partial(current[0], seg.audio())) + tasks.append(partial_task) + except WebSocketDisconnect: + return + except Exception as exc: + await ws_fail(ws, exc) + finally: + for task in tasks: + task.cancel() + for close in closers: + close() + + async def ws_fail(ws, exc): + if isinstance(exc, Fault): + fault = exc + elif isinstance(exc, (TimeoutError, ValueError, TypeError)): + fault = invalid() + else: + fault = Fault(500, "internal", "Host error.") + try: + await ws.send_json(dict(type="error", error=fault.detail)) + await ws.close(code=1011 if fault.status >= 500 else 1008) + except (RuntimeError, WebSocketDisconnect): + pass # the client is already gone + return app diff --git a/host/sessions/diarizer.py b/host/sessions/diarizer.py new file mode 100644 index 0000000..48a2119 --- /dev/null +++ b/host/sessions/diarizer.py @@ -0,0 +1,173 @@ +"""Optional live speaker labels from NVIDIA's Nemotron-3-Diarization, streamed through NeMo-Speech.cpp's C library. + +Unlike CAM++ (one voiceprint per finished sentence), the diarizer hears the whole session: every 32 ms of audio +is pushed into one stream, and a sentence's label is read from the speakers it found over that sentence's time. +It keeps people apart for a whole meeting and also reports a second person talking over the first. +Labels trail the audio by 0.1-1.1 s (steps of ~1 s of audio, ~0.15 s CPU each), so a label is ready about when +the end-of-sentence pause is over. No enrolment: speakers are S1..S8 in order of appearance. + +Needs OPENVOICE_DIAR_LIB (libnemo_speech_asr_c dylib from the NeMo-Speech.cpp release) and OPENVOICE_DIAR_MODEL +(Nemotron-3-Diarization.q8_0.gguf, SHA-256 checked). +""" +import ctypes as C +import hashlib +import os +import queue +import threading +import time +from functools import lru_cache +from pathlib import Path + +import numpy as np + +MODEL_ID = "nemotron-3-diarization-q8_0" +MODEL_SHA256 = "08456d9e22cd9a323c0364d98375f3746d6e68507ebb705cd46438c534c7a3a1" +WAIT_S = 1.5 # longest a sentence waits for its label: measured lag max 1.12 s + one 0.16 s model step +ALSO_S = 0.3 # someone else counts as "also speaking" after this much talk inside the sentence... +ALSO_SHARE = 0.15 # ...and this share of it + + +def available(): + lib, model = os.getenv("OPENVOICE_DIAR_LIB"), os.getenv("OPENVOICE_DIAR_MODEL") + return bool(lib and model and Path(lib).is_file() and Path(model).is_file()) + + +def pick(segments, start, end): + """The label for [start, end) from (begin, end, speaker) segments: who spoke most, and who else spoke enough.""" + talk = {} + for a, b, s in segments: + overlap = min(b, end) - max(a, start) + if overlap > 0: + talk[s] = talk.get(s, 0.0) + overlap + if not talk: + return None + main = max(talk, key=talk.get) + total = sum(talk.values()) + label = {"id": f"S{main}", "score": round(talk[main] / total, 3)} + also = [f"S{s}" for s in sorted(talk) if s != main and talk[s] >= max(ALSO_S, ALSO_SHARE * (end - start))] + if also: + label["also"] = also + return label + + +class _Cfg(C.Structure): + _fields_ = [("size", C.c_size_t), ("model_path", C.c_char_p), ("gpu", C.c_int32), ("preset", C.c_char_p), + ("chunk_frames", C.c_int32), ("right_context_frames", C.c_int32), ("left_context_frames", C.c_int32), + ("fifo_frames", C.c_int32), ("spkcache_frames", C.c_int32), ("update_period_frames", C.c_int32)] + + +class _Seg(C.Structure): + _fields_ = [("start_time", C.c_double), ("end_time", C.c_double), ("speaker", C.c_int32)] + + +class _Model: + """One loaded diarizer, shared by sessions (the library serialises compute internally).""" + + def __init__(self, lib_path, model_path): + lib = C.CDLL(lib_path) + lib.nemo_speech_diar_frame_count.restype = C.c_int64 + lib.nemo_speech_diar_seconds_per_frame.restype = C.c_double + lib.nemo_speech_asr_last_error.restype = C.c_char_p + self.lib = lib + cfg = _Cfg(size=C.sizeof(_Cfg), model_path=str(model_path).encode(), gpu=-1, preset=None, left_context_frames=-1) + self.handle = C.c_void_p() + self.check(lib.nemo_speech_diar_create(C.byref(cfg), C.byref(self.handle))) + self.seconds_per_frame = lib.nemo_speech_diar_seconds_per_frame(self.handle) + + def check(self, status): + if status: + raise RuntimeError(f"diarizer: {self.lib.nemo_speech_asr_last_error()!r}") + + +@lru_cache(maxsize=1) +def _load(lib_path, model_path): + digest = hashlib.sha256() + with open(model_path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + digest.update(block) + if digest.hexdigest() != MODEL_SHA256: + raise ValueError("Diarization checkpoint does not match the measured model") + return _Model(lib_path, model_path) + + +def load(): + return _load(os.environ["OPENVOICE_DIAR_LIB"], os.environ["OPENVOICE_DIAR_MODEL"]) + + +class DiarSession: + """One listen session's stream. feed() never blocks; label() waits until the sentence is labelled. + The C stream is single-threaded by contract, so every call on it happens on this session's own thread.""" + + wait_s = WAIT_S + + def __init__(self, model): + self.model, self.jobs, self.dead = model, queue.Queue(), False + self.stream = C.c_void_p() + model.check(model.lib.nemo_speech_diar_stream_open(model.handle, C.byref(self.stream))) + self.thread = threading.Thread(target=self._run, daemon=True, name="diarizer") + self.thread.start() + + def feed(self, pcm): + if not self.dead: # nobody reads the queue once the thread has died + self.jobs.put(pcm) + + def label(self, pcm, span=None): + """span: (start, speech end) in session seconds. Returns {"id", "score", "also"?} or raises ValueError.""" + if span is None: + raise ValueError("The diarizer needs the sentence's time span") + if self.dead: + raise ValueError("The diarizer stopped") + done = threading.Event() + box = {} + self.jobs.put((span, done, box)) + if not done.wait(self.wait_s + 0.5): + raise ValueError("Diarizer fell behind") + if box.get("label") is None: + raise ValueError("No speaker found in this sentence") + return box["label"] + + def close(self): + self.jobs.put(None) + + def _run(self): + lib, pending = self.model.lib, [] + try: + while True: + try: + job = self.jobs.get(timeout=0.05) + except queue.Empty: + job = () + if job is None: + break + if isinstance(job, bytes): + x = np.frombuffer(job, "= span[1] or now - asked >= self.wait_s: + box["label"] = pick(self._segments(), *span) + done.set() + else: + keep.append((asked, span, done, box)) + pending = keep + finally: + self.dead = True + while not self.jobs.empty(): # free the memory and any label() that is still waiting + job = self.jobs.get_nowait() + if isinstance(job, tuple) and job: + pending.append((0, *job)) + for _, _, done, _ in pending: + done.set() + lib.nemo_speech_diar_stream_close(self.stream) + + def _segments(self): + lib, n = self.model.lib, C.c_size_t() + self.model.check(lib.nemo_speech_diar_segments(self.stream, None, None, 0, C.byref(n))) + buf = (_Seg * max(n.value, 1))() + self.model.check(lib.nemo_speech_diar_segments(self.stream, None, buf, n.value, C.byref(n))) + return [(s.start_time, s.end_time, s.speaker) for s in buf[:n.value]] diff --git a/host/sessions/mcp_tools.py b/host/sessions/mcp_tools.py new file mode 100644 index 0000000..3b3172f --- /dev/null +++ b/host/sessions/mcp_tools.py @@ -0,0 +1,89 @@ +"""MCP servers as respond-mode tools: the host is an MCP client, and every server's tools are offered to the model. + +OPENVOICE_MCP names a JSON file in the common `mcpServers` format (see host/mcp.example.json): + {"mcpServers": {"mac": {"command": "python", "args": ["-m", "host.mcp_servers.mac"]}, + "docs": {"url": "http://127.0.0.1:9000/mcp"}}} +Optional per server: "confirm": "auto" (default: ask the user unless the tool declares readOnlyHint) or "always". +There is no "never": a tool that changes anything must ask the user first. +A server that fails to start is skipped with a warning; the host still runs. +""" +import json +import logging +import re +import sys +from contextlib import AsyncExitStack + +log = logging.getLogger("openvoice.mcp") +RESULT_CHARS = 4000 # tool output fed back to a 4B model; longer results crowd out the conversation + + +class MCPTools: + def __init__(self): + self.specs, self.tools = [], {} # tools: model-facing name -> (session, server, tool name, confirm?) + + async def start(self, path, stack: AsyncExitStack): + from mcp import ClientSession, StdioServerParameters + from mcp.client.stdio import stdio_client + from mcp.client.streamable_http import streamablehttp_client + with open(path, encoding="utf-8") as f: + servers = json.load(f).get("mcpServers", {}) + for server, cfg in servers.items(): + try: + if cfg.get("url"): + read, write, _ = await stack.enter_async_context(streamablehttp_client(cfg["url"], headers=cfg.get("headers"))) + else: + # "python" means the host's own interpreter, so example servers find the mcp package. + command = sys.executable if cfg["command"] in ("python", "python3") else cfg["command"] + params = StdioServerParameters(command=command, args=cfg.get("args", []), env=cfg.get("env"), cwd=cfg.get("cwd")) + read, write = await stack.enter_async_context(stdio_client(params)) + session = await stack.enter_async_context(ClientSession(read, write)) + await session.initialize() + listed = (await session.list_tools()).tools + except Exception as exc: # one bad server must not take the host down + log.warning("MCP server %s skipped: %s", server, exc) + continue + policy = cfg.get("confirm", "auto") + if policy not in ("auto", "always"): + log.warning("MCP server %s: confirm %r is not supported; using \"auto\"", server, policy) + for tool in listed: + read_only = bool(tool.annotations and tool.annotations.readOnlyHint) + confirm = policy == "always" or not read_only + self.add(server, tool.name, tool.description or "", tool.inputSchema, session, confirm) + log.info("MCP server %s: %d tools", server, len(listed)) + + def add(self, server, tool, description, schema, session, confirm): + # Plain tool names unless two servers clash: Qwen3-4B wrote "mac__open_url" calls out as text (eval t04). + clean = lambda s: re.sub(r"[^A-Za-z0-9_-]", "_", s)[:64] + # Checked on the cleaned name: "open.url" and "open_url" must not replace each other (or each other's confirm). + name = base = clean(tool) if clean(tool) not in self.tools else clean(f"{server}__{tool}") + n = 2 + while name in self.tools: + name, n = f"{base[:60]}_{n}", n + 1 + self.tools[name] = (session, server, tool, confirm) + self.specs.append({"type": "function", "function": { + "name": name, "description": description[:1000] or tool, + "parameters": schema or {"type": "object", "properties": {}}}}) + + def __contains__(self, name): + return name in self.tools + + def needs_confirm(self, name): + return self.tools[name][3] + + def label(self, name): + return f"{self.tools[name][1]}: {self.tools[name][2]}" + + async def call(self, name, args): + session, server, tool, action = self.tools[name] + try: + result = await session.call_tool(tool, args) + except Exception as exc: + log.warning("MCP %s.%s%s failed: %r", server, tool, args, exc) + return f"The {tool} tool failed ({type(exc).__name__}). Tell the user it did not work." + text = "\n".join(getattr(part, "text", "") or f"[{part.type}]" for part in result.content) + if result.isError: + log.warning("MCP %s.%s%s returned an error: %s", server, tool, args, text[:300]) + return f"The {tool} tool reported an error: {text[:500]}. Tell the user it did not work." + if action: # a bare "Reminder added: ..." made Qwen3-4B repeat the user's request instead of confirming it + return f"Done. {text[:RESULT_CHARS]} Tell the user in one short sentence what was done." + return text[:RESULT_CHARS] or "Done." diff --git a/host/sessions/models/LICENSE-silero-vad b/host/sessions/models/LICENSE-silero-vad new file mode 100644 index 0000000..0bf5e90 --- /dev/null +++ b/host/sessions/models/LICENSE-silero-vad @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-present Silero Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/host/sessions/models/README.md b/host/sessions/models/README.md new file mode 100644 index 0000000..c5c221c --- /dev/null +++ b/host/sessions/models/README.md @@ -0,0 +1,6 @@ +# Bundled models + +- `silero_vad_16k_op15.onnx`: Silero VAD (MIT, `LICENSE-silero-vad`), from snakers4/silero-vad at commit + `446da2ad95fc90d67a3b12e12ea3f5410b9b3ec4` (`src/silero_vad/data/`). + SHA-256 `59892301a48e373121ff29ef512598b4e5ff7ebba1a461e05d490fb3c21b354b`. + Bundled (1.25 MB) so listening needs no download (Local First). diff --git a/host/sessions/models/silero_vad_16k_op15.onnx b/host/sessions/models/silero_vad_16k_op15.onnx new file mode 100644 index 0000000..5c410bd Binary files /dev/null and b/host/sessions/models/silero_vad_16k_op15.onnx differ diff --git a/host/sessions/options.py b/host/sessions/options.py new file mode 100644 index 0000000..60fffc5 --- /dev/null +++ b/host/sessions/options.py @@ -0,0 +1,59 @@ +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field, StringConstraints + + +class Fields(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +TermText = Annotated[str, StringConstraints(max_length=100)] + + +class Term(Fields): + term: TermText + aliases: list[TermText] = Field(default_factory=list, max_length=10) + + +class Context(Fields): + app_id: str = "" + app_name: str = "" + field_kind: Literal["chat", "email", "document", "code", "search", "terminal", "other"] = "other" + text_before: str = Field(default="", max_length=2000) + selected_text: str = Field(default="", max_length=8000) + url_host: str = Field(default="", pattern=r"^[^/\s?#@]*$") + + +class Turn(Fields): + role: Literal["user", "assistant"] + content: str = Field(max_length=8000) + + +class Options(Fields): + request_id: str = Field(default="", max_length=64) + mode: Literal["transcribe", "polish", "translate", "respond"] = "polish" + language: str = Field(default="auto", pattern=r"^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$") + output_language: str = Field(default="", pattern=r"^([a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*)?$") + style: Literal["as_is", "casual", "neutral", "formal"] = "neutral" + clean_up: bool = True # translate: drop um, uh, 呃, 嗯 and resolve "2 p.m. No, 3 p.m." before translating + speed: Literal["accurate", "fast"] = "accurate" # fast: the 4-bit speech model, when the host has one + history: list[Turn] = Field(default_factory=list, max_length=20) # respond: earlier turns, for follow-ups + instructions: str = Field(default="", max_length=2000) + dictionary: list[Term] = Field(default_factory=list, max_length=500) + context: Context = Field(default_factory=Context) + + +class TranslateRequest(Fields): + request_id: str = Field(default="", max_length=64) + text: str = Field(min_length=1, max_length=8000) + output_language: str = Field(pattern=r"^[a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*$") + dictionary: list[Term] = Field(default_factory=list, max_length=500) + + +class RespondRequest(Fields): + """A typed request or follow-up for respond mode (no audio).""" + request_id: str = Field(default="", max_length=64) + text: str = Field(min_length=1, max_length=8000) + output_language: str = Field(default="", pattern=r"^([a-zA-Z]{2,8}(-[a-zA-Z0-9]{1,8})*)?$") + history: list[Turn] = Field(default_factory=list, max_length=20) + context: Context = Field(default_factory=Context) diff --git a/host/sessions/prompts/LICENSE-Voxt b/host/sessions/prompts/LICENSE-Voxt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/host/sessions/prompts/LICENSE-Voxt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/host/sessions/prompts/NOTICE b/host/sessions/prompts/NOTICE new file mode 100644 index 0000000..1d99523 --- /dev/null +++ b/host/sessions/prompts/NOTICE @@ -0,0 +1,13 @@ +The OpenVoice cleanup prompt adapts the editing rules in VoxtNew's +internal/compose/templates/en/cleanup.txt. OpenVoice rewrote the instructions +for a JSON transcript envelope, added bilingual examples and specified how to +handle dictated questions and commands. + +VoxtNew +Copyright 2026 ActNow (https://actnow.dev) and the SGLang-Omni Team. +Licensed under the Apache License 2.0 (LICENSE-Voxt). +Source: https://github.com/sgl-project/sglang-omni/blob/f494d63a5d2651e25454d67ba7f402039c5e8cfa/Voxt/internal/compose/templates/en/cleanup.txt +Upstream notices: https://github.com/sgl-project/sglang-omni/blob/f494d63a5d2651e25454d67ba7f402039c5e8cfa/Voxt/NOTICE + +The ASCEND transcript excerpts quoted in host/eval/README.md derive from ASCEND +(Holy Lovenia et al., LREC 2022, CAiRE/ASCEND on Hugging Face), CC BY-SA 4.0. diff --git a/host/sessions/prompts/__init__.py b/host/sessions/prompts/__init__.py new file mode 100644 index 0000000..75e38fa --- /dev/null +++ b/host/sessions/prompts/__init__.py @@ -0,0 +1,273 @@ +"""Polish messages and the host's raw-text fallback policy.""" +import json +import re +from collections import Counter +import unicodedata +from datetime import datetime +from difflib import SequenceMatcher +from pathlib import Path + +BASE = ("Copyedit dictated speech. Preserve meaning and language. Return only the edited " + "transcript. Preserve questions as questions. Never answer them.") +POLICY = Path(__file__).with_name("cleanup.txt") +QUESTION = re.compile( + r"\b(?:who|what|where|when|why|how|which)\b|" + r"^(?:do|does|did|can|could|should|would|will|is|are|was|were|have|has)\b|" + r"[??]|[吗嗎么麼呢]|什么|為什麼|怎么|怎樣|如何|是不是|会不会|會不會", re.I) + + +# Fillers and stutters the clean-up model removes. Qwen3-ASR already punctuates and capitalises, so an +# utterance with none of these is sent as recognised and the model is skipped (~190 ms, T17). +DISFLUENCY = re.compile( + r"\b(?:um+|uh+|ah+|erm+|hmm+|you know|i mean)\b|[呃嗯额唉诶欸]|那个|就是说|(?:^|[,,。])\s*就是" + r"|\b(\w+(?:\W+\w+){0,2})\W+\1\b" # repeated 1-3 words: "I I", "I don't, I don't" + r"|([\u4e00-\u9fff]{1,3})\2" # repeated Han run: 专业专业, 的的 (also 谢谢: polish just runs) + r"|([\u4e00-\u9fff]{2,4})[,,]\s*\3", # repeated across a comma: 我这个,我这个 + re.I) + + +# Words a spoken self-correction may use ("2 p.m. No, 3 p.m.", "John, I mean Jake", "七点,不对,八点"), anywhere and with or +# without punctuation: live ASR often drops it. A look-alike ("there's no milk") only costs one clean-up call (~0.2 s); +# the model leaves it as it is, and the guard below only lets a correction delete words. +CORRECTION = re.compile(r"\b(?:no|nope|not|sorry|actually|wait|i mean|rather|make it|make that|scratch that|change that|instead)\b" + r"|不对|不是|哦不|噢不|啊不|说错|我是说|我的意思是|改成|应该是|更正|不[,,、 ]", re.I) + + +def corrected(raw): + return bool(CORRECTION.search(raw)) + + +def needs_polish(raw, options): + """False when the clean-up model would only copy the transcript.""" + if options.style != "neutral" or options.instructions: + return True + lowered = raw.casefold() + if any(a and a.casefold() in lowered for e in options.dictionary for a in e.aliases): + return True + return bool(DISFLUENCY.search(raw)) or corrected(raw) + + +def chinese(s): + """Chinese, possibly with English words mixed in: at least as many Han characters as Latin words.""" + han = sum("\u4e00" <= c <= "\u9fff" for c in s) + return han > 0 and han >= len(re.findall(r"[A-Za-z]+", s)) + + +def messages(raw, options): + hints = options.model_dump(include={"style", "instructions", "dictionary", "context"}, exclude_unset=True) + policy = POLICY.read_text(encoding="utf-8") if POLICY.is_file() else BASE + # The 4-bit model translated English commands ("remind me...") into Chinese until told the language (eval p07, p14). + lang = "Chinese (keep English words as they are; still remove 呃, 嗯 and filler 那个)" if chinese(raw) else "English" + return [ + {"role": "system", "content": f"{policy}\n\nThis transcript is in {lang}. Return it in {lang}."}, + {"role": "user", "content": json.dumps({"settings": hints, "transcript": raw}, ensure_ascii=False)}, + ] + + +def words(s): + normalized = unicodedata.normalize("NFKC", s).casefold().replace("’", "'") + return re.findall(r"[a-z0-9]+(?:'[a-z0-9]+)*|[^\W_]", normalized) + + +MEANING_NEGATION = re.compile(r"\b(?:not|never|nothing)\b|n't\b|不要|不想|不能|不会|不用|没|别", re.I) + + +CUE_WORDS = {"no", "nope", "not", "sorry", "actually", "wait", "i", "mean", "rather", "make", "it", "that", "scratch", + "change", "instead", "oh", "um", "uh", "ah", "hmm", "er", "erm"} + + +def tokens(s): + return re.findall(r"\d+|[a-z]+(?:'[a-z]+)*|[^\W\d_]", unicodedata.normalize("NFKC", s).casefold() + .replace("’", "'").replace("p.m.", "pm").replace("a.m.", "am")) + + +def bad_correction(raw, candidate): + """An edit of a sentence with a correction cue that changes its meaning: it drops every negation ("not the 3 p.m. + one" -> "the 3 p.m. slot"), or drops only cue words such as "sorry" or "actually" while replacing nothing.""" + if MEANING_NEGATION.search(raw) and not MEANING_NEGATION.search(candidate): + return True + lost = Counter(tokens(raw)) - Counter(tokens(candidate)) + return bool(lost) and set(lost) <= CUE_WORDS and bool(set(lost) & {"sorry", "actually", "no", "nope", "wait", "instead", "rather"}) + + +def only_deleted(raw, candidate): + """A self-correction only removes words: the edit adds at most one new word in ten, and keeps at least 30%.""" + before, after = tokens(raw), tokens(candidate) + added = sum((Counter(after) - Counter(before)).values()) + return bool(after) and added <= len(after) // 10 and 0.3 * len(before) <= len(after) <= len(before) + + +def accepted(raw, candidate, dictionary=()): + if not isinstance(candidate, str) or not candidate.strip(): + return False + comparable = raw + for entry in dictionary: + if entry.term and entry.term.casefold() in candidate.casefold(): + for alias in entry.aliases: + if alias: + comparable = re.sub(r"(?= 0.70 + + +# Target languages for translate (Hy-MT2's documented set, by name, so any chat model can follow the prompt too). +LANGUAGES = { + "en": "English", "zh": "Simplified Chinese", "zh-Hans": "Simplified Chinese", "zh-Hant": "Traditional Chinese", + "yue": "Cantonese", "ja": "Japanese", "ko": "Korean", "fr": "French", "de": "German", "es": "Spanish", + "pt": "Portuguese", "it": "Italian", "ru": "Russian", "ar": "Arabic", "tr": "Turkish", "nl": "Dutch", + "pl": "Polish", "cs": "Czech", "uk": "Ukrainian", "vi": "Vietnamese", "th": "Thai", "id": "Indonesian", + "ms": "Malay", "tl": "Filipino", "hi": "Hindi", "bn": "Bengali", "ur": "Urdu", "fa": "Persian", "he": "Hebrew", + "km": "Khmer", "my": "Burmese", "ta": "Tamil", "te": "Telugu", "mr": "Marathi", "gu": "Gujarati", +} + + +def translation(text, target, dictionary=()): + """Hy-MT2's documented English prompt (terminology variant when the dictionary has terms); no system prompt.""" + name = LANGUAGES[target] + terms = "".join(f"{e.term} translates to {e.term}" for e in dictionary if e.term) + prefix = f"Reference the following translations:{terms}" if terms else "" + return [{"role": "user", "content": f"{prefix}Translate the following text into {name}. Note that you must ONLY output " + f"the translated result without any additional explanation:{text}"}] + + +# Hesitations only, with the commas around them. Not "you know", 那个 or repeats: those can carry meaning, and +# running the LLM clean-up before translating risked answering or changing the language (T9). +FILLER = re.compile(r"(?:[,,、]\s*)?(?:\b(?:u+h+m*|u+m+|a+h+|e+r+m*|h+m+|m{2,})\b|[呃嗯]+)(?:\s*[,,、])?", re.I) + + +def unfill(text): + """The transcript without um, uh, ah, er, hmm, 呃, 嗯; the transcript itself when nothing else is left.""" + t = re.sub(r"([.!?。!?])(?: +\.|\s*。)", r"\1", FILLER.sub("", text)) # "again. Hmm. Can" left "again. . Can" + t = re.sub(r"\s+([,.!?,。!?])", r"\1", re.sub(r"[ \t]{2,}", " ", t)) + t = re.sub(r"^[\s,,、.。]+", "", t).rstrip(" ,,、") + return t or text + + +def translated(source, candidate): + """Reject empty or runaway output; translation length varies too much across scripts for a tighter check.""" + return isinstance(candidate, str) and bool(candidate.strip()) and len(candidate) <= 4 * len(source) + 40 + + +RESPOND = ("You are OpenVoice, a voice assistant on the user's computer. The user spoke a request; you get its " + "transcript, and sometimes text they selected. With selected text, the request is about that text " + "(rewrite, shorten, explain, reply to it, translate it). Otherwise answer the question or write what " + "they asked for. If tools are available, use get_weather for weather and web_search for current facts you do not know. " + "Output only the final text to show or insert: no preamble (never start with Sure, Here is, 当然 or 以下是) and no quotes. Plain text only, because it is " + "typed into other apps: never use asterisks, bold, headings or bullet symbols; write lists as lines " + "starting with 1. 2. 3. Be concise.") + + +# An intro line the model adds before a drafted message ("当然可以,以下是回复:", "Sure, here's a reply:"). The prompt +# alone did not stop it (eval r11), and a few-shot example made the model copy the example, so it is removed here. +INTRO = re.compile(r"^(?:当然|好的|可以|没问题|以下是|下面是|sure|certainly|of course|here(?:'s| is| are))[^\n]{0,60}[::]\s*\n+", re.I) + + +def tidy(answer): + """The answer to insert: no intro line, no quotes around the drafted text, no Markdown line-break spaces.""" + text = re.sub(r"[ \t]+\n", "\n", answer).strip() + body = INTRO.sub("", text, count=1) + if body != text and len(body) > 2 and body[0] + body[-1] in ('""', "“”", "「」"): + body = body[1:-1].strip() + return body or text + + +TAG = re.compile(r"^\s*\[(?:To|Speaker) [^\]\n]{1,64}\]\s*") + + +def untag(text): + """The answer without the [To S2] tag the model copies from its tagged history; "" while a tag may still be + arriving in a stream.""" + if TAG.match(text): + return TAG.sub("", text, count=1) + start = text.lstrip() + return "" if start.startswith("[") and "]" not in start and len(start) < 72 else text + + +def respond(raw, options, actions=False, speakers=False): + """Messages for respond mode (answer the request or rewrite the selected text). actions: tools that act on the user's computer are offered. + speakers: user turns start with a voice tag ("[Speaker S1] ") because several people may be talking.""" + system = RESPOND + if speakers: + system += (" Several people may be talking. Each message from them begins with a tag like [Speaker S1] saying " + "who spoke, recognised from their voice, and each of your replies begins with [To S1], the person it " + "answered. Keep track of who said what: I, me and my mean that speaker. You are only the assistant: " + "answer that speaker in one reply and never write lines for the speakers. Refer to anyone other than the " + "person you answer by their label, such as S2; I and me are only ever you, the assistant, who eats and " + "wants nothing. When people want different things, suggest something that works for everyone.") + if actions: + system += (" Some tools act on the user's computer or accounts. When the user asks for such an action, call the " + "tool right away: the user is asked to confirm every action before it runs, so never ask for " + "permission in text. Say that something was done only when a tool result says so. Today is " + f"{datetime.now():%A %d %B %Y}; you do not know the time of day without a tool. " + # last on purpose: after a text-only turn in the history, the model claimed "reminder created" without + # calling the tool (eval t09); the same hint in the user turn flipped Chinese answers to English + "For any action, call the tool; never say it is done unless a tool result says so.") + if options.output_language: + system += f" Write the answer in {LANGUAGES[options.output_language]}." + else: + # Mixed Chinese-English requests got English answers (eval r11), so the default is decided here. + spoken = "Chinese" if chinese(raw) else "the language they spoke" + system += f" Answer in the language the user asks for, otherwise in {spoken}." + user = raw if not options.context.selected_text else f"Request: {raw}\n\nSelected text:\n{options.context.selected_text}" + if options.output_language: # repeated here: tool schemas follow the system prompt and drown it out (eval r13) + user += f"\n\n(Write the answer in {LANGUAGES[options.output_language]}.)" + history = [{"role": t.role, "content": t.content} for t in options.history] + return [{"role": "system", "content": system}, *history, {"role": "user", "content": user}] + + +YES = {"yes", "yeah", "yep", "yup", "sure", "ok", "okay", "go ahead", "do it", "confirm", "please do", "yes please", + "好", "好的", "是", "是的", "可以", "对", "行", "确认", "确定"} # not 嗯: usually a hesitation, not consent +AFFIRM = {"yes", "yeah", "yep", "yup", "sure", "ok", "okay", "alright", "confirm", "go", "ahead", "do", "it", "please", + "thanks", "thank", "you"} +NEGATION = re.compile(r"\b(?:no|nope|not|don't|dont|cancel|stop|never|wait)\b|不|别|取消|算了") + + +def yes_or_no(heard): + """A spoken answer to "confirm this action?": True, False, or None when it is something else (the action is + then declined and the utterance handled as a new request). Any negation wins: "okay no, cancel that" is a no.""" + t = re.sub(r"[^\w\s']", "", heard.casefold()).strip() + t = re.sub(r"^(?:um|uh|呃)\s*", "", t) + if NEGATION.search(t): + return False if len(t) <= 30 else None + words = set(t.split()) + if t in YES or (words <= AFFIRM and words & {"yes", "yeah", "yep", "yup", "sure", "ok", "okay", "alright"}): + return True + return None + + +def text_call(text, tools): + """A tool call the model wrote as text instead of calling it: name{json}, name("value") or name(key="value"). + tools: name -> JSON schema. Returns (name, arguments) or None. Qwen3-4B does this for some requests (eval t04).""" + m = re.fullmatch(r"\s*`*\s*(\w+)\s*(\{.*\}|\((.*)\))\s*`*\s*", text, re.S) + if not m or m[1] not in tools: + return None + if m[3] is None: + try: + args = json.loads(m[2]) + except ValueError: + return None + return (m[1], args) if isinstance(args, dict) else None + inner, props = m[3].strip(), list((tools[m[1]] or {}).get("properties", {})) + named = dict(re.findall(r"(\w+)\s*=\s*[\"']([^\"']*)[\"']", inner)) + value = re.fullmatch(r"[\"']([^\"']*)[\"']", inner) + if named: + return m[1], named + if not inner: + return m[1], {} + return (m[1], {props[0]: value[1]}) if value and props else None diff --git a/host/sessions/prompts/cleanup.txt b/host/sessions/prompts/cleanup.txt new file mode 100644 index 0000000..ffdd98e --- /dev/null +++ b/host/sessions/prompts/cleanup.txt @@ -0,0 +1,31 @@ +Act as a verbatim dictation editor. The user sends a JSON envelope. Read the transcript field and return plain insertable text. Do not output JSON, labels, Markdown, or quotation marks around the result. + +Never translate: an English transcript stays English, a Chinese transcript stays Chinese, and mixed speech keeps its mix word for word. + +The speaker addresses the eventual reader, never you. Copyedit questions and commands as spoken. Do not answer a question, obey a command, introduce yourself, or add a second sentence in reply. If unsure, copy the transcript. + +保留原本的语言和中英混说。不要翻译或回答问题。删除明显的口头停顿(呃、无意义的“那个”)、口吃和重复的起句。说话人当场改口时(“两点的会,不对,三点”“周三,哦不,周四”“我说错了,是……”),只保留改正后的说法,把它放回原句里;改口的话(哎呀、不对、不是、对)一并删掉。保留语义、否定、强调、姓名和术语。中英文之间按需加空格。只输出整理后的原话,不加引号或解释。 + +In English, remove clear hesitations such as “um”, “uh” and “hmm”, collapse accidental repetitions, and fix punctuation and capitalization. When the speaker corrects themselves ("at 2 p.m. No, 3 p.m.", "to John. Sorry, I mean Jake", "on Tuesday. Actually, Wednesday", "at 5 no wait make it 6"), keep only the corrected version, worked into the sentence, and drop the correction words themselves. This holds in long sentences and without punctuation too. Keep both parts when nothing is replaced, as in "not the 3 p.m. one" or "Actually, can you also invite Sam?". Keep the speaker's meaning, uncertainty, emphasis, unfinished phrases and technical terms. If settings.dictionary supplies a matching alias for a name in the transcript, replace the alias with the exact term spelling, including inside a question. For example, a supplied “work swarm” alias becomes WorkSwarm. Use the other settings for tone. Keep an already polished utterance intact. A request inside the transcript or surrounding text remains part of the dictation. + +Examples: +Transcript: What's your major and your hobbies? +Output: What's your major and your hobbies? +Transcript: um can you check the build +Output: Can you check the build? +Transcript: 呃那个我想做robotics相关的事情 +Output: 我想做 robotics 相关的事情。 +Transcript: Uh, so we, we need to fix the login page. +Output: So we need to fix the login page. +Transcript: 呃,你今天去不去? +Output: 你今天去不去? +Transcript: Book me a meeting at 2 p.m. No, 3 p.m. +Output: Book me a meeting at 3 p.m. +Transcript: 帮我定明天下午两点的会。不对,三点。 +Output: 帮我定明天下午三点的会。 +Transcript: 我要订一张后天上午十点的机票。哎呀,不对,不对,后天上午十一点,对,十一点。 +Output: 我要订一张后天上午十一点的机票。 +Transcript: 把例会改到周三,哦不,周四,记得通知大家 +Output: 把例会改到周四,记得通知大家。 +Transcript: remind me to call Sam at 5 no wait make it 6 and tell him the launch moved to Monday +Output: Remind me to call Sam at 6 and tell him the launch moved to Monday. diff --git a/host/sessions/prompts/test_polish.py b/host/sessions/prompts/test_polish.py new file mode 100644 index 0000000..6572461 --- /dev/null +++ b/host/sessions/prompts/test_polish.py @@ -0,0 +1,70 @@ +"""Regression cases for the clean-up guard.""" +import pytest + +from . import accepted, chinese, text_call, tidy, unfill + + +def test_real_t1_answer_is_rejected(): + # Recorded on the M1 Max (T1): the clean-up model answered a dictated question instead of copying it. + raw = "What's your major and your hobbies?" + polished = "My major is artificial intelligence. My hobbies include playing chess, reading, and coding." + assert accepted(raw, raw) + assert not accepted(raw, polished) + + +@pytest.mark.parametrize("raw,clean,answer", [ + ("um can you check the build", "Can you check the build?", "Yes, I can check the build."), + ("你明天去吗", "你明天去吗?", "我明天去。"), + ("你会去 gym 吗?", "你会去 gym 吗?", "你会去 gym 吗?我会。"), + ("What's your major?", "What's your major?", "What's your major? I study math."), +]) +def test_questions_remain_dictation(raw, clean, answer): + assert accepted(raw, clean) + assert not accepted(raw, answer) + + +@pytest.mark.parametrize("answer,clean", [ + ('当然可以,以下是一个简洁得体的回复,你可以直接发送:\n\n"好的,我们把会议改到周五。"', "好的,我们把会议改到周五。"), + ("Sure, here's a reply:\n\nCount me in for Friday.", "Count me in for Friday."), + ("可以,我来帮你写个回复:\n\n会议改到周五。", "会议改到周五。"), + ("1. Boil water. \n2. Add tea.", "1. Boil water.\n2. Add tea."), + ("好的,会议改到周五。", "好的,会议改到周五。"), # no colon line: an answer, kept + ("Here is why: it rains.", "Here is why: it rains."), # colon but no line break: kept +]) +def test_tidy_removes_only_an_intro_line(answer, clean): + assert tidy(answer) == clean + + +def test_language_hint(): + assert chinese("我们明天的 meeting 要 reschedule 吗?") and chinese("那我专业是那个ISM,Information Systems Management。") + assert not chinese("Please email the 鼎泰丰 team about Friday.") and not chinese("Um, translate this into Chinese.") + + +URL = {"open_url": {"type": "object", "properties": {"url": {"type": "string"}}}} + + +@pytest.mark.parametrize("text,call", [ + ('open_url("https://www.youtube.com")', ("open_url", {"url": "https://www.youtube.com"})), + ('open_url{"url": "https://a.org"}', ("open_url", {"url": "https://a.org"})), + ("open_url(url='https://a.org')", ("open_url", {"url": "https://a.org"})), + ('Sure: open_url("https://a.org")', None), # prose around it: an answer, not a call + ('delete_all("x")', None), # not an offered tool +]) +def test_text_call(text, call): + assert text_call(text, URL) == call + + +@pytest.mark.parametrize("raw, clean", [ + ("Um, I uh think we should, uh, meet tomorrow at, ah, ten.", "I think we should meet tomorrow at ten."), + ("So, um, the build is broken, uh.", "So the build is broken."), + ("Hmm, errm, where is Ahmed?", "where is Ahmed?"), # names and words that start like a filler stay + ("呃,那个,我们明天,嗯,开会吧。", "那个,我们明天开会吧。"), + ("嗯", "嗯"), # nothing left: keep what was said + ("So, um, the build is, ah, broken again. Hmm. Can you, ah, check it?", "So the build is broken again. Can you check it?"), + ("Hmm. 我们走吧。", "我们走吧。"), + ("好了。嗯。走吧。", "好了。走吧。"), + ("Wait... um, okay.", "Wait... okay."), + ("Uhm, the umbrella is in the hmmm hall.", "the umbrella is in the hall."), +]) +def test_unfill_drops_only_clear_fillers(raw, clean): + assert unfill(raw) == clean diff --git a/host/sessions/speakers.py b/host/sessions/speakers.py new file mode 100644 index 0000000..590c4c3 --- /dev/null +++ b/host/sessions/speakers.py @@ -0,0 +1,142 @@ +"""Optional, on-device speaker attribution for one hands-free session.""" + +import hashlib +import json +import os +import tempfile +from functools import lru_cache +from importlib.util import find_spec +from pathlib import Path +from threading import Lock + +import numpy as np + +MODEL_ID = "3dspeaker_speech_campplus_sv_zh_en_16k-common_advanced" +MODEL_SHA256 = "53cab20ba8f2eb2f6e2d89ecc18e88ef3222169b61b4419cbc13666744a4574b" +THRESHOLD = 0.35 +_load_lock = Lock() + + +def available(): + path = os.getenv("OPENVOICE_SPEAKER_MODEL") + return bool(path and Path(path).is_file() and find_spec("sherpa_onnx")) + + +def unit(vector): + vector = np.asarray(vector, dtype=np.float32) + norm = np.linalg.norm(vector) + if vector.ndim != 1 or not np.isfinite(norm) or norm < 1e-8: + raise ValueError("Invalid speaker embedding") + return vector / norm + + +class Embedder: + def __init__(self, path): + import sherpa_onnx + + config = sherpa_onnx.SpeakerEmbeddingExtractorConfig( + model=str(path), num_threads=4, provider="cpu" + ) + self.extractor = sherpa_onnx.SpeakerEmbeddingExtractor(config) + self.lock = Lock() + + def __call__(self, pcm): + # Bound CPU cost on long turns. Session PCM is 16 kHz mono signed little-endian. + audio = np.frombuffer(pcm, dtype="= len(self.names): # Keep opt-in enrolment references fixed. + self.sums[index] += vector + result = {"id": f"S{index + 1}", "score": round(score, 3)} + if index < len(self.names): + result["name"] = self.names[index] + return result diff --git a/host/sessions/test_sessions.py b/host/sessions/test_sessions.py new file mode 100644 index 0000000..656f8af --- /dev/null +++ b/host/sessions/test_sessions.py @@ -0,0 +1,978 @@ +import json + +import httpx +import pytest +from fastapi.testclient import TestClient + +from .app import create_app, wav + + +def sse_chat(content="", tool_calls=None): + """A streamed chat completion as vLLM sends it: content in pieces, then any tool calls, then [DONE].""" + chunks = [{"content": piece} for piece in (content.split(" ") if content else [])] + chunks = [{"content": c["content"] + (" " if i < len(chunks) - 1 else "")} for i, c in enumerate(chunks)] + chunks += [{"tool_calls": [dict(index=i, id=t["id"], function=t["function"])]} for i, t in enumerate(tool_calls or [])] + body = "".join(f"data: {json.dumps({'choices': [{'delta': d}]})}\n\n" for d in chunks) + "data: [DONE]\n\n" + return httpx.Response(200, text=body, headers={"content-type": "text/event-stream"}) + + +@pytest.fixture +def backend(monkeypatch): + for k in ("HOST", "TOKEN", "ASR_MODEL", "LLM_MODEL"): + monkeypatch.delenv("OPENVOICE_" + k, raising=False) + monkeypatch.setenv("OPENVOICE_MAX_AUDIO_SECONDS", "1") + calls = [] + def serve(req): + calls.append(req) + body = req.read() + if req.url.path == "/v1/models": + return httpx.Response(200, json={"data": [{"id": "Qwen/Qwen3-ASR-1.7B"}]}) + if req.url.path == "/v1/audio/transcriptions": + if b"offline" in body: + raise httpx.ConnectError("offline") + if b"broken" in body: + return httpx.Response(500) + return httpx.Response(200, json={"text": "language Englishum hi there"}) + assert req.url.path == "/v1/chat/completions" + if b"fail-polish" in body: + return httpx.Response(200, json={"choices": []}) + if json.loads(body).get("stream"): + return sse_chat("Hi there.") + return httpx.Response(200, json={"choices": [{"message": {"content": "Hi there."}}]}) + return httpx.MockTransport(serve), calls + + +def connect(backend): + return TestClient(create_app(backend[0]), base_url="http://127.0.0.1") + + +def post(client, opts=None, data=None): + return client.post("/v1/dictate", files={"audio": ("clip.wav", wav(b"\1\0"*1600) if data is None else data)}, + data={"options": json.dumps(opts or {})}) + + +def test_http_and_retry(backend): + with connect(backend) as c: + assert c.get("/v1/health").json()["status"] == "degraded" + assert not c.get("/v1/capabilities").json()["streaming"]["partials"] + opts = {"request_id": "abc", "dictionary": [{"term": "OpenVoice", "aliases": ["open voice"]}], + "context": {"app_name": "Notes"}, "language": "en"} + result = post(c, opts).json() + assert (result["text"], result["raw"], result["language"]) == ("Hi there.", "um hi there", "en") + assert result["warnings"] == [] + asr, llm = backend[1][-2:] + assert b"OpenVoice" in asr.content and b"Notes" in llm.content and b"open voice" in llm.content + assert post(c, opts, b"").json() == result + assert len(backend[1]) == 4 + assert post(c, {"mode": "transcribe"}).json()["text"] == "um hi there" + result = post(c, {"instructions": "fail-polish"}).json() + assert result["text"] == result["raw"] and result["warnings"] == ["polish_failed"] + + +@pytest.mark.parametrize("opts,audio,status,code", [ + ({"mode":"command"}, b"", 400, "unsupported_option"), ({"output_language":"en"}, b"", 400, "unsupported_option"), + ({"dictionary":[{}]}, b"", 400, "bad_request"), ({}, b"invalid", 415, "bad_audio"), + ({}, wav(b"\1\0"*16001), 413, "audio_too_long"), + ({"dictionary":[{"term":"offline"}]}, None, 503, "backend_unavailable"), + ({"dictionary":[{"term":"broken"}]}, None, 502, "asr_failed")]) +def test_errors(backend, opts, audio, status, code): + with connect(backend) as c: + r = post(c, opts, audio) + assert r.status_code == status and r.json()["error"]["code"] == code + + +def test_empty_and_bad_form(backend): + with connect(backend) as c: + for audio in (b"", wav(b""), wav(bytes(640))): + result = post(c, data=audio).json() + assert result["raw"] == result["text"] == "" + assert not backend[1] + assert c.post("/v1/dictate").json()["error"]["code"] == "bad_request" + assert c.post("/v1/dictate", files={"audio": ("a", b"")}, data={"options":"{"}).status_code == 400 + + +START = {"type": "start", "audio": {"encoding": "pcm_s16le", "sample_rate": 16000, "channels": 1}} + + +def test_stream_and_http_retry(backend, monkeypatch): + monkeypatch.setenv("OPENVOICE_MAX_SESSIONS", "1") + with connect(backend) as c: + with c.websocket_connect("ws://127.0.0.1/v1/dictate/stream") as ws: + ws.send_json(START) + ready = ws.receive_json() + assert ready["type"] == "ready" + busy = post(c) + assert busy.status_code == 429 and busy.headers["retry-after"] + busy = c.post("/v1/dictate?stream=true", files={"audio": ("clip.wav", wav(b"\1\0"*1600))}) + assert busy.status_code == 429 # refused before the upload is decoded + ws.send_bytes(b"\1\0"*320) + ws.send_json({"type":"stop"}) + final = ws.receive_json() + assert final["type"] == "final" + assert post(c, {"request_id": ready["request_id"]}).json() == final["result"] + assert len(backend[1]) == 2 + + +@pytest.mark.parametrize("frame,kind", [(b"x", "error"), ({"type":"cancel"}, "cancelled")]) +def test_stream_termination(backend, frame, kind): + with connect(backend) as c, c.websocket_connect("ws://127.0.0.1/v1/dictate/stream") as ws: + ws.send_json(START) + assert ws.receive_json()["type"] == "ready" + (ws.send_bytes if isinstance(frame, bytes) else ws.send_json)(frame) + assert ws.receive_json()["type"] == kind + assert not backend[1] + + +def test_auth(backend, monkeypatch): + monkeypatch.setenv("OPENVOICE_HOST", "0.0.0.0") + with pytest.raises(ValueError): + create_app() + monkeypatch.setenv("OPENVOICE_TOKEN", "test") + with connect(backend) as c: + assert c.get("/v1/health").status_code == 401 + assert c.get("/v1/health", headers={"Authorization":"Bearer test"}).status_code == 200 + with c.websocket_connect("/v1/dictate/stream") as ws: + assert ws.receive_json()["error"]["code"] == "unauthorized" + with c.websocket_connect("/v1/dictate/stream?token=test") as ws: + ws.send_json(START) + assert ws.receive_json()["type"] == "ready" + + +def test_recorded_answer_falls_back(backend): + raw = "Um, what's your major and your hobbies?" # a filler, so the model is called and the guard is tested + def reply(req): + if req.url.path.endswith("transcriptions"): + return httpx.Response(200, json={"text": raw, "language": "en"}) + return httpx.Response(200, json={"choices":[{"message":{"content": + "My major is artificial intelligence. My hobbies include playing chess, reading, and coding."}}]}) + with connect((httpx.MockTransport(reply), [])) as c: + result = post(c).json() + assert result["raw"] == result["text"] == raw + assert result["warnings"] == ["polish_failed"] + + +def test_compressed_upload(backend): + import subprocess + encoded = subprocess.run( + ["ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-f", "mp3", "pipe:1"], + input=wav(b"\0\x40" * 8000), capture_output=True, check=True).stdout + with connect(backend) as c: + result = post(c, data=encoded).json() + assert result["text"] == "Hi there." + assert b"RIFF" in backend[1][0].content + + +def test_dictionary_in_question(): + from .options import Term + from .prompts import accepted + terms = [Term(term="WorkSwarm", aliases=["work swarm"])] + assert accepted("Can work swarm do this?", "Can WorkSwarm do this?", terms) + assert not accepted("Um, can work swarm do this", "Can WorkSwarm do this? Yes.", terms) + + +# --- translate (stage 1) --- + +def test_dictate_translate_returns_translation_and_keeps_source(backend): + with connect(backend) as c: + r = post(c, {"mode": "translate", "output_language": "zh"}) + assert r.status_code == 200 + body = r.json() + assert body["raw"] == "um hi there" and body["text"] == "Hi there." and body["models"]["mt"] + assert "translate" in body["timings_ms"] and body["warnings"] == [] + prompt = json.loads(backend[1][-1].read())["messages"][0]["content"] + assert "into Simplified Chinese" in prompt and prompt.endswith(":hi there") # fillers dropped first + + +def test_translate_clean_up_can_be_turned_off(backend): + with connect(backend) as c: + assert post(c, {"mode": "translate", "output_language": "zh", "clean_up": False}).status_code == 200 + assert json.loads(backend[1][-1].read())["messages"][0]["content"].endswith(":um hi there") + + +def test_translate_needs_supported_language_and_only_in_translate_mode(backend): + with connect(backend) as c: + assert post(c, {"mode": "translate"}).json()["error"]["code"] == "unsupported_option" + assert post(c, {"mode": "translate", "output_language": "xx"}).json()["error"]["code"] == "unsupported_option" + assert post(c, {"mode": "polish", "output_language": "en"}).json()["error"]["code"] == "unsupported_option" + + +def test_translate_failure_keeps_the_transcript(backend): + with connect(backend) as c: + r = post(c, {"mode": "translate", "output_language": "en", "dictionary": [{"term": "fail-polish"}]}) + assert r.json()["text"] == "um hi there" and "translate_failed" in r.json()["warnings"] + + +def test_translate_text_endpoint(backend): + with connect(backend) as c: + _translate_text_checks(c, backend) + + +def _translate_text_checks(c, backend): + r = c.post("/v1/translate", json={"text": "你好", "output_language": "en", "dictionary": [{"term": "WorkSwarm"}]}) + assert r.status_code == 200 and r.json()["text"] == "Hi there." and r.json()["source"] == "你好" + assert "WorkSwarm translates to WorkSwarm" in json.loads(backend[1][-1].read())["messages"][0]["content"] + assert c.post("/v1/translate", json={"text": "x", "output_language": "xx"}).status_code == 400 + assert c.post("/v1/translate", json={"text": "fail-polish", "output_language": "en"}).json()["error"]["code"] == "mt_failed" + assert "translate" in c.get("/v1/capabilities").json()["modes"] + + + +def test_demo_page_served_on_loopback(backend): + with connect(backend) as c: + r = c.get("/demo") + assert r.status_code == 200 and "OpenVoice host demo" in r.text + + +# --- clean-up gate: skip the model when the transcript has nothing to fix (T17) --- + +def test_needs_polish_gate(): + from .options import Options + from .prompts import needs_polish + o = Options() + assert not needs_polish("What's your major and your hobbies?", o) + assert not needs_polish("我想做 robotics 相关的事情。", o) + for raw in ["Um. Actually, I found a job.", "I I think so", "And I don't, I don't do it.", "呃,更具有一点。", + "我们专业专业课", "我这个,我这个车", "那个你们那个专业的", "就是很多人"]: + assert needs_polish(raw, o), raw + assert needs_polish("clean text", Options(style="formal")) + assert needs_polish("call work swarm now", Options(dictionary=[{"term": "WorkSwarm", "aliases": ["work swarm"]}])) + + +def test_clean_transcript_skips_the_model(backend, monkeypatch): + def serve(req): + if req.url.path == "/v1/audio/transcriptions": + return httpx.Response(200, json={"text": "language EnglishSee you at three."}) + raise AssertionError("the clean-up model must not be called") + with TestClient(create_app(httpx.MockTransport(serve)), base_url="http://127.0.0.1") as c: + body = post(c).json() + assert body["text"] == body["raw"] == "See you at three." and body["warnings"] == ["polish_not_needed"] + + + +# --- speed switch: accurate (default) or fast speech model (T17) --- + +def test_speed_switch_picks_the_fast_model(backend, monkeypatch): + monkeypatch.setenv("OPENVOICE_ASR_FAST_URL", "http://fast") + with connect(backend) as c: + assert c.get("/v1/capabilities").json()["speeds"] == ["accurate", "fast"] + body = post(c, {"speed": "fast", "mode": "transcribe"}).json() + asr_calls = [r for r in backend[1] if r.url.path.endswith("transcriptions")] + assert asr_calls[-1].url.host == "fast" and body["models"]["asr"] == "Qwen3-ASR-1.7B-4bit" + post(c, {"mode": "transcribe"}) + assert [r for r in backend[1] if r.url.path.endswith("transcriptions")][-1].url.host == "127.0.0.1" + + +def test_fast_without_a_fast_model_is_rejected(backend): + with connect(backend) as c: + assert c.get("/v1/capabilities").json()["speeds"] == ["accurate"] + assert post(c, {"speed": "fast"}).json()["error"]["code"] == "unsupported_option" + + +# --- respond mode: answers and rewrites, with tools (T18) --- + +def test_respond_calls_a_tool_then_answers(backend, monkeypatch): + monkeypatch.setenv("OPENVOICE_TOOLS", "1") + seen = [] + def serve(req): + body = req.read() + if req.url.path == "/v1/audio/transcriptions": + return httpx.Response(200, json={"text": "language EnglishHow's the weather in Toronto? Answer in Chinese."}) + if req.url.host == "wttr.in": + return httpx.Response(200, json={"current_condition": [{"weatherDesc": [{"value": "Sunny"}], "temp_C": "5", + "FeelsLikeC": "2", "humidity": "60", "windspeedKmph": "10"}], "weather": [{"mintempC": "1", "maxtempC": "7"}], + "nearest_area": [{"areaName": [{"value": "Toronto"}]}]}) + msgs = json.loads(body)["messages"] + seen.append(msgs) + if msgs[-1]["role"] == "user": + return sse_chat(tool_calls=[{"id": "c1", "function": {"name": "get_weather", "arguments": "{\"location\": \"Toronto\"}"}}]) + assert msgs[-1]["role"] == "tool" and "Sunny, 5°C" in msgs[-1]["content"] + return sse_chat("多伦多现在晴,5°C。") + with TestClient(create_app(httpx.MockTransport(serve)), base_url="http://127.0.0.1") as c: + body = post(c, {"mode": "respond"}).json() + assert body["text"] == "多伦多现在晴,5°C。" and body["raw"].startswith("How's the weather") + assert body["tool_calls"][0]["name"] == "get_weather" and body["tool_calls"][0]["arguments"] == {"location": "Toronto"} + assert "respond" in body["timings_ms"] and "Selected text" not in seen[0][1]["content"] + + +def test_respond_uses_selected_text_and_reply_language(backend): + with connect(backend) as c: + r = post(c, {"mode": "respond", "output_language": "zh", "context": {"selected_text": "See you at 3."}}) + assert r.status_code == 200 and r.json()["text"] == "Hi there." + sent = json.loads(backend[1][-1].read())["messages"] + assert "Simplified Chinese" in sent[0]["content"] and "Selected text:\nSee you at 3." in sent[1]["content"] + + +def test_respond_failure_keeps_the_transcript(backend): + with connect(backend) as c: + body = post(c, {"mode": "respond", "context": {"selected_text": "fail-polish"}}).json() + assert body["raw"] and body["text"] == "" and "respond_failed" in body["warnings"] + + +def test_web_search_reads_wikipedia_summaries(): + import asyncio + from . import tools + def serve(req): + assert req.url.host == "en.wikipedia.org" and req.url.params["gsrsearch"] == "F1 champion" + return httpx.Response(200, json={"query": {"pages": {"2": {"index": 2, "title": "B", "extract": "second"}, + "1": {"index": 1, "title": "A", "extract": "first"}}}}) + async def go(): + async with httpx.AsyncClient(transport=httpx.MockTransport(serve)) as client: + return await tools.run(client, "web_search", {"query": "F1 champion"}) + assert asyncio.run(go()) == "A: first\n\nB: second" + + + +# --- streaming answers and follow-ups (T19) --- + +def events(response): + """Parse a server-sent-event body into [(event, data)].""" + out = [] + for block in response.text.strip().split("\n\n"): + lines = dict(line.split(": ", 1) for line in block.splitlines()) + out.append((lines["event"], json.loads(lines["data"]))) + return out + + +def test_respond_streams_transcript_then_answer_pieces(backend): + with connect(backend) as c: + r = c.post("/v1/dictate?stream=1", files={"audio": ("a.wav", wav(b"\1\0" * 1600))}, + data={"options": json.dumps({"mode": "respond"})}) + assert r.headers["content-type"].startswith("text/event-stream") + ev = events(r) + assert ev[0] == ("transcript", {"raw": "um hi there", "language": "en"}) + assert [d["text"] for k, d in ev if k == "delta"] == ["Hi ", "there."] + assert ev[-1][0] == "final" and ev[-1][1]["text"] == "Hi there." + + +def test_streamed_tool_call_is_announced_then_answered(backend, monkeypatch): + monkeypatch.setenv("OPENVOICE_TOOLS", "1") + def serve(req): + body = req.read() + if req.url.host == "wttr.in": + return httpx.Response(200, json={"current_condition": [{"weatherDesc": [{"value": "Rain"}], "temp_C": "3", + "FeelsLikeC": "0", "humidity": "90", "windspeedKmph": "20"}], "weather": [{"mintempC": "1", "maxtempC": "4"}]}) + msgs = json.loads(body)["messages"] + if msgs[-1]["role"] == "user": + return sse_chat(tool_calls=[{"id": "c1", "function": {"name": "get_weather", "arguments": "{\"location\": \"Oslo\"}"}}]) + return sse_chat("Rainy, 3°C.") + with TestClient(create_app(httpx.MockTransport(serve)), base_url="http://127.0.0.1") as c: + ev = events(c.post("/v1/respond?stream=1", json={"text": "weather in Oslo?"})) + kinds = [k for k, _ in ev] + assert kinds[0] == "tool" and kinds[-1] == "final" and set(kinds[1:-1]) == {"delta"} + assert "".join(d["text"] for k, d in ev if k == "delta") == "Rainy, 3°C." + assert ev[0][1] == {"name": "get_weather", "arguments": {"location": "Oslo"}} + assert ev[-1][1]["text"] == "Rainy, 3°C." and ev[-1][1]["tool_calls"][0]["name"] == "get_weather" + + +def test_follow_up_sends_the_conversation(backend): + history = [{"role": "user", "content": "Write a note saying I'm late."}, {"role": "assistant", "content": "I'm running late."}] + with connect(backend) as c: + r = c.post("/v1/respond", json={"text": "Now in Chinese.", "history": history}) + assert r.status_code == 200 and r.json()["text"] == "Hi there." + sent = json.loads(backend[1][-1].read())["messages"] + assert [m["role"] for m in sent] == ["system", "user", "assistant", "user"] and sent[-1]["content"] == "Now in Chinese." + with connect(backend) as c: + assert c.post("/v1/respond", json={"text": "x", "history": [{"role": "tool", "content": "y"}]}).status_code == 400 + + + +def test_tools_are_off_unless_opted_in(backend): + with connect(backend) as c: + assert c.get("/v1/capabilities").json()["tools"] == {"enabled": False, "mcp": []} + post(c, {"mode": "respond"}) + sent = json.loads([r for r in backend[1] if r.url.path == "/v1/chat/completions"][-1].read()) + assert "tools" not in sent # nothing can leave the device without OPENVOICE_TOOLS=1 + + +# --- listening sessions: VAD, partials, follow-ups (hands-free) --- + +from .vad import CHUNK_BYTES, Segmenter, SileroVAD + + +def test_segmenter_finds_an_utterance_with_pre_roll(): + seg, quiet, loud = Segmenter(end_chunks=4), b"\0" * CHUNK_BYTES, b"\1\0" * (CHUNK_BYTES // 2) + events = [seg.feed(quiet, 0.0) for _ in range(10)] + events += [seg.feed(loud, 0.9) for _ in range(8)] + events += [seg.feed(quiet, 0.1) for _ in range(4)] + kinds = [e[0] for e in events if e] + assert kinds == ["start", "end"] + audio = [e for e in events if e and e[0] == "end"][0][1] + assert len(audio) == (8 + 5 + 4) * CHUNK_BYTES # pre-roll (5 quiet + 3 loud) + 5 loud + 4 quiet + + +def test_segmenter_drops_blips_and_flushes_at_stop(): + seg = Segmenter(end_chunks=3) + assert [seg.feed(b"x" * CHUNK_BYTES, p) for p in (0.9, 0.9, 0.9)][-1] == ("start", None) + assert [seg.feed(b"x" * CHUNK_BYTES, 0.0) for _ in range(3)][-1] == ("drop", None) # 3 chunks < 192 ms of speech + for p in [0.9] * 10: + seg.feed(b"y" * CHUNK_BYTES, p) + assert seg.flush()[0] == "end" and not seg.active + + +def test_silero_ignores_noise(): + import numpy as np + vad, seg = SileroVAD(), Segmenter() + noise = np.random.default_rng(0).normal(0, 3000, 16000 * 2).astype("= 125 # every piece, silence included: 4.2 s of audio + assert fake.spans[0][0] <= 0.3 and abs(fake.spans[0][1] - 1.3) < 0.1 # the speech, without the ending pause + assert fake.closed + + +def test_diarizer_pick_main_speaker_and_overlap(): + from .diarizer import pick + segs = [(0.0, 2.0, 1), (1.5, 1.9, 2), (5.0, 6.0, 3)] + assert pick(segs, 0.0, 2.0) == {"id": "S1", "score": 0.833, "also": ["S2"]} + assert pick(segs, 0.0, 4.0) == {"id": "S1", "score": 0.833} # 0.4 s is under 15% of a 4 s sentence + assert pick(segs, 3.0, 4.0) is None + + +def test_untag_strips_the_reply_tag_even_mid_stream(): + from .prompts import untag + assert untag("[To S2] You prefer sushi.") == untag(" [To Ali] You prefer sushi.") == "You prefer sushi." + assert untag("[To S") == untag("[") == "" # held back until the tag is complete + assert untag("[1] is a footnote") == "[1] is a footnote" and untag("Hi") == "Hi" + + +def test_level_vad_learns_the_room_and_flags_loud_chunks(): + import numpy as np + from .vad import LevelVAD + vad, rng = LevelVAD(), np.random.default_rng(0) + quiet = lambda: rng.normal(0, 100, 512).astype("" + (heard.pop(0) if len(heard) > 1 else heard[0])}) + msgs = json.loads(body)["messages"] + if msgs[-1]["role"] == "user": + assert any(t["function"]["name"] == tool for t in json.loads(body)["tools"]) + return sse_chat(tool_calls=[{"id": "c1", "function": {"name": tool, "arguments": "{\"url\": \"https://example.com\"}"}}]) + return sse_chat("Result: " + msgs[-1]["content"]) + return httpx.MockTransport(serve) + + +def test_mcp_action_waits_for_confirmation(backend): + mcp = FakeMCP() + with TestClient(create_app(mcp_backend("open_url"), mcp=mcp), base_url="http://127.0.0.1") as c: + assert c.get("/v1/capabilities").json()["tools"]["mcp"] == ["now", "open_url", "web__now"] + ev = [] + with c.stream("POST", "/v1/respond?stream=1", json={"text": "open example.com"}) as r: + for line in r.iter_lines(): + if line.startswith("data: "): + ev.append(json.loads(line[6:])) + if "label" in ev[-1]: # the confirm event: nothing ran yet + assert mcp.ran == [] and ev[-1]["label"] == "mac: open_url" + assert c.post("/v1/confirm", json={"id": ev[-1]["id"], "approve": True}).status_code == 200 + assert c.post("/v1/confirm", json={"id": "gone", "approve": True}).status_code == 404 + assert mcp.ran == [("open_url", {"url": "https://example.com"})] + assert ev[-1]["text"] == "Result: Opened." and ev[-1]["tool_calls"][0]["approved"] is True + + +def test_mcp_action_is_declined_without_a_way_to_ask(backend): + mcp = FakeMCP() + with TestClient(create_app(mcp_backend("open_url"), mcp=mcp), base_url="http://127.0.0.1") as c: + body = c.post("/v1/respond", json={"text": "open example.com"}).json() + assert mcp.ran == [] and body["tool_calls"][0]["approved"] is False and "confirmation" in body["text"] + + +def test_read_only_mcp_tool_runs_without_asking(backend): + mcp = FakeMCP() + with TestClient(create_app(mcp_backend("now"), mcp=mcp), base_url="http://127.0.0.1") as c: + body = c.post("/v1/respond", json={"text": "what time is it"}).json() + assert mcp.ran == [("now", {"url": "https://example.com"})] and body["text"] == "Result: 14:05" + + +def test_listen_session_takes_a_spoken_yes(backend): + mcp = FakeMCP() + app = create_app(mcp_backend("open_url", asr=("open example.com", "yes please")), vad_factory=FakeVAD, mcp=mcp) + with TestClient(app, base_url="http://127.0.0.1") as c, c.websocket_connect("ws://127.0.0.1/v1/listen") as ws: + ws.send_text(json.dumps({"type": "start", "options": {"mode": "respond"}, "vad": {"partials": False}, + "audio": {"encoding": "pcm_s16le", "sample_rate": 16000, "channels": 1}})) + speak(ws) + assert listen_events(ws, "confirm")[-1]["name"] == "open_url" and mcp.ran == [] + speak(ws) + got = listen_events(ws, "final") + ws.send_text(json.dumps({"type": "stop"})) + listen_events(ws, "done") + assert {"type": "transcript", "utterance": 2, "raw": "yes please", "answer": "yes"} in got + assert mcp.ran and got[-1]["utterance"] == 1 and got[-1]["result"]["text"] == "Result: Opened." + + +@pytest.mark.parametrize("heard,answer", [("Yes.", True), ("Yeah, go ahead", True), ("好的。", True), ("um okay", True), + ("No.", False), ("Cancel that", False), ("算了", False), ("What's the weather tomorrow?", None), ("", None), + ("Okay no, cancel that", False), ("yes, don't", False), ("好的,不要了", False), ("嗯", None), ("嗯。", None), + ("okay what time is it", None)]) +def test_yes_or_no(heard, answer): + assert yes_or_no(heard) is answer + + +def test_mcp_results_tell_the_model_what_happened(): + import asyncio + from types import SimpleNamespace as NS + class Session: + async def call_tool(self, tool, args): + return NS(isError=tool == "bad", content=[NS(type="text", text=f"{tool} ok")]) + m = MCPTools() + for tool, action in (("now", False), ("add", True), ("bad", True)): + m.add("mac", tool, "", None, Session(), action) + run = lambda name: asyncio.run(m.call(name, {})) + assert run("now") == "now ok" + assert run("add").startswith("Done. add ok") and "did not work" in run("bad") + + +def test_reminder_due_accepts_bare_times(): + from datetime import datetime + from host.mcp_servers.mac import parse_due + now = datetime(2026, 12, 3, 14, 50) + assert parse_due("2026-12-03T15:00:00-05:00", now) == datetime(2026, 12, 3, 15, 0) + assert parse_due("15:00", now) == datetime(2026, 12, 3, 15, 0) + assert parse_due("3 pm", now) == parse_due("3:00 PM", now) == datetime(2026, 12, 3, 15, 0) + assert parse_due("9:30am", now) == datetime(2026, 12, 4, 9, 30) # already past today: tomorrow + with pytest.raises(ValueError): + parse_due("later", now) + + +# --- review fixes (PR #3) --- + +def test_other_web_pages_cannot_use_the_host(backend): + with connect(backend) as c: + evil = {"origin": "http://evil.example"} + assert c.get("/v1/capabilities", headers=evil).status_code == 403 + assert c.post("/v1/translate", json={"text": "hi", "target_language": "fr"}, headers=evil).status_code == 403 + assert c.get("/v1/capabilities", headers={"host": "evil.example"}).status_code == 403 # DNS rebinding + assert c.get("/v1/capabilities", headers={"origin": "http://127.0.0.1"}).status_code == 200 # the demo page + for path in ("/v1/dictate/stream", "/v1/listen"): + with c.websocket_connect("ws://127.0.0.1" + path, headers=evil) as ws: + assert ws.receive_json()["error"]["code"] == "forbidden_origin" + + +def test_other_origins_work_with_the_token(backend, monkeypatch): + monkeypatch.setenv("OPENVOICE_TOKEN", "test") + with connect(backend) as c: + assert c.get("/v1/capabilities", headers={"origin": "tauri://localhost", "Authorization": "Bearer test"}).status_code == 200 + + +def test_tools_not_offered_are_not_run(backend, monkeypatch): + from . import tools + ran = [] + async def run(client, name, args): + ran.append(name) + return "sunny" + monkeypatch.setattr(tools, "run", run) + def serve(req): + msgs = json.loads(req.read())["messages"] + if msgs[-1]["role"] == "user": # OPENVOICE_TOOLS is unset, so no tools were offered + return sse_chat(tool_calls=[{"id": "c1", "function": {"name": "get_weather", "arguments": "{}"}}]) + return sse_chat("I can't check that.") + with TestClient(create_app(httpx.MockTransport(serve)), base_url="http://127.0.0.1") as c: + body = c.post("/v1/respond", json={"text": "weather?"}).json() + assert ran == [] and body["text"] == "I can't check that." + + +def test_last_round_offers_no_tools(backend): + mcp, sent = FakeMCP(), [] + def serve(req): + body = json.loads(req.read()) + sent.append("tools" in body) + if "tools" in body: # a model that keeps calling tools + return sse_chat(tool_calls=[{"id": f"c{len(sent)}", "function": {"name": "now", "arguments": "{}"}}]) + return sse_chat("It is 14:05.") + with TestClient(create_app(httpx.MockTransport(serve), mcp=mcp), base_url="http://127.0.0.1") as c: + body = c.post("/v1/respond", json={"text": "time?"}).json() + assert sent == [True, True, False] and body["text"] == "It is 14:05." and len(mcp.ran) == 2 + + +def test_mcp_clash_is_checked_on_the_model_facing_name(): + m = MCPTools() + m.add("a", "open_url", "", None, None, confirm=True) + m.add("b", "open.url", "", None, None, confirm=False) + m.add("c", "open_url", "", None, None, confirm=False) + m.add("c", "open url", "", None, None, confirm=False) + assert m.needs_confirm("open_url") and m.label("open_url") == "a: open_url" + assert sorted(m.tools) == ["b__open_url", "c__open_url", "c__open_url_2", "open_url"] + assert len({t["function"]["name"] for t in m.specs}) == 4 + + +def test_diarizer_that_died_drops_audio_and_fails_fast(): + import time + from . import diarizer + class Lib: + nemo_speech_diar_stream_open = lambda self, handle, out: 0 + nemo_speech_diar_stream_push_f32 = lambda self, *a: 1 # the C library fails on the first push + nemo_speech_diar_stream_close = lambda self, stream: None + class Model: + lib, handle = Lib(), None + def check(self, status): + if status: + raise RuntimeError("push failed") + s = diarizer.DiarSession(Model()) + s.feed(b"\0\0" * 512) + s.thread.join(1) + for _ in range(100): + s.feed(b"\0\0" * 512) + assert s.jobs.qsize() == 0 + t = time.monotonic() + with pytest.raises(ValueError): + s.label(b"", span=(0, 1)) + assert time.monotonic() - t < 0.1 + + +# --- spoken self-corrections: "at 2 p.m. No, 3 p.m." keeps only 3 p.m. --- + +from .prompts import accepted, corrected + + +@pytest.mark.parametrize("raw,cue", [ + ("Book me a meeting at 2 p.m. No, 3 p.m.", True), ("book me a meeting at 2pm no 3pm", True), + ("Book me a meeting at 2 p.m., no wait, 3 p.m.", True), ("Book me a meeting at 2 p.m. Make it 3 p.m.", True), + ("Book me a meeting at 2 p.m., or rather 3 p.m.", True), ("Send the report to John. Sorry, I mean Jake.", True), + ("能,呃,我想要买一张明天晚上七点钟的电影票。哎呀,不对,不对,明天晚上八点钟。", True), ("帮我定两点的会,哦不,三点。", True), + ("帮我定两点的会,不是,三点。", True), ("把这个报告发给王总我说错了是发给刘总", True), ("帮我订明天下午两点的会 不对 三点", True), + ("There's no milk left.", True), # a look-alike: the model sees it and keeps it as it is + ("Please send the report to Jake.", False), ("我想买一张明天晚上八点的电影票。", False)]) +def test_self_correction_cue(raw, cue): + assert corrected(raw) is cue + + +@pytest.mark.parametrize("raw,edit,ok", [ + ("能,呃,我想要买一张明天晚上七点钟的电影票。哎呀,不对,不对,不对,不对,明天晚上八点钟,对,八点钟。", + "能,我想要买一张明天晚上八点钟的电影票。", True), # removing a lot is fine when nothing is added + ("Can you book me a meeting with the design team tomorrow afternoon at 2pm no 3pm in the big conference room", + "Can you book me a meeting with the design team tomorrow afternoon at 3 p.m. in the big conference room?", True), + ("Set a timer for 10 minutes. No, 15.", "Set a timer for 15 minutes.", True), + ("Book me a meeting on Monday at 2 p.m. No, Tuesday.", "Book me a meeting on Tuesday at 2 p.m.", True), + ("Can we move the call to Friday? No. Thursday?", "Can we move the call to Thursday?", True), + ("Can we move the call to Friday? No. Thursday?", "Yes, Thursday works for me.", False), # an answer + ("Why is the build not passing?", "Because a test is failing.", False), + ("Book me a meeting at 2 p.m. No, 3 p.m.", "3 p.m.", False), # too much gone + ("帮我定两点的会,不对,三点。", "Book a meeting at three.", False), # translated + ("Do not delete the file. Sorry, the folder.", "Delete the folder.", False), # a lost "not" flips the meaning + ("Do not delete the file. Sorry, the folder.", "Do not delete the folder.", True), + ("我不想七点去,不对,八点。", "我八点去。", False), + ("I'd like the 2 p.m. slot, not the 3 p.m. one, because of the doctor.", "I'd like the 3 p.m. slot, because of the doctor.", False), + ("Sorry I'm late, the train was delayed again this morning.", "I'm late, the train was delayed again this morning.", False), + ("I finished the report. Actually, it was easier than I expected.", "I finished the report. It was easier than I expected.", False), + ("Um, sorry I'm late, the train was delayed.", "Sorry I'm late, the train was delayed.", True), # only the filler went + ("I mean, the results are, um, honestly not great.", "The results are honestly not great.", True)]) # "I mean" as filler +def test_guard_lets_a_correction_delete_but_not_add(raw, edit, ok): + assert accepted(raw, edit) is ok + + +def correction_backend(heard, sent): + """ASR hears `heard`; the clean-up model keeps the correction; translation echoes what it was given.""" + def serve(req): + body = req.read() + if req.url.path == "/v1/audio/transcriptions": + return httpx.Response(200, json={"text": "language English" + heard}) + msgs = json.loads(body)["messages"] + sent.append(msgs[-1]["content"]) + if msgs[0]["role"] == "system": # clean-up + return httpx.Response(200, json={"choices": [{"message": {"content": "Book me a meeting at 3 p.m."}}]}) + return httpx.Response(200, json={"choices": [{"message": {"content": "Réservez-moi une réunion à 15 h."}}]}) + return httpx.MockTransport(serve) + + +def test_polish_keeps_only_the_correction(backend): + sent = [] + with TestClient(create_app(correction_backend("Book me a meeting at 2 p.m. No, 3 p.m.", sent)), base_url="http://127.0.0.1") as c: + r = post(c, {"mode": "polish"}).json() + assert r["text"] == "Book me a meeting at 3 p.m." and r["raw"] == "Book me a meeting at 2 p.m. No, 3 p.m." and len(sent) == 1 + + +def test_translate_applies_a_correction_before_translating(backend): + sent = [] + with TestClient(create_app(correction_backend("Book me a meeting at 2 p.m. No, 3 p.m.", sent)), base_url="http://127.0.0.1") as c: + r = post(c, {"mode": "translate", "output_language": "fr"}).json() + assert r["text"] == "Réservez-moi une réunion à 15 h." and sent[-1].endswith(":Book me a meeting at 3 p.m.") + sent.clear() + post(c, {"mode": "translate", "output_language": "fr", "clean_up": False, "request_id": "x2"}) + assert len(sent) == 1 and "2 p.m. No, 3 p.m." in sent[0] # clean_up off: translated as spoken, no extra call diff --git a/host/sessions/tools.py b/host/sessions/tools.py new file mode 100644 index 0000000..19eccd8 --- /dev/null +++ b/host/sessions/tools.py @@ -0,0 +1,59 @@ +"""Tools the respond-mode model may call. Only the query leaves this machine (Ali, 3 Dec: lookups allowed).""" +import os +from urllib.parse import quote + +import httpx + +# Wikimedia's robot policy wants a contact (project URL or email) in the User-Agent; without one it may answer 403. +USER_AGENT = "OpenVoice/0.1" + (f" (+{os.environ['OPENVOICE_CONTACT']})" if os.getenv("OPENVOICE_CONTACT") else "") + +SPECS = [ + {"type": "function", "function": { + "name": "get_weather", + "description": "Current weather and today's forecast for a city. Use for any weather question.", + "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "City, e.g. Toronto"}}, + "required": ["location"]}}}, + {"type": "function", "function": { + "name": "web_search", + "description": "Look up facts and recent events you do not know (Wikipedia). Returns article summaries.", + "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}, +] + + +async def get_weather(client: httpx.AsyncClient, location: str) -> str: + r = await client.get(f"https://wttr.in/{quote(location)}", params={"format": "j1"}, timeout=8) + r.raise_for_status() + d = r.json() + now = d["current_condition"][0] + area = d.get("nearest_area", [{}])[0].get("areaName", [{"value": location}])[0]["value"] + # Three days, so follow-ups like "and tomorrow?" are answered from data, not invented. + days = [] + for label, day in zip(("Today", "Tomorrow", "Day after"), d["weather"]): + noon = (day.get("hourly") or [{}])[len(day.get("hourly") or []) // 2] if day.get("hourly") else {} + sky = noon.get("weatherDesc", [{}])[0].get("value", "") + days.append(f"{label} ({day.get('date', '')}): {day['mintempC']}–{day['maxtempC']}°C" + (f", {sky}" if sky else "")) + return (f"{area} now: {now['weatherDesc'][0]['value']}, {now['temp_C']}°C (feels {now['FeelsLikeC']}°C), " + f"humidity {now['humidity']}%, wind {now['windspeedKmph']} km/h. " + "; ".join(days) + ".") + + +async def web_search(client: httpx.AsyncClient, query: str) -> str: + # Wikipedia's API: reachable from our network (DuckDuckGo timed out), no key, one request for 3 summaries. + # shortcut: encyclopedic and recent-events coverage only, no breaking news; add a news source if needed. + r = await client.get("https://en.wikipedia.org/w/api.php", timeout=8, params={ + "action": "query", "generator": "search", "gsrsearch": query, "gsrlimit": 3, "prop": "extracts", + "exintro": 1, "explaintext": 1, "exchars": 900, "format": "json"}, + headers={"User-Agent": USER_AGENT}) + r.raise_for_status() + pages = sorted(r.json().get("query", {}).get("pages", {}).values(), key=lambda p: p.get("index", 0)) + return "\n\n".join(f"{p['title']}: {p.get('extract', '').strip()}" for p in pages) or "No results." + + +async def run(client: httpx.AsyncClient, name: str, args: dict) -> str: + try: + if name == "get_weather": + return await get_weather(client, str(args.get("location", ""))) + if name == "web_search": + return await web_search(client, str(args.get("query", ""))) + return f"Unknown tool {name}." + except (httpx.HTTPError, KeyError, IndexError, ValueError, TypeError) as exc: + return f"The {name} lookup failed ({type(exc).__name__}). Say you could not look it up." diff --git a/host/sessions/vad.py b/host/sessions/vad.py new file mode 100644 index 0000000..04a7094 --- /dev/null +++ b/host/sessions/vad.py @@ -0,0 +1,100 @@ +"""Voice activity detection for listening sessions: Silero VAD (MIT, ONNX, 16 kHz) plus an endpointer. + +The model scores each 32 ms chunk for speech; the Segmenter turns scores into utterances. A model, not loudness, +decides, so typing, music and room noise do not start an utterance, and a turn can end after a shorter pause. +""" +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +CHUNK = 512 # samples per model step: 32 ms at 16 kHz +CHUNK_BYTES = CHUNK * 2 +MODEL = Path(__file__).with_name("models") / "silero_vad_16k_op15.onnx" + + +class SileroVAD: + """Speech probability per 512-sample chunk of 16 kHz PCM16. One instance per stream (it keeps state).""" + + def __init__(self, path=MODEL): + import onnxruntime as ort # imported here so the host still starts without it when listening is unused + options = ort.SessionOptions() + options.intra_op_num_threads = options.inter_op_num_threads = 1 + self.session = ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"]) + self.reset() + + def reset(self): + self.state = np.zeros((2, 1, 128), dtype=np.float32) + self.context = np.zeros((1, 64), dtype=np.float32) # Silero v5+: each chunk is scored with the last 64 samples + + def __call__(self, chunk: bytes) -> float: + x = np.frombuffer(chunk, dtype=" float: + x = np.frombuffer(chunk, dtype="= self.start_prob else 0 + if self._loud >= self.start_chunks: + self.active, self._audio, self._quiet, self._speech = True, list(self._ring), 0, self._loud + self._ring = [] + return ("start", None) + return None + self._audio.append(chunk) + if prob >= self.end_prob: + self._quiet, self._speech = 0, self._speech + 1 + else: + self._quiet += 1 + if self._quiet >= self.end_chunks or len(self._audio) >= self.max_chunks: + return self.flush() + return None + + def flush(self): + """Ends the current utterance now (end of stream).""" + if not self.active: + return None + audio, speech = b"".join(self._audio), self._speech + self.active, self._audio, self._loud, self._quiet, self._speech = False, [], 0, 0, 0 + return ("end", audio) if speech >= self.min_speech_chunks else ("drop", None) + + def audio(self) -> bytes: + """Audio of the utterance so far (for live partial transcripts).""" + return b"".join(self._audio) diff --git a/host/workers/.gitkeep b/host/workers/.gitkeep deleted file mode 100644 index 8b13789..0000000 --- a/host/workers/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/host/workers/mlx_cache_profile/sitecustomize.py b/host/workers/mlx_cache_profile/sitecustomize.py new file mode 100644 index 0000000..b7c6afb --- /dev/null +++ b/host/workers/mlx_cache_profile/sitecustomize.py @@ -0,0 +1,7 @@ +"""Opt-in for ASR server processes only: bound unused MLX buffers.""" +import os + +if os.environ.get("OPENVOICE_MLX_CACHE_MIB"): + import mlx.core as mx + + mx.set_cache_limit(int(os.environ["OPENVOICE_MLX_CACHE_MIB"]) * 1024**2) diff --git a/host/workers/quantize_asr.py b/host/workers/quantize_asr.py new file mode 100644 index 0000000..ef2a902 --- /dev/null +++ b/host/workers/quantize_asr.py @@ -0,0 +1,34 @@ +"""Make a vllm-metal STT snapshot from the official Qwen3-ASR HF-layout weights.""" +import argparse +import json +import shutil +from pathlib import Path + +import mlx.core as mx + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument("source", type=Path) +p.add_argument("destination", type=Path) +p.add_argument("bits", type=int, choices=(4, 8)) +a = p.parse_args() +a.destination.mkdir(exist_ok=False) +config = json.loads((a.source / "config.json").read_text()) +config["quantization"] = {"group_size": 64, "bits": a.bits, "mode": "affine"} +(a.destination / "config.json").write_text(json.dumps(config)) +for f in a.source.iterdir(): + if f.suffix in (".txt", ".json") and f.name != "config.json" and ".index." not in f.name: + shutil.copyfile(f, a.destination / f.name) +# Keep the encoder in HF layout. The Metal loader itself transposes its convolutions. +weights = {} +count = 0 +for f in sorted(a.source.glob("*.safetensors")): + for name, value in mx.load(str(f)).items(): + if name.startswith("thinker.model.") and name.endswith(".weight") and value.ndim == 2: + q, scales, biases = mx.quantize(value, group_size=64, bits=a.bits) + prefix = name.removesuffix("weight") + weights.update({name: q, prefix+"scales": scales, prefix+"biases": biases}) + count += 1 + else: + weights[name] = value +assert count == 197, f"Unexpected decoder layout: {count} matrices" +mx.save_safetensors(str(a.destination / "model.safetensors"), weights) diff --git a/host/workers/start_local.sh b/host/workers/start_local.sh new file mode 100755 index 0000000..7cb1893 --- /dev/null +++ b/host/workers/start_local.sh @@ -0,0 +1,50 @@ +#!/bin/bash +# Start OpenVoice phase 1 on this Mac: the local model workers and the host. Idempotent: anything already +# answering is left alone. Ports: +# 8100 Qwen3-ASR-1.7B (speech, accurate) 8103 the same with a 4-bit decoder (speech, fast) +# 8101 Qwen3-4B-Instruct 4-bit (clean-up, translation, respond; tool calling enabled) +# 8102 optional translation model: MT_MODEL=mlx-community/Hy-MT2-7B-4bit (+5.4 GB) +# 8765 the host (API + /demo page) +# Needs vllm-metal (docs/subsystems/model-workers.md) and a venv with host/requirements.txt (GW_PY). +# Respond-mode lookups stay off unless OPENVOICE_TOOLS=1 (they send the query off the device). +set -uo pipefail +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +W=${OPENVOICE_WORK:-$HOME/openvoice-work} +VLLM=${VLLM:-$W/vllm-metal/.venv-vllm-metal/bin} +GW_PY=${GW_PY:-$ROOT/.venv/bin/python} +MT_MODEL=${MT_MODEL:-none} +LOGS=${LOGS:-$W/logs}; mkdir -p "$LOGS" +up() { curl -s -m 2 -o /dev/null -w '%{http_code}' "$1" | grep -q 200; } +start() { nohup "$@" < /dev/null & } +CACHE="OPENVOICE_MLX_CACHE_MIB=128 PYTHONPATH=$ROOT/host/workers/mlx_cache_profile" # halves ASR memory (T13) + +up 127.0.0.1:8100/v1/models || start env $CACHE "$VLLM/vllm" serve Qwen/Qwen3-ASR-1.7B --host 127.0.0.1 --port 8100 > "$LOGS/asr.log" 2>&1 +Q4=$W/models/qwen3-asr-1.7b-q4 +[ -f "$Q4/model.safetensors" ] || "$VLLM/python" "$ROOT/host/workers/quantize_asr.py" \ + "$(ls -d "$HOME"/.cache/huggingface/hub/models--Qwen--Qwen3-ASR-1.7B/snapshots/*/ | head -1)" "$Q4" 4 > "$LOGS/quantize.log" 2>&1 +up 127.0.0.1:8103/v1/models || start env $CACHE "$VLLM/vllm" serve "$Q4" --served-model-name Qwen3-ASR-1.7B-4bit \ + --host 127.0.0.1 --port 8103 > "$LOGS/asr-fast.log" 2>&1 +up 127.0.0.1:8101/v1/models || start "$VLLM/vllm" serve mlx-community/Qwen3-4B-Instruct-2507-4bit --host 127.0.0.1 --port 8101 \ + --max-model-len 4096 --max-num-seqs 1 --kv-cache-memory-bytes 1073741824 --enable-auto-tool-choice --tool-call-parser hermes \ + > "$LOGS/llm.log" 2>&1 +MT_ENV="" +if [ "$MT_MODEL" != none ]; then + up 127.0.0.1:8102/v1/models || start "$VLLM/vllm" serve "$MT_MODEL" --host 127.0.0.1 --port 8102 \ + --max-model-len 4096 --max-num-seqs 1 --kv-cache-memory-bytes 1073741824 > "$LOGS/mt.log" 2>&1 + MT_ENV="OPENVOICE_MT_URL=http://127.0.0.1:8102 OPENVOICE_MT_MODEL=$MT_MODEL" +fi + +echo "Loading models (first start takes 1-3 min)..." +for i in $(seq 1 100); do + up 127.0.0.1:8100/v1/models && up 127.0.0.1:8103/v1/models && up 127.0.0.1:8101/v1/models \ + && { [ "$MT_MODEL" = none ] || up 127.0.0.1:8102/v1/models; } && break + sleep 3 +done + +cd "$ROOT" +up 127.0.0.1:8765/v1/capabilities || start env $MT_ENV OPENVOICE_LLM_MODEL=mlx-community/Qwen3-4B-Instruct-2507-4bit \ + OPENVOICE_ASR_FAST_URL=http://127.0.0.1:8103 OPENVOICE_ASR_FAST_MODEL=Qwen3-ASR-1.7B-4bit \ + ${OPENVOICE_TOOLS:+OPENVOICE_TOOLS=$OPENVOICE_TOOLS} "$GW_PY" -m host.sessions > "$LOGS/host.log" 2>&1 +for i in $(seq 1 20); do up 127.0.0.1:8765/v1/capabilities && break; sleep 1; done +curl -s 127.0.0.1:8765/v1/health; echo +echo "Demo page: http://127.0.0.1:8765/demo" diff --git a/spikes/t20_speakers/benchmark.py b/spikes/t20_speakers/benchmark.py new file mode 100644 index 0000000..889ad7e --- /dev/null +++ b/spikes/t20_speakers/benchmark.py @@ -0,0 +1,207 @@ +"""Run from the repository root with python -m spikes.t20_speakers.benchmark.""" + +import argparse +import itertools +import json +import resource +import sys +import time +import wave +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np +from scipy.optimize import linear_sum_assignment + +from host.sessions import vad +from host.sessions.speakers import Embedder, SpeakerSession + + +def pcm(path): + with wave.open(str(path), "rb") as w: + assert (w.getnchannels(), w.getsampwidth(), w.getframerate()) == (1, 2, 16000) + return w.readframes(w.getnframes()) + + +def match(matrix): + if not matrix.size: + return 0 + a, b = linear_sum_assignment(matrix, maximize=True) + return matrix[a, b].sum() + + +def classify(rows, threshold, enroll): + refs = defaultdict(list) + if enroll: + for row in rows: + if row["role"] == "enroll": + refs[row["speaker"]].extend(row["vectors"]) + session = SpeakerSession( + None, + threshold=threshold, + enrolled={s: np.mean(v, axis=0) for s, v in refs.items()}, + ) + pairs = [] + named = 0 + for r in rows: + if r["role"] != "test": + continue + label = session.assign(r["vectors"][0]) + pairs.append((r["speaker"], label["id"])) + named += label.get("name") == r["speaker"] + truth = sorted({a for a, _ in pairs}) + found = sorted({b for _, b in pairs}) + counts = Counter(pairs) + matrix = np.array([[counts[a, b] for b in found] for a in truth]) + return dict( + n=len(pairs), + correct=int(match(matrix)), + named=named, + split=sum((matrix > 0).sum(axis=1) > 1).item(), + speakers=len(truth), + merge=sum((matrix > 0).sum(axis=0) > 1).item(), + clusters=len(found), + ) + + +def diarize(audio, embedder, threshold): + detector, endpointer = vad.SileroVAD(), vad.Segmenter() + session = SpeakerSession(embedder, enrolled={}, threshold=threshold) + hyp = [] + voiced = [] + for start in range(0, len(audio), vad.CHUNK_BYTES): + block = audio[start : start + vad.CHUNK_BYTES].ljust(vad.CHUNK_BYTES, b"\0") + t = start / 32000 + probability = detector(block) + if probability >= endpointer.end_prob: + voiced.append(t) + event = endpointer.feed(block, probability) + if start + vad.CHUNK_BYTES >= len(audio) and event is None: + event = endpointer.flush() + if event and event[0] == "end": + payload = event[1] + end = t + 0.032 + begin = max(0, end - len(payload) / 32000) + active = [v for v in voiced if v >= begin - 1e-6] + if active: + label = session.label(payload)["id"] + hyp.append( + (active[0], min(end, active[-1] + 0.032, len(audio) / 32000), label) + ) + voiced.clear() + return hyp + + +def error_times(ref, hyp, duration, collar=0.25): + # Exact piecewise-constant integration. Exclude +/- collar at reference boundaries. + boundaries = {t for a, b, _ in ref for t in (a, b)} + edges = {0.0, duration} | {t for a, b, _ in [*ref, *hyp] for t in (a, b)} + for t in boundaries: + edges.update((t - collar, t + collar)) + edges = sorted(x for x in edges if 0 <= x <= duration) + speakers = sorted({s for _, _, s in ref}) + labels = sorted({s for _, _, s in hyp}) + co = np.zeros((len(speakers), len(labels))) + miss = fa = common = total = 0.0 + for a, b in itertools.pairwise(edges): + t = (a + b) / 2 + if any(abs(t - edge) < collar for edge in boundaries): + continue + r = {s for x, y, s in ref if x <= t < y} + h = {s for x, y, s in hyp if x <= t < y} + dt = b - a + for s in r: + for label in h: + co[speakers.index(s), labels.index(label)] += dt + miss += dt * max(0, len(r) - len(h)) + fa += dt * max(0, len(h) - len(r)) + common += dt * min(len(r), len(h)) + total += dt * len(r) + confusion = max(0.0, common - match(co)) + return dict(ref_s=total, miss_s=miss, fa_s=fa, confusion_s=confusion) + + +def main(): + args = argparse.ArgumentParser() + args.add_argument("data", type=Path) + args.add_argument("model", type=Path) + args.add_argument("output", type=Path) + opts = args.parse_args() + rows = [ + json.loads(s) for s in (opts.data / "manifest.jsonl").read_text().splitlines() + ] + start = time.perf_counter() + embed = Embedder(opts.model) + load_ms = (time.perf_counter() - start) * 1000 + groups = defaultdict(list) + timings = [] + cold = None + timer_cluster = SpeakerSession(None, enrolled={}) + for row in rows: + audio = pcm(row["path"]) + chunks = [audio] + if row["role"] == "enroll": + assert len(audio) >= 320000 + chunks = [audio[i : i + 80000] for i in range(0, 320000, 80000)] + vectors = [] + for chunk in chunks: + t = time.perf_counter() + vec = embed(chunk) + if cold is None: + cold = load_ms + (time.perf_counter() - t) * 1000 + if row["role"] == "test": + timer_cluster.assign(vec) + timings.append((time.perf_counter() - t) * 1000) + vectors.append(vec) + groups[row["split"], row["session"]].append(dict(row, vectors=vectors)) + + def dev_score(t): + result = [ + classify(g, t, enrolled) + for (split, _), g in groups.items() + if split == "dev" + for enrolled in (False, True) + ] + assert result + return sum( + r["correct"] if i % 2 == 0 else r["named"] for i, r in enumerate(result) + ) + + grid = [round(i / 100, 2) for i in range(20, 81, 5)] + threshold = max(grid, key=dev_score) + live = { + s: { + k: classify(g, threshold, e) + for k, e in [("anon", False), ("enrolled", True)] + } + for (split, s), g in groups.items() + if split == "test" + } + result = dict( + threshold=threshold, + dev_scores={str(t): dev_score(t) for t in grid}, + load_ms=load_ms, + cold_ms=cold, + latency_n=len(timings), + latency_ms=np.percentile(timings, [50, 90]).tolist(), + live=live, + recordings={}, + ) + for line in (opts.data / "recordings.jsonl").read_text().splitlines(): + rec = json.loads(line) + if rec["session"] not in live: + continue + audio = pcm(rec["path"]) + hyp = diarize(audio, embed, threshold) + result["recordings"][rec["session"]] = error_times( + rec["segments"], hyp, len(audio) / 32000 + ) + result["peak_rss_mib"] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / ( + 1024**2 if sys.platform == "darwin" else 1024 + ) + opts.output.write_text(json.dumps(result, indent=2) + "\n") + + +if __name__ == "__main__": + assert error_times([(0, 3, "a"), (1, 2, "b")], [(0, 3, "x")], 3, 0)["miss_s"] == 1 + main() diff --git a/spikes/t20_speakers/check_host.py b/spikes/t20_speakers/check_host.py new file mode 100644 index 0000000..94b7119 --- /dev/null +++ b/spikes/t20_speakers/check_host.py @@ -0,0 +1,122 @@ +"""Paired in-process listen check with real VAD/embedding and zero-network mocked ASR.""" + +import argparse +import json +import time +from collections import defaultdict +from pathlib import Path + +import httpx +import numpy as np +from fastapi.testclient import TestClient + +from host.sessions.app import create_app +from host.sessions.speakers import SpeakerSession, load_embedder +from spikes.t20_speakers.benchmark import pcm + + +def run(data): + rows_all = [ + json.loads(line) for line in (data / "manifest.jsonl").read_text().splitlines() + ] + sessions = defaultdict(list) + for row in rows_all: + if row["split"] == "test" and row["role"] == "test": + sessions[row["session"]].append(row) + + def backend(request): + assert request.url.path == "/v1/audio/transcriptions" + return httpx.Response(200, json={"text": "language EnglishOK"}) + + host = create_app(httpx.MockTransport(backend)) + marks = {} + + async def traced(scope, receive, send): + async def capture(message): + if message["type"] == "websocket.send" and "text" in message: + e = json.loads(message["text"]) + marks[e["type"], e.get("utterance")] = time.perf_counter() + await send(message) + + await host(scope, receive, capture) + + deltas, labelled = [], 0 + with TestClient(traced, base_url="http://127.0.0.1") as client: + for rows in sessions.values(): + for index, row in enumerate(rows[:8]): + latencies = {} + for enabled in (bool(index % 2), not bool(index % 2)): + marks.clear() + with client.websocket_connect("ws://127.0.0.1/v1/listen") as ws: + ws.send_json( + { + "type": "start", + "speakers": enabled, + "options": {"mode": "transcribe"}, + "vad": {"partials": False}, + "audio": { + "encoding": "pcm_s16le", + "sample_rate": 16000, + "channels": 1, + }, + } + ) + first = ws.receive_json() + assert first["type"] == "ready", first + audio = pcm(row["path"]) + for i in range(0, len(audio), 3200): + ws.send_bytes(audio[i : i + 3200]) + ws.send_json({"type": "stop"}) + while True: + event = ws.receive_json() + if event["type"] == "done": + break + if event["type"] == "final" and event["utterance"] == 1: + labelled += enabled and "speaker" in event + latencies[enabled] = 1000 * ( + marks["final", 1] - marks["speech_end", 1] + ) + if len(latencies) == 2: + deltas.append(latencies[True] - latencies[False]) + # One enrolled speaker at a time. Count false names on other people's turns. + embed = load_embedder() + positives = hits = negatives = false_names = 0 + for scope_rows in sessions.values(): + sid = scope_rows[0]["session"] + vectors = [embed(pcm(r["path"])) for r in scope_rows] + for ref in rows_all: + if ref["role"] != "enroll" or ref["session"] != sid: + continue + audio = pcm(ref["path"]) + voice = np.mean( + [embed(audio[i : i + 80000]) for i in range(0, 320000, 80000)], axis=0 + ) + speaker = ref["speaker"] + session = SpeakerSession(embed, enrolled={speaker: voice}) + for r, vector in zip(scope_rows, vectors, strict=True): + named = session.assign(vector).get("name") == speaker + if r["speaker"] == speaker: + positives += 1 + hits += named + else: + negatives += 1 + false_names += named + print( + json.dumps( + dict( + pairs=len(deltas), + labelled=labelled, + added_ms_p50_p90_max=[*np.percentile(deltas, [50, 90]), max(deltas)], + positives=positives, + hits=hits, + negatives=negatives, + false_names=false_names, + ) + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("data", type=Path) + run(parser.parse_args().data) diff --git a/spikes/t20_speakers/enroll.py b/spikes/t20_speakers/enroll.py new file mode 100644 index 0000000..31f9c97 --- /dev/null +++ b/spikes/t20_speakers/enroll.py @@ -0,0 +1,41 @@ +"""Create a new, private enrolment file from consenting speakers' 16 kHz PCM WAVs.""" + +import argparse +import json +import os +import wave +from pathlib import Path + +from host.sessions.speakers import MODEL_ID, enrol_vector, load_embedder + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("samples", nargs="+", metavar="NAME=FILE.wav") + args = parser.parse_args() + embed = load_embedder() + voices = {} + for item in args.samples: + name, path = item.split("=", 1) + if not name.strip() or name in voices: + parser.error("Each name must be nonempty and unique") + with wave.open(path, "rb") as w: + if (w.getframerate(), w.getnchannels(), w.getsampwidth()) != (16000, 1, 2): + parser.error("Supply a mono 16 kHz PCM16 WAV") + audio = w.readframes(160000) + try: + voices[name] = enrol_vector(embed, audio).tolist() + except ValueError as exc: + parser.error(str(exc)) + # Publish a complete owner-only file without replacing an existing store. + import tempfile + + with tempfile.NamedTemporaryFile(dir=args.output.parent) as tmp: + tmp.write(json.dumps({"model": MODEL_ID, "voices": voices}).encode()) + tmp.flush() + os.link(tmp.name, args.output) + + +if __name__ == "__main__": + main() diff --git a/spikes/t20_speakers/prepare_data.py b/spikes/t20_speakers/prepare_data.py new file mode 100644 index 0000000..2f04ef2 --- /dev/null +++ b/spikes/t20_speakers/prepare_data.py @@ -0,0 +1,277 @@ +"""Prepare the small T20 benchmark locally. Requires pyarrow, curl and ffmpeg. + +AMI Consortium, CC BY 4.0 (AMI audio and BUTSpeechFIT word RTTM). +AliMeeting (Yu et al.) and ASCEND (Lovenia et al.), CC BY-SA 4.0. +Local derivatives retain the corresponding corpus license. See docs/results/T20.md. +""" + +import argparse +import io +import json +import re +import subprocess +import tempfile +import wave +from collections import defaultdict +from pathlib import Path + +import pyarrow.parquet as pq + +HF = "https://huggingface.co/datasets/" +AMI = ( + HF + + "FluidInference/ami-corpus-mirror/resolve/722d8891643e1e4dc62cfd0d198fa05a1646c3cc/sdm/" +) +RTTM = "https://raw.githubusercontent.com/BUTSpeechFIT/AMI-diarization-setup/2509d8933721023fab4def2618aabd5c28eb82e9/only_words/rttms/test/" +ALI = ( + HF + "argmaxinc/ali-meetings/resolve/67b7506f0db35d211aca5d0fae7ff946439f1bea/data/" +) +ASC = HF + "CAiRE/ASCEND/resolve/737e9800ae31be9932ba8464c80366559bd28424/main/" +RATE = 16000 +BPS = RATE * 2 + + +def fetch(base, name, cache): + path = cache / name + if not path.exists(): + part = path.with_suffix(".part") + subprocess.run( + ["curl", "-fsSL", "--retry", "3", base + name, "-o", part], check=True + ) + part.replace(path) + return path + + +def pcm(source): + with wave.open(source, "rb") as w: + assert (w.getframerate(), w.getnchannels(), w.getsampwidth()) == (RATE, 1, 2) + return w.readframes(w.getnframes()) + + +def save(path, audio): + assert len(audio) > 0 and len(audio) % 2 == 0 + with wave.open(str(path), "wb") as w: + w.setparams((1, 2, RATE, 0, "NONE", "not compressed")) + w.writeframes(audio) + return str(path) + + +def cut(audio, a, b): + return audio[round(a * RATE) * 2 : round(b * RATE) * 2] + + +def trials(output, session, split, by_speaker): + """Each item is (sort key, audio, source description). No item is reused.""" + manifest, scored = [], [] + for speaker, items in sorted(by_speaker.items()): + items = iter(items) + enrollment, sources = bytearray(), [] + while len(enrollment) < 10.2 * BPS: + _, audio, source = next(items) + enrollment.extend(audio) + sources.append(source) + + def row(role, path, origin): + return dict( + session=session, + split=split, + speaker=speaker, + role=role, + path=path, + source=origin, + ) + + path = save( + output / f"{session}-{speaker}-enroll.wav", enrollment[: round(10.2 * BPS)] + ) + manifest.append(row("enroll", path, sources)) + remaining = list(items) + assert len(remaining) >= 4, (session, speaker, len(remaining)) + count = min(8, len(remaining)) + for i in range(count): + key, audio, source = remaining[ + round(i * (len(remaining) - 1) / (count - 1)) + ] + path = save(output / f"{session}-{speaker}-{i}.wav", audio) + scored.append((key, row("test", path, source))) + scored.sort(key=lambda pair: pair[0]) + return manifest + [r for _, r in scored] + + +def meeting(output, session, split, audio, segments): + # First two-minute window on a minute grid with at least one second of overlap. + overlaps = [ + (max(a, c), min(b, d)) + for a, b, s in segments + for c, d, t in segments + if s < t and a < d and b > c + ] + lo = next( + i + for i in range(0, int(len(audio) / BPS) - 119, 60) + if any(min(end, i + 120) - max(start, i) >= 1 for start, end in overlaps) + ) + hi = lo + 120 + assert hi <= len(audio) / BPS + reference = [ + [round(max(lo, a) - lo, 5), round(min(hi, b) - lo, 5), s] + for a, b, s in sorted(segments) + if a < hi and b > lo + ] + assert any( + a < d and b > c and s != t for a, b, s in reference for c, d, t in reference + ) + recording = dict( + session=session, + split=split, + source_start=lo, + synthetic=False, + path=save(output / f"{session}-meeting.wav", cut(audio, lo, hi)), + segments=reference, + ) + groups = defaultdict(list) + for a, b, s in sorted(segments): + # Score only annotated solo turns. Prevent the recording and live sets from intersecting. + if a < hi and b > lo: + continue + cursor = a + intervals = [] + for start, stop in sorted( + (x, y) for x, y, t in segments if t != s and x < b and y > a + ): + if cursor < start: + intervals.append((cursor, start)) + cursor = max(cursor, stop) + if cursor < b: + intervals.append((cursor, b)) + for start, stop in intervals: + if stop - start >= 1.0: + end = min(stop, start + 6) + groups[s].append((start, cut(audio, start, end), [session, start, end])) + assert set(groups) == {s for _, _, s in segments} + return trials(output, session, split, groups), recording + + +def ascend(output, split, file): + session = "ASCEND-" + split + groups = defaultdict(list) + for row in pq.read_table(file).to_pylist(): + transcript = row["transcription"] + if ( + row["language"] != "mixed" + or not 1.2 <= row["duration"] <= 8 + or not re.search("[a-zA-Z]", transcript) + or not re.search("[\u4e00-\u9fff]", transcript) + ): + continue + speaker = str(row["original_speaker_id"]) + name = Path(row["path"]).name + assert f"_spk{speaker}_" in name + groups[speaker].append( + (row["id"], pcm(io.BytesIO(row["audio"]["bytes"])), name) + ) + assert 2 <= len(groups) <= 4 + rows = trials(output, session, split, groups) + turns = [row for row in rows if row["role"] == "test"] + # Interleave speakers with a reproducible 400 ms silent pause. + turns.sort( + key=lambda r: (int(Path(r["path"]).stem.rsplit("-", 1)[1]), r["speaker"]) + ) + audio, segments = bytearray(), [] + for row in turns: + start = len(audio) / BPS + audio.extend(pcm(row["path"])) + segments.append([start, len(audio) / BPS, row["speaker"]]) + audio.extend(bytes(round(0.4 * BPS))) + return [r for r in rows if r["role"] == "enroll"] + turns, dict( + session=session, + split=split, + synthetic=True, + segments=segments, + path=save(output / f"{session}-meeting.wav", audio), + ) + + +def prepare(output, cache): + live, recordings = [], [] + for index, (split, ami) in enumerate([("dev", "ES2004a"), ("test", "TS3003b")]): + ann = fetch(RTTM, ami + ".rttm", cache).read_text().splitlines() + segments = [] + for line in ann: + _, sid, _, start, duration, _, _, speaker, *_ = line.split() + assert sid == ami + segments.append( + (float(start), round(float(start) + float(duration), 5), speaker) + ) + audio = pcm(str(fetch(AMI, ami + ".Mix-Headset.wav", cache))) + rows, rec = meeting(output, "AMI-" + ami, split, audio, segments) + live.extend(rows) + recordings.append(rec) + shard = fetch(ALI, f"test-{index:05d}-of-00020.parquet", cache) + table = pq.read_table(shard) + # One full multichannel recording per shard. Avoid copying its bytes into Python. + assert table.num_rows == 1 + blob = table["audio"][0] + sid = Path(blob["path"].as_py()).stem + with tempfile.TemporaryDirectory(dir=cache) as d: + raw, mono = Path(d) / "multichannel.wav", Path(d) / "mono.wav" + with raw.open("wb") as f: + f.write(memoryview(blob["bytes"].as_buffer())) + subprocess.run( + [ + "ffmpeg", + "-loglevel", + "error", + "-i", + raw, + "-af", + "pan=mono|c0=c0", + "-ar", + str(RATE), + "-c:a", + "pcm_s16le", + mono, + ], + check=True, + ) + audio = pcm(str(mono)) + segments = list( + zip( + *( + table[k][0].as_py() + for k in ("timestamps_start", "timestamps_end", "speakers") + ), + strict=True, + ) + ) + del table, blob + rows, rec = meeting(output, "AliMeeting-" + sid, split, audio, segments) + live.extend(rows) + recordings.append(rec) + official = "validation" if split == "dev" else "test" + rows, rec = ascend( + output, split, fetch(ASC, official + "-00000-of-00001.parquet", cache) + ) + live.extend(rows) + recordings.append(rec) + dev = {r["speaker"] for r in live if r["split"] == "dev"} + assert dev.isdisjoint({r["speaker"] for r in live if r["split"] == "test"}) + for name, data in [("manifest", live), ("recordings", recordings)]: + (output / (name + ".jsonl")).write_text( + "".join(json.dumps(r) + "\n" for r in data) + ) + + +if __name__ == "__main__": + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--output", type=Path, default=Path("/tmp/t20-data")) + p.add_argument( + "--cache", type=Path, help="Retain downloaded source files in this directory" + ) + args = p.parse_args() + output = args.output.resolve() + output.mkdir(mode=0o700, parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp: + cache = args.cache or Path(tmp) + cache.mkdir(parents=True, exist_ok=True) + prepare(output, cache) diff --git a/spikes/t20_speakers/recording_model.py b/spikes/t20_speakers/recording_model.py new file mode 100644 index 0000000..b3d601e --- /dev/null +++ b/spikes/t20_speakers/recording_model.py @@ -0,0 +1,80 @@ +"""Measure NVIDIA's native CPU diarizer on the prepared held-out meeting WAVs (macOS).""" + +import argparse +import json +import re +import subprocess +import tempfile +import time +import wave +from pathlib import Path + +from .benchmark import error_times + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("manifest", type=Path) + parser.add_argument("cli", type=Path) + parser.add_argument("model", type=Path) + args = parser.parse_args() + for line in args.manifest.read_text().splitlines(): + row = json.loads(line) + if row["split"] != "test": + continue + with tempfile.TemporaryDirectory() as tmp: + rttm = Path(tmp) / "output.rttm" + start = time.perf_counter() + proc = subprocess.run( + [ + "/usr/bin/time", + "-l", + str(args.cli), + "diarize", + row["path"], + "--model", + str(args.model), + "--device", + "cpu", + "--preset", + "v3-offline", + "--format", + "rttm", + "--output", + str(rttm), + ], + stderr=subprocess.PIPE, + text=True, + ) + wall = time.perf_counter() - start + if proc.returncode: + raise RuntimeError(proc.stderr) + peak = re.search(r"(\d+)\s+maximum resident set size", proc.stderr) + if peak is None: + raise ValueError("macOS time did not report process RSS") + hyp = [] + for turn in rttm.read_text().splitlines(): + fields = turn.split() + if fields[0] != "SPEAKER" or len(fields) != 10: + raise ValueError(f"Invalid RTTM record: {turn!r}") + begin, length = map(float, fields[3:5]) + hyp.append((begin, begin + length, fields[7])) + with wave.open(row["path"]) as audio: + duration = audio.getnframes() / audio.getframerate() + scores = error_times(row["segments"], hyp, duration) + print( + json.dumps( + dict( + session=row["session"], + duration_s=duration, + wall_s=wall, + peak_bytes=int(peak[1]), + **scores, + ) + ), + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/spikes/t20_speakers/results/cam.json b/spikes/t20_speakers/results/cam.json new file mode 100644 index 0000000..cfe2bd2 --- /dev/null +++ b/spikes/t20_speakers/results/cam.json @@ -0,0 +1,108 @@ +{ + "threshold": 0.35, + "dev_scores": { + "0.2": 144, + "0.25": 160, + "0.3": 168, + "0.35": 169, + "0.4": 168, + "0.45": 169, + "0.5": 167, + "0.55": 159, + "0.6": 143, + "0.65": 116, + "0.7": 71, + "0.75": 41, + "0.8": 18 + }, + "load_ms": 212.78166699994472, + "cold_ms": 235.29595800027892, + "latency_n": 168, + "latency_ms": [ + 19.047124500502832, + 19.51291249897622 + ], + "live": { + "AMI-TS3003b": { + "anon": { + "n": 32, + "correct": 32, + "named": 0, + "split": 0, + "speakers": 4, + "merge": 0, + "clusters": 4 + }, + "enrolled": { + "n": 32, + "correct": 32, + "named": 32, + "split": 0, + "speakers": 4, + "merge": 0, + "clusters": 4 + } + }, + "AliMeeting-R8002_M8003_MS803": { + "anon": { + "n": 32, + "correct": 30, + "named": 0, + "split": 1, + "speakers": 4, + "merge": 1, + "clusters": 4 + }, + "enrolled": { + "n": 32, + "correct": 32, + "named": 32, + "split": 0, + "speakers": 4, + "merge": 0, + "clusters": 4 + } + }, + "ASCEND-test": { + "anon": { + "n": 16, + "correct": 14, + "named": 0, + "split": 1, + "speakers": 2, + "merge": 0, + "clusters": 3 + }, + "enrolled": { + "n": 16, + "correct": 14, + "named": 14, + "split": 1, + "speakers": 2, + "merge": 0, + "clusters": 3 + } + } + }, + "recordings": { + "AMI-TS3003b": { + "ref_s": 86.21000000000001, + "miss_s": 15.260000000000039, + "fa_s": 0.0, + "confusion_s": 0.7620000000000005 + }, + "AliMeeting-R8002_M8003_MS803": { + "ref_s": 75.27000000000001, + "miss_s": 6.618000000000023, + "fa_s": 2.7159999999999584, + "confusion_s": 7.643999999999977 + }, + "ASCEND-test": { + "ref_s": 48.470187500000016, + "miss_s": 0.7360000000000042, + "fa_s": 0.0, + "confusion_s": 19.540000000000006 + } + }, + "peak_rss_mib": 228.234375 +} diff --git a/spikes/t20_speakers/results/eres.json b/spikes/t20_speakers/results/eres.json new file mode 100644 index 0000000..9c46fc5 --- /dev/null +++ b/spikes/t20_speakers/results/eres.json @@ -0,0 +1,108 @@ +{ + "threshold": 0.5, + "dev_scores": { + "0.2": 120, + "0.25": 136, + "0.3": 152, + "0.35": 152, + "0.4": 160, + "0.45": 168, + "0.5": 176, + "0.55": 168, + "0.6": 157, + "0.65": 133, + "0.7": 103, + "0.75": 67, + "0.8": 22 + }, + "load_ms": 91.9928749990504, + "cold_ms": 185.70891699891945, + "latency_n": 168, + "latency_ms": [ + 101.15583350034285, + 104.99072509956022 + ], + "live": { + "AMI-TS3003b": { + "anon": { + "n": 32, + "correct": 31, + "named": 0, + "split": 1, + "speakers": 4, + "merge": 0, + "clusters": 5 + }, + "enrolled": { + "n": 32, + "correct": 31, + "named": 31, + "split": 1, + "speakers": 4, + "merge": 0, + "clusters": 5 + } + }, + "AliMeeting-R8002_M8003_MS803": { + "anon": { + "n": 32, + "correct": 32, + "named": 0, + "split": 0, + "speakers": 4, + "merge": 0, + "clusters": 4 + }, + "enrolled": { + "n": 32, + "correct": 32, + "named": 32, + "split": 0, + "speakers": 4, + "merge": 0, + "clusters": 4 + } + }, + "ASCEND-test": { + "anon": { + "n": 16, + "correct": 14, + "named": 0, + "split": 1, + "speakers": 2, + "merge": 0, + "clusters": 3 + }, + "enrolled": { + "n": 16, + "correct": 14, + "named": 14, + "split": 1, + "speakers": 2, + "merge": 0, + "clusters": 3 + } + } + }, + "recordings": { + "AMI-TS3003b": { + "ref_s": 86.21000000000001, + "miss_s": 15.260000000000039, + "fa_s": 0.0, + "confusion_s": 0.960000000000008 + }, + "AliMeeting-R8002_M8003_MS803": { + "ref_s": 75.27000000000001, + "miss_s": 6.618000000000023, + "fa_s": 2.7159999999999584, + "confusion_s": 7.913999999999973 + }, + "ASCEND-test": { + "ref_s": 48.470187500000016, + "miss_s": 0.7360000000000042, + "fa_s": 0.0, + "confusion_s": 19.540000000000006 + } + }, + "peak_rss_mib": 362.3125 +} diff --git a/spikes/t20_speakers/results/host.json b/spikes/t20_speakers/results/host.json new file mode 100644 index 0000000..65667da --- /dev/null +++ b/spikes/t20_speakers/results/host.json @@ -0,0 +1 @@ +{"pairs": 24, "labelled": 24, "added_ms_p50_p90_max": [18.939126000077522, 19.971913100380334, 21.188208000239683], "positives": 80, "hits": 78, "negatives": 208, "false_names": 3} diff --git a/spikes/t20_speakers/results/nemotron.jsonl b/spikes/t20_speakers/results/nemotron.jsonl new file mode 100644 index 0000000..38579df --- /dev/null +++ b/spikes/t20_speakers/results/nemotron.jsonl @@ -0,0 +1,3 @@ +{"session": "AMI-TS3003b", "duration_s": 120.0, "wall_s": 1.3541104169999016, "peak_bytes": 199835648, "ref_s": 86.21000000000002, "miss_s": 11.555000000000032, "fa_s": 0.41799999999999216, "confusion_s": 0.06999999999999318} +{"session": "AliMeeting-R8002_M8003_MS803", "duration_s": 120.0, "wall_s": 1.3426210420002462, "peak_bytes": 194625536, "ref_s": 75.27000000000001, "miss_s": 3.944000000000022, "fa_s": 0.29500000000001414, "confusion_s": 1.5589999999999975} +{"session": "ASCEND-test", "duration_s": 62.8701875, "wall_s": 0.6622172910010704, "peak_bytes": 175210496, "ref_s": 48.470187500000016, "miss_s": 0.39099999999999824, "fa_s": 0.0, "confusion_s": 5.0290000000000035}