Pin Applio 3.6.5 and verified basis assets, migrate private voice provenance, and coordinate conversion/live/training with Deck GPU leases. Prepare an inactive voice profile and a restricted studio container. Move CUDA and Torch caches out of the small temporary filesystem to prevent OmniVoice reference failures. Package app updates from the explicit allowlist in one Docker layer.
275 lines
11 KiB
Python
275 lines
11 KiB
Python
"""Authenticated-by-network WebSocket bridge to Applio's realtime RVC pipeline."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import os,secrets,signal
|
|
import json
|
|
import subprocess
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
|
from pydantic import BaseModel, Field, ValidationError
|
|
from websockets.asyncio.client import connect
|
|
from websockets.exceptions import ConnectionClosed
|
|
|
|
from ..config import get_settings
|
|
from ..jobs.enums import JobStatus
|
|
from ..services.models import get_model
|
|
|
|
router = APIRouter(tags=["realtime"])
|
|
_session_lock = asyncio.Lock()
|
|
|
|
|
|
class RealtimeInit(BaseModel):
|
|
model_name: str
|
|
pitch: int = Field(default=0, ge=-24, le=24)
|
|
f0_method: str = Field(default="fcpe", pattern="^(rmvpe|fcpe|crepe|crepe-tiny)$")
|
|
index_rate: float = Field(default=0.7, ge=0, le=1)
|
|
protect: float = Field(default=0.33, ge=0, le=0.5)
|
|
volume_envelope: float = Field(default=0.2, ge=0, le=1)
|
|
chunk_ms: int = Field(default=120, ge=40, le=500)
|
|
crossfade_seconds: float = Field(default=0.05, ge=0.02, le=0.2)
|
|
context_seconds: float = Field(default=0.5, ge=0.1, le=3.0)
|
|
silence_threshold_db: int = Field(default=-80, ge=-90, le=-30)
|
|
vad_enabled: bool = False
|
|
autotune: bool = False
|
|
|
|
|
|
def _container_model_path(host_path: str) -> str:
|
|
settings = get_settings()
|
|
source = Path(host_path).resolve()
|
|
try:
|
|
relative = source.relative_to(settings.models_dir.resolve())
|
|
except ValueError as exc:
|
|
raise ValueError("Modellpfad liegt außerhalb des freigegebenen Modellverzeichnisses") from exc
|
|
return str(Path(settings.applio_models_dir) / relative)
|
|
|
|
|
|
def build_applio_init(init: RealtimeInit) -> dict[str, object]:
|
|
model = get_model(init.model_name)
|
|
if model is None or not model.pth_path or not model.index_path:
|
|
raise ValueError(f"Modell '{init.model_name}' ist nicht einsatzbereit")
|
|
|
|
return {
|
|
"type": "init",
|
|
# Applio counts 128-sample blocks, not samples or milliseconds.
|
|
"chunk_size": max(1, (init.chunk_ms * 48 + 64) // 128),
|
|
"cross_fade_overlap_size": init.crossfade_seconds,
|
|
"extra_convert_size": init.context_seconds,
|
|
"model_path": _container_model_path(model.pth_path),
|
|
"index_path": _container_model_path(model.index_path),
|
|
"f0_method": init.f0_method,
|
|
"embedder_model": "contentvec",
|
|
"embedder_model_custom": "",
|
|
"silent_threshold": init.silence_threshold_db,
|
|
"vad_enabled": init.vad_enabled,
|
|
"sid": 0,
|
|
"input_audio_gain": 100,
|
|
"f0_up_key": init.pitch,
|
|
"index_rate": init.index_rate,
|
|
"protect": init.protect,
|
|
"volume_envelope": init.volume_envelope,
|
|
"autotune": init.autotune,
|
|
"autotune_strength": 1.0,
|
|
"proposed_pitch": False,
|
|
"proposed_pitch_threshold": 155.0,
|
|
"clean_audio": False,
|
|
"clean_strength": 0.5,
|
|
"post_process": False,
|
|
"kwargs": {},
|
|
}
|
|
|
|
|
|
def _health_url(websocket_url: str) -> str:
|
|
parsed = urlsplit(websocket_url)
|
|
scheme = "https" if parsed.scheme == "wss" else "http"
|
|
return urlunsplit((scheme, parsed.netloc, "/docs", "", ""))
|
|
|
|
|
|
async def _upstream_ready() -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=2.0) as client:
|
|
response = await client.get(_health_url(get_settings().applio_realtime_url))
|
|
return response.status_code < 500
|
|
except httpx.HTTPError:
|
|
return False
|
|
|
|
|
|
async def _ensure_realtime_server() -> None:
|
|
if await _upstream_ready():
|
|
return
|
|
|
|
settings = get_settings()
|
|
if os.environ.get('APPLIO_LEASE_SOCKET'):
|
|
from ..adapters.native_runner import get_native_runner
|
|
runner=get_native_runner();runner.unload()
|
|
proc=subprocess.Popen([str(settings.applio_python),os.environ['APPLIO_WORKER_SCRIPT'],'--exec',str(settings.applio_python),'-m','uvicorn','rvc.realtime.client:app','--host','127.0.0.1','--port','6970'],cwd=settings.applio_workdir,env=runner.env,start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
for _ in range(40):
|
|
if await _upstream_ready():return proc
|
|
if proc.poll() is not None:raise RuntimeError('Live-Worker konnte nicht starten.')
|
|
await asyncio.sleep(.5)
|
|
os.killpg(proc.pid,signal.SIGTERM)
|
|
raise RuntimeError('Live-Worker nicht bereit.')
|
|
probe = await asyncio.to_thread(
|
|
subprocess.run,
|
|
[
|
|
"docker", "exec", settings.applio_container, "sh", "-c",
|
|
"pgrep -f '[u]vicorn rvc.realtime.client:app.*6970' >/dev/null",
|
|
],
|
|
capture_output=True,
|
|
timeout=10,
|
|
check=False,
|
|
)
|
|
if probe.returncode != 0:
|
|
await asyncio.to_thread(
|
|
subprocess.run,
|
|
[
|
|
"docker", "exec", "-d", "-w", settings.applio_workdir,
|
|
settings.applio_container, str(settings.applio_python), "-m", "uvicorn",
|
|
"rvc.realtime.client:app", "--host", "0.0.0.0", "--port", "6970",
|
|
],
|
|
capture_output=True,
|
|
timeout=15,
|
|
check=True,
|
|
)
|
|
|
|
for _ in range(40):
|
|
if await _upstream_ready():
|
|
return
|
|
await asyncio.sleep(0.5)
|
|
raise RuntimeError("Applios Echtzeitdienst konnte nicht gestartet werden")
|
|
|
|
|
|
async def _send_error(websocket: WebSocket, message: str, code: int = 1011) -> None:
|
|
await websocket.send_json({"type": "error", "value": message})
|
|
await websocket.close(code=code)
|
|
|
|
|
|
@router.websocket("/realtime/audio")
|
|
async def realtime_audio(websocket: WebSocket):
|
|
key_file=os.environ.get('APPLIO_BRIDGE_KEY_FILE')
|
|
if key_file and not secrets.compare_digest(websocket.headers.get('X-Applio-Bridge',''),Path(key_file).read_text().strip()):
|
|
await websocket.close(code=1008);return
|
|
await websocket.accept()
|
|
if _session_lock.locked():
|
|
await _send_error(websocket, "Es läuft bereits eine Live-Umwandlung", 1008)
|
|
return
|
|
|
|
async with _session_lock:
|
|
app = websocket.app
|
|
queue = app.state.job_queue
|
|
store = app.state.job_store
|
|
if queue.get_running() or store.list(status=JobStatus.WAITING, limit=1):
|
|
await _send_error(
|
|
websocket,
|
|
"Live-Umwandlung kann erst starten, wenn keine Datei- oder Trainingsaufträge laufen.",
|
|
1008,
|
|
)
|
|
return
|
|
|
|
lease=None;native_process=None
|
|
app.state.realtime_active = True
|
|
try:
|
|
raw = await asyncio.wait_for(websocket.receive_text(), timeout=20)
|
|
init = RealtimeInit.model_validate_json(raw)
|
|
payload = build_applio_init(init)
|
|
if os.environ.get('APPLIO_LEASE_SOCKET'):
|
|
from ..adapters.native_runner import reserve,get_native_runner
|
|
lease,gpu=await asyncio.to_thread(reserve)
|
|
get_native_runner().env=dict(os.environ,CUDA_VISIBLE_DEVICES=gpu,HF_HUB_OFFLINE='1')
|
|
native_process=await _ensure_realtime_server()
|
|
|
|
async with connect(
|
|
get_settings().applio_realtime_url,
|
|
max_size=None,
|
|
open_timeout=20,
|
|
close_timeout=5,
|
|
) as upstream:
|
|
await upstream.send(json.dumps(payload))
|
|
await websocket.send_json(
|
|
{
|
|
"type": "configured",
|
|
"sample_rate": 48000,
|
|
"block_frame": payload["chunk_size"] * 128,
|
|
}
|
|
)
|
|
|
|
async def browser_to_applio() -> None:
|
|
while True:
|
|
message = await websocket.receive()
|
|
if message.get("type") == "websocket.disconnect":
|
|
return
|
|
audio = message.get("bytes")
|
|
if audio is not None:
|
|
await upstream.send(audio)
|
|
|
|
async def applio_to_browser() -> None:
|
|
ready = False
|
|
async for message in upstream:
|
|
if isinstance(message, bytes):
|
|
# Applio has no init acknowledgement. Only converted
|
|
# audio proves that its pipeline actually started.
|
|
if not ready:
|
|
await websocket.send_json({"type": "ready"})
|
|
ready = True
|
|
await websocket.send_bytes(message)
|
|
else:
|
|
await websocket.send_text(message)
|
|
raise RuntimeError(
|
|
"Applios Echtzeitdienst hat die Verbindung beendet. "
|
|
"Die Live-Umwandlung wurde gestoppt."
|
|
)
|
|
|
|
tasks = {
|
|
asyncio.create_task(browser_to_applio()),
|
|
asyncio.create_task(applio_to_browser()),
|
|
}
|
|
try:
|
|
done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
|
finally:
|
|
for task in tasks:
|
|
if not task.done():
|
|
task.cancel()
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
for task in done:
|
|
task.result()
|
|
except (ValidationError, ValueError) as exc:
|
|
await _send_error(websocket, str(exc), 1008)
|
|
except (WebSocketDisconnect, asyncio.CancelledError):
|
|
pass
|
|
except ConnectionClosed:
|
|
try:
|
|
await _send_error(
|
|
websocket,
|
|
"Applios Echtzeitdienst hat die Verbindung beendet. "
|
|
"Die Live-Umwandlung wurde gestoppt.",
|
|
)
|
|
except RuntimeError:
|
|
pass
|
|
except Exception as exc: # noqa: BLE001 -- WebSocket boundary returns a visible error
|
|
try:
|
|
await _send_error(websocket, f"Live-Umwandlung fehlgeschlagen: {exc}")
|
|
except RuntimeError:
|
|
pass
|
|
finally:
|
|
if native_process and native_process.poll() is None:
|
|
try:os.killpg(native_process.pid,signal.SIGTERM);await asyncio.to_thread(native_process.wait,10)
|
|
except (ProcessLookupError,subprocess.TimeoutExpired):
|
|
try:os.killpg(native_process.pid,signal.SIGKILL)
|
|
except ProcessLookupError:pass
|
|
if lease:lease.close()
|
|
app.state.realtime_active = False
|
|
|
|
|
|
@router.get("/realtime/status")
|
|
def realtime_status():
|
|
return {
|
|
"available": True,
|
|
"active": _session_lock.locked(),
|
|
"sample_rate": 48000,
|
|
"single_session": True,
|
|
}
|