Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions backend/api/routers/api_activity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Administrator-only, session-scoped speech API activity."""
from fastapi import APIRouter, Depends, Request

from api.dependencies import require_admin_action, require_admin_diagnostics
from core.api_activity import store

router = APIRouter()


async def _require_clear_access(request: Request) -> None:
# This gate performs no I/O; diagnostics must not wait for HTTP workers.
require_admin_action(request)


@router.get("/system/api-activity", dependencies=[Depends(require_admin_diagnostics)], include_in_schema=False)
async def api_activity():
return store.snapshot()


@router.delete("/system/api-activity", dependencies=[Depends(_require_clear_access)], include_in_schema=False)
async def clear_api_activity():
return {"cleared": store.clear_finished()}
5 changes: 5 additions & 0 deletions backend/api/routers/generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2058,6 +2058,8 @@ async def generate_speech(
sampling_defaults = tts_defaults(engine_id)
try:
backend_cls = get_backend_class(engine_id)
from core.api_activity import update_current
update_current(stage="queued", engine=backend_cls.id)
except ValueError:
raise HTTPException(
status_code=400,
Expand Down Expand Up @@ -2577,6 +2579,9 @@ async def _stream_events():

def _line(obj) -> bytes:
"""Encode one streaming synthesis event as a compact NDJSON line."""
if obj.get("type") == "error":
from core.api_activity import mark_error_current
mark_error_current()
return (json.dumps(obj, separators=(",", ":")) + "\n").encode("utf-8")

try:
Expand Down
27 changes: 24 additions & 3 deletions backend/api/routers/openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,9 @@ def _engine_instructions(backend, instructions: Optional[str]) -> Optional[str]:


def _speech_event(event: dict) -> str:
if event.get("type") == "error":
from core.api_activity import mark_error_current
mark_error_current()
return f"data: {json.dumps(event)}\n\n"


Expand Down Expand Up @@ -854,6 +857,9 @@ async def create_speech(req: SpeechRequest):
# OpenAI's error shape; `detail` keeps the models for VoiceStudio clients.
raise OpenAIError(403, exc.detail(), param="model", code=exc.detail()["code"]) from exc

from core.api_activity import bind as bind_activity, update_current
update_current(engine=backend.id)

# Compressed formats need ffmpeg: fail fast, before any model load or GPU
# work, and never fall back to a body that doesn't match the format.
ffmpeg = None
Expand Down Expand Up @@ -1006,9 +1012,15 @@ async def create_speech(req: SpeechRequest):
from services.model_manager import _model_load_timeout
from core import diagnostic_reports
diagnostic_epoch = diagnostic_reports.inherited_grant()
update_current(stage="queued")

def load_for_request():
update_current(stage="loading_model")
return backend.ensure_ready()

try:
await diagnostic_reports.await_owned(run_on_gpu_pool_guarded(
backend.ensure_ready,
bind_activity(load_for_request),
what=f"TTS engine '{backend.id}' model load",
timeout=_model_load_timeout(),
), diagnostic_epoch)
Expand Down Expand Up @@ -1086,23 +1098,27 @@ async def create_speech(req: SpeechRequest):

async def render(segment: str) -> tuple[bytes, str, str]:
def generate():
update_current(stage="generating")
with engine_in_use(backend, yield_to_native=True):
return _run_tts(backend, segment, kw)

try:
update_current(stage="queued")
wav, sr = await run_on_gpu_pool_guarded(
generate, what="OpenAI TTS generate",
bind_activity(generate), what="OpenAI TTS generate",
timeout=generate_timeout_s(segment, engine=backend))
except EngineBusyError:
# A native stream owns this engine until it closes.
raise _native_pcm_busy() from None
update_current(stage="encoding")
return await _encode_audio(wav, sr, req.response_format, ffmpeg)

# Finish the first segment before sending headers so validation and
# first-render errors retain their normal HTTP status.
diagnostic_epoch = diagnostic_reports.inherited_grant()
try:
if native:
update_current(stage="generating")
sse = req.stream_format == "sse"
stream = _native_pcm_stream(backend, text, kw, sse=sse)
first = await diagnostic_reports.await_owned(anext(stream), diagnostic_epoch)
Expand Down Expand Up @@ -1410,7 +1426,10 @@ async def _transcribe_request(
explicit_engine = model if _is_asr_engine_id(model) else None

def _run():
from core.api_activity import update_current
update_current(stage="loading_model")
backend = load_active_asr_backend(warm=True, require_installed=require_installed)
update_current(stage="generating", engine=getattr(backend, "id", None))
if explicit_engine and getattr(backend, "id", None) != explicit_engine:
raise _ModelNotActive(explicit_engine, getattr(backend, "id", "?"))
extra = _backend_request_kwargs(backend, options)
Expand All @@ -1422,8 +1441,10 @@ def _run():
raise _TaskUnsupported(backend.id)
return backend.transcribe(tmp_path, word_timestamps=word_ts, **extra)

from core.api_activity import bind as bind_activity, update_current
update_current(stage="queued")
result = await diagnostic_reports.await_owned(
run_transcribe_guarded(_gpu_pool, _run, what="OpenAI", audio_path=tmp_path), diagnostic_epoch)
run_transcribe_guarded(_gpu_pool, bind_activity(_run), what="OpenAI", audio_path=tmp_path), diagnostic_epoch)

segments = _result_segments(result)
full_text = (result.get("text") or "").strip() if not segments else " ".join(
Expand Down
2 changes: 1 addition & 1 deletion backend/core/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
logger = logging.getLogger("omnivoice.activity")

# Polls of these paths are how owners observe the backend; they are not use.
_PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity"})
_PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity", "/system/api-activity"})

_lock = threading.Lock()
_inflight = 0
Expand Down
Loading
Loading