[Full Duplex] Feat: Support Full-Duplex realtime runtime & add MiniCPM-o 4.5 demo (#3907)
Signed-off-by: Sy03 <1370724210@qq.com> Signed-off-by: lishunyang12 <lishunyang03@gmail.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: lishunyang12 <lishunyang03@gmail.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: StormMelody <22371184@zju.edu.cn> Co-authored-by: Gao Han <hgaoaf@connect.ust.hk> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
142 files changed
+48389
-1013
No files matched your search
@@ -1,159 +1,139 @@
|
||||
# MiniCPM-o 4.5: Online serving
|
||||
|
||||
OpenAI-compatible `/v1/chat/completions` serving for **MiniCPM-o 4.5**, plus a
|
||||
Gradio UI and curl / Python clients.
|
||||
This directory contains MiniCPM-o 4.5 online serving demos for vLLM-Omni.
|
||||
Inputs can include text, image, audio, or video; outputs are text and optional
|
||||
24 kHz speech.
|
||||
|
||||
Inputs: text / image / audio / video. Outputs: text and optional **24 kHz** speech.
|
||||
For the experimental native duplex runtime architecture, lifecycle invariants,
|
||||
capability boundary, and validation scope, see
|
||||
[`vllm_omni/experimental/fullduplex/DESIGN.md`](../../../vllm_omni/experimental/fullduplex/DESIGN.md).
|
||||
|
||||
## Installation
|
||||
|
||||
Please refer to [README.md](../../../README.md). Install the talker extra:
|
||||
Install vLLM-Omni with the MiniCPM-o talker dependencies:
|
||||
|
||||
```bash
|
||||
pip install 'vllm-omni[minicpmo]'
|
||||
|
||||
# From a source checkout:
|
||||
pip install -e '.[minicpmo]'
|
||||
```
|
||||
|
||||
## Launch the server
|
||||
The `minicpmo` extra installs `stepaudio2-minicpmo` and its audio dependencies,
|
||||
including `librosa`.
|
||||
|
||||
The deploy config auto-loads via `--omni`; the default
|
||||
`vllm_omni/deploy/minicpmo_4_5.yaml` targets a single-GPU layout (thinker
|
||||
and talker + t2w co-located on GPU 0). For other hardware layouts pick
|
||||
one of the deploy variants below.
|
||||
## Start the backend server
|
||||
|
||||
| deploy config | GPUs | Notes |
|
||||
|---|---|---|
|
||||
| `minicpmo_4_5.yaml` (default) | 1 | Thinker and talker+t2w co-located on GPU0. |
|
||||
| `minicpmo_4_5_2gpu.yaml` | 2 | Thinker on GPU0, talker+t2w on GPU1. |
|
||||
| `minicpmo_4_5_3gpu.yaml` | 3 | Thinker 2-way TP on GPU0/1, talker+t2w share GPU2. |
|
||||
| `minicpmo_4_5_8x4090.yaml` | 8 | Full 8x4090 layout. |
|
||||
Pick a deploy config that matches your GPU layout:
|
||||
|
||||
Default (single-GPU):
|
||||
| config | GPUs | TP | Notes |
|
||||
|---|---|---|---|
|
||||
| `minicpmo_4_5.yaml` | 1 | 1 | Thinker and talker+t2w co-located on GPU0. |
|
||||
| `minicpmo_4_5_2gpu.yaml` | 2 | 1 | Thinker on GPU0, talker+t2w on GPU1. |
|
||||
| `minicpmo_4_5_3gpu.yaml` | 3 | 2 | Thinker 2-way TP on GPU0/1, talker+t2w share GPU2. |
|
||||
| `minicpmo_4_5_8x4090.yaml` | 8 | 4 | Thinker 4-way TP on GPU0-3, talker+t2w on GPU4. |
|
||||
| `minicpmo_4_5_3gpu_stage1_replicas.yaml` | 3 | 1 | Experimental validation profile: Thinker on GPU0, two talker+Token2wav replicas on GPU1/2. |
|
||||
| `minicpmo_4_5_4gpu_stage1_replicas.yaml` | 4 | 1 | Experimental validation profile: Thinker on GPU0, three talker+Token2wav replicas on GPU1/2/3. |
|
||||
| `minicpmo_4_5_8x4090_stage1_replicas.yaml` | 8 | 4 | Experimental validation profile: Thinker 4-way TP on GPU0-3, four talker+Token2wav replicas on GPU4-7. |
|
||||
| `minicpmo_4_5_duplex.yaml` | 2 | 1 | Experimental native duplex profile. |
|
||||
|
||||
```bash
|
||||
vllm serve openbmb/MiniCPM-o-4_5 --omni \
|
||||
vllm-omni serve openbmb/MiniCPM-o-4_5 \
|
||||
--omni \
|
||||
--deploy-config vllm_omni/deploy/minicpmo_4_5.yaml \
|
||||
--trust-remote-code \
|
||||
--host 0.0.0.0 --port 8099
|
||||
```
|
||||
|
||||
Other layouts:
|
||||
For local ModelScope checkpoints, replace `openbmb/MiniCPM-o-4_5` with the
|
||||
checkpoint path. To start the experimental native duplex backend, use
|
||||
`vllm_omni/deploy/minicpmo_4_5_duplex.yaml`.
|
||||
|
||||
```bash
|
||||
vllm serve openbmb/MiniCPM-o-4_5 --omni \
|
||||
--deploy-config vllm_omni/deploy/minicpmo_4_5_3gpu.yaml \
|
||||
--trust-remote-code \
|
||||
--host 0.0.0.0 --port 8099
|
||||
```
|
||||
The `*_stage1_replicas.yaml` files exercise composite Stage1 replica routing
|
||||
and failure recovery. They are validation profiles, not recommended production
|
||||
entrypoints.
|
||||
|
||||
### Stage-based CLI (optional)
|
||||
## Send chat requests
|
||||
|
||||
Stage 0 (thinker + API) and stage 1 (talker) can run in separate processes:
|
||||
|
||||
```bash
|
||||
# Stage 0
|
||||
CUDA_VISIBLE_DEVICES=0 vllm serve openbmb/MiniCPM-o-4_5 --omni \
|
||||
--trust-remote-code --port 8099 --stage-id 0 \
|
||||
--omni-master-address 127.0.0.1 --omni-master-port 26000
|
||||
|
||||
# Stage 1 (headless)
|
||||
CUDA_VISIBLE_DEVICES=1 vllm serve openbmb/MiniCPM-o-4_5 --omni \
|
||||
--trust-remote-code --stage-id 1 --headless \
|
||||
--omni-master-address 127.0.0.1 --omni-master-port 26000
|
||||
```
|
||||
|
||||
### Per-stage overrides
|
||||
|
||||
```bash
|
||||
vllm serve openbmb/MiniCPM-o-4_5 --omni --trust-remote-code --port 8099 \
|
||||
--stage-overrides '{"0": {"gpu_memory_utilization": 0.65}}'
|
||||
```
|
||||
|
||||
## Send multimodal requests
|
||||
|
||||
```bash
|
||||
cd examples/online_serving/minicpmo
|
||||
```
|
||||
|
||||
### curl
|
||||
From this directory, run the MiniCPM-specific curl or Python clients:
|
||||
|
||||
```bash
|
||||
bash run_curl_multimodal_generation.sh text
|
||||
bash run_curl_multimodal_generation.sh use_image
|
||||
bash run_curl_multimodal_generation.sh use_audio '["text"]' # text-only
|
||||
```
|
||||
bash run_curl_multimodal_generation.sh use_audio '["text"]'
|
||||
|
||||
Text + speech smoke test (TTS needs top-level `chat_template_kwargs`):
|
||||
|
||||
```bash
|
||||
curl http://localhost:8099/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "openbmb/MiniCPM-o-4_5",
|
||||
"messages": [{"role": "user", "content": "Say hello, then introduce vLLM in one sentence."}],
|
||||
"modalities": ["text", "audio"],
|
||||
"chat_template_kwargs": {"use_tts_template": true}
|
||||
}'
|
||||
```
|
||||
|
||||
### Python client
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type use_image \
|
||||
--port 8099 \
|
||||
--host localhost
|
||||
|
||||
# Text-only (faster; no <|tts_bos|>)
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type text \
|
||||
--modalities text \
|
||||
--prompt "Briefly introduce yourself."
|
||||
```
|
||||
|
||||
Shared helpers also work if you pass MiniCPM defaults yourself:
|
||||
|
||||
```bash
|
||||
python ../openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--model openbmb/MiniCPM-o-4_5 \
|
||||
--query-type text \
|
||||
--host localhost \
|
||||
--port 8099
|
||||
```
|
||||
|
||||
(Note: the shared client does **not** set `use_tts_template`; prefer the
|
||||
MiniCPM-specific client above for speech.)
|
||||
Speech output requires `chat_template_kwargs.use_tts_template=true`. Put that
|
||||
field at the request root for curl; the OpenAI Python SDK can merge it from
|
||||
`extra_body`.
|
||||
|
||||
### Gradio demo
|
||||
## Launch the Gradio demo
|
||||
|
||||
```bash
|
||||
bash run_gradio_demo.sh
|
||||
bash examples/online_serving/minicpmo/run_gradio_demo.sh
|
||||
|
||||
# Or:
|
||||
python gradio_demo.py \
|
||||
# Or run the Python entry point directly:
|
||||
python examples/online_serving/minicpmo/gradio_demo.py \
|
||||
--minicpmo45-api-base http://localhost:8099/v1 \
|
||||
--minicpmo45-model openbmb/MiniCPM-o-4_5 \
|
||||
--port 7862
|
||||
```
|
||||
|
||||
Open `http://<host>:7862`. Uncheck **"Generate speech output (TTS)"** for
|
||||
text-only responses.
|
||||
Open `http://<host>:7862` in a browser.
|
||||
|
||||
## Modality control
|
||||
## Run the Realtime duplex CLI demo
|
||||
|
||||
| Modalities | Output |
|
||||
|---|---|
|
||||
| `["text"]` | Text only (no TTS bos) |
|
||||
| `["text", "audio"]` / unset | Text + 24 kHz speech |
|
||||
After the duplex backend is running, stream one WAV through the Realtime
|
||||
WebSocket endpoint:
|
||||
|
||||
Speech requires `chat_template_kwargs.use_tts_template=true` so the chat
|
||||
template appends `<|tts_bos|>`. For **curl**, put that field at the request
|
||||
root; nested `extra_body` is ignored. The OpenAI Python SDK may use
|
||||
`extra_body` because it merges those fields into the root.
|
||||
```bash
|
||||
python examples/online_serving/minicpmo/realtime_duplex_demo.py \
|
||||
--url ws://localhost:8099/v1/realtime?duplex=1 \
|
||||
--model openbmb/MiniCPM-o-4_5 \
|
||||
--input-wav /path/to/input_16k_mono_pcm16.wav \
|
||||
--ref-audio /path/to/MiniCPM-o-Demo/assets/ref_audio/ref_minicpm_signature.wav \
|
||||
--output-dir /tmp/minicpmo_realtime_duplex_demo
|
||||
```
|
||||
|
||||
## Notes
|
||||
## Open the experimental browser client
|
||||
|
||||
- Stage 1 is capped at `max_num_seqs: 1` in the deploy YAML (talker shares
|
||||
request-0 audio metadata).
|
||||
- Output audio is base64 WAV in `message.audio.data` (24 kHz mono).
|
||||
- Offline counterpart:
|
||||
[`examples/offline_inference/minicpmo/`](../../offline_inference/minicpmo/)
|
||||
- Recipe:
|
||||
[`recipes/OpenBMB/MiniCPM-o-4_5.md`](../../../recipes/OpenBMB/MiniCPM-o-4_5.md)
|
||||
The browser UI serves the page and proxies the same-origin Realtime WebSocket to
|
||||
the backend:
|
||||
|
||||
```bash
|
||||
python -m examples.online_serving.minicpmo.realtime_web \
|
||||
--port 7862 \
|
||||
--ws-backend ws://127.0.0.1:8099 \
|
||||
--ref-audio /path/to/MiniCPM-o-Demo/assets/ref_audio/ref_minicpm_signature.wav
|
||||
```
|
||||
|
||||
Open `http://<host>:7862/`. When using a reverse proxy, open the URL mapped to
|
||||
port `7862`; the browser derives its WebSocket endpoint relative to that URL.
|
||||
|
||||
If the page proxy serves HTTP but does not forward WebSocket upgrades, point the
|
||||
browser at a separately exposed Realtime endpoint:
|
||||
|
||||
```bash
|
||||
python -m examples.online_serving.minicpmo.realtime_web \
|
||||
--port 7862 \
|
||||
--ws-backend ws://127.0.0.1:8099 \
|
||||
--public-realtime-url wss://public.example/v1/realtime
|
||||
```
|
||||
|
||||
## Validate soft-interrupt behavior
|
||||
|
||||
The soft-interrupt E2E driver defaults to `--validation-mode model-policy`,
|
||||
which checks lifecycle and streaming invariants for arbitrary input audio. The
|
||||
stronger `response-required` mode is diagnostic: it requires a purpose-built
|
||||
two-response WAV, its `--input-sha256`, and an
|
||||
`--expect-second-response-substring` value.
|
||||
|
||||
## Related examples
|
||||
|
||||
- [Offline MiniCPM-o inference](../../offline_inference/minicpmo/)
|
||||
- [MiniCPM-o 4.5 recipe](../../../recipes/OpenBMB/MiniCPM-o-4_5.md)
|
||||
@@ -0,0 +1,399 @@
|
||||
"""Minimal single-input MiniCPM-o 4.5 Realtime duplex demo.
|
||||
|
||||
Run this after starting the duplex server. Strict lifecycle, overlap, and
|
||||
multi-session validation lives under ``tests/e2e/online_serving``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from vllm_omni.experimental.fullduplex.client import ( # noqa: E402
|
||||
PCM16_BYTES_PER_SAMPLE,
|
||||
PCM16_SAMPLE_RATE,
|
||||
RealtimeDuplexClient,
|
||||
RealtimeEventCollector,
|
||||
build_realtime_url,
|
||||
read_pcm16_wav,
|
||||
wait_for,
|
||||
write_pcm16_wav,
|
||||
)
|
||||
|
||||
|
||||
class _StreamingOutputWriter:
|
||||
"""Persist and report output deltas as the client receives them."""
|
||||
|
||||
def __init__(self, output_dir: Path) -> None:
|
||||
self.output_dir = output_dir
|
||||
self.audio_chunk_dir = output_dir / "audio_chunks"
|
||||
self.audio_chunk_paths: list[Path] = []
|
||||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.audio_chunk_dir.mkdir(parents=True, exist_ok=True)
|
||||
(self.output_dir / "output.pcm").write_bytes(b"")
|
||||
|
||||
def handle(self, event: dict[str, object]) -> None:
|
||||
event_type = event.get("type")
|
||||
if event_type in {
|
||||
"response.audio_transcript.delta",
|
||||
"response.output_text.delta",
|
||||
}:
|
||||
delta = event.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
print(delta, end="", file=sys.stderr, flush=True)
|
||||
return
|
||||
if event_type != "response.audio.delta":
|
||||
return
|
||||
|
||||
delta = event.get("delta") or event.get("audio")
|
||||
if not isinstance(delta, str) or not delta:
|
||||
return
|
||||
try:
|
||||
pcm16 = base64.b64decode(delta)
|
||||
except ValueError:
|
||||
return
|
||||
if not pcm16:
|
||||
return
|
||||
|
||||
chunk_index = len(self.audio_chunk_paths) + 1
|
||||
chunk_path = self.audio_chunk_dir / f"chunk_{chunk_index:04d}.wav"
|
||||
sample_rate_hz = event.get("sample_rate_hz")
|
||||
if not isinstance(sample_rate_hz, int) or sample_rate_hz <= 0:
|
||||
sample_rate_hz = 24_000
|
||||
with (self.output_dir / "output.pcm").open("ab") as output_pcm:
|
||||
output_pcm.write(pcm16)
|
||||
write_pcm16_wav(chunk_path, pcm16, sample_rate_hz=sample_rate_hz)
|
||||
self.audio_chunk_paths.append(chunk_path)
|
||||
print(
|
||||
f"\n[audio chunk {chunk_index}: {len(pcm16)} bytes -> {chunk_path}]",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
class _StreamingEventCollector(RealtimeEventCollector):
|
||||
def __init__(self, writer: _StreamingOutputWriter) -> None:
|
||||
super().__init__()
|
||||
self._writer = writer
|
||||
|
||||
def add(self, event: dict[str, object], *, received_at_s: float | None = None) -> None:
|
||||
super().add(event, received_at_s=received_at_s)
|
||||
self._writer.handle(self.events[-1])
|
||||
|
||||
|
||||
def _input_committed_index(
|
||||
events: list[dict[str, object]],
|
||||
after_index: int,
|
||||
) -> int | None:
|
||||
for index, event in enumerate(events[max(after_index, 0) :], start=max(after_index, 0)):
|
||||
if event.get("type") == "input_audio_buffer.committed":
|
||||
return index
|
||||
return None
|
||||
|
||||
|
||||
def _post_commit_model_decision(
|
||||
events: list[dict[str, object]],
|
||||
committed_index: int | None,
|
||||
) -> str | None:
|
||||
if committed_index is None:
|
||||
return None
|
||||
for event in events[committed_index + 1 :]:
|
||||
event_type = event.get("type")
|
||||
if event_type == "response.listen":
|
||||
return "listen"
|
||||
if event_type == "response.done":
|
||||
response = event.get("response")
|
||||
if not isinstance(response, dict) or response.get("status") != "cancelled":
|
||||
return "speak"
|
||||
return None
|
||||
|
||||
|
||||
def _latest_model_decision(
|
||||
events: list[dict[str, object]],
|
||||
after_index: int,
|
||||
) -> str | None:
|
||||
decision: str | None = None
|
||||
for event in events[max(after_index, 0) :]:
|
||||
event_type = event.get("type")
|
||||
if event_type == "response.listen":
|
||||
decision = "listen"
|
||||
elif event_type == "response.done":
|
||||
response = event.get("response")
|
||||
if not isinstance(response, dict) or response.get("status") != "cancelled":
|
||||
decision = "speak"
|
||||
return decision
|
||||
|
||||
|
||||
def _chunk_period_ms(events: list[dict[str, object]]) -> int:
|
||||
for event in reversed(events):
|
||||
session = event.get("session")
|
||||
if not isinstance(session, dict):
|
||||
continue
|
||||
capabilities = session.get("capabilities")
|
||||
if not isinstance(capabilities, dict):
|
||||
continue
|
||||
chunk_period_ms = capabilities.get("chunk_period_ms")
|
||||
if isinstance(chunk_period_ms, int) and chunk_period_ms > 0:
|
||||
return chunk_period_ms
|
||||
return 1000
|
||||
|
||||
|
||||
def _has_residual_model_unit(pcm16: bytes, *, chunk_period_ms: int) -> bool:
|
||||
unit_bytes = PCM16_SAMPLE_RATE * PCM16_BYTES_PER_SAMPLE * chunk_period_ms // 1000
|
||||
return bool(unit_bytes > 0 and len(pcm16) % unit_bytes)
|
||||
|
||||
|
||||
def _response_in_progress(events: list[dict[str, object]]) -> bool:
|
||||
return sum(event.get("type") == "response.created" for event in events) > sum(
|
||||
event.get("type") == "response.done" for event in events
|
||||
)
|
||||
|
||||
|
||||
def _event_count_after(
|
||||
events: list[dict[str, object]],
|
||||
event_type: str,
|
||||
index: int | None,
|
||||
) -> int:
|
||||
if index is None:
|
||||
return 0
|
||||
return sum(event.get("type") == event_type for event in events[index + 1 :])
|
||||
|
||||
|
||||
def _ref_audio_data_url(path: str | None) -> str | None:
|
||||
if path is None:
|
||||
return None
|
||||
ref_path = Path(path).expanduser()
|
||||
return "data:audio/wav;base64," + base64.b64encode(ref_path.read_bytes()).decode("ascii")
|
||||
|
||||
|
||||
async def run_demo(args: argparse.Namespace) -> dict[str, object]:
|
||||
input_pcm16 = read_pcm16_wav(Path(args.input_wav))
|
||||
if not input_pcm16:
|
||||
raise ValueError("input WAV has no audio")
|
||||
|
||||
output_dir = Path(args.output_dir)
|
||||
stream_writer = _StreamingOutputWriter(output_dir)
|
||||
|
||||
url = build_realtime_url(
|
||||
args.url,
|
||||
args.model,
|
||||
autostart=False if args.ref_audio else None,
|
||||
session_id=args.session_id,
|
||||
)
|
||||
client = RealtimeDuplexClient(url)
|
||||
client.events = _StreamingEventCollector(stream_writer)
|
||||
async with client:
|
||||
await client.configure(
|
||||
args.model,
|
||||
ref_audio=_ref_audio_data_url(args.ref_audio),
|
||||
session_id=args.session_id,
|
||||
timeout_s=args.timeout_s,
|
||||
)
|
||||
stream_event_cursor = len(client.events.events)
|
||||
await client.stream_pcm16(
|
||||
input_pcm16,
|
||||
chunk_ms=args.chunk_ms,
|
||||
realtime=not args.no_realtime_pacing,
|
||||
)
|
||||
commit_event_cursor = len(client.events.events)
|
||||
stream_decision = _latest_model_decision(client.events.events, stream_event_cursor)
|
||||
input_has_residual_model_unit = _has_residual_model_unit(
|
||||
input_pcm16,
|
||||
chunk_period_ms=_chunk_period_ms(client.events.events),
|
||||
)
|
||||
wait_for_post_commit_decision = False
|
||||
commit_sent_at_s = time.monotonic()
|
||||
await client.commit()
|
||||
wait_error: str | None = None
|
||||
committed_index: int | None = None
|
||||
post_commit_decision: str | None = None
|
||||
try:
|
||||
await wait_for(
|
||||
lambda: _input_committed_index(client.events.events, commit_event_cursor) is not None,
|
||||
timeout_s=args.timeout_s,
|
||||
label="input_audio_buffer.committed",
|
||||
)
|
||||
committed_index = _input_committed_index(client.events.events, commit_event_cursor)
|
||||
stream_decision = _latest_model_decision(client.events.events[: committed_index + 1], stream_event_cursor)
|
||||
wait_for_post_commit_decision = input_has_residual_model_unit or _response_in_progress(
|
||||
client.events.events[: committed_index + 1]
|
||||
)
|
||||
if wait_for_post_commit_decision:
|
||||
await wait_for(
|
||||
lambda: _post_commit_model_decision(client.events.events, committed_index) is not None,
|
||||
timeout_s=args.timeout_s,
|
||||
label="post-commit model decision or response drain",
|
||||
)
|
||||
post_commit_decision = _post_commit_model_decision(client.events.events, committed_index)
|
||||
except TimeoutError as exc:
|
||||
wait_error = str(exc)
|
||||
await client.acknowledge_playback()
|
||||
close_error: str | None = None
|
||||
try:
|
||||
await client.close_session(timeout_s=args.timeout_s)
|
||||
except TimeoutError as exc:
|
||||
close_error = str(exc)
|
||||
|
||||
audio = client.events.audio_bytes()
|
||||
first_text_at_s = client.events.first_received_at(
|
||||
"response.audio_transcript.delta",
|
||||
"response.output_text.delta",
|
||||
after_s=commit_sent_at_s,
|
||||
)
|
||||
first_audio_at_s = client.events.first_received_at(
|
||||
"response.audio.delta",
|
||||
after_s=commit_sent_at_s,
|
||||
)
|
||||
response_created_at_s = client.events.first_received_at(
|
||||
"response.created",
|
||||
after_s=commit_sent_at_s,
|
||||
)
|
||||
response_done_at_s = client.events.first_received_at(
|
||||
"response.done",
|
||||
after_s=commit_sent_at_s,
|
||||
)
|
||||
audio_duration_s = len(audio) / (client.events.output_sample_rate_hz * 2)
|
||||
response_generation_s = (
|
||||
response_done_at_s - response_created_at_s
|
||||
if response_done_at_s is not None and response_created_at_s is not None
|
||||
else None
|
||||
)
|
||||
transcript_deltas = [
|
||||
str(event.get("delta", ""))
|
||||
for event in client.events.events
|
||||
if event.get("type")
|
||||
in {
|
||||
"response.audio_transcript.delta",
|
||||
"response.output_text.delta",
|
||||
}
|
||||
]
|
||||
response_id = client.events.response_ids[0] if client.events.response_ids else None
|
||||
timing = client.events.timing_summary(
|
||||
after_s=commit_sent_at_s,
|
||||
input_committed_at_s=commit_sent_at_s,
|
||||
response_id=response_id,
|
||||
)
|
||||
errors = client.events.errors()
|
||||
if wait_error:
|
||||
errors.append({"type": "client.timeout", "message": wait_error})
|
||||
if close_error:
|
||||
errors.append({"type": "client.timeout", "message": close_error})
|
||||
model_decision = post_commit_decision or stream_decision
|
||||
(output_dir / "events.jsonl").write_text(
|
||||
"".join(json.dumps(event, ensure_ascii=False) + "\n" for event in client.events.events),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(output_dir / "output.pcm").write_bytes(audio)
|
||||
if audio:
|
||||
write_pcm16_wav(
|
||||
output_dir / "output.wav",
|
||||
audio,
|
||||
sample_rate_hz=client.events.output_sample_rate_hz,
|
||||
)
|
||||
|
||||
result = {
|
||||
"ok": (
|
||||
client.events.count("session.created") > 0
|
||||
and client.events.count("session.closed") > 0
|
||||
and not errors
|
||||
and model_decision is not None
|
||||
and (bool(audio) or not args.require_audio)
|
||||
),
|
||||
"model_decision": model_decision,
|
||||
"post_commit": {
|
||||
"input_committed_event_index": committed_index,
|
||||
"decision": post_commit_decision,
|
||||
"decision_required": wait_for_post_commit_decision,
|
||||
"input_had_residual_model_unit": input_has_residual_model_unit,
|
||||
"response_listen_count": _event_count_after(
|
||||
client.events.events,
|
||||
"response.listen",
|
||||
committed_index,
|
||||
),
|
||||
"response_done_count": _event_count_after(
|
||||
client.events.events,
|
||||
"response.done",
|
||||
committed_index,
|
||||
),
|
||||
},
|
||||
"audio_bytes": len(audio),
|
||||
"audio_chunk_count": len(stream_writer.audio_chunk_paths),
|
||||
"audio_chunk_files": [str(path) for path in stream_writer.audio_chunk_paths],
|
||||
"output_sample_rate_hz": client.events.output_sample_rate_hz,
|
||||
"latency": {
|
||||
"ttft_ms": (
|
||||
round((first_text_at_s - commit_sent_at_s) * 1000, 2) if first_text_at_s is not None else None
|
||||
),
|
||||
"ttfp_ms": (
|
||||
round((first_audio_at_s - commit_sent_at_s) * 1000, 2) if first_audio_at_s is not None else None
|
||||
),
|
||||
"rtf": (
|
||||
round(response_generation_s / audio_duration_s, 4)
|
||||
if response_generation_s is not None and audio_duration_s > 0
|
||||
else None
|
||||
),
|
||||
"response_generation_ms": (
|
||||
round(response_generation_s * 1000, 2) if response_generation_s is not None else None
|
||||
),
|
||||
"text_stream_ms": (
|
||||
round((response_done_at_s - first_text_at_s) * 1000, 2)
|
||||
if response_done_at_s is not None and first_text_at_s is not None
|
||||
else None
|
||||
),
|
||||
"transcript_delta_count": len(transcript_deltas),
|
||||
"audio_duration_s": round(audio_duration_s, 3),
|
||||
"measurement_origin": "input_audio_buffer.commit send",
|
||||
},
|
||||
"timing": timing,
|
||||
"response_ids": client.events.response_ids,
|
||||
"transcript": "".join(transcript_deltas),
|
||||
"errors": errors,
|
||||
"output_dir": str(output_dir),
|
||||
}
|
||||
(output_dir / "result.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--url", default="ws://localhost:8099/v1/realtime?duplex=1")
|
||||
parser.add_argument("--model", default="openbmb/MiniCPM-o-4_5")
|
||||
parser.add_argument("--session-id")
|
||||
parser.add_argument("--input-wav", required=True)
|
||||
parser.add_argument(
|
||||
"--ref-audio",
|
||||
required=True,
|
||||
help=(
|
||||
"Reference WAV for the MiniCPM-o duplex assistant voice. "
|
||||
"This demo matches the official flow by always providing a reference audio clip."
|
||||
),
|
||||
)
|
||||
parser.add_argument("--output-dir", default="/tmp/minicpmo_realtime_duplex_demo")
|
||||
parser.add_argument("--chunk-ms", type=int, default=200)
|
||||
parser.add_argument("--timeout-s", type=float, default=60.0)
|
||||
parser.add_argument("--no-realtime-pacing", action="store_true")
|
||||
parser.add_argument("--require-audio", action="store_true")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
result = asyncio.run(run_demo(parse_args()))
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
if not result["ok"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Browser demo for the experimental full-duplex runtime."""
|
||||
|
||||
from .server import build_app
|
||||
|
||||
__all__ = ["build_app"]
|
||||
@@ -0,0 +1,4 @@
|
||||
from .server import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>MiniCPM-o 4.5 Voice</title>
|
||||
<link rel="stylesheet" href="static/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div>
|
||||
<p class="eyebrow">Experimental full-duplex runtime</p>
|
||||
<h1>MiniCPM-o 4.5 Voice</h1>
|
||||
</div>
|
||||
<span id="connectionState" class="status status-offline">Offline</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section class="call-bar" aria-label="Session controls">
|
||||
<div class="call-actions">
|
||||
<button id="callButton" class="primary" type="button">Start session</button>
|
||||
<button id="muteButton" class="secondary" type="button" disabled>Mute</button>
|
||||
<button id="cameraButton" class="secondary" type="button" disabled>Camera</button>
|
||||
<video id="cameraPreview" muted playsinline style="display:none;width:96px;height:72px;border-radius:8px;object-fit:cover;background:#000"></video>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;align-items:flex-start;margin-top:8px;width:100%">
|
||||
<label style="display:inline-flex;flex-direction:column;gap:4px;font-size:13px;opacity:.85;white-space:nowrap">
|
||||
Prompt preset
|
||||
<select id="promptPreset" style="font-size:13px;padding:4px 6px;border-radius:6px">
|
||||
<option value="omni" selected>Omni (official omni preset)</option>
|
||||
<option value="chinese_call">中文通话 (official audio preset)</option>
|
||||
<option value="english_call">English Call (official audio preset)</option>
|
||||
<option value="custom">Custom</option>
|
||||
</select>
|
||||
</label>
|
||||
<textarea id="systemPrompt" rows="2" placeholder="System prompt" style="flex:1;font-size:13px;padding:6px 8px;border-radius:6px;resize:vertical">Streaming Omni Conversation.</textarea>
|
||||
</div>
|
||||
<div class="meter" aria-label="Microphone level">
|
||||
<span>Mic</span>
|
||||
<div class="meter-track"><div id="meterFill" class="meter-fill"></div></div>
|
||||
</div>
|
||||
<dl class="runtime-status">
|
||||
<div><dt>Model</dt><dd id="modelState">Idle</dd></div>
|
||||
<div><dt>Playback</dt><dd id="playbackState">Idle</dd></div>
|
||||
<div><dt>Session</dt><dd id="sessionTimer">00:00</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="conversation-section" aria-labelledby="conversationTitle">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Live transcript</p>
|
||||
<h2 id="conversationTitle">Conversation</h2>
|
||||
</div>
|
||||
<span class="policy-label">Model-controlled listen / speak</span>
|
||||
</div>
|
||||
<div id="conversation" class="conversation" aria-live="polite">
|
||||
<p id="emptyConversation" class="empty-state">Start a session and speak naturally.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<details class="diagnostics" open>
|
||||
<summary>
|
||||
<span>Event log</span>
|
||||
<span id="eventCount" class="event-count">0 events</span>
|
||||
</summary>
|
||||
<div class="log-toolbar">
|
||||
<span id="runtimeDetail">No active connection</span>
|
||||
<button id="clearLogButton" class="icon-button" type="button" title="Clear event log">Clear</button>
|
||||
</div>
|
||||
<pre id="eventLog" class="event-log" aria-live="polite"></pre>
|
||||
</details>
|
||||
</main>
|
||||
|
||||
<script>window.FULL_DUPLEX_CONFIG = __FULL_DUPLEX_CONFIG__;</script>
|
||||
<script src="static/app.js?v=__FULL_DUPLEX_APP_VERSION__"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,671 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const config = window.FULL_DUPLEX_CONFIG || {};
|
||||
const callButton = document.getElementById('callButton');
|
||||
const muteButton = document.getElementById('muteButton');
|
||||
const cameraButton = document.getElementById('cameraButton');
|
||||
const cameraPreview = document.getElementById('cameraPreview');
|
||||
const promptPreset = document.getElementById('promptPreset');
|
||||
const systemPromptInput = document.getElementById('systemPrompt');
|
||||
const connectionState = document.getElementById('connectionState');
|
||||
const modelState = document.getElementById('modelState');
|
||||
const playbackState = document.getElementById('playbackState');
|
||||
const sessionTimer = document.getElementById('sessionTimer');
|
||||
const meterFill = document.getElementById('meterFill');
|
||||
const conversation = document.getElementById('conversation');
|
||||
const emptyConversation = document.getElementById('emptyConversation');
|
||||
const eventLog = document.getElementById('eventLog');
|
||||
const eventCount = document.getElementById('eventCount');
|
||||
const runtimeDetail = document.getElementById('runtimeDetail');
|
||||
const clearLogButton = document.getElementById('clearLogButton');
|
||||
|
||||
const INPUT_RATE = 16000;
|
||||
const OUTPUT_RATE = 24000;
|
||||
const SEND_INTERVAL_MS = 200;
|
||||
const ECHO_GUARD_MS = 300;
|
||||
const INITIAL_PLAYBACK_BUFFER_MS = 400;
|
||||
const SESSION_CLOSE_TIMEOUT_MS = 1000;
|
||||
|
||||
// Default prompts mirroring the official MiniCPM-o-Demo presets
|
||||
// (assets/presets/{omni,audio_duplex}/*.yaml).
|
||||
const PROMPT_PRESETS = {
|
||||
omni: 'Streaming Omni Conversation.',
|
||||
chinese_call: '扮演一个具有以上声音特征的助手。请认真、高质量地回复用户的问题。'
|
||||
+ '请用高自然度的方式和用户聊天。你处于双工模式,可以一边听、一边说。'
|
||||
+ '你是由面壁智能开发的人工智能助手:面壁小钢炮。',
|
||||
english_call: 'Replicate the tone and style from the input audio. Your task is to be '
|
||||
+ 'a helpful assistant using this voice pattern. Please answer the user\'s questions '
|
||||
+ 'seriously and in a high quality. Please chat with the user in a high naturalness '
|
||||
+ 'style. You are in duplex mode, where you can listen and speak at the same time.',
|
||||
};
|
||||
|
||||
let socket = null;
|
||||
let mediaStream = null;
|
||||
let captureContext = null;
|
||||
let captureNode = null;
|
||||
let playbackContext = null;
|
||||
let playbackNode = null;
|
||||
let sendTimer = null;
|
||||
let clockTimer = null;
|
||||
let startedAt = 0;
|
||||
let running = false;
|
||||
let muted = false;
|
||||
let assistantActive = false;
|
||||
let captureRate = INPUT_RATE;
|
||||
let cameraStream = null;
|
||||
let cameraTimer = null;
|
||||
let cameraPendingFrame = null;
|
||||
const cameraCanvas = document.createElement('canvas');
|
||||
let playbackRate = OUTPUT_RATE;
|
||||
let pendingCapture = [];
|
||||
let currentResponseId = null;
|
||||
let responseHasAudio = false;
|
||||
let logCount = 0;
|
||||
let liveUserTurn = null;
|
||||
let liveAssistantTurn = null;
|
||||
let sessionCloseResolver = null;
|
||||
|
||||
function staticAssetUrl(path) {
|
||||
const version = String(config.appVersion || '').trim();
|
||||
return version ? `${path}?v=${encodeURIComponent(version)}` : path;
|
||||
}
|
||||
|
||||
if (promptPreset && systemPromptInput) {
|
||||
promptPreset.addEventListener('change', () => {
|
||||
const preset = PROMPT_PRESETS[promptPreset.value];
|
||||
if (preset !== undefined) systemPromptInput.value = preset;
|
||||
});
|
||||
systemPromptInput.addEventListener('input', () => {
|
||||
promptPreset.value = 'custom';
|
||||
});
|
||||
}
|
||||
|
||||
function realtimeUrl() {
|
||||
const url = new URL(config.realtimePath, window.location.href);
|
||||
url.protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
url.searchParams.set('duplex', '1');
|
||||
url.searchParams.set('model', config.model || 'openbmb/MiniCPM-o-4_5');
|
||||
url.searchParams.set('minicpmo45_native_duplex', '1');
|
||||
url.searchParams.set('autostart', '0');
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function setConnection(label, kind) {
|
||||
connectionState.textContent = label;
|
||||
connectionState.className = `status status-${kind}`;
|
||||
}
|
||||
|
||||
function setModel(label) {
|
||||
modelState.textContent = label;
|
||||
}
|
||||
|
||||
function setPlayback(label) {
|
||||
playbackState.textContent = label;
|
||||
}
|
||||
|
||||
function compactEvent(event) {
|
||||
const fields = [];
|
||||
const payload = event.event || event;
|
||||
const responseId = responseIdOf(event);
|
||||
if (responseId) fields.push(`response=${responseId}`);
|
||||
if (event.item_id) fields.push(`item=${event.item_id}`);
|
||||
if (event.code) fields.push(`code=${event.code}`);
|
||||
if (event.response && event.response.status) fields.push(`status=${event.response.status}`);
|
||||
if (payload.played_ms !== undefined) fields.push(`played=${payload.played_ms}ms`);
|
||||
if (payload.committed_ms !== undefined) fields.push(`committed=${payload.committed_ms}ms`);
|
||||
if (payload.history_committed !== undefined) fields.push(`history=${payload.history_committed}`);
|
||||
return fields.join(' ');
|
||||
}
|
||||
|
||||
function appendLog(message, error = false) {
|
||||
const time = new Date().toLocaleTimeString([], { hour12: false });
|
||||
const line = document.createElement('span');
|
||||
if (error) line.className = 'log-error';
|
||||
line.textContent = `${time} ${message}\n`;
|
||||
eventLog.appendChild(line);
|
||||
eventLog.scrollTop = eventLog.scrollHeight;
|
||||
logCount += 1;
|
||||
eventCount.textContent = `${logCount} ${logCount === 1 ? 'event' : 'events'}`;
|
||||
}
|
||||
|
||||
function appendEventLog(event) {
|
||||
const detail = compactEvent(event);
|
||||
appendLog(`${event.type || 'unknown'}${detail ? ` ${detail}` : ''}`, event.type === 'error');
|
||||
}
|
||||
|
||||
function responseIdOf(event) {
|
||||
return event.response_id || (event.response && event.response.id) || null;
|
||||
}
|
||||
|
||||
function ensureTurn(role) {
|
||||
const existing = role === 'user' ? liveUserTurn : liveAssistantTurn;
|
||||
if (existing) return existing;
|
||||
if (emptyConversation) emptyConversation.remove();
|
||||
const row = document.createElement('div');
|
||||
row.className = `turn turn-${role} turn-live`;
|
||||
const label = document.createElement('div');
|
||||
label.className = 'turn-role';
|
||||
label.textContent = role === 'user' ? 'You' : 'Assistant';
|
||||
const text = document.createElement('div');
|
||||
text.className = 'turn-text';
|
||||
row.append(label, text);
|
||||
conversation.appendChild(row);
|
||||
conversation.scrollTop = conversation.scrollHeight;
|
||||
const turn = { row, text, value: '' };
|
||||
if (role === 'user') liveUserTurn = turn;
|
||||
else liveAssistantTurn = turn;
|
||||
return turn;
|
||||
}
|
||||
|
||||
function addTranscript(role, delta) {
|
||||
if (!delta) return;
|
||||
const turn = ensureTurn(role);
|
||||
turn.value += delta;
|
||||
turn.text.textContent = turn.value;
|
||||
conversation.scrollTop = conversation.scrollHeight;
|
||||
}
|
||||
|
||||
function finishTranscript(role, finalText = '') {
|
||||
const turn = role === 'user' ? liveUserTurn : liveAssistantTurn;
|
||||
if (!turn && !finalText) return;
|
||||
const current = turn || ensureTurn(role);
|
||||
if (finalText) {
|
||||
current.value = finalText;
|
||||
current.text.textContent = finalText;
|
||||
}
|
||||
current.row.classList.remove('turn-live');
|
||||
if (role === 'user') liveUserTurn = null;
|
||||
else liveAssistantTurn = null;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
let binary = '';
|
||||
const chunkSize = 0x8000;
|
||||
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function int16ToBase64(pcm) {
|
||||
return bytesToBase64(new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength));
|
||||
}
|
||||
|
||||
function base64ToBytes(encoded) {
|
||||
const binary = atob(encoded);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function resampleInt16(input, sourceRate, targetRate) {
|
||||
if (sourceRate === targetRate) return input;
|
||||
const ratio = sourceRate / targetRate;
|
||||
const output = new Int16Array(Math.floor(input.length / ratio));
|
||||
for (let index = 0; index < output.length; index += 1) {
|
||||
const start = Math.floor(index * ratio);
|
||||
const end = Math.max(start + 1, Math.min(input.length, Math.floor((index + 1) * ratio)));
|
||||
let sum = 0;
|
||||
for (let source = start; source < end; source += 1) sum += input[source];
|
||||
output[index] = sum / (end - start);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
async function decodeAudioDelta(event) {
|
||||
const encoded = event.delta || (event.response && event.response.audio);
|
||||
if (!encoded) return null;
|
||||
const bytes = base64ToBytes(encoded);
|
||||
const format = String(event.format || event.audio_format || 'pcm16').toLowerCase();
|
||||
const sourceRate = Number(event.sample_rate_hz || event.sample_rate || OUTPUT_RATE);
|
||||
if (format.includes('f32')) {
|
||||
const floats = new Float32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));
|
||||
const pcm = new Int16Array(floats.length);
|
||||
for (let index = 0; index < floats.length; index += 1) {
|
||||
const sample = Math.max(-1, Math.min(1, floats[index]));
|
||||
pcm[index] = sample < 0 ? sample * 32768 : sample * 32767;
|
||||
}
|
||||
return { pcm, sourceRate };
|
||||
}
|
||||
if (format.includes('wav')) {
|
||||
const decoded = await playbackContext.decodeAudioData(bytes.buffer.slice(0));
|
||||
const channel = decoded.getChannelData(0);
|
||||
const pcm = new Int16Array(channel.length);
|
||||
for (let index = 0; index < channel.length; index += 1) {
|
||||
const sample = Math.max(-1, Math.min(1, channel[index]));
|
||||
pcm[index] = sample < 0 ? sample * 32768 : sample * 32767;
|
||||
}
|
||||
return { pcm, sourceRate: decoded.sampleRate };
|
||||
}
|
||||
return {
|
||||
pcm: new Int16Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 2)),
|
||||
sourceRate,
|
||||
};
|
||||
}
|
||||
|
||||
function updateMeter(pcm) {
|
||||
let peak = 0;
|
||||
for (let index = 0; index < pcm.length; index += 8) peak = Math.max(peak, Math.abs(pcm[index]));
|
||||
meterFill.style.width = `${Math.min(100, (peak / 32768) * 150).toFixed(0)}%`;
|
||||
}
|
||||
|
||||
function microphoneUploadEnabled() {
|
||||
return running && !muted;
|
||||
}
|
||||
|
||||
function flushCapture() {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN || pendingCapture.length === 0) return;
|
||||
if (!microphoneUploadEnabled()) {
|
||||
pendingCapture = [];
|
||||
return;
|
||||
}
|
||||
const length = pendingCapture.reduce((total, chunk) => total + chunk.length, 0);
|
||||
const merged = new Int16Array(length);
|
||||
let offset = 0;
|
||||
for (const chunk of pendingCapture) {
|
||||
merged.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
pendingCapture = [];
|
||||
const pcm = resampleInt16(merged, captureRate, INPUT_RATE);
|
||||
const appendEvent = {
|
||||
type: 'input_audio_buffer.append',
|
||||
audio: int16ToBase64(pcm),
|
||||
format: 'pcm16',
|
||||
sample_rate_hz: INPUT_RATE,
|
||||
};
|
||||
// Omni duplex: ~1 fps camera frame rides the audio append (official
|
||||
// MiniCPM-o-Demo contract: one base64 JPEG per ~1 s chunk).
|
||||
if (cameraPendingFrame) {
|
||||
appendEvent.video_frames = [cameraPendingFrame];
|
||||
cameraPendingFrame = null;
|
||||
}
|
||||
socket.send(JSON.stringify(appendEvent));
|
||||
}
|
||||
|
||||
function beginAssistant(responseId) {
|
||||
currentResponseId = responseId || currentResponseId;
|
||||
responseHasAudio = false;
|
||||
assistantActive = true;
|
||||
setModel('Speaking');
|
||||
}
|
||||
|
||||
function feedPlayback(decoded, responseId) {
|
||||
if (!decoded || !decoded.pcm || decoded.pcm.length === 0 || !playbackNode) return;
|
||||
const pcm = resampleInt16(decoded.pcm, decoded.sourceRate, playbackRate);
|
||||
responseHasAudio = true;
|
||||
assistantActive = true;
|
||||
setPlayback('Buffering');
|
||||
playbackNode.port.postMessage({
|
||||
type: 'audio',
|
||||
pcm,
|
||||
responseId: responseId || currentResponseId,
|
||||
initialBufferMs: INITIAL_PLAYBACK_BUFFER_MS,
|
||||
}, [pcm.buffer]);
|
||||
}
|
||||
|
||||
function requestPlaybackDrain(responseId) {
|
||||
if (!playbackNode) return;
|
||||
playbackNode.port.postMessage({ type: 'drain', responseId: responseId || currentResponseId });
|
||||
}
|
||||
|
||||
function sendPlaybackAck(responseId, playedMs) {
|
||||
if (!responseId || !socket || socket.readyState !== WebSocket.OPEN || playedMs <= 0) {
|
||||
if (!responseId && playedMs > 0) appendLog('playback ack skipped: missing response id', true);
|
||||
return;
|
||||
}
|
||||
socket.send(JSON.stringify({
|
||||
type: 'playback.ack',
|
||||
response_id: responseId,
|
||||
item_id: `item_${responseId}`,
|
||||
played_ms: playedMs,
|
||||
committed_ms: playedMs,
|
||||
}));
|
||||
}
|
||||
|
||||
function playbackDrained(message) {
|
||||
const responseId = message.responseId || currentResponseId;
|
||||
sendPlaybackAck(responseId, Number(message.playedMs) || 0);
|
||||
setPlayback('Idle');
|
||||
if (message.underrunMs > 0) {
|
||||
appendLog(`playback underrun ${message.underrunMs} ms`);
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
assistantActive = false;
|
||||
currentResponseId = null;
|
||||
responseHasAudio = false;
|
||||
if (running) setModel('Listening');
|
||||
}, ECHO_GUARD_MS);
|
||||
}
|
||||
|
||||
function handleEvent(event) {
|
||||
appendEventLog(event);
|
||||
const responseId = responseIdOf(event);
|
||||
switch (event.type) {
|
||||
case 'session.created':
|
||||
case 'session.updated':
|
||||
setConnection('Connected', 'online');
|
||||
setModel('Listening');
|
||||
break;
|
||||
case 'response.listen':
|
||||
assistantActive = false;
|
||||
setModel('Listening');
|
||||
break;
|
||||
case 'response.created':
|
||||
case 'response.speak':
|
||||
beginAssistant(responseId);
|
||||
break;
|
||||
case 'response.audio.delta':
|
||||
currentResponseId = responseId || currentResponseId;
|
||||
assistantActive = true;
|
||||
setModel('Speaking');
|
||||
decodeAudioDelta(event)
|
||||
.then((decoded) => feedPlayback(decoded, responseId))
|
||||
.catch((error) => appendLog(`audio decode failed: ${error.message || error}`, true));
|
||||
break;
|
||||
case 'response.audio.done':
|
||||
requestPlaybackDrain(responseId);
|
||||
break;
|
||||
case 'response.audio_transcript.delta':
|
||||
addTranscript('assistant', event.delta || '');
|
||||
break;
|
||||
case 'response.audio_transcript.done':
|
||||
finishTranscript('assistant', event.transcript || '');
|
||||
break;
|
||||
case 'conversation.item.input_audio_transcription.delta':
|
||||
addTranscript('user', event.delta || '');
|
||||
break;
|
||||
case 'conversation.item.input_audio_transcription.completed':
|
||||
finishTranscript('user', event.transcript || '');
|
||||
break;
|
||||
case 'response.done':
|
||||
finishTranscript('assistant');
|
||||
if (!responseHasAudio) requestPlaybackDrain(responseId);
|
||||
break;
|
||||
case 'playback.acknowledged':
|
||||
{
|
||||
const acknowledgement = event.event || event;
|
||||
runtimeDetail.textContent = `Playback committed ${acknowledgement.committed_ms || 0} ms`;
|
||||
}
|
||||
break;
|
||||
case 'session.closed':
|
||||
if (sessionCloseResolver) sessionCloseResolver();
|
||||
sessionCloseResolver = null;
|
||||
break;
|
||||
case 'error':
|
||||
setConnection('Error', 'error');
|
||||
runtimeDetail.textContent = String(event.error || event.code || 'Server error');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function openPlayback() {
|
||||
playbackContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: OUTPUT_RATE });
|
||||
playbackRate = playbackContext.sampleRate;
|
||||
await playbackContext.audioWorklet.addModule(staticAssetUrl('static/playback_worklet.js'));
|
||||
playbackNode = new AudioWorkletNode(playbackContext, 'fullduplex-pcm-playback');
|
||||
playbackNode.port.onmessage = (message) => {
|
||||
if (message.data.type === 'playback-started') setPlayback('Playing');
|
||||
else if (message.data.type === 'playback-drained') playbackDrained(message.data);
|
||||
else if (message.data.type === 'playback-underrun') {
|
||||
runtimeDetail.textContent = `Playback underrun ${message.data.underrunMs || 0} ms`;
|
||||
}
|
||||
};
|
||||
playbackNode.connect(playbackContext.destination);
|
||||
await playbackContext.resume();
|
||||
}
|
||||
|
||||
async function openCapture() {
|
||||
mediaStream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
channelCount: 1,
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
sampleRate: { ideal: INPUT_RATE },
|
||||
},
|
||||
});
|
||||
try {
|
||||
captureContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: INPUT_RATE });
|
||||
} catch (_error) {
|
||||
captureContext = new (window.AudioContext || window.webkitAudioContext)();
|
||||
}
|
||||
captureRate = captureContext.sampleRate;
|
||||
await captureContext.audioWorklet.addModule(staticAssetUrl('static/pcm_worklet.js'));
|
||||
const source = captureContext.createMediaStreamSource(mediaStream);
|
||||
captureNode = new AudioWorkletNode(captureContext, 'fullduplex-pcm-capture');
|
||||
captureNode.port.onmessage = (message) => {
|
||||
const pcm = new Int16Array(message.data);
|
||||
updateMeter(pcm);
|
||||
if (microphoneUploadEnabled()) pendingCapture.push(pcm);
|
||||
};
|
||||
const silentSink = captureContext.createGain();
|
||||
silentSink.gain.value = 0;
|
||||
source.connect(captureNode);
|
||||
captureNode.connect(silentSink).connect(captureContext.destination);
|
||||
await captureContext.resume();
|
||||
}
|
||||
|
||||
function openSocket() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = realtimeUrl();
|
||||
socket = new WebSocket(url);
|
||||
let settled = false;
|
||||
socket.onopen = () => {
|
||||
settled = true;
|
||||
const extraBody = {
|
||||
auto_response: true,
|
||||
minicpmo45_native_duplex: true,
|
||||
};
|
||||
const session = {
|
||||
modalities: ['audio', 'text'],
|
||||
voice: 'default',
|
||||
extra_body: extraBody,
|
||||
};
|
||||
// Reference voice for TTS cloning, provided by the server via
|
||||
// --ref-audio (mirrors the official demo's default ref audio).
|
||||
if (config.refAudio) session.ref_audio = config.refAudio;
|
||||
const instructions = systemPromptInput ? systemPromptInput.value.trim() : '';
|
||||
if (instructions) session.instructions = instructions;
|
||||
socket.send(JSON.stringify({ type: 'session.update', session }));
|
||||
runtimeDetail.textContent = `${captureRate} Hz capture / ${playbackRate} Hz playback`;
|
||||
appendLog(`websocket open ${url}`);
|
||||
resolve();
|
||||
};
|
||||
socket.onmessage = (message) => {
|
||||
if (typeof message.data !== 'string') return;
|
||||
try {
|
||||
handleEvent(JSON.parse(message.data));
|
||||
} catch (error) {
|
||||
appendLog(`invalid server event: ${error.message || error}`, true);
|
||||
}
|
||||
};
|
||||
socket.onerror = () => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(new Error(`WebSocket connection failed: ${url}`));
|
||||
}
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
appendLog(`websocket closed code=${event.code}`);
|
||||
if (running) {
|
||||
setConnection('Disconnected', 'error');
|
||||
stopSession();
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function formatElapsed(seconds) {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${String(minutes).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function startClock() {
|
||||
startedAt = Date.now();
|
||||
clockTimer = window.setInterval(() => {
|
||||
sessionTimer.textContent = formatElapsed(Math.floor((Date.now() - startedAt) / 1000));
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
async function startSession() {
|
||||
if (running) return;
|
||||
callButton.disabled = true;
|
||||
setConnection('Connecting', 'connecting');
|
||||
runtimeDetail.textContent = 'Requesting microphone access';
|
||||
try {
|
||||
await openPlayback();
|
||||
await openCapture();
|
||||
await openSocket();
|
||||
running = true;
|
||||
muted = false;
|
||||
assistantActive = false;
|
||||
sendTimer = window.setInterval(flushCapture, SEND_INTERVAL_MS);
|
||||
startClock();
|
||||
callButton.textContent = 'End session';
|
||||
callButton.classList.add('is-active');
|
||||
muteButton.disabled = false;
|
||||
cameraButton.disabled = false;
|
||||
setConnection('Connected', 'online');
|
||||
setModel('Listening');
|
||||
appendLog('session started');
|
||||
} catch (error) {
|
||||
appendLog(`start failed: ${error.message || error}`, true);
|
||||
setConnection('Error', 'error');
|
||||
runtimeDetail.textContent = String(error.message || error);
|
||||
await stopSession();
|
||||
} finally {
|
||||
callButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startCamera() {
|
||||
if (cameraStream) return;
|
||||
cameraStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
|
||||
cameraPreview.srcObject = cameraStream;
|
||||
cameraPreview.style.display = '';
|
||||
await cameraPreview.play().catch(() => {});
|
||||
// Official omni-duplex cadence: one JPEG (quality 0.7) per ~1 s chunk,
|
||||
// no client-side resize (the server normalizes at scale_resolution=448).
|
||||
cameraTimer = window.setInterval(() => {
|
||||
if (!cameraStream || cameraPreview.videoWidth === 0) return;
|
||||
cameraCanvas.width = cameraPreview.videoWidth;
|
||||
cameraCanvas.height = cameraPreview.videoHeight;
|
||||
cameraCanvas.getContext('2d').drawImage(cameraPreview, 0, 0);
|
||||
cameraPendingFrame = cameraCanvas.toDataURL('image/jpeg', 0.7).split(',')[1];
|
||||
}, 1000);
|
||||
cameraButton.textContent = 'Camera off';
|
||||
cameraButton.classList.add('is-active');
|
||||
appendLog('camera on (1 fps omni frames)');
|
||||
}
|
||||
|
||||
function stopCamera() {
|
||||
if (cameraTimer !== null) clearInterval(cameraTimer);
|
||||
cameraTimer = null;
|
||||
if (cameraStream) {
|
||||
for (const track of cameraStream.getTracks()) track.stop();
|
||||
}
|
||||
cameraStream = null;
|
||||
cameraPendingFrame = null;
|
||||
cameraPreview.srcObject = null;
|
||||
cameraPreview.style.display = 'none';
|
||||
cameraButton.textContent = 'Camera';
|
||||
cameraButton.classList.remove('is-active');
|
||||
}
|
||||
|
||||
cameraButton.addEventListener('click', () => {
|
||||
if (cameraStream) {
|
||||
stopCamera();
|
||||
appendLog('camera off');
|
||||
return;
|
||||
}
|
||||
startCamera().catch((error) => appendLog(`camera failed: ${error.message || error}`, true));
|
||||
});
|
||||
|
||||
function waitForSessionClosed(targetSocket, timeoutMs) {
|
||||
if (!targetSocket || targetSocket.readyState !== WebSocket.OPEN) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
if (sessionCloseResolver === finish) sessionCloseResolver = null;
|
||||
resolve();
|
||||
};
|
||||
sessionCloseResolver = finish;
|
||||
window.setTimeout(finish, timeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function stopSession({ terminal = true } = {}) {
|
||||
running = false;
|
||||
assistantActive = false;
|
||||
pendingCapture = [];
|
||||
if (sendTimer !== null) clearInterval(sendTimer);
|
||||
if (clockTimer !== null) clearInterval(clockTimer);
|
||||
sendTimer = null;
|
||||
clockTimer = null;
|
||||
if (socket) {
|
||||
const closingSocket = socket;
|
||||
socket = null;
|
||||
closingSocket.onclose = null;
|
||||
if (terminal && closingSocket.readyState === WebSocket.OPEN) {
|
||||
const closed = waitForSessionClosed(closingSocket, SESSION_CLOSE_TIMEOUT_MS);
|
||||
closingSocket.send(JSON.stringify({ type: 'session.close' }));
|
||||
await closed;
|
||||
}
|
||||
closingSocket.close(1000, 'client stop');
|
||||
}
|
||||
if (playbackNode) playbackNode.port.postMessage({ type: 'clear' });
|
||||
if (mediaStream) {
|
||||
for (const track of mediaStream.getTracks()) track.stop();
|
||||
}
|
||||
mediaStream = null;
|
||||
stopCamera();
|
||||
cameraButton.disabled = true;
|
||||
if (captureContext) await captureContext.close().catch(() => {});
|
||||
if (playbackContext) await playbackContext.close().catch(() => {});
|
||||
captureContext = null;
|
||||
captureNode = null;
|
||||
playbackContext = null;
|
||||
playbackNode = null;
|
||||
currentResponseId = null;
|
||||
responseHasAudio = false;
|
||||
meterFill.style.width = '0%';
|
||||
sessionTimer.textContent = '00:00';
|
||||
callButton.textContent = 'Start session';
|
||||
callButton.classList.remove('is-active');
|
||||
muteButton.textContent = 'Mute';
|
||||
muteButton.classList.remove('is-active');
|
||||
muteButton.disabled = true;
|
||||
setConnection('Offline', 'offline');
|
||||
setModel('Idle');
|
||||
setPlayback('Idle');
|
||||
if (runtimeDetail.textContent.startsWith('Playback committed')) return;
|
||||
if (!runtimeDetail.textContent.startsWith('start failed')) runtimeDetail.textContent = 'No active connection';
|
||||
}
|
||||
|
||||
function toggleMute() {
|
||||
if (!running) return;
|
||||
muted = !muted;
|
||||
pendingCapture = [];
|
||||
muteButton.textContent = muted ? 'Unmute' : 'Mute';
|
||||
muteButton.classList.toggle('is-active', muted);
|
||||
appendLog(muted ? 'microphone muted' : 'microphone unmuted');
|
||||
}
|
||||
|
||||
callButton.addEventListener('click', () => {
|
||||
if (running) stopSession();
|
||||
else startSession();
|
||||
});
|
||||
muteButton.addEventListener('click', toggleMute);
|
||||
clearLogButton.addEventListener('click', () => {
|
||||
eventLog.textContent = '';
|
||||
logCount = 0;
|
||||
eventCount.textContent = '0 events';
|
||||
});
|
||||
window.addEventListener('beforeunload', () => { stopSession({ terminal: false }); });
|
||||
})();
|
||||
@@ -0,0 +1,15 @@
|
||||
class FullDuplexPcmCapture extends AudioWorkletProcessor {
|
||||
process(inputs) {
|
||||
const channel = inputs[0] && inputs[0][0];
|
||||
if (!channel || channel.length === 0) return true;
|
||||
const pcm = new Int16Array(channel.length);
|
||||
for (let index = 0; index < channel.length; index += 1) {
|
||||
const sample = Math.max(-1, Math.min(1, channel[index]));
|
||||
pcm[index] = sample < 0 ? sample * 32768 : sample * 32767;
|
||||
}
|
||||
this.port.postMessage(pcm.buffer, [pcm.buffer]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('fullduplex-pcm-capture', FullDuplexPcmCapture);
|
||||
@@ -0,0 +1,153 @@
|
||||
class FullDuplexPcmPlayback extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.queue = [];
|
||||
this.offset = 0;
|
||||
this.playedFrames = 0;
|
||||
this.underrunFrames = 0;
|
||||
this.drain = null;
|
||||
this.started = false;
|
||||
this.activeResponseId = null;
|
||||
this.initialBufferFrames = Math.round(sampleRate * 0.2);
|
||||
this.bufferWaitFrames = this.initialBufferFrames;
|
||||
this.rebuffering = false;
|
||||
this.fadeFrames = Math.max(1, Math.round(sampleRate * 0.005));
|
||||
this.fadeInFrames = 0;
|
||||
this.port.onmessage = (event) => this.handleMessage(event.data || {});
|
||||
}
|
||||
|
||||
handleMessage(message) {
|
||||
if (message.type === 'audio' && message.pcm) {
|
||||
const wasEmpty = this.queue.length === 0;
|
||||
if (!this.started && !this.activeResponseId) {
|
||||
this.activeResponseId = message.responseId || null;
|
||||
}
|
||||
if (!this.started && Number.isFinite(message.initialBufferMs)) {
|
||||
this.initialBufferFrames = Math.max(0, Math.round((sampleRate * message.initialBufferMs) / 1000));
|
||||
}
|
||||
this.queue.push(message.pcm);
|
||||
if (!this.started && wasEmpty && !this.rebuffering) {
|
||||
this.bufferWaitFrames = this.initialBufferFrames;
|
||||
}
|
||||
} else if (message.type === 'drain') {
|
||||
this.drain = { responseId: message.responseId || null };
|
||||
if (!this.started && this.bufferedFrames() > 0) {
|
||||
this.bufferWaitFrames = 0;
|
||||
this.startPlayback();
|
||||
}
|
||||
this.notifyIfDrained();
|
||||
} else if (message.type === 'clear') {
|
||||
this.queue = [];
|
||||
this.offset = 0;
|
||||
this.playedFrames = 0;
|
||||
this.underrunFrames = 0;
|
||||
this.drain = null;
|
||||
this.started = false;
|
||||
this.activeResponseId = null;
|
||||
this.bufferWaitFrames = this.initialBufferFrames;
|
||||
this.rebuffering = false;
|
||||
this.fadeInFrames = 0;
|
||||
}
|
||||
}
|
||||
|
||||
bufferedFrames() {
|
||||
return this.queue.reduce((total, pcm, index) => (
|
||||
total + pcm.length - (index === 0 ? this.offset : 0)
|
||||
), 0);
|
||||
}
|
||||
|
||||
startPlayback() {
|
||||
if (this.started) return;
|
||||
this.started = true;
|
||||
this.fadeInFrames = this.fadeFrames;
|
||||
if (this.playedFrames === 0) {
|
||||
this.port.postMessage({ type: 'playback-started', responseId: this.activeResponseId });
|
||||
}
|
||||
}
|
||||
|
||||
notifyIfDrained() {
|
||||
if (!this.drain || this.queue.length > 0) return;
|
||||
this.port.postMessage({
|
||||
type: 'playback-drained',
|
||||
responseId: this.drain.responseId,
|
||||
playedMs: Math.round((this.playedFrames * 1000) / sampleRate),
|
||||
underrunMs: Math.round((this.underrunFrames * 1000) / sampleRate),
|
||||
});
|
||||
this.playedFrames = 0;
|
||||
this.underrunFrames = 0;
|
||||
this.drain = null;
|
||||
this.started = false;
|
||||
this.activeResponseId = null;
|
||||
this.bufferWaitFrames = this.initialBufferFrames;
|
||||
this.rebuffering = false;
|
||||
this.fadeInFrames = 0;
|
||||
}
|
||||
|
||||
reportUnderrun() {
|
||||
this.port.postMessage({
|
||||
type: 'playback-underrun',
|
||||
responseId: this.activeResponseId,
|
||||
underrunMs: Math.round((this.underrunFrames * 1000) / sampleRate),
|
||||
});
|
||||
}
|
||||
|
||||
process(_inputs, outputs) {
|
||||
const output = outputs[0][0];
|
||||
output.fill(0);
|
||||
if (!this.started) {
|
||||
if (this.rebuffering && !this.drain) {
|
||||
this.underrunFrames += output.length;
|
||||
this.reportUnderrun();
|
||||
}
|
||||
if (this.queue.length > 0 && this.bufferWaitFrames > 0) {
|
||||
this.bufferWaitFrames = Math.max(0, this.bufferWaitFrames - output.length);
|
||||
return true;
|
||||
}
|
||||
if (this.queue.length > 0) {
|
||||
this.startPlayback();
|
||||
this.rebuffering = false;
|
||||
}
|
||||
}
|
||||
if (!this.started) {
|
||||
this.notifyIfDrained();
|
||||
return true;
|
||||
}
|
||||
let target = 0;
|
||||
while (target < output.length && this.queue.length > 0) {
|
||||
const pcm = this.queue[0];
|
||||
const count = Math.min(output.length - target, pcm.length - this.offset);
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
let sample = pcm[this.offset + index] / 32768;
|
||||
if (this.fadeInFrames > 0) {
|
||||
const elapsed = this.fadeFrames - this.fadeInFrames;
|
||||
sample *= elapsed / this.fadeFrames;
|
||||
this.fadeInFrames -= 1;
|
||||
}
|
||||
output[target + index] = sample;
|
||||
}
|
||||
target += count;
|
||||
this.offset += count;
|
||||
this.playedFrames += count;
|
||||
if (this.offset >= pcm.length) {
|
||||
this.queue.shift();
|
||||
this.offset = 0;
|
||||
}
|
||||
}
|
||||
if (target < output.length && !this.drain) {
|
||||
const fadeCount = Math.min(target, this.fadeFrames);
|
||||
for (let index = 0; index < fadeCount; index += 1) {
|
||||
output[target - fadeCount + index] *= (fadeCount - index - 1) / fadeCount;
|
||||
}
|
||||
this.underrunFrames += output.length - target;
|
||||
this.reportUnderrun();
|
||||
this.started = false;
|
||||
this.rebuffering = true;
|
||||
this.bufferWaitFrames = this.initialBufferFrames;
|
||||
this.fadeInFrames = 0;
|
||||
}
|
||||
this.notifyIfDrained();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('fullduplex-pcm-playback', FullDuplexPcmPlayback);
|
||||
@@ -0,0 +1,127 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
color: #20252b;
|
||||
background: #f4f6f7;
|
||||
font-synthesis: none;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body { margin: 0; min-width: 320px; }
|
||||
|
||||
button, summary { font: inherit; }
|
||||
|
||||
button:focus-visible, summary:focus-visible {
|
||||
outline: 3px solid rgba(21, 101, 192, .25);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
min-height: 104px;
|
||||
padding: 24px clamp(20px, 5vw, 64px);
|
||||
background: #ffffff;
|
||||
border-bottom: 1px solid #d9dee3;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
h1, h2, p { margin: 0; }
|
||||
h1 { font-size: 24px; line-height: 1.2; letter-spacing: 0; }
|
||||
h2 { font-size: 18px; line-height: 1.3; letter-spacing: 0; }
|
||||
|
||||
.eyebrow {
|
||||
margin-bottom: 5px;
|
||||
color: #68717b;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .08em;
|
||||
}
|
||||
|
||||
main { width: min(1040px, calc(100% - 40px)); margin: 28px auto 48px; }
|
||||
|
||||
.status {
|
||||
min-width: 88px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid;
|
||||
border-radius: 6px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status-offline { color: #616971; background: #f0f2f3; border-color: #cbd1d6; }
|
||||
.status-connecting { color: #8a4b00; background: #fff5df; border-color: #e6b76a; }
|
||||
.status-online { color: #176a3a; background: #e9f7ef; border-color: #7dc49b; }
|
||||
.status-error { color: #a12222; background: #fff0f0; border-color: #df8f8f; }
|
||||
|
||||
.call-bar {
|
||||
min-height: 86px;
|
||||
padding: 16px 18px;
|
||||
background: #252b31;
|
||||
color: #ffffff;
|
||||
border-radius: 6px;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(150px, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.call-actions { display: flex; gap: 8px; }
|
||||
button { border-radius: 5px; border: 1px solid transparent; cursor: pointer; }
|
||||
button:disabled { opacity: .46; cursor: default; }
|
||||
.primary { padding: 10px 15px; color: #ffffff; background: #16834b; font-weight: 700; }
|
||||
.primary.is-active { background: #b43636; }
|
||||
.secondary { padding: 10px 13px; color: #ffffff; background: #39414a; border-color: #59636d; }
|
||||
.secondary.is-active { color: #2b2525; background: #ffc9c9; border-color: #e58f8f; }
|
||||
|
||||
.meter { min-width: 0; display: flex; align-items: center; gap: 10px; color: #c8cfd6; font-size: 12px; }
|
||||
.meter-track { height: 8px; flex: 1; overflow: hidden; background: #444d56; border-radius: 4px; }
|
||||
.meter-fill { width: 0; height: 100%; background: #54bd7d; transition: width 70ms linear; }
|
||||
|
||||
.runtime-status { margin: 0; display: flex; gap: 24px; }
|
||||
.runtime-status div { min-width: 68px; }
|
||||
.runtime-status dt { color: #9fa8b1; font-size: 10px; text-transform: uppercase; }
|
||||
.runtime-status dd { margin: 3px 0 0; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.conversation-section { margin-top: 22px; padding: 22px 0 10px; }
|
||||
.section-heading { display: flex; justify-content: space-between; align-items: end; gap: 16px; padding: 0 2px 14px; border-bottom: 1px solid #cfd5da; }
|
||||
.policy-label { color: #5e6871; font-size: 12px; }
|
||||
.conversation { min-height: 260px; max-height: 440px; overflow-y: auto; padding: 18px 2px; }
|
||||
.empty-state { color: #7a838b; font-size: 14px; }
|
||||
|
||||
.turn { display: grid; grid-template-columns: 92px minmax(0, 1fr); gap: 12px; padding: 12px 0; border-bottom: 1px solid #e0e4e7; }
|
||||
.turn-role { padding-top: 2px; color: #68717b; font-size: 11px; font-weight: 800; text-transform: uppercase; }
|
||||
.turn-user .turn-role { color: #1565c0; }
|
||||
.turn-assistant .turn-role { color: #a45117; }
|
||||
.turn-text { min-width: 0; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.55; }
|
||||
.turn-live .turn-text::after { content: ""; display: inline-block; width: 6px; height: 14px; margin-left: 4px; background: #9098a0; vertical-align: -2px; animation: blink 1s step-end infinite; }
|
||||
@keyframes blink { 50% { opacity: 0; } }
|
||||
|
||||
.diagnostics { margin-top: 18px; border-top: 1px solid #bfc6cc; border-bottom: 1px solid #bfc6cc; background: #ffffff; }
|
||||
.diagnostics summary { padding: 13px 14px; display: flex; justify-content: space-between; cursor: pointer; font-weight: 700; list-style: none; }
|
||||
.diagnostics summary::-webkit-details-marker { display: none; }
|
||||
.event-count { color: #6f7880; font-size: 12px; font-weight: 500; }
|
||||
.log-toolbar { min-height: 40px; padding: 7px 12px; border-top: 1px solid #e0e4e7; display: flex; align-items: center; justify-content: space-between; gap: 12px; color: #69727a; font-size: 12px; }
|
||||
.icon-button { padding: 5px 9px; color: #394149; background: #f4f6f7; border-color: #cdd3d8; }
|
||||
.event-log { height: 200px; margin: 0; padding: 12px 14px; overflow: auto; background: #171b1f; color: #d9e0e6; font: 11px/1.55 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre-wrap; }
|
||||
.log-error { color: #ff9f9f; }
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.app-header { min-height: 88px; padding: 18px 20px; }
|
||||
h1 { font-size: 20px; }
|
||||
main { width: min(100% - 24px, 620px); margin-top: 16px; }
|
||||
.call-bar { grid-template-columns: 1fr; gap: 15px; }
|
||||
.call-actions button { flex: 1; }
|
||||
.runtime-status { justify-content: space-between; gap: 10px; }
|
||||
.section-heading { align-items: start; flex-direction: column; gap: 7px; }
|
||||
.conversation { min-height: 230px; }
|
||||
.turn { grid-template-columns: 72px minmax(0, 1fr); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; }
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Static host and same-origin Realtime proxy for the full-duplex demo."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import uvicorn
|
||||
import websockets
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||
from fastapi.responses import HTMLResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
APP_DIR = Path(__file__).parent / "app"
|
||||
STATIC_DIR = APP_DIR / "static"
|
||||
|
||||
|
||||
def _join_ws_url(base: str, path: str, query: str) -> str:
|
||||
return base.rstrip("/") + path + (("?" + query) if query else "")
|
||||
|
||||
|
||||
async def _pump_client_to_backend(client: WebSocket, backend) -> None:
|
||||
try:
|
||||
while True:
|
||||
message = await client.receive()
|
||||
if message["type"] == "websocket.disconnect":
|
||||
await backend.close()
|
||||
return
|
||||
if message.get("text") is not None:
|
||||
await backend.send(message["text"])
|
||||
elif message.get("bytes") is not None:
|
||||
await backend.send(message["bytes"])
|
||||
except (WebSocketDisconnect, websockets.ConnectionClosed):
|
||||
with contextlib.suppress(Exception):
|
||||
await backend.close()
|
||||
|
||||
|
||||
async def _pump_backend_to_client(client: WebSocket, backend) -> None:
|
||||
try:
|
||||
async for message in backend:
|
||||
if isinstance(message, bytes):
|
||||
await client.send_bytes(message)
|
||||
else:
|
||||
await client.send_text(message)
|
||||
except (WebSocketDisconnect, websockets.ConnectionClosed):
|
||||
return
|
||||
except RuntimeError as exc:
|
||||
if "websocket.send" in str(exc) and "websocket.close" in str(exc):
|
||||
return
|
||||
raise
|
||||
|
||||
|
||||
def _expected_proxy_close(exc: BaseException) -> bool:
|
||||
if isinstance(exc, (WebSocketDisconnect, websockets.ConnectionClosed, asyncio.CancelledError)):
|
||||
return True
|
||||
return isinstance(exc, RuntimeError) and "websocket.send" in str(exc) and "websocket.close" in str(exc)
|
||||
|
||||
|
||||
def build_app(
|
||||
*,
|
||||
ws_backend: str = "ws://127.0.0.1:8099",
|
||||
model: str = "openbmb/MiniCPM-o-4_5",
|
||||
public_realtime_url: str | None = None,
|
||||
ref_audio: str | None = None,
|
||||
) -> FastAPI:
|
||||
app = FastAPI(title="Experimental Full-Duplex Web Demo")
|
||||
index_path = APP_DIR / "index.html"
|
||||
app_version_hash = hashlib.sha256()
|
||||
for asset_path in (
|
||||
STATIC_DIR / "app.js",
|
||||
STATIC_DIR / "pcm_worklet.js",
|
||||
STATIC_DIR / "playback_worklet.js",
|
||||
):
|
||||
app_version_hash.update(asset_path.read_bytes())
|
||||
app_version = app_version_hash.hexdigest()[:12]
|
||||
|
||||
ref_audio_uri: str | None = None
|
||||
if ref_audio:
|
||||
ref_path = Path(ref_audio)
|
||||
if not ref_path.is_file():
|
||||
raise SystemExit(f"--ref-audio not found: {ref_audio}")
|
||||
encoded = base64.b64encode(ref_path.read_bytes()).decode("ascii")
|
||||
ref_audio_uri = f"data:audio/wav;base64,{encoded}"
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
def index() -> HTMLResponse:
|
||||
config = json.dumps(
|
||||
{
|
||||
"model": model,
|
||||
"realtimePath": public_realtime_url or "v1/realtime",
|
||||
"refAudio": ref_audio_uri,
|
||||
"appVersion": app_version,
|
||||
},
|
||||
ensure_ascii=True,
|
||||
)
|
||||
html = (
|
||||
index_path.read_text(encoding="utf-8")
|
||||
.replace("__FULL_DUPLEX_CONFIG__", config)
|
||||
.replace("__FULL_DUPLEX_APP_VERSION__", app_version)
|
||||
)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz() -> Response:
|
||||
return Response(content="ok", media_type="text/plain")
|
||||
|
||||
@app.websocket("/v1/realtime")
|
||||
async def realtime_proxy(websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
query = urlencode(websocket.query_params.multi_items())
|
||||
backend_url = _join_ws_url(ws_backend, "/v1/realtime", query)
|
||||
logger.info("Proxying Realtime WebSocket to %s", backend_url)
|
||||
try:
|
||||
async with websockets.connect(
|
||||
backend_url,
|
||||
max_size=64 * 1024 * 1024,
|
||||
) as backend:
|
||||
tasks = {
|
||||
asyncio.create_task(_pump_client_to_backend(websocket, backend)),
|
||||
asyncio.create_task(_pump_backend_to_client(websocket, backend)),
|
||||
}
|
||||
done, pending = await asyncio.wait(
|
||||
tasks,
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
for result in await asyncio.gather(*done, return_exceptions=True):
|
||||
if isinstance(result, BaseException) and not _expected_proxy_close(result):
|
||||
raise result
|
||||
except (WebSocketDisconnect, websockets.ConnectionClosed):
|
||||
return
|
||||
except Exception:
|
||||
logger.exception("Realtime WebSocket proxy failed")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close(code=1011)
|
||||
|
||||
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||
return app
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--host", default="0.0.0.0")
|
||||
parser.add_argument("--port", type=int, default=7862)
|
||||
parser.add_argument("--ws-backend", default="ws://127.0.0.1:8099")
|
||||
parser.add_argument(
|
||||
"--public-realtime-url",
|
||||
help="Browser-visible ws:// or wss:// Realtime URL; defaults to the same-origin proxy.",
|
||||
)
|
||||
parser.add_argument("--model", default="openbmb/MiniCPM-o-4_5")
|
||||
parser.add_argument(
|
||||
"--ref-audio",
|
||||
required=True,
|
||||
help=(
|
||||
"Reference voice wav for TTS voice cloning, e.g. the "
|
||||
"official MiniCPM-o-Demo assets/ref_audio/ref_minicpm_signature.wav"
|
||||
),
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
uvicorn.run(
|
||||
build_app(
|
||||
ws_backend=args.ws_backend,
|
||||
model=args.model,
|
||||
public_realtime_url=args.public_realtime_url,
|
||||
ref_audio=args.ref_audio,
|
||||
),
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
log_level="info",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user