YTShortMakerArchx commited on
Commit
b3346ac
Β·
verified Β·
1 Parent(s): 29364a4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +822 -0
app.py ADDED
@@ -0,0 +1,822 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Qwen3-ForcedAligner-0.6B β€” Word Timestamp Service v1.5
3
+
4
+ API CONTRACT β€” identical to MFA Aligner v5.5 so the controller can route
5
+ to either backend without knowing which is behind a given slot.
6
+
7
+ ═══════════════════════════════════════════════════════════════════════════════
8
+ CHANGES vs v1.0 (original single-endpoint design)
9
+ ═══════════════════════════════════════════════════════════════════════════════
10
+
11
+ 1. JOB QUEUE INFRASTRUCTURE ADDED
12
+ /align now returns a job_id and status ("running" | "queued") instead of
13
+ blocking until alignment is complete. Matches MFA contract exactly:
14
+ Β· queue_position, heartbeat_needed, heartbeat_url, poll_url
15
+ Β· estimated_wait_s (rolling average of last 10 completed jobs)
16
+ Β· duplicate_warning when client_id already has an active job
17
+
18
+ 2. ALL MFA ENDPOINTS ADDED
19
+ GET /job/{id}?slim=true β€” unified status + result (slim omits word_timestamps)
20
+ GET /result/{id} β€” legacy compat alias for /job/{id}
21
+ GET /queue/status β€” can_submit, slot_available, queue_full, worker_ready
22
+ POST /heartbeat/{id} β€” keep-alive; safe to call in any job state
23
+ POST /cancel/{id} β€” explicit cancellation; idempotent on terminal jobs
24
+ GET /metrics β€” lifetime aggregate stats
25
+
26
+ 3. /health NOW MATCHES MFA FIELD SET
27
+ worker_alive, worker_ready, worker_restarting, model,
28
+ shm_free_mb, shm_ok, avg_align_s, job_counts, total_jobs
29
+
30
+ 4. AUDIO VALIDATION ADDED AT SUBMISSION TIME
31
+ base64 decode, WAV parse, format check (16-bit PCM or 32-bit float),
32
+ duration bounds (0.3 s – 180 s), mono/stereo normalisation.
33
+ Invalid audio returns HTTP 400 immediately β€” no job created.
34
+
35
+ 5. THREAD-BASED EXECUTION (no subprocess)
36
+ Qwen3-ForcedAligner runs in asyncio ThreadPoolExecutor β€” no multiprocessing
37
+ needed because it has no Kaldi child processes. Alignment tasks fire as
38
+ asyncio Tasks; the event loop remains unblocked throughout.
39
+
40
+ 6. LIGHTER TEXT CLEANING (vs MFA)
41
+ MFA strips digits because english_mfa dict has no pronunciations for them.
42
+ Qwen3 is neural and handles numbers natively, so digits are kept.
43
+ Cleaning: unicode normalisation β†’ whitespace collapse β†’ empty-text guard.
44
+
45
+ ═══════════════════════════════════════════════════════════════════════════════
46
+ IDENTICAL TO MFA v5.5
47
+ ═══════════════════════════════════════════════════════════════════════════════
48
+ Β· JobStatus values + TERMINAL_STATUSES
49
+ Β· _job_view() response shape for every status
50
+ Β· /align request body (audio_base64, text, language, pass_number, client_id)
51
+ Β· /heartbeat client_id ownership check + response fields
52
+ Β· /cancel RUNNING vs QUEUED handling
53
+ Β· Heartbeat grace period on job start (HEARTBEAT_GRACE=15 s)
54
+ Β· TTL-based job purging (JOB_TTL_SECONDS=300)
55
+ Β· Cleanup loop tick (CLEANUP_INTERVAL=5 s)
56
+ Β· Rolling average window (ROLLING_AVG_WINDOW=10)
57
+ Β· All error_code strings in 4xx/5xx responses
58
+ """
59
+
60
+ import os, re, uuid, base64, logging, io, wave, time, tempfile
61
+ import asyncio
62
+ import queue as _stdlib_queue
63
+ from collections import deque
64
+ from pathlib import Path
65
+ from datetime import datetime, timedelta
66
+ from typing import Dict, Any, Optional
67
+
68
+ import numpy as np
69
+ import torch
70
+ from fastapi import FastAPI, HTTPException, Request, Query
71
+ from fastapi.middleware.cors import CORSMiddleware
72
+ from fastapi.responses import JSONResponse
73
+ from pydantic import BaseModel
74
+ from qwen_asr import Qwen3ForcedAligner
75
+
76
+ logging.basicConfig(level=logging.INFO)
77
+ logger = logging.getLogger(__name__)
78
+
79
+ app = FastAPI(title="Qwen3-ForcedAligner Service", version="1.5.0")
80
+ app.add_middleware(
81
+ CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
82
+ )
83
+
84
+ MODEL_ID = "Qwen/Qwen3-ForcedAligner-0.6B"
85
+
86
+ CLEANUP_INTERVAL = 5 # s β€” cleanup loop tick rate
87
+ JOB_TTL_SECONDS = 300 # s β€” terminal jobs purged after this
88
+ AVG_ALIGN_SECONDS = 30 # s β€” fallback before rolling average has data
89
+ MIN_AUDIO_SECONDS = 0.3 # s β€” reject very short audio
90
+ MAX_AUDIO_SECONDS = 180.0 # s β€” cap alignment latency
91
+ ROLLING_AVG_WINDOW = 10 # n jobs β€” rolling average window for wait estimate
92
+
93
+
94
+ # ══════════════════════════════════════════════════════════════════════════════���
95
+ # MODELS
96
+ # ═══════════════════════════════════════════════════════════════════════════════
97
+
98
+ class JobStatus:
99
+ QUEUED = "queued"
100
+ RUNNING = "running"
101
+ COMPLETED = "completed"
102
+ ABANDONED = "abandoned"
103
+ FAILED = "failed"
104
+
105
+ TERMINAL_STATUSES = {JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.ABANDONED}
106
+
107
+ class AlignRequest(BaseModel):
108
+ audio_base64: str
109
+ text: str
110
+ language: str = "English"
111
+ pass_number: int = 1
112
+ client_id: Optional[str] = None
113
+
114
+ class CancelRequest(BaseModel):
115
+ client_id: Optional[str] = None
116
+
117
+ # ── Shared state ──────────────────────────────────────────────────────────────
118
+ jobs: Dict[str, Dict[str, Any]] = {}
119
+ jobs_lock: asyncio.Lock = asyncio.Lock()
120
+
121
+ # ── Aligner model ─────────────────────────────────────────────────────────────
122
+ _aligner = None
123
+ _worker_ready: bool = False # True after model finishes loading
124
+ _worker_restarting: bool = False # Always False β€” no subprocess to restart
125
+
126
+ # ── Metrics ───────────────────────────────────────────────────────────────────
127
+ _metrics: Dict[str, Any] = {
128
+ "total_submitted": 0,
129
+ "total_completed": 0,
130
+ "total_failed": 0,
131
+ "total_abandoned": 0,
132
+ "total_cancelled": 0,
133
+ "start_time": None,
134
+ }
135
+ _recent_durations: deque = deque(maxlen=ROLLING_AVG_WINDOW)
136
+
137
+
138
+ # ═══════════════════════════════════════════════════════════════════════════════
139
+ # UTILITIES
140
+ # ═══════════════════════════════════════════════════════════════════════════════
141
+
142
+ def _avg_align_s() -> float:
143
+ if not _recent_durations:
144
+ return AVG_ALIGN_SECONDS
145
+ return round(sum(_recent_durations) / len(_recent_durations), 1)
146
+
147
+ def _tmp_free_mb() -> Optional[float]:
148
+ """Check free space in /tmp (Qwen uses /tmp, not /dev/shm)."""
149
+ try:
150
+ st = os.statvfs("/tmp")
151
+ return round(st.f_bavail * st.f_frsize / 1_048_576, 1)
152
+ except Exception:
153
+ return None
154
+
155
+ def _normalise_wav(wav_bytes: bytes) -> bytes:
156
+ """
157
+ Normalise WAV to mono 16-bit PCM.
158
+ Handles 32-bit float β†’ int16 and stereo β†’ mono downmix.
159
+ 16-bit mono returned unchanged (zero copy).
160
+ """
161
+ buf = io.BytesIO(wav_bytes)
162
+ with wave.open(buf) as wf:
163
+ sample_width = wf.getsampwidth()
164
+ n_channels = wf.getnchannels()
165
+ frame_rate = wf.getframerate()
166
+ n_frames = wf.getnframes()
167
+ raw = wf.readframes(n_frames)
168
+
169
+ if sample_width == 2 and n_channels == 1:
170
+ return wav_bytes # fast path
171
+
172
+ if sample_width == 4:
173
+ samples = np.frombuffer(raw, dtype=np.float32)
174
+ samples = np.clip(samples, -1.0, 1.0)
175
+ else:
176
+ samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
177
+
178
+ if n_channels == 2:
179
+ samples = samples.reshape(-1, 2).mean(axis=1)
180
+ elif n_channels > 2:
181
+ samples = samples.reshape(-1, n_channels).mean(axis=1)
182
+
183
+ pcm = (np.clip(samples, -1.0, 1.0) * 32767).astype(np.int16)
184
+ out = io.BytesIO()
185
+ with wave.open(out, "wb") as wf:
186
+ wf.setnchannels(1)
187
+ wf.setsampwidth(2)
188
+ wf.setframerate(frame_rate)
189
+ wf.writeframes(pcm.tobytes())
190
+ return out.getvalue()
191
+
192
+
193
+ def _validate_audio(audio_b64: str) -> tuple[bytes, float]:
194
+ """
195
+ Decode and validate audio at submission time.
196
+ Returns (wav_bytes_mono_16bit, duration_s) or raises HTTPException 400.
197
+ Identical validation rules to MFA v5.5.
198
+ """
199
+ try:
200
+ raw = base64.b64decode(audio_b64)
201
+ except Exception:
202
+ raise HTTPException(400, {
203
+ "error": "Invalid audio",
204
+ "error_code": "AUDIO_DECODE_ERROR",
205
+ "detail": "audio_base64 is not valid base64.",
206
+ })
207
+
208
+ try:
209
+ buf = io.BytesIO(raw)
210
+ with wave.open(buf) as wf:
211
+ sample_width = wf.getsampwidth()
212
+ n_channels = wf.getnchannels()
213
+ frame_rate = wf.getframerate()
214
+ n_frames = wf.getnframes()
215
+ except Exception as e:
216
+ raise HTTPException(400, {
217
+ "error": "Invalid audio",
218
+ "error_code": "AUDIO_PARSE_ERROR",
219
+ "detail": f"Could not parse as WAV: {e}",
220
+ })
221
+
222
+ if sample_width not in (2, 4):
223
+ raise HTTPException(400, {
224
+ "error": "Unsupported audio format",
225
+ "error_code": "AUDIO_FORMAT_ERROR",
226
+ "detail": f"Only 16-bit PCM or 32-bit float WAV supported (got {sample_width*8}-bit).",
227
+ })
228
+ if frame_rate < 8000:
229
+ raise HTTPException(400, {
230
+ "error": "Unsupported audio format",
231
+ "error_code": "AUDIO_RATE_ERROR",
232
+ "detail": f"Sample rate too low: {frame_rate} Hz (minimum 8000 Hz).",
233
+ })
234
+ if n_frames == 0:
235
+ raise HTTPException(400, {
236
+ "error": "Invalid audio",
237
+ "error_code": "AUDIO_EMPTY",
238
+ "detail": "WAV file contains no audio frames.",
239
+ })
240
+
241
+ duration = n_frames / frame_rate
242
+ if duration < MIN_AUDIO_SECONDS:
243
+ raise HTTPException(400, {
244
+ "error": "Audio too short",
245
+ "error_code": "AUDIO_TOO_SHORT",
246
+ "detail": f"Audio is {duration:.2f}s β€” minimum is {MIN_AUDIO_SECONDS}s.",
247
+ })
248
+ if duration > MAX_AUDIO_SECONDS:
249
+ raise HTTPException(400, {
250
+ "error": "Audio too long",
251
+ "error_code": "AUDIO_TOO_LONG",
252
+ "detail": f"Audio is {duration:.1f}s β€” maximum is {MAX_AUDIO_SECONDS}s.",
253
+ })
254
+
255
+ wav_normalised = _normalise_wav(raw)
256
+ return wav_normalised, duration
257
+
258
+
259
+ def _clean_text(text: str) -> str:
260
+ """
261
+ Light text normalisation for Qwen3 (neural model β€” handles digits natively).
262
+
263
+ Unlike MFA's _clean(), we do NOT strip digits: Qwen3 was trained on real
264
+ speech and aligns "25 years old" correctly. We only:
265
+ Β· Normalise common unicode punctuation to ASCII equivalents
266
+ Β· Collapse whitespace / newlines
267
+ Β· Strip leading/trailing whitespace
268
+ The result is validated non-empty by the caller.
269
+ """
270
+ # Curly quotes β†’ straight
271
+ text = text.replace("\u2018", "'").replace("\u2019", "'")
272
+ text = text.replace("\u201c", '"').replace("\u201d", '"')
273
+ # Em/en dash β†’ space
274
+ text = text.replace("\u2014", " ").replace("\u2013", " ")
275
+ # Ellipsis β†’ space
276
+ text = text.replace("\u2026", " ")
277
+ # Newlines β†’ space
278
+ text = text.replace("\n", " ").replace("\r", " ")
279
+ # Collapse whitespace
280
+ text = re.sub(r"\s+", " ", text).strip()
281
+ return text
282
+
283
+
284
+ def _job_view(job_id: str, job: Dict[str, Any], slim: bool = False) -> Dict[str, Any]:
285
+ """
286
+ Canonical response body for /job/{id} and /result/{id}.
287
+ Identical field names and semantics to MFA v5.5.
288
+ slim=True omits word_timestamps from COMPLETED responses.
289
+ """
290
+ status = job["status"]
291
+ base = {
292
+ "job_id": job_id,
293
+ "status": status,
294
+ "created_at": job["created_at"].isoformat(),
295
+ }
296
+
297
+ if status == JobStatus.QUEUED:
298
+ base.update({
299
+ "queue_position": 1,
300
+ "estimated_wait_s": _avg_align_s(),
301
+ "message": "Queued at position 1. Poll /job/{id} every 2 s.",
302
+ })
303
+
304
+ elif status == JobStatus.RUNNING:
305
+ elapsed = (
306
+ (datetime.utcnow() - job["started_at"]).total_seconds()
307
+ if job.get("started_at") else None
308
+ )
309
+ base.update({
310
+ "started_at": job["started_at"].isoformat() if job.get("started_at") else None,
311
+ "elapsed_s": round(elapsed, 1) if elapsed is not None else None,
312
+ "estimated_remaining_s": max(0, round(_avg_align_s() - (elapsed or 0), 1)),
313
+ "message": "Running.",
314
+ })
315
+
316
+ elif status == JobStatus.COMPLETED:
317
+ base.update({
318
+ "total_words": len(job["result"]),
319
+ "language": job["request"].language,
320
+ "pass_number": job["request"].pass_number,
321
+ "model": MODEL_ID,
322
+ "fine_tuned": False,
323
+ "started_at": job["started_at"].isoformat() if job.get("started_at") else None,
324
+ "completed_at": job["terminal_at"].isoformat() if job.get("terminal_at") else None,
325
+ "duration_s": round(
326
+ (job["terminal_at"] - job["started_at"]).total_seconds(), 2
327
+ ) if job.get("started_at") and job.get("terminal_at") else None,
328
+ })
329
+ if not slim:
330
+ base["word_timestamps"] = job["result"]
331
+
332
+ elif status in (JobStatus.FAILED, JobStatus.ABANDONED):
333
+ base.update({
334
+ "error": job.get("error", "Unknown error"),
335
+ "completed_at": job["terminal_at"].isoformat() if job.get("terminal_at") else None,
336
+ })
337
+
338
+ return base
339
+
340
+
341
+ # ═══════════════════════════════════════════════════════════════════════════════
342
+ # ALIGNMENT TASK (thread-based, no subprocess)
343
+ # ══��════════════════════════════════════════════════════════════════════════════
344
+
345
+ async def _run_alignment(job_id: str) -> None:
346
+ """
347
+ Run alignment for a RUNNING job as an asyncio Task.
348
+
349
+ Uses ThreadPoolExecutor so the event loop is never blocked.
350
+ On completion (success or error) updates the job and promotes the next
351
+ queued job.
352
+
353
+ If the job was abandoned (heartbeat timeout) before the thread finishes,
354
+ the result is silently discarded β€” the status is already ABANDONED and
355
+ the next job has been promoted.
356
+ """
357
+ async with jobs_lock:
358
+ if job_id not in jobs:
359
+ return
360
+ job = jobs[job_id]
361
+ if job["status"] != JobStatus.RUNNING:
362
+ return
363
+ wav_bytes = job["_wav_bytes"]
364
+ req = job["request"]
365
+
366
+ tmp_path = None
367
+ try:
368
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
369
+ tmp.write(wav_bytes)
370
+ tmp_path = tmp.name
371
+
372
+ t_start = time.monotonic()
373
+ logger.info(f"[{job_id}] Aligning {len(req.text)} chars, language={req.language}")
374
+
375
+ loop = asyncio.get_running_loop()
376
+ results = await loop.run_in_executor(
377
+ None,
378
+ lambda: _aligner.align(
379
+ audio=tmp_path,
380
+ text=req.text.strip(),
381
+ language=req.language,
382
+ )
383
+ )
384
+
385
+ word_timestamps = []
386
+ if results and results[0]:
387
+ for token in results[0]:
388
+ word = (token.text or "").strip()
389
+ if not word:
390
+ continue
391
+ word_timestamps.append({
392
+ "word": word,
393
+ "start": round(float(token.start_time), 3),
394
+ "end": round(float(token.end_time), 3),
395
+ })
396
+
397
+ duration = round(time.monotonic() - t_start, 2)
398
+ logger.info(f"[{job_id}] Done β€” {len(word_timestamps)} words in {duration}s")
399
+
400
+ async with jobs_lock:
401
+ if job_id in jobs and jobs[job_id]["status"] == JobStatus.RUNNING:
402
+ now = datetime.utcnow()
403
+ jobs[job_id]["status"] = JobStatus.COMPLETED
404
+ jobs[job_id]["result"] = word_timestamps
405
+ jobs[job_id]["terminal_at"] = now
406
+ _metrics["total_completed"] += 1
407
+ _recent_durations.append(duration)
408
+ await _promote_queued()
409
+
410
+ except Exception as e:
411
+ logger.exception(f"[{job_id}] Alignment failed")
412
+ async with jobs_lock:
413
+ if job_id in jobs and jobs[job_id]["status"] == JobStatus.RUNNING:
414
+ jobs[job_id]["status"] = JobStatus.FAILED
415
+ jobs[job_id]["error"] = str(e)
416
+ jobs[job_id]["terminal_at"] = datetime.utcnow()
417
+ _metrics["total_failed"] += 1
418
+ await _promote_queued()
419
+
420
+ finally:
421
+ if tmp_path and os.path.exists(tmp_path):
422
+ os.unlink(tmp_path)
423
+
424
+
425
+ # ═══════════════════════════════════════════════════════════════════════════════
426
+ # QUEUE MANAGEMENT
427
+ # ═══════════════════════════════════════════════════════════════════════════════
428
+
429
+ async def _promote_queued() -> Optional[str]:
430
+ """
431
+ Promote the oldest QUEUED job β†’ RUNNING and fire its alignment task.
432
+ Must be called with jobs_lock held.
433
+ """
434
+ if any(info["status"] == JobStatus.RUNNING for info in jobs.values()):
435
+ return None
436
+ queued = sorted(
437
+ [(jid, info) for jid, info in jobs.items() if info["status"] == JobStatus.QUEUED],
438
+ key=lambda x: x[1]["created_at"],
439
+ )
440
+ if not queued:
441
+ return None
442
+ jid, info = queued[0]
443
+ now = datetime.utcnow()
444
+ info["status"] = JobStatus.RUNNING
445
+ info["started_at"] = now
446
+ logger.info(f"Promoted queued job {jid} β†’ RUNNING.")
447
+ asyncio.create_task(_run_alignment(jid))
448
+ return jid
449
+
450
+
451
+ async def _cleanup_loop() -> None:
452
+ """
453
+ Periodic maintenance:
454
+ 1. Abandon RUNNING jobs whose heartbeat has expired.
455
+ 2. Purge terminal jobs past TTL.
456
+ 3. Promote next queued job after any change.
457
+ """
458
+ while True:
459
+ await asyncio.sleep(CLEANUP_INTERVAL)
460
+ async with jobs_lock:
461
+ now = datetime.utcnow()
462
+ ttl_cutoff = now - timedelta(seconds=JOB_TTL_SECONDS)
463
+
464
+ expired = [
465
+ jid for jid, info in jobs.items()
466
+ if info["status"] in TERMINAL_STATUSES
467
+ and (info.get("terminal_at") or now) < ttl_cutoff
468
+ ]
469
+ for jid in expired:
470
+ logger.info(f"Purging TTL-expired job {jid}.")
471
+ del jobs[jid]
472
+
473
+ await _promote_queued()
474
+
475
+
476
+ # ═══════════════════════════════════════════════════════════════════════════════
477
+ # STARTUP / SHUTDOWN
478
+ # ═══════════════════════════════════════════════════════════════════════════════
479
+
480
+ @app.on_event("startup")
481
+ async def startup():
482
+ global _aligner, _worker_ready
483
+ _metrics["start_time"] = datetime.utcnow()
484
+ logger.info(f"Loading {MODEL_ID} ...")
485
+
486
+ loop = asyncio.get_running_loop()
487
+ def _load():
488
+ return Qwen3ForcedAligner.from_pretrained(
489
+ MODEL_ID,
490
+ dtype=torch.float32,
491
+ device_map="cpu",
492
+ )
493
+ _aligner = await loop.run_in_executor(None, _load)
494
+ _worker_ready = True
495
+ logger.info(f"βœ… {MODEL_ID} loaded β€” worker_ready=True")
496
+
497
+ asyncio.create_task(_cleanup_loop())
498
+ logger.info("Qwen3-ForcedAligner Service v1.5 ready.")
499
+
500
+
501
+ # ═══════════════════════════════════════════════════════════════════════════════
502
+ # ENDPOINTS
503
+ # ═══════════════════════════════════════════════════════════════════════════════
504
+
505
+ @app.get("/")
506
+ async def root():
507
+ return {
508
+ "name": "Qwen3-ForcedAligner Service",
509
+ "version": "1.5.0",
510
+ "status": "ready" if _aligner else "loading",
511
+ "model": MODEL_ID,
512
+ "endpoints": {
513
+ "POST /align": "Submit alignment job",
514
+ "GET /job/{id}": "Unified status + result [preferred]",
515
+ "GET /job/{id}?slim=true": "Status only β€” omits word_timestamps (use while polling)",
516
+ "GET /result/{id}": "Legacy result poll [compat]",
517
+ "GET /queue/status": "Queue availability",
518
+ "POST /cancel/{id}": "Explicit job cancellation",
519
+ "GET /health": "Service health + job counts",
520
+ "GET /metrics": "Aggregate metrics",
521
+ },
522
+ }
523
+
524
+
525
+ @app.get("/health")
526
+ async def health():
527
+ """
528
+ Identical field set to MFA /health so the controller can use one
529
+ health-check parser for both backends.
530
+
531
+ worker_alive β€” True when model is loaded and ready to process
532
+ worker_ready β€” True after model finishes loading (same as worker_alive here)
533
+ worker_restarting β€” Always False (no subprocess to restart)
534
+ shm_free_mb β€” Free space in /tmp (Qwen uses /tmp, not /dev/shm)
535
+ shm_ok β€” True when /tmp has β‰₯ 200 MB free
536
+ """
537
+ worker_alive = _aligner is not None
538
+ tmp_free = _tmp_free_mb()
539
+ shm_ok = tmp_free is None or tmp_free >= 200
540
+
541
+ async with jobs_lock:
542
+ counts = {s: 0 for s in [
543
+ JobStatus.QUEUED, JobStatus.RUNNING,
544
+ JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.ABANDONED,
545
+ ]}
546
+ for info in jobs.values():
547
+ counts[info["status"]] = counts.get(info["status"], 0) + 1
548
+
549
+ overall = "healthy"
550
+ if not worker_alive:
551
+ overall = "degraded"
552
+ if not shm_ok:
553
+ overall = "degraded"
554
+
555
+ return {
556
+ "status": overall,
557
+ "worker_alive": worker_alive,
558
+ "worker_ready": _worker_ready,
559
+ "worker_restarting": _worker_restarting,
560
+ "model": MODEL_ID,
561
+ "shm_free_mb": tmp_free,
562
+ "shm_ok": shm_ok,
563
+ "avg_align_s": _avg_align_s(),
564
+ "job_counts": counts,
565
+ "total_jobs": sum(counts.values()),
566
+ }
567
+
568
+
569
+ @app.get("/metrics")
570
+ async def metrics():
571
+ uptime = (
572
+ round((datetime.utcnow() - _metrics["start_time"]).total_seconds(), 0)
573
+ if _metrics["start_time"] else None
574
+ )
575
+ total = _metrics["total_completed"] + _metrics["total_failed"] + _metrics["total_abandoned"]
576
+ success_rate = round(_metrics["total_completed"] / total, 3) if total > 0 else None
577
+
578
+ return {
579
+ "uptime_s": uptime,
580
+ "total_submitted": _metrics["total_submitted"],
581
+ "total_completed": _metrics["total_completed"],
582
+ "total_failed": _metrics["total_failed"],
583
+ "total_abandoned": _metrics["total_abandoned"],
584
+ "total_cancelled": _metrics["total_cancelled"],
585
+ "success_rate": success_rate,
586
+ "worker_restarts": 0, # no subprocess to restart
587
+ "avg_align_s": _avg_align_s(),
588
+ "recent_durations": list(_recent_durations),
589
+ }
590
+
591
+
592
+ @app.get("/queue/status")
593
+ async def queue_status():
594
+ async with jobs_lock:
595
+ running_job = next(
596
+ (jid for jid, info in jobs.items() if info["status"] == JobStatus.RUNNING), None
597
+ )
598
+ queued_job = next(
599
+ (jid for jid, info in jobs.items() if info["status"] == JobStatus.QUEUED), None
600
+ )
601
+ return {
602
+ "can_submit": running_job is None and queued_job is None,
603
+ "slot_available": running_job is None,
604
+ "queue_full": running_job is not None and queued_job is not None,
605
+ "running_job_id": running_job,
606
+ "queued_job_id": queued_job,
607
+ "worker_ready": _worker_ready,
608
+ "estimated_wait_s": _avg_align_s() if running_job else 0,
609
+ }
610
+
611
+
612
+ @app.post("/align")
613
+ async def align_audio(req: AlignRequest):
614
+ """
615
+ Submit an alignment job. All validation runs before the job enters the
616
+ queue β€” invalid requests get an immediate HTTP 400.
617
+
618
+ Response fields (identical to MFA v5.5):
619
+ job_id β€” use for all subsequent calls
620
+ status β€” "running" | "queued"
621
+ queue_position β€” 0 = started immediately, 1 = queued
622
+ poll_url β€” GET here for status / result
623
+ estimated_wait_s β€” rolling average, 0 if running now
624
+ duplicate_warning β€” present if client_id already has an active job
625
+
626
+ Frontend flow:
627
+ queue_position==0: poll for "completed"
628
+ queue_position==1: poll every 2 s until "running".
629
+ 503 QUEUE_FULL: wait retry_after seconds, then retry
630
+ """
631
+ # ── 1. Model check ────────────────────────────────────────────────────────
632
+ if _aligner is None:
633
+ raise HTTPException(503, {
634
+ "error": "Worker unavailable",
635
+ "error_code": "WORKER_DOWN",
636
+ "detail": "Model is still loading. Retry in a few seconds.",
637
+ })
638
+
639
+ # ── 2. Text validation ────────────────────────────────────────────────────
640
+ cleaned_text = _clean_text(req.text)
641
+ if not cleaned_text:
642
+ raise HTTPException(400, {
643
+ "error": "Invalid text",
644
+ "error_code": "TEXT_EMPTY",
645
+ "detail": "Text is empty after normalisation.",
646
+ })
647
+
648
+ # ── 3. Audio validation (CPU work β€” run in executor) ──────────────────────
649
+ loop = asyncio.get_running_loop()
650
+ try:
651
+ wav_normalised, audio_duration = await loop.run_in_executor(
652
+ None, _validate_audio, req.audio_base64
653
+ )
654
+ except HTTPException:
655
+ raise
656
+
657
+ async with jobs_lock:
658
+ running_exists = any(info["status"] == JobStatus.RUNNING for info in jobs.values())
659
+ queued_exists = any(info["status"] == JobStatus.QUEUED for info in jobs.values())
660
+
661
+ # ── 4. Queue full check ───────────────────────────────────────────────
662
+ if running_exists and queued_exists:
663
+ return JSONResponse(
664
+ status_code=503,
665
+ content={
666
+ "error": "Service busy",
667
+ "error_code": "QUEUE_FULL",
668
+ "detail": "One job running, one already queued. Retry after current jobs finish.",
669
+ "retry_after": _avg_align_s(),
670
+ },
671
+ headers={"Retry-After": str(int(_avg_align_s()))},
672
+ )
673
+
674
+ # ── 5. Duplicate client check ─────────────────────────────────────────
675
+ duplicate_warning = None
676
+ if req.client_id:
677
+ existing = next(
678
+ (jid for jid, info in jobs.items()
679
+ if info.get("client_id") == req.client_id
680
+ and info["status"] in (JobStatus.RUNNING, JobStatus.QUEUED)),
681
+ None
682
+ )
683
+ if existing:
684
+ duplicate_warning = {
685
+ "message": "You already have an active job.",
686
+ "existing_job_id": existing,
687
+ "existing_status": jobs[existing]["status"],
688
+ }
689
+
690
+ # ── 6. Create job ─────────────────────────────────────────────────────
691
+ status = JobStatus.QUEUED if running_exists else JobStatus.RUNNING
692
+ job_id = uuid.uuid4().hex[:12]
693
+ queue_position = 1 if status == JobStatus.QUEUED else 0
694
+ now = datetime.utcnow()
695
+
696
+ jobs[job_id] = {
697
+ "request": req,
698
+ "status": status,
699
+ "created_at": now,
700
+ "started_at": now if status == JobStatus.RUNNING else None,
701
+ "terminal_at": None,
702
+ "result": None,
703
+ "error": None,
704
+ "client_id": req.client_id,
705
+ "audio_duration": round(audio_duration, 2),
706
+ "_wav_bytes": wav_normalised, # consumed by _run_alignment, not serialised
707
+ }
708
+
709
+ _metrics["total_submitted"] += 1
710
+ logger.info(
711
+ f"Job {job_id} created β€” status={status}, "
712
+ f"duration={audio_duration:.1f}s, client={req.client_id}"
713
+ )
714
+
715
+ if status == JobStatus.RUNNING:
716
+ asyncio.create_task(_run_alignment(job_id))
717
+
718
+ response = {
719
+ "job_id": job_id,
720
+ "status": status,
721
+ "queue_position": queue_position,
722
+ "poll_url": f"/job/{job_id}",
723
+ "estimated_wait_s": 0 if status == JobStatus.RUNNING else _avg_align_s(),
724
+ "audio_duration_s": round(audio_duration, 2),
725
+ "message": (
726
+ f"Job started. Poll GET /job/{job_id}."
727
+ if status == JobStatus.RUNNING else
728
+ f"Job queued at position 1. Poll GET /job/{job_id} every 2 s."
729
+ ),
730
+ }
731
+ if duplicate_warning:
732
+ response["duplicate_warning"] = duplicate_warning
733
+
734
+ return JSONResponse(response)
735
+
736
+
737
+ @app.get("/job/{job_id}")
738
+ async def get_job(job_id: str, slim: bool = Query(False)):
739
+ """
740
+ Unified status + result endpoint.
741
+
742
+ ?slim=true β€” omits word_timestamps from COMPLETED responses.
743
+ Use during polling; fetch without slim=true once completed.
744
+
745
+ Frontend state machine:
746
+ "queued" β†’ poll every 2 s (slim=true)
747
+ "running" β†’ keep polling (slim=true)
748
+ "completed" β†’ fetch /job/{id} (slim=false) for timestamps
749
+ "failed" β†’ show error
750
+ "abandoned" β†’ resubmit
751
+ """
752
+ async with jobs_lock:
753
+ if job_id not in jobs:
754
+ raise HTTPException(404, detail={
755
+ "error": "Job not found",
756
+ "error_code": "JOB_NOT_FOUND",
757
+ "detail": "Job may have been purged (TTL=5 min) or never existed.",
758
+ })
759
+ return _job_view(job_id, jobs[job_id], slim=slim)
760
+
761
+
762
+ @app.get("/result/{job_id}")
763
+ async def get_result(job_id: str):
764
+ """Legacy endpoint β€” use GET /job/{id} instead."""
765
+ async with jobs_lock:
766
+ if job_id not in jobs:
767
+ raise HTTPException(404, "Job not found")
768
+ return _job_view(job_id, jobs[job_id])
769
+
770
+
771
+ @app.post("/cancel/{job_id}")
772
+ async def cancel_job(job_id: str, body: CancelRequest):
773
+ """
774
+ Explicitly cancel a job.
775
+
776
+ RUNNING: marks abandoned. The alignment thread may still finish but its
777
+ result will be discarded (status != RUNNING guard in the task).
778
+ QUEUED: removes cleanly, no side effects.
779
+ Terminal: idempotent 200.
780
+ """
781
+ async with jobs_lock:
782
+ if job_id not in jobs:
783
+ raise HTTPException(404, detail={
784
+ "error": "Job not found",
785
+ "error_code": "JOB_NOT_FOUND",
786
+ })
787
+
788
+ job = jobs[job_id]
789
+ status = job["status"]
790
+
791
+ stored = job.get("client_id")
792
+ if stored and (body.client_id is None or body.client_id != stored):
793
+ raise HTTPException(403, detail={
794
+ "error": "Client ID mismatch",
795
+ "error_code": "FORBIDDEN",
796
+ "detail": "You are not the owner of this job.",
797
+ })
798
+
799
+ if status in TERMINAL_STATUSES:
800
+ return {
801
+ "cancelled": False,
802
+ "status": status,
803
+ "message": f"Job was already {status} β€” nothing to cancel.",
804
+ }
805
+
806
+ now = datetime.utcnow()
807
+ jobs[job_id]["status"] = JobStatus.ABANDONED
808
+ jobs[job_id]["error"] = "Cancelled by client"
809
+ jobs[job_id]["terminal_at"] = now
810
+ _metrics["total_cancelled"] += 1
811
+
812
+ was_running = status == JobStatus.RUNNING
813
+ logger.info(f"Job {job_id} cancelled ({'RUNNING' if was_running else 'QUEUED'}).")
814
+
815
+ await _promote_queued()
816
+
817
+ return {
818
+ "cancelled": True,
819
+ "job_id": job_id,
820
+ "restarting": False, # no subprocess β€” field kept for contract compat
821
+ "message": "Job cancelled.",
822
+ }