File size: 37,092 Bytes
b3346ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10b1b68
 
 
 
b3346ac
10b1b68
 
 
 
 
 
 
b3346ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f87f70a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
"""
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
# ═══════════════════════════════════════════════════════════════════════════════

@app.on_event("startup")
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
# ═══════════════════════════════════════════════════════════════════════════════

@app.get("/")
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",
        },
    }


@app.get("/health")
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()),
    }


@app.get("/metrics")
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),
    }


@app.get("/queue/status")
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,
        }


@app.post("/align")
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)


@app.get("/job/{job_id}")
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)


@app.get("/result/{job_id}")
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])


@app.post("/cancel/{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.",
    }

@app.post("/benchmark")
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)