videogen/apps/api/app/domains/routing/providers/muse_voice_transcribe.py
caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

152 lines
6.1 KiB
Python

"""Muse Voice Transcribe (speech-to-text) via Meta Model API — a REAL, live-verified adapter.
Meta's Model API (https://dev.meta.ai, Meta for Developers blog, 2026-09-01:
https://developer.meta.com/ai/resources/blog/meet-muse-voice-transcribe-streaming-speech-to-text/)
ships ``muse-voice-transcribe-1.0``: audio in, a text transcript out, with
turn-level timestamps and optional speaker diarization. Billed flat at
**$0.18/hour** of audio processed ($3.00 per 1,000 minutes), rounded down to
whole seconds; failed requests and 429s are not charged.
Real flow (one-shot file transcription, not the realtime WebSocket variant —
this product only ever transcribes an already-uploaded clip, never a live
mic):
``POST https://api.meta.ai/v1/asr/transcribe?sessionId=<id>``
(Bearer ``MODEL_API_KEY``, multipart/form-data)
parts: ``request`` (JSON: ``{"mode": "ENDPOINTING", "model":
"muse-voice-transcribe-1.0", "audioEncoding": "WAV"}``), ``audio`` (a mono
16-bit PCM WAV file)
-> ``{"sessionId": "...", "transcript": "...", "audioDurationMs": N,
"turns": [{"turnId": 0, "startMs": 0, "endMs": N, "transcript": "...",
"speaker": "..."}]}``
Verified live 2026-10-29 (owner's Meta Global AI Developer Hackathon credit,
same ``MODEL_API_KEY`` already used by :mod:`muse_image` and
:mod:`sam_segment`): a synthetic 1s pure sine-wave WAV returned a real `200`
with an empty transcript (no speech present, correctly reported, not an
error); a short real spoken WAV ("Nobody tells you this about fades, start
high, taper low, and always check the guard before you touch the blade")
returned a real `200` with a turn-accurate transcript matching the spoken
line almost verbatim. Every call fails closed with a documented "not
configured" :class:`ProviderCallError` (``kind="auth"``) only when no key is
set, same convention as every other adapter in this package.
"""
from __future__ import annotations
import json
import time
from typing import Any
from app.domains.routing.providers.kling_fal import KlingError as ProviderCallError
from app.domains.routing.providers.muse_image import muse_api_key
_BASE = "https://api.meta.ai/v1"
MUSE_VOICE_TRANSCRIBE_MODEL = "muse-voice-transcribe-1.0"
#: Confirmed flat price (2026-09-01 Meta for Developers announcement): $0.18/hour.
MUSE_VOICE_TRANSCRIBE_PRICE_PER_HOUR_USD = 0.18
#: One request turn detection mode per Meta's docs: PUSH_TO_TALK (single turn,
#: caller delimits it), ENDPOINTING (model-detected turn boundaries, one turn
#: per speech segment — what this product wants for a whole-clip transcript),
#: DIARIZATION (adds per-turn speaker labels).
MODE_ENDPOINTING = "ENDPOINTING"
MODE_DIARIZATION = "DIARIZATION"
def _json(resp) -> dict:
try:
body = resp.json()
except Exception:
return {}
return body if isinstance(body, dict) else {"data": body}
def transcribe_wav(
wav_bytes: bytes,
*,
api_key: str = "",
mode: str = MODE_ENDPOINTING,
session_id: str = "",
session: Any = None,
timeout_s: float = 120.0,
max_retries: int = 3,
sleep=time.sleep,
) -> dict[str, Any]:
"""Transcribe one mono 16-bit PCM WAV clip via Muse Voice Transcribe.
Returns the real response dict (``transcript``, ``turns``,
``audioDurationMs``) — callers decide what to do with an empty transcript
(no speech detected is a real, valid result, not an error).
"""
key = api_key or muse_api_key()
if not key:
raise ProviderCallError(
"Meta Model API key not configured (set MODEL_API_KEY or MUSE_API_KEY)",
kind="auth",
)
import requests
sess = session or requests.Session()
request_part = json.dumps({"mode": mode, "model": MUSE_VOICE_TRANSCRIBE_MODEL, "audioEncoding": "WAV"})
params = {"sessionId": session_id} if session_id else {}
attempt = 0
while True:
attempt += 1
try:
resp = sess.request(
"POST",
f"{_BASE}/asr/transcribe",
headers={"Authorization": f"Bearer {key}"},
params=params,
files={"audio": ("audio.wav", wav_bytes, "audio/wav")},
data={"request": request_part},
timeout=timeout_s,
)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as exc:
if attempt <= max_retries:
sleep(min(20.0, 2 ** (attempt - 1)))
continue
raise ProviderCallError(
f"meta model api network error: {exc}", kind="transient", retryable=True
) from exc
status = resp.status_code
payload = _json(resp)
if 200 <= status < 300:
return {
"transcript": str(payload.get("transcript") or ""),
"turns": list(payload.get("turns") or []),
"audio_duration_ms": int(payload.get("audioDurationMs") or 0),
}
msg = (
str((payload.get("error") or {}).get("message"))
if isinstance(payload, dict) and isinstance(payload.get("error"), dict)
else ""
) or f"HTTP {status}"
if status in (401, 403):
raise ProviderCallError(f"meta model api auth failed: {msg}", kind="auth", status=status)
if status in (400, 422):
raise ProviderCallError(f"meta model api rejected request: {msg}", kind="validation", status=status)
if status == 429:
if attempt <= max_retries:
sleep(min(30.0, 2**attempt))
continue
raise ProviderCallError("meta model api rate limit", kind="rate_limit", retryable=True, status=429)
if status >= 500:
if attempt <= max_retries:
sleep(min(20.0, 2 ** (attempt - 1)))
continue
raise ProviderCallError(
f"meta model api server error: {msg}", kind="transient", retryable=True, status=status
)
raise ProviderCallError(f"meta model api unexpected status {status}: {msg}", kind="provider", status=status)
__all__ = [
"MODE_DIARIZATION",
"MODE_ENDPOINTING",
"MUSE_VOICE_TRANSCRIBE_MODEL",
"MUSE_VOICE_TRANSCRIBE_PRICE_PER_HOUR_USD",
"transcribe_wav",
]