Download app.py from Qwen-Forced-Aligner-polygot/qwenforcedaligner-python: direct link, hf CLI and curl.
- Browser
- Download file 37.1 kB
-
https://huggingface.co/spaces/Qwen-Forced-Aligner-polygot/qwenforcedaligner-python/resolve/main/app.py
- Command line
-
hf download hf://spaces/Qwen-Forced-Aligner-polygot/qwenforcedaligner-python/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Qwen-Forced-Aligner-polygot/qwenforcedaligner-python/resolve/main/app.py
37.1 kB
| """ | |
| Qwen3-ForcedAligner-0.6B β Word Timestamp Service v1.5 | |
| API CONTRACT β identical to MFA Aligner v5.5 so the controller can route | |
| to either backend without knowing which is behind a given slot. | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CHANGES vs v1.0 (original single-endpoint design) | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 1. JOB QUEUE INFRASTRUCTURE ADDED | |
| /align now returns a job_id and status ("running" | "queued") instead of | |
| blocking until alignment is complete. Matches MFA contract exactly: | |
| Β· queue_position, heartbeat_needed, heartbeat_url, poll_url | |
| Β· estimated_wait_s (rolling average of last 10 completed jobs) | |
| Β· duplicate_warning when client_id already has an active job | |
| 2. ALL MFA ENDPOINTS ADDED | |
| GET /job/{id}?slim=true β unified status + result (slim omits word_timestamps) | |
| GET /result/{id} β legacy compat alias for /job/{id} | |
| GET /queue/status β can_submit, slot_available, queue_full, worker_ready | |
| POST /heartbeat/{id} β keep-alive; safe to call in any job state | |
| POST /cancel/{id} β explicit cancellation; idempotent on terminal jobs | |
| GET /metrics β lifetime aggregate stats | |
| 3. /health NOW MATCHES MFA FIELD SET | |
| worker_alive, worker_ready, worker_restarting, model, | |
| shm_free_mb, shm_ok, avg_align_s, job_counts, total_jobs | |
| 4. AUDIO VALIDATION ADDED AT SUBMISSION TIME | |
| base64 decode, WAV parse, format check (16-bit PCM or 32-bit float), | |
| duration bounds (0.3 s β 180 s), mono/stereo normalisation. | |
| Invalid audio returns HTTP 400 immediately β no job created. | |
| 5. THREAD-BASED EXECUTION (no subprocess) | |
| Qwen3-ForcedAligner runs in asyncio ThreadPoolExecutor β no multiprocessing | |
| needed because it has no Kaldi child processes. Alignment tasks fire as | |
| asyncio Tasks; the event loop remains unblocked throughout. | |
| 6. LIGHTER TEXT CLEANING (vs MFA) | |
| MFA strips digits because english_mfa dict has no pronunciations for them. | |
| Qwen3 is neural and handles numbers natively, so digits are kept. | |
| Cleaning: unicode normalisation β whitespace collapse β empty-text guard. | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| IDENTICAL TO MFA v5.5 | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| Β· JobStatus values + TERMINAL_STATUSES | |
| Β· _job_view() response shape for every status | |
| Β· /align request body (audio_base64, text, language, pass_number, client_id) | |
| Β· /heartbeat client_id ownership check + response fields | |
| Β· /cancel RUNNING vs QUEUED handling | |
| Β· Heartbeat grace period on job start (HEARTBEAT_GRACE=15 s) | |
| Β· TTL-based job purging (JOB_TTL_SECONDS=300) | |
| Β· Cleanup loop tick (CLEANUP_INTERVAL=5 s) | |
| Β· Rolling average window (ROLLING_AVG_WINDOW=10) | |
| Β· All error_code strings in 4xx/5xx responses | |
| """ | |
| import os, re, uuid, base64, logging, io, wave, time, tempfile | |
| import asyncio | |
| import queue as _stdlib_queue | |
| from collections import deque | |
| from pathlib import Path | |
| from datetime import datetime, timedelta | |
| from typing import Dict, Any, Optional | |
| import numpy as np | |
| import torch | |
| from fastapi import FastAPI, HTTPException, Request, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from pydantic import BaseModel | |
| from qwen_asr import Qwen3ForcedAligner | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| app = FastAPI(title="Qwen3-ForcedAligner Service", version="1.5.0") | |
| app.add_middleware( | |
| CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"] | |
| ) | |
| MODEL_ID = "Qwen/Qwen3-ForcedAligner-0.6B" | |
| CLEANUP_INTERVAL = 5 # s β cleanup loop tick rate | |
| JOB_TTL_SECONDS = 300 # s β terminal jobs purged after this | |
| AVG_ALIGN_SECONDS = 30 # s β fallback before rolling average has data | |
| MIN_AUDIO_SECONDS = 0.3 # s β reject very short audio | |
| MAX_AUDIO_SECONDS = 180.0 # s β cap alignment latency | |
| ROLLING_AVG_WINDOW = 10 # n jobs β rolling average window for wait estimate | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MODELS | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class JobStatus: | |
| QUEUED = "queued" | |
| RUNNING = "running" | |
| COMPLETED = "completed" | |
| ABANDONED = "abandoned" | |
| FAILED = "failed" | |
| TERMINAL_STATUSES = {JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.ABANDONED} | |
| class AlignRequest(BaseModel): | |
| audio_base64: str | |
| text: str | |
| language: str = "English" | |
| pass_number: int = 1 | |
| client_id: Optional[str] = None | |
| class CancelRequest(BaseModel): | |
| client_id: Optional[str] = None | |
| # ββ Shared state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| jobs: Dict[str, Dict[str, Any]] = {} | |
| jobs_lock: asyncio.Lock = asyncio.Lock() | |
| # ββ Aligner model βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _aligner = None | |
| _worker_ready: bool = False # True after model finishes loading | |
| _worker_restarting: bool = False # Always False β no subprocess to restart | |
| # ββ Metrics βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _metrics: Dict[str, Any] = { | |
| "total_submitted": 0, | |
| "total_completed": 0, | |
| "total_failed": 0, | |
| "total_abandoned": 0, | |
| "total_cancelled": 0, | |
| "start_time": None, | |
| } | |
| _recent_durations: deque = deque(maxlen=ROLLING_AVG_WINDOW) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # UTILITIES | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _avg_align_s() -> float: | |
| if not _recent_durations: | |
| return AVG_ALIGN_SECONDS | |
| return round(sum(_recent_durations) / len(_recent_durations), 1) | |
| def _tmp_free_mb() -> Optional[float]: | |
| """Check free space in /tmp (Qwen uses /tmp, not /dev/shm).""" | |
| try: | |
| st = os.statvfs("/tmp") | |
| return round(st.f_bavail * st.f_frsize / 1_048_576, 1) | |
| except Exception: | |
| return None | |
| def _normalise_wav(wav_bytes: bytes) -> bytes: | |
| """ | |
| Normalise WAV to mono 16-bit PCM. | |
| Handles 32-bit float β int16 and stereo β mono downmix. | |
| 16-bit mono returned unchanged (zero copy). | |
| """ | |
| buf = io.BytesIO(wav_bytes) | |
| with wave.open(buf) as wf: | |
| sample_width = wf.getsampwidth() | |
| n_channels = wf.getnchannels() | |
| frame_rate = wf.getframerate() | |
| n_frames = wf.getnframes() | |
| raw = wf.readframes(n_frames) | |
| if sample_width == 2 and n_channels == 1: | |
| return wav_bytes # fast path | |
| if sample_width == 4: | |
| samples = np.frombuffer(raw, dtype=np.float32) | |
| samples = np.clip(samples, -1.0, 1.0) | |
| else: | |
| samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0 | |
| if n_channels == 2: | |
| samples = samples.reshape(-1, 2).mean(axis=1) | |
| elif n_channels > 2: | |
| samples = samples.reshape(-1, n_channels).mean(axis=1) | |
| pcm = (np.clip(samples, -1.0, 1.0) * 32767).astype(np.int16) | |
| out = io.BytesIO() | |
| with wave.open(out, "wb") as wf: | |
| wf.setnchannels(1) | |
| wf.setsampwidth(2) | |
| wf.setframerate(frame_rate) | |
| wf.writeframes(pcm.tobytes()) | |
| return out.getvalue() | |
| def _validate_audio(audio_b64: str) -> tuple[bytes, float]: | |
| """ | |
| Decode and validate audio at submission time. | |
| Returns (wav_bytes_mono_16bit, duration_s) or raises HTTPException 400. | |
| Identical validation rules to MFA v5.5. | |
| """ | |
| try: | |
| raw = base64.b64decode(audio_b64) | |
| except Exception: | |
| raise HTTPException(400, { | |
| "error": "Invalid audio", | |
| "error_code": "AUDIO_DECODE_ERROR", | |
| "detail": "audio_base64 is not valid base64.", | |
| }) | |
| try: | |
| buf = io.BytesIO(raw) | |
| with wave.open(buf) as wf: | |
| sample_width = wf.getsampwidth() | |
| n_channels = wf.getnchannels() | |
| frame_rate = wf.getframerate() | |
| n_frames = wf.getnframes() | |
| except Exception as e: | |
| raise HTTPException(400, { | |
| "error": "Invalid audio", | |
| "error_code": "AUDIO_PARSE_ERROR", | |
| "detail": f"Could not parse as WAV: {e}", | |
| }) | |
| if sample_width not in (2, 4): | |
| raise HTTPException(400, { | |
| "error": "Unsupported audio format", | |
| "error_code": "AUDIO_FORMAT_ERROR", | |
| "detail": f"Only 16-bit PCM or 32-bit float WAV supported (got {sample_width*8}-bit).", | |
| }) | |
| if frame_rate < 8000: | |
| raise HTTPException(400, { | |
| "error": "Unsupported audio format", | |
| "error_code": "AUDIO_RATE_ERROR", | |
| "detail": f"Sample rate too low: {frame_rate} Hz (minimum 8000 Hz).", | |
| }) | |
| if n_frames == 0: | |
| raise HTTPException(400, { | |
| "error": "Invalid audio", | |
| "error_code": "AUDIO_EMPTY", | |
| "detail": "WAV file contains no audio frames.", | |
| }) | |
| duration = n_frames / frame_rate | |
| if duration < MIN_AUDIO_SECONDS: | |
| raise HTTPException(400, { | |
| "error": "Audio too short", | |
| "error_code": "AUDIO_TOO_SHORT", | |
| "detail": f"Audio is {duration:.2f}s β minimum is {MIN_AUDIO_SECONDS}s.", | |
| }) | |
| if duration > MAX_AUDIO_SECONDS: | |
| raise HTTPException(400, { | |
| "error": "Audio too long", | |
| "error_code": "AUDIO_TOO_LONG", | |
| "detail": f"Audio is {duration:.1f}s β maximum is {MAX_AUDIO_SECONDS}s.", | |
| }) | |
| wav_normalised = _normalise_wav(raw) | |
| return wav_normalised, duration | |
| def _clean_text(text: str) -> str: | |
| """ | |
| Light text normalisation for Qwen3 (neural model β handles digits natively). | |
| Unlike MFA's _clean(), we do NOT strip digits: Qwen3 was trained on real | |
| speech and aligns "25 years old" correctly. We only: | |
| Β· Normalise common unicode punctuation to ASCII equivalents | |
| Β· Collapse whitespace / newlines | |
| Β· Strip leading/trailing whitespace | |
| The result is validated non-empty by the caller. | |
| """ | |
| # Curly quotes β straight | |
| text = text.replace("\u2018", "'").replace("\u2019", "'") | |
| text = text.replace("\u201c", '"').replace("\u201d", '"') | |
| # Em/en dash β space | |
| text = text.replace("\u2014", " ").replace("\u2013", " ") | |
| # Ellipsis β space | |
| text = text.replace("\u2026", " ") | |
| # Newlines β space | |
| text = text.replace("\n", " ").replace("\r", " ") | |
| # Collapse whitespace | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text | |
| def _job_view(job_id: str, job: Dict[str, Any], slim: bool = False) -> Dict[str, Any]: | |
| """ | |
| Canonical response body for /job/{id} and /result/{id}. | |
| Identical field names and semantics to MFA v5.5. | |
| slim=True omits word_timestamps from COMPLETED responses. | |
| """ | |
| status = job["status"] | |
| base = { | |
| "job_id": job_id, | |
| "status": status, | |
| "created_at": job["created_at"].isoformat(), | |
| } | |
| if status == JobStatus.QUEUED: | |
| base.update({ | |
| "queue_position": 1, | |
| "estimated_wait_s": _avg_align_s(), | |
| "message": "Queued at position 1. Poll /job/{id} every 2 s.", | |
| }) | |
| elif status == JobStatus.RUNNING: | |
| elapsed = ( | |
| (datetime.utcnow() - job["started_at"]).total_seconds() | |
| if job.get("started_at") else None | |
| ) | |
| base.update({ | |
| "started_at": job["started_at"].isoformat() if job.get("started_at") else None, | |
| "elapsed_s": round(elapsed, 1) if elapsed is not None else None, | |
| "estimated_remaining_s": max(0, round(_avg_align_s() - (elapsed or 0), 1)), | |
| "message": "Running.", | |
| }) | |
| elif status == JobStatus.COMPLETED: | |
| base.update({ | |
| "total_words": len(job["result"]), | |
| "language": job["request"].language, | |
| "pass_number": job["request"].pass_number, | |
| "model": MODEL_ID, | |
| "fine_tuned": False, | |
| "started_at": job["started_at"].isoformat() if job.get("started_at") else None, | |
| "completed_at": job["terminal_at"].isoformat() if job.get("terminal_at") else None, | |
| "duration_s": round( | |
| (job["terminal_at"] - job["started_at"]).total_seconds(), 2 | |
| ) if job.get("started_at") and job.get("terminal_at") else None, | |
| }) | |
| if not slim: | |
| base["word_timestamps"] = job["result"] | |
| elif status in (JobStatus.FAILED, JobStatus.ABANDONED): | |
| base.update({ | |
| "error": job.get("error", "Unknown error"), | |
| "completed_at": job["terminal_at"].isoformat() if job.get("terminal_at") else None, | |
| }) | |
| return base | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # ALIGNMENT TASK (thread-based, no subprocess) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def _run_alignment(job_id: str) -> None: | |
| """ | |
| Run alignment for a RUNNING job as an asyncio Task. | |
| Uses ThreadPoolExecutor so the event loop is never blocked. | |
| On completion (success or error) updates the job and promotes the next | |
| queued job. | |
| If the job was abandoned (heartbeat timeout) before the thread finishes, | |
| the result is silently discarded β the status is already ABANDONED and | |
| the next job has been promoted. | |
| """ | |
| async with jobs_lock: | |
| if job_id not in jobs: | |
| return | |
| job = jobs[job_id] | |
| if job["status"] != JobStatus.RUNNING: | |
| return | |
| wav_bytes = job["_wav_bytes"] | |
| req = job["request"] | |
| tmp_path = None | |
| try: | |
| with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp: | |
| tmp.write(wav_bytes) | |
| tmp_path = tmp.name | |
| t_start = time.monotonic() | |
| logger.info(f"[{job_id}] Aligning {len(req.text)} chars, language={req.language}") | |
| loop = asyncio.get_running_loop() | |
| results = await loop.run_in_executor( | |
| None, | |
| lambda: _aligner.align( | |
| audio=tmp_path, | |
| text=req.text.strip(), | |
| language=req.language, | |
| ) | |
| ) | |
| word_timestamps = [] | |
| if results and results[0]: | |
| for token in results[0]: | |
| word = (token.text or "").strip() | |
| if not word: | |
| continue | |
| word_timestamps.append({ | |
| "word": word, | |
| "start": round(float(token.start_time), 3), | |
| "end": round(float(token.end_time), 3), | |
| }) | |
| duration = round(time.monotonic() - t_start, 2) | |
| logger.info(f"[{job_id}] Done β {len(word_timestamps)} words in {duration}s") | |
| async with jobs_lock: | |
| if job_id in jobs and jobs[job_id]["status"] == JobStatus.RUNNING: | |
| now = datetime.utcnow() | |
| jobs[job_id]["status"] = JobStatus.COMPLETED | |
| jobs[job_id]["result"] = word_timestamps | |
| jobs[job_id]["terminal_at"] = now | |
| _metrics["total_completed"] += 1 | |
| _recent_durations.append(duration) | |
| await _promote_queued() | |
| except Exception as e: | |
| logger.exception(f"[{job_id}] Alignment failed") | |
| async with jobs_lock: | |
| if job_id in jobs and jobs[job_id]["status"] == JobStatus.RUNNING: | |
| jobs[job_id]["status"] = JobStatus.FAILED | |
| jobs[job_id]["error"] = str(e) | |
| jobs[job_id]["terminal_at"] = datetime.utcnow() | |
| _metrics["total_failed"] += 1 | |
| await _promote_queued() | |
| finally: | |
| if tmp_path and os.path.exists(tmp_path): | |
| os.unlink(tmp_path) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # QUEUE MANAGEMENT | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def _promote_queued() -> Optional[str]: | |
| """ | |
| Promote the oldest QUEUED job β RUNNING and fire its alignment task. | |
| Must be called with jobs_lock held. | |
| """ | |
| if any(info["status"] == JobStatus.RUNNING for info in jobs.values()): | |
| return None | |
| queued = sorted( | |
| [(jid, info) for jid, info in jobs.items() if info["status"] == JobStatus.QUEUED], | |
| key=lambda x: x[1]["created_at"], | |
| ) | |
| if not queued: | |
| return None | |
| jid, info = queued[0] | |
| now = datetime.utcnow() | |
| info["status"] = JobStatus.RUNNING | |
| info["started_at"] = now | |
| logger.info(f"Promoted queued job {jid} β RUNNING.") | |
| asyncio.create_task(_run_alignment(jid)) | |
| return jid | |
| async def _cleanup_loop() -> None: | |
| """ | |
| Periodic maintenance: | |
| 1. Abandon RUNNING jobs whose heartbeat has expired. | |
| 2. Purge terminal jobs past TTL. | |
| 3. Promote next queued job after any change. | |
| """ | |
| while True: | |
| await asyncio.sleep(CLEANUP_INTERVAL) | |
| async with jobs_lock: | |
| now = datetime.utcnow() | |
| ttl_cutoff = now - timedelta(seconds=JOB_TTL_SECONDS) | |
| expired = [ | |
| jid for jid, info in jobs.items() | |
| if info["status"] in TERMINAL_STATUSES | |
| and (info.get("terminal_at") or now) < ttl_cutoff | |
| ] | |
| for jid in expired: | |
| logger.info(f"Purging TTL-expired job {jid}.") | |
| del jobs[jid] | |
| await _promote_queued() | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # STARTUP / SHUTDOWN | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def startup(): | |
| global _aligner, _worker_ready | |
| _metrics["start_time"] = datetime.utcnow() | |
| logger.info(f"Loading {MODEL_ID} ...") | |
| loop = asyncio.get_running_loop() | |
| def _load(): | |
| return Qwen3ForcedAligner.from_pretrained( | |
| MODEL_ID, | |
| dtype=torch.float32, | |
| device_map="cpu", | |
| ) | |
| _aligner = await loop.run_in_executor(None, _load) | |
| _worker_ready = True | |
| logger.info(f"β {MODEL_ID} loaded β worker_ready=True") | |
| asyncio.create_task(_cleanup_loop()) | |
| logger.info("Qwen3-ForcedAligner Service v1.5 ready.") | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # ENDPOINTS | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def root(): | |
| return { | |
| "name": "Qwen3-ForcedAligner Service", | |
| "version": "1.5.0", | |
| "status": "ready" if _aligner else "loading", | |
| "model": MODEL_ID, | |
| "endpoints": { | |
| "POST /align": "Submit alignment job", | |
| "GET /job/{id}": "Unified status + result [preferred]", | |
| "GET /job/{id}?slim=true": "Status only β omits word_timestamps (use while polling)", | |
| "GET /result/{id}": "Legacy result poll [compat]", | |
| "GET /queue/status": "Queue availability", | |
| "POST /cancel/{id}": "Explicit job cancellation", | |
| "GET /health": "Service health + job counts", | |
| "GET /metrics": "Aggregate metrics", | |
| }, | |
| } | |
| async def health(): | |
| """ | |
| Identical field set to MFA /health so the controller can use one | |
| health-check parser for both backends. | |
| worker_alive β True when model is loaded and ready to process | |
| worker_ready β True after model finishes loading (same as worker_alive here) | |
| worker_restarting β Always False (no subprocess to restart) | |
| shm_free_mb β Free space in /tmp (Qwen uses /tmp, not /dev/shm) | |
| shm_ok β True when /tmp has β₯ 200 MB free | |
| """ | |
| worker_alive = _aligner is not None | |
| tmp_free = _tmp_free_mb() | |
| shm_ok = tmp_free is None or tmp_free >= 200 | |
| async with jobs_lock: | |
| counts = {s: 0 for s in [ | |
| JobStatus.QUEUED, JobStatus.RUNNING, | |
| JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.ABANDONED, | |
| ]} | |
| for info in jobs.values(): | |
| counts[info["status"]] = counts.get(info["status"], 0) + 1 | |
| overall = "healthy" | |
| if not worker_alive: | |
| overall = "degraded" | |
| if not shm_ok: | |
| overall = "degraded" | |
| return { | |
| "status": overall, | |
| "worker_alive": worker_alive, | |
| "worker_ready": _worker_ready, | |
| "worker_restarting": _worker_restarting, | |
| "model": MODEL_ID, | |
| "shm_free_mb": tmp_free, | |
| "shm_ok": shm_ok, | |
| "avg_align_s": _avg_align_s(), | |
| "job_counts": counts, | |
| "total_jobs": sum(counts.values()), | |
| } | |
| async def metrics(): | |
| uptime = ( | |
| round((datetime.utcnow() - _metrics["start_time"]).total_seconds(), 0) | |
| if _metrics["start_time"] else None | |
| ) | |
| total = _metrics["total_completed"] + _metrics["total_failed"] + _metrics["total_abandoned"] | |
| success_rate = round(_metrics["total_completed"] / total, 3) if total > 0 else None | |
| return { | |
| "uptime_s": uptime, | |
| "total_submitted": _metrics["total_submitted"], | |
| "total_completed": _metrics["total_completed"], | |
| "total_failed": _metrics["total_failed"], | |
| "total_abandoned": _metrics["total_abandoned"], | |
| "total_cancelled": _metrics["total_cancelled"], | |
| "success_rate": success_rate, | |
| "worker_restarts": 0, # no subprocess to restart | |
| "avg_align_s": _avg_align_s(), | |
| "recent_durations": list(_recent_durations), | |
| } | |
| async def queue_status(): | |
| async with jobs_lock: | |
| running_job = next( | |
| (jid for jid, info in jobs.items() if info["status"] == JobStatus.RUNNING), None | |
| ) | |
| queued_job = next( | |
| (jid for jid, info in jobs.items() if info["status"] == JobStatus.QUEUED), None | |
| ) | |
| running_count = 1 if running_job else 0 | |
| waiting_count = 1 if queued_job else 0 | |
| return { | |
| # ββ NEW: integer counts the controller reads ββββββββββββββββββββββ | |
| "running": running_count, | |
| "waiting": waiting_count, | |
| # ββ Existing fields kept for backwards compat βββββββββββββββββββββ | |
| "can_submit": running_count == 0 and waiting_count == 0, | |
| "slot_available": running_count == 0, | |
| "queue_full": running_count == 1 and waiting_count == 1, | |
| "running_job_id": running_job, | |
| "queued_job_id": queued_job, | |
| "worker_ready": _worker_ready, | |
| "estimated_wait_s": _avg_align_s() if running_job else 0, | |
| } | |
| async def align_audio(req: AlignRequest): | |
| """ | |
| Submit an alignment job. All validation runs before the job enters the | |
| queue β invalid requests get an immediate HTTP 400. | |
| Response fields (identical to MFA v5.5): | |
| job_id β use for all subsequent calls | |
| status β "running" | "queued" | |
| queue_position β 0 = started immediately, 1 = queued | |
| poll_url β GET here for status / result | |
| estimated_wait_s β rolling average, 0 if running now | |
| duplicate_warning β present if client_id already has an active job | |
| Frontend flow: | |
| queue_position==0: poll for "completed" | |
| queue_position==1: poll every 2 s until "running". | |
| 503 QUEUE_FULL: wait retry_after seconds, then retry | |
| """ | |
| # ββ 1. Model check ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if _aligner is None: | |
| raise HTTPException(503, { | |
| "error": "Worker unavailable", | |
| "error_code": "WORKER_DOWN", | |
| "detail": "Model is still loading. Retry in a few seconds.", | |
| }) | |
| # ββ 2. Text validation ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| cleaned_text = _clean_text(req.text) | |
| if not cleaned_text: | |
| raise HTTPException(400, { | |
| "error": "Invalid text", | |
| "error_code": "TEXT_EMPTY", | |
| "detail": "Text is empty after normalisation.", | |
| }) | |
| # ββ 3. Audio validation (CPU work β run in executor) ββββββββββββββββββββββ | |
| loop = asyncio.get_running_loop() | |
| try: | |
| wav_normalised, audio_duration = await loop.run_in_executor( | |
| None, _validate_audio, req.audio_base64 | |
| ) | |
| except HTTPException: | |
| raise | |
| async with jobs_lock: | |
| running_exists = any(info["status"] == JobStatus.RUNNING for info in jobs.values()) | |
| queued_exists = any(info["status"] == JobStatus.QUEUED for info in jobs.values()) | |
| # ββ 4. Queue full check βββββββββββββββββββββββββββββββββββββββββββββββ | |
| if running_exists and queued_exists: | |
| return JSONResponse( | |
| status_code=503, | |
| content={ | |
| "error": "Service busy", | |
| "error_code": "QUEUE_FULL", | |
| "detail": "One job running, one already queued. Retry after current jobs finish.", | |
| "retry_after": _avg_align_s(), | |
| }, | |
| headers={"Retry-After": str(int(_avg_align_s()))}, | |
| ) | |
| # ββ 5. Duplicate client check βββββββββββββββββββββββββββββββββββββββββ | |
| duplicate_warning = None | |
| if req.client_id: | |
| existing = next( | |
| (jid for jid, info in jobs.items() | |
| if info.get("client_id") == req.client_id | |
| and info["status"] in (JobStatus.RUNNING, JobStatus.QUEUED)), | |
| None | |
| ) | |
| if existing: | |
| duplicate_warning = { | |
| "message": "You already have an active job.", | |
| "existing_job_id": existing, | |
| "existing_status": jobs[existing]["status"], | |
| } | |
| # ββ 6. Create job βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| status = JobStatus.QUEUED if running_exists else JobStatus.RUNNING | |
| job_id = uuid.uuid4().hex[:12] | |
| queue_position = 1 if status == JobStatus.QUEUED else 0 | |
| now = datetime.utcnow() | |
| jobs[job_id] = { | |
| "request": req, | |
| "status": status, | |
| "created_at": now, | |
| "started_at": now if status == JobStatus.RUNNING else None, | |
| "terminal_at": None, | |
| "result": None, | |
| "error": None, | |
| "client_id": req.client_id, | |
| "audio_duration": round(audio_duration, 2), | |
| "_wav_bytes": wav_normalised, # consumed by _run_alignment, not serialised | |
| } | |
| _metrics["total_submitted"] += 1 | |
| logger.info( | |
| f"Job {job_id} created β status={status}, " | |
| f"duration={audio_duration:.1f}s, client={req.client_id}" | |
| ) | |
| if status == JobStatus.RUNNING: | |
| asyncio.create_task(_run_alignment(job_id)) | |
| response = { | |
| "job_id": job_id, | |
| "status": status, | |
| "queue_position": queue_position, | |
| "poll_url": f"/job/{job_id}", | |
| "estimated_wait_s": 0 if status == JobStatus.RUNNING else _avg_align_s(), | |
| "audio_duration_s": round(audio_duration, 2), | |
| "message": ( | |
| f"Job started. Poll GET /job/{job_id}." | |
| if status == JobStatus.RUNNING else | |
| f"Job queued at position 1. Poll GET /job/{job_id} every 2 s." | |
| ), | |
| } | |
| if duplicate_warning: | |
| response["duplicate_warning"] = duplicate_warning | |
| return JSONResponse(response) | |
| async def get_job(job_id: str, slim: bool = Query(False)): | |
| """ | |
| Unified status + result endpoint. | |
| ?slim=true β omits word_timestamps from COMPLETED responses. | |
| Use during polling; fetch without slim=true once completed. | |
| Frontend state machine: | |
| "queued" β poll every 2 s (slim=true) | |
| "running" β keep polling (slim=true) | |
| "completed" β fetch /job/{id} (slim=false) for timestamps | |
| "failed" β show error | |
| "abandoned" β resubmit | |
| """ | |
| async with jobs_lock: | |
| if job_id not in jobs: | |
| raise HTTPException(404, detail={ | |
| "error": "Job not found", | |
| "error_code": "JOB_NOT_FOUND", | |
| "detail": "Job may have been purged (TTL=5 min) or never existed.", | |
| }) | |
| return _job_view(job_id, jobs[job_id], slim=slim) | |
| async def get_result(job_id: str): | |
| """Legacy endpoint β use GET /job/{id} instead.""" | |
| async with jobs_lock: | |
| if job_id not in jobs: | |
| raise HTTPException(404, "Job not found") | |
| return _job_view(job_id, jobs[job_id]) | |
| async def cancel_job(job_id: str, body: CancelRequest): | |
| """ | |
| Explicitly cancel a job. | |
| RUNNING: marks abandoned. The alignment thread may still finish but its | |
| result will be discarded (status != RUNNING guard in the task). | |
| QUEUED: removes cleanly, no side effects. | |
| Terminal: idempotent 200. | |
| """ | |
| async with jobs_lock: | |
| if job_id not in jobs: | |
| raise HTTPException(404, detail={ | |
| "error": "Job not found", | |
| "error_code": "JOB_NOT_FOUND", | |
| }) | |
| job = jobs[job_id] | |
| status = job["status"] | |
| stored = job.get("client_id") | |
| if stored and (body.client_id is None or body.client_id != stored): | |
| raise HTTPException(403, detail={ | |
| "error": "Client ID mismatch", | |
| "error_code": "FORBIDDEN", | |
| "detail": "You are not the owner of this job.", | |
| }) | |
| if status in TERMINAL_STATUSES: | |
| return { | |
| "cancelled": False, | |
| "status": status, | |
| "message": f"Job was already {status} β nothing to cancel.", | |
| } | |
| now = datetime.utcnow() | |
| jobs[job_id]["status"] = JobStatus.ABANDONED | |
| jobs[job_id]["error"] = "Cancelled by client" | |
| jobs[job_id]["terminal_at"] = now | |
| _metrics["total_cancelled"] += 1 | |
| was_running = status == JobStatus.RUNNING | |
| logger.info(f"Job {job_id} cancelled ({'RUNNING' if was_running else 'QUEUED'}).") | |
| await _promote_queued() | |
| return { | |
| "cancelled": True, | |
| "job_id": job_id, | |
| "restarting": False, # no subprocess β field kept for contract compat | |
| "message": "Job cancelled.", | |
| } | |
| async def benchmark_align(req: AlignRequest): | |
| """ | |
| Runs alignment synchronously and returns timing + input stats. | |
| Used for calibrating the estimator β not for production use. | |
| """ | |
| if _aligner is None: | |
| raise HTTPException(503, {"error": "Model not loaded yet"}) | |
| cleaned_text = _clean_text(req.text) | |
| if not cleaned_text: | |
| raise HTTPException(400, {"error": "Empty text"}) | |
| wav_normalised, audio_duration = await asyncio.get_running_loop().run_in_executor( | |
| None, _validate_audio, req.audio_base64 | |
| ) | |
| word_count = len(cleaned_text.split()) | |
| tmp_path = None | |
| try: | |
| with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp: | |
| tmp.write(wav_normalised) | |
| tmp_path = tmp.name | |
| t_start = time.monotonic() | |
| loop = asyncio.get_running_loop() | |
| results = await loop.run_in_executor( | |
| None, | |
| lambda: _aligner.align( | |
| audio=tmp_path, | |
| text=cleaned_text, | |
| language=req.language, | |
| ) | |
| ) | |
| actual_duration_s = round(time.monotonic() - t_start, 3) | |
| word_timestamps = [] | |
| if results and results[0]: | |
| for token in results[0]: | |
| word = (token.text or "").strip() | |
| if not word: | |
| continue | |
| word_timestamps.append({ | |
| "word": word, | |
| "start": round(float(token.start_time), 3), | |
| "end": round(float(token.end_time), 3), | |
| }) | |
| return { | |
| "audio_duration_s": round(audio_duration, 3), | |
| "word_count": word_count, | |
| "actual_align_s": actual_duration_s, | |
| "realtime_factor": round(actual_duration_s / audio_duration, 3), | |
| "ms_per_word": round((actual_duration_s / word_count) * 1000, 1) if word_count else None, | |
| "words_aligned": len(word_timestamps), | |
| "language": req.language, | |
| "timestamp": datetime.utcnow().isoformat(), | |
| } | |
| finally: | |
| if tmp_path and os.path.exists(tmp_path): | |
| os.unlink(tmp_path) |