Open-Source Frontier Voice AI
Python
Remove remote audio URL fetching from streaming ASR
pengzhiliang9c3402aa231e
diff --git a/docs/vibevoice-vllm-asr-streaming.md b/docs/vibevoice-vllm-asr-streaming.mdindex fe2164a..745e58c 100644--- a/docs/vibevoice-vllm-asr-streaming.md+++ b/docs/vibevoice-vllm-asr-streaming.md@@ -173,6 +173,20 @@ relaying to http://localhost:8000, open http://localhost:7860| `POST /v1/chat/completions` | OpenAI-compatible, for existing clients || `GET /v1/config` | Sample rate and chunk geometry of the loaded checkpoint |+### Audio inputs++The HTTP endpoints accept inline audio only:++- `/v1/transcribe`: send the file contents in `audio_base64`.+- `/v1/transcribe_batch`: send `audio_base64` in each item of `audios`.+- `/v1/chat/completions`: use an `audio_url` message part whose `url` is a+ base64 data URI, for example `data:audio/wav;base64,...`.++HTTP(S) audio URLs are not supported. Clients using remote files must download+them on the client side and send the audio contents. Decoded audio is limited to+256 MiB per file. WebSocket PCM streaming and the demo's file upload and+microphone inputs continue to work as before.+### Environment Variables| Variable | Description | Default |diff --git a/tests/test_streaming_audio_inputs.py b/tests/test_streaming_audio_inputs.pynew file mode 100644index 0000000..6cc5686--- /dev/null+++ b/tests/test_streaming_audio_inputs.py@@ -0,0 +1,224 @@+"""Exercise the real HTTP routes without loading vLLM or a GPU checkpoint."""+import base64+import importlib.util+from pathlib import Path+import socket+import sys+import types+from unittest.mock import Mock++from fastapi.testclient import TestClient+import pytest+import requests+++def server(monkeypatch):+ # The package initializer registers GPU models. These tests need only the+ # actual transport and sequence modules, with their normal dependencies.+ root = Path(__file__).resolve().parents[1] / "vllm_plugin"+ package = types.ModuleType("vllm_plugin")+ package.__path__ = [str(root)]+ monkeypatch.setitem(sys.modules, "vllm_plugin", package)+ for name in ("asr_streaming", "asr_streaming_server"):+ fullname = f"vllm_plugin.{name}"+ spec = importlib.util.spec_from_file_location(fullname, root / f"{name}.py")+ module = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, fullname, module)+ spec.loader.exec_module(module)+ return module+++def client(server, monkeypatch):+ geometry = server.ChunkGeometry(24000, 3200, 15, 4)+ monkeypatch.setattr(server.ChunkGeometry, "from_pretrained",+ lambda _: geometry)+ app = server.create_app(server.ServerConfig(model="unused-test-model"))+ app.state.engine = types.SimpleNamespace(geometry=geometry)+ # Do not enter the lifespan: the tests must never load a model.+ client = TestClient(app)+ yield client+ client.close()+++def outbound(monkeypatch):+ # Assert both that responses are safe and that no request/DNS lookup was+ # attempted. The tests never contact an internal or external destination.+ request = Mock(side_effect=AssertionError("unexpected outbound HTTP request"))+ resolve = Mock(side_effect=AssertionError("unexpected DNS lookup"))+ connect = Mock(side_effect=AssertionError("unexpected outbound connection"))+ monkeypatch.setattr(requests.sessions.Session, "request", request)+ monkeypatch.setattr(socket, "getaddrinfo", resolve)+ monkeypatch.setattr(socket.socket, "connect", connect)+ yield+ request.assert_not_called()+ resolve.assert_not_called()+ connect.assert_not_called()+++ROUTES = ("/v1/transcribe", "/v1/transcribe_batch", "/v1/chat/completions")+++def payload_for(route, *, url=None, encoded=None, stream=False):+ if route == "/v1/chat/completions":+ if encoded is not None:+ url = f"data:audio/wav;base64,{encoded}"+ return {"stream": stream, "messages": [{+ "role": "user", "content": [+ {"type": "audio_url", "audio_url": {"url": url}},+ ],+ }]}+ item = {"audio_url": url} if url is not None else {"audio_base64": encoded}+ return {"audios": [item]} if route.endswith("_batch") else item++[email protected]("route", ROUTES)[email protected]("url", [+ "http://127.0.0.1:8001/audio.wav",+ "http://localhost/audio.wav",+ "http://10.0.0.1/audio.wav",+ "http://172.16.0.1/audio.wav",+ "http://192.168.1.1/audio.wav",+ "http://169.254.169.254/audio.wav",+ "http://[::1]/audio.wav",+ "http://[::ffff:127.0.0.1]/audio.wav",+ "http://2130706433/audio.wav",+ "https://example.com/audio.wav",+ "https://example.com/redirect?url=http://127.0.0.1/",+ "https://user:[email protected]/audio.wav",+ "//example.com/audio.wav",+ "ftp://example.com/audio.wav",+ "file:///tmp/audio.wav",+])+def test_disallowed_urls_never_access_network(client, outbound, inference,+ route, url):+ response = client.post(route, json=payload_for(route, url=url))+ assert response.status_code == 400+ assert url not in response.text+ inference[1].assert_not_called()+++def inference(server, monkeypatch):+ raw = b"test audio bytes"+ decoder = Mock(return_value=server.np.zeros(24000, dtype=server.np.float32))+ monkeypatch.setattr(server, "load_audio_bytes", decoder)++ class Session:+ async def transcribe(self, audio):+ yield "Speaker 1: hello"++ async def push(self, window):+ return "Speaker 1: hello"++ monkeypatch.setattr(server, "_new_session", lambda *_: Session())+ return raw, decoder++[email protected]("route", ROUTES)+def test_inline_audio_reaches_inference(client, outbound, inference, route):+ raw, decoder = inference+ encoded = base64.b64encode(raw).decode("ascii")+ response = client.post(route, json=payload_for(route, encoded=encoded))+ assert response.status_code == 200+ assert "hello" in response.text+ decoder.assert_called_once_with(raw, 24000)+++def test_inline_audio_chat_stream(client, outbound, inference):+ raw, decoder = inference+ encoded = base64.b64encode(raw).decode("ascii")+ response = client.post("/v1/chat/completions", json=payload_for(+ "/v1/chat/completions", encoded=encoded, stream=True))+ assert response.status_code == 200+ assert "hello" in response.text+ assert "data: [DONE]" in response.text+ decoder.assert_called_once_with(raw, 24000)+++def test_remote_url_rejected_before_chat_stream(client, outbound, inference):+ response = client.post("/v1/chat/completions", json=payload_for(+ "/v1/chat/completions", url="https://example.com/audio.wav", stream=True))+ assert response.status_code == 400+ assert response.headers["content-type"] == "application/json"+ inference[1].assert_not_called()++[email protected]("route", ROUTES)[email protected]("encoded", ["", "%%%", "YQ", "YQ==!", "\u2603"])+def test_invalid_base64_returns_client_error(client, outbound, inference,+ route, encoded):+ response = client.post(route, json=payload_for(route, encoded=encoded))+ assert response.status_code == 400+ inference[1].assert_not_called()++[email protected]("url", [+ None, 7, {},+ "data:audio/wav;base64",+ "data:audio/wav,YXVkaW8=",+ "data:audio/wav;base64;extra,YXVkaW8=",+ "data:audio/wav;base64,http://127.0.0.1/audio.wav",+])+def test_invalid_data_uri_returns_client_error(client, outbound, inference, url):+ response = client.post("/v1/chat/completions", json=payload_for(+ "/v1/chat/completions", url=url))+ assert response.status_code == 400+ inference[1].assert_not_called()++[email protected]("route", ROUTES)[email protected]("size", [4, 5, 7])+def test_inline_audio_size_limit(client, outbound, server, inference,+ monkeypatch, route, size):+ monkeypatch.setattr(server, "MAX_AUDIO_BYTES", 4)+ raw = b"a" * size+ encoded = base64.b64encode(raw).decode("ascii")+ response = client.post(route, json=payload_for(route, encoded=encoded))+ if size == 4:+ assert response.status_code == 200+ inference[1].assert_called_once_with(raw, 24000)+ else:+ assert response.status_code == 413+ inference[1].assert_not_called()+++def test_batch_accepts_multiple_inline_files(client, outbound, inference):+ raw, decoder = inference+ encoded = base64.b64encode(raw).decode("ascii")+ response = client.post("/v1/transcribe_batch", json={"audios": [+ {"audio_base64": encoded}, {"audio_base64": encoded},+ ]})+ assert response.status_code == 200+ assert len(response.json()["results"]) == 2+ assert decoder.call_count == 2++[email protected]("route", ["/v1/transcribe", "/v1/transcribe_batch"])+def test_extra_url_cannot_trigger_download_with_inline_audio(+ client, outbound, inference, route):+ raw, decoder = inference+ item = {"audio_base64": base64.b64encode(raw).decode("ascii"),+ "audio_url": "http://127.0.0.1/audio.wav"}+ payload = {"audios": [item]} if route.endswith("_batch") else item+ response = client.post(route, json=payload)+ assert response.status_code == 200+ decoder.assert_called_once_with(raw, 24000)+++def test_openapi_only_advertises_inline_audio(client):+ schemas = client.get("/openapi.json").json()["components"]["schemas"]+ for name in ("TranscribeRequest", "BatchAudioItem"):+ assert "audio_base64" in schemas[name]["properties"]+ assert "audio_url" not in schemas[name]["properties"]+++def test_websocket_audio_still_transcribes(client, outbound, server, inference):+ with client.websocket_connect("/v1/stream") as ws:+ ws.send_json({})+ ws.send_bytes(server.np.zeros(24000, dtype="<f4").tobytes())+ ws.send_text("end")+ assert "hello" in ws.receive_json()["text"]+ assert ws.receive_json()["done"] is Truediff --git a/vllm_plugin/asr_streaming_server.py b/vllm_plugin/asr_streaming_server.pyindex 90d315b..60780b8 100644--- a/vllm_plugin/asr_streaming_server.py+++ b/vllm_plugin/asr_streaming_server.py@@ -27,6 +27,7 @@ Run:import argparseimport asyncioimport base64+import binasciiimport jsonimport loggingimport re@@ -35,10 +36,8 @@ import uuidfrom contextlib import asynccontextmanagerfrom dataclasses import dataclassfrom typing import Any, Dict, List, Optional, Sequence-from urllib.parse import urlparseimport numpy as np-import requestsimport uvicornfrom fastapi import (FastAPI, HTTPException, Request, WebSocket,WebSocketDisconnect)@@ -351,27 +350,26 @@ class StreamingSession:# --- transport -------------------------------------------------------------def _fetch_url(url: str, timeout: int) -> bytes:- """Fetch audio over http(s), refusing other schemes and oversized bodies."""- if urlparse(url).scheme not in ("http", "https"):- raise HTTPException(status_code=400,- detail="audio_url must be http or https")+def _decode_audio_base64(encoded: str) -> bytes:+ """Decode inline audio, rejecting malformed or oversized input."""+ if len(encoded) > 4 * ((MAX_AUDIO_BYTES + 2) // 3):+ raise HTTPException(status_code=413,+ detail=f"Audio exceeds {MAX_AUDIO_BYTES} bytes")try:- resp = requests.get(url, timeout=timeout, stream=True)- resp.raise_for_status()- body = resp.raw.read(MAX_AUDIO_BYTES + 1, decode_content=True)- except requests.RequestException as exc:+ body = base64.b64decode(encoded, validate=True)+ except (binascii.Error, ValueError):raise HTTPException(status_code=400,- detail=f"Failed to fetch audio_url: {exc}") from None+ detail="Invalid base64 audio") from None+ if not body:+ raise HTTPException(status_code=400, detail="Audio is empty")if len(body) > MAX_AUDIO_BYTES:raise HTTPException(status_code=413,- detail=f"audio_url body exceeds {MAX_AUDIO_BYTES} bytes")+ detail=f"Audio exceeds {MAX_AUDIO_BYTES} bytes")return bodyclass TranscribeRequest(BaseModel):audio_base64: Optional[str] = Field(None, description="Base64 audio bytes.")- audio_url: Optional[str] = Field(None, description="Audio URL if no base64.")context_info: Optional[str] = Field(None, description="Hotwords / context.")max_tokens: int = Field(256, ge=1, le=2048)# Greedy is the reference decoding config; 2.0 is where the demo's slider@@ -383,11 +381,10 @@ class TranscribeRequest(BaseModel):def audio_bytes(self) -> bytes:if self.audio_base64:- return base64.b64decode(self.audio_base64)- if self.audio_url:- return _fetch_url(self.audio_url, timeout=10)+ return _decode_audio_base64(self.audio_base64)raise HTTPException(status_code=400,- detail="audio_base64 or audio_url is required")+ detail="audio_base64 is required; remote audio URLs "+ "are not supported")class TranscribeResponse(BaseModel):@@ -403,7 +400,6 @@ class TranscribeResponse(BaseModel):class BatchAudioItem(BaseModel):audio_base64: Optional[str] = None- audio_url: Optional[str] = Noneclass BatchTranscribeRequest(BaseModel):@@ -436,9 +432,8 @@ def _new_session(engine: VibeVoiceAsyncEngine,async def _run_clip(engine: VibeVoiceAsyncEngine,req: TranscribeRequest) -> TranscribeResponse:- # Both of these block, and both go to a thread for the same reason: a URL- # fetch waits on the network and ffmpeg shells out, either of which would- # otherwise stall the event loop for every other in-flight session.+ # Decode base64 and run ffmpeg off the event loop so large clips do not+ # stall every other in-flight session.raw = await asyncio.to_thread(req.audio_bytes)sample_rate = engine.geometry.sample_rateaudio = await asyncio.to_thread(load_audio_bytes, raw, sample_rate)@@ -489,10 +484,18 @@ def _audio_from_messages(messages: list) -> bytes:for part in content:if part.get("type") != "audio_url":continue- url = (part.get("audio_url") or {}).get("url", "")- if url.startswith("data:"):- return base64.b64decode(url.split(",", 1)[1])- return _fetch_url(url, timeout=30)+ audio_url = part.get("audio_url")+ url = audio_url.get("url") if isinstance(audio_url, dict) else None+ if not isinstance(url, str) or not url.startswith("data:"):+ raise HTTPException(+ status_code=400,+ detail="audio_url must be a base64 data URI; remote audio "+ "URLs are not supported")+ header, separator, encoded = url.partition(",")+ if not separator or not header.endswith(";base64"):+ raise HTTPException(status_code=400,+ detail="audio_url must be a base64 data URI")+ return _decode_audio_base64(encoded)raise HTTPException(status_code=400, detail="No audio_url part in messages")@@ -603,7 +606,6 @@ def create_app(config: ServerConfig) -> FastAPI:subs = [TranscribeRequest(audio_base64=item.audio_base64,- audio_url=item.audio_url,context_info=req.context_info,max_tokens=req.max_tokens,temperature=req.temperature,@@ -642,8 +644,7 @@ def create_app(config: ServerConfig) -> FastAPI:# malformed body or an out-of-range temperature returns 500, which# reads as a server fault for what is a client mistake.raise HTTPException(status_code=400, detail=str(exc))- # To a thread for the same reason as _run_clip: an audio_url part is- # fetched over the network, and a stall here stalls every other session.+ # Decode inline base64 off the event loop, as in _run_clip.audio_bytes = await asyncio.to_thread(_audio_from_messages, messages)cid = f"chatcmpl-{uuid.uuid4().hex[:24]}"sample_rate = geometry.sample_rate