File size: 53,698 Bytes
c94f394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b52518
 
 
 
c94f394
6b52518
 
 
 
 
 
 
c94f394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
"""
Montreal Forced Aligner (MFA) — Word Timestamp Service  v5.5
Changes vs v5.4:

═══════════════════════════════════════════════════════════════════════════════
CORRECTNESS / SAFETY FIXES
═══════════════════════════════════════════════════════════════════════════════

1. EARLY AUDIO + TEXT VALIDATION (was: validated inside worker after queuing)
   /align now validates at submission time and returns HTTP 400 immediately:
     · base64 decode failure
     · not a valid WAV file
     · sample width not 16-bit or 32-bit float (unsupported format)
     · mono or stereo only (>2 channels rejected)
     · audio duration < MIN_AUDIO_SECONDS (0.3 s) — MFA fails on very short audio
     · audio duration > MAX_AUDIO_SECONDS (180 s) — cap is alignment latency, not memory
       (HF free tier gives ~7–9 GB /dev/shm; 180 s audio is only ~5.8 MB)
     · text empty after _clean() — all-symbol / all-emoji inputs
   Jobs that would fail are now rejected before entering the queue, so the
   frontend gets a 400 immediately instead of FAILED after a full cycle.

2. /dev/shm FREE SPACE CHECK (was: missing)
   /align rejects with 503 if /dev/shm has less than SHM_MIN_FREE_MB (500 MB)
   free.  HF free tier gives ~7–9 GB /dev/shm; 500 MB guards against genuinely
   stressed RAM (MFA MFCC/Kaldi temp files for 180 s audio can reach 200–500 MB).

3. WORKER LIVENESS CHECK AT SUBMISSION (was: missing)
   /align rejects with 503 if the worker process is not alive AND a restart is
   not already in progress, rather than silently queueing jobs that will never
   be processed.

4. /cancel NO LONGER BLOCKS THE EVENT LOOP (was: _restart_worker called sync)
   _restart_worker() calls terminate()+join() which can block ~3–5 s.
   /cancel now fires it via loop.run_in_executor so the endpoint returns
   immediately and other requests are not stalled.

5. GRACE PERIOD EXTENDED DURING WORKER RESTART (was: fixed 10 s)
   When _promote_queued() is called while a restart is in progress,
   last_heartbeat is extended by HEARTBEAT_GRACE + WORKER_RESTART_GRACE (15 s)
   so the promoted job is not abandoned while the new worker boots.

═══════════════════════════════════════════════════════════════════════════════
PERFORMANCE IMPROVEMENTS
═══════════════════════════════════════════════════════════════════════════════

6. AUDIO PASSED VIA /dev/shm FILE, NOT PICKLED THROUGH MPQueue (was: bytes)
   Previously the full audio bytes were serialised via multiprocessing.Queue
   (pickle).  For a 30-second 16kHz mono WAV that is ~1 MB of pickle overhead
   per job.  Now /align writes the validated WAV directly to a temp file under
   WORK_ROOT and sends only the file *path* through the queue.  The worker
   reads the file, processes it, then deletes the temp file.  IPC payload
   drops from O(audio_size) to O(1).

7. ROLLING AVERAGE FOR estimated_wait_s (was: hardcoded AVG_ALIGN_SECONDS=5)
   A deque of the last ROLLING_AVG_WINDOW (10) completed job durations is
   maintained.  estimated_wait_s in /align, /job, and /queue/status responses
   now reflects the real recent average alignment time.

8. worker_ready FLAG IN /health (was: missing)
   The worker signals warm-up completion by putting ("ready",) on the result
   queue.  /health exposes worker_ready:bool so the frontend can show a
   "warming up" state instead of submitting a job that will be delayed by the
   warm-up overhead.

═══════════════════════════════════════════════════════════════════════════════
FRONTEND / EDGE-CASE IMPROVEMENTS
═══════════════════════════════════════════════════════════════════════════════

9. GET /metrics — monitoring endpoint
   Returns: total_jobs_submitted, total_completed, total_failed, total_abandoned,
   total_cancelled, avg_align_s (rolling), worker_restarts, uptime_s.

10. DUPLICATE CLIENT DETECTION — /align
    If a client_id already has an active (QUEUED or RUNNING) job and submits
    again, the response includes a warning with the existing job_id instead of
    silently creating a second job.  The duplicate is still accepted (the
    caller may have a legitimate reason) but the frontend is informed.

11. GET /job/{id}?slim=true — skip word_timestamps during polling
    During the polling loop the frontend doesn't need the full timestamp array
    on every response — it only needs it once on completion.  ?slim=true omits
    word_timestamps from COMPLETED responses, reducing payload size.

═══════════════════════════════════════════════════════════════════════════════
RETAINED FROM v5.4
═══════════════════════════════════════════════════════════════════════════════
  · Persistent PretrainedAligner (skips 22–30 s setup per job).
  · /dev/shm RAM tmpfs for all MFA I/O.
  · TTL-based job purging (JOB_TTL_SECONDS=300).
  · Worker restart outside jobs_lock.
  · fine_tune=False, _clear_dir() optimisation.
  · Queued jobs don't heartbeat; grace period on promotion.
  · Unified _job_view(), /cancel, /job, /result (legacy).
"""

import os, re, uuid, base64, logging, shutil, io, wave, time
import asyncio
import queue as _stdlib_queue
from collections import deque
from pathlib import Path
from multiprocessing import Process, Queue as MPQueue
from datetime import datetime, timedelta
from typing import Dict, Any, Optional

import numpy as np
from fastapi import FastAPI, HTTPException, Request, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from praatio import textgrid as tgio

from montreal_forced_aligner.alignment import PretrainedAligner

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="MFA Aligner — RAM-Optimised v5.5", version="5.5.0")
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)

MFA_ACOUSTIC   = "english_mfa"
MFA_DICTIONARY = "english_mfa"
MFA_ROOT       = os.environ.get("MFA_ROOT_DIR", "/mfa")
WORK_ROOT      = "/dev/shm/mfa_work"

# ── Timing & size constants ───────────────────────────────────────────────────
CLEANUP_INTERVAL     = 5     # s — cleanup loop tick rate
JOB_TTL_SECONDS      = 300   # s — terminal jobs purged after this
AVG_ALIGN_SECONDS    = 15    # s — fallback before rolling average has data (conservative for 180 s audio)
MIN_AUDIO_SECONDS    = 0.3   # s — MFA fails on very short audio
MAX_AUDIO_SECONDS    = 180.0 # s — cap is latency not memory (180 s audio ≈ 5.8 MB WAV;
                              #     HF Spaces free tier has 14–18 GB RAM so /dev/shm is ~7–9 GB)
SHM_MIN_FREE_MB      = 500   # MB — HF free tier gives ~7–9 GB /dev/shm; MFA MFCC/Kaldi
                              #     temp files for 180 s audio can reach 200–500 MB so we
                              #     guard against genuinely stressed RAM, not theoretical OOM
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

jobs: Dict[str, Dict[str, Any]] = {}
jobs_lock = asyncio.Lock()

_work_queue:   MPQueue = MPQueue()
_result_queue: MPQueue = MPQueue()

# ── Worker state ──────────────────────────────────────────────────────────────
_worker_restarting: bool = False
_worker_ready:      bool = False   # set True when warm-up completes

# ── Metrics (all mutated under jobs_lock or atomically) ───────────────────────
_metrics: Dict[str, Any] = {
    "total_submitted": 0,
    "total_completed": 0,
    "total_failed":    0,
    "total_abandoned": 0,
    "total_cancelled": 0,
    "worker_restarts": 0,
    "start_time":      None,          # set at startup
}
# Rolling deque of (duration_s,) for completed jobs — used for wait estimate
_recent_durations: deque = deque(maxlen=ROLLING_AVG_WINDOW)


# ═══════════════════════════════════════════════════════════════════════════════
# UTILITIES
# ═══════════════════════════════════════════════════════════════════════════════

def _shm_free_mb() -> Optional[float]:
    try:
        st = os.statvfs("/dev/shm")
        return round(st.f_bavail * st.f_frsize / 1_048_576, 1)
    except Exception:
        return None

def _avg_align_s() -> float:
    """Rolling average of recent job durations, or fallback constant."""
    if not _recent_durations:
        return AVG_ALIGN_SECONDS
    return round(sum(_recent_durations) / len(_recent_durations), 1)

def _clear_dir(path: Path) -> None:
    """Unlink dir contents without destroying the inode — faster than rmtree+mkdir."""
    for child in path.iterdir():
        if child.is_dir():
            shutil.rmtree(str(child), ignore_errors=True)
        else:
            child.unlink(missing_ok=True)

def _normalise_wav(wav_bytes: bytes) -> bytes:
    """
    Normalise a WAV to the exact format MFA requires: mono, 16-bit PCM.
    Handles:
      · 32-bit float → int16 conversion
      · stereo → mono downmix (average of channels)
    16-bit mono WAVs are returned unchanged (zero copy).
    Called once at submission time so the worker always gets a clean file.
    """
    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)

    # Fast path: already mono 16-bit
    if sample_width == 2 and n_channels == 1:
        return wav_bytes

    # Decode samples
    if sample_width == 4:
        samples = np.frombuffer(raw, dtype=np.float32)
        samples = np.clip(samples, -1.0, 1.0)
    else:
        # 16-bit PCM — reshape for possible stereo downmix
        samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0

    # Stereo → mono downmix
    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)

    # Back to int16
    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 _clean(text: str) -> str:
    """
    Normalise text for MFA's english_mfa dictionary.

    Rules (each justified by what english_mfa can/cannot pronounce):

    1. Unicode punctuation → ASCII equivalents
       · curly apostrophes (\u2018 \u2019) → straight apostrophe (')
         Keeps contractions intact: "it\u2019s" → "it's" ✓
       · em/en dash (\u2014 \u2013) → space
         "well\u2014known" → "well known" (two words MFA knows)

    2. Digits stripped entirely (not replaced with words)
       english_mfa has no pronunciation for "123", "42", etc.
       OOV digits cause alignment failure or silently skipped words
       depending on MFA version.  Stripping is safer than leaving them in.
       If the caller needs digit-to-word conversion (e.g. "42" → "forty two")
       that should happen upstream before calling /align.

    3. Only ASCII letters, mid-word apostrophes, mid-word hyphens, and spaces
       are kept.  Everything else becomes a space.

    4. Mid-word apostrophe rule:
       Only apostrophes flanked by a letter on BOTH sides are kept.
       · "don't"    → "don't"   ✓  (mid-word)
       · "'hello'"  → "hello"   ✓  (leading/trailing quote apostrophes stripped)
       · "it's"     → "it's"    ✓
       · "rock 'n' roll" → "rock n roll"  (apostrophes not mid-word)
       This is applied AFTER the main strip so the regex sees clean input.

    5. Mid-word hyphen rule:
       Only hyphens flanked by a letter on BOTH sides are kept.
       · "well-known" → "well-known"  ✓ (in english_mfa dict)
       · "- item"     → "  item"      (leading hyphen stripped)
       · "item -"     → "item  "      (trailing hyphen stripped)

    6. Newlines → space (single-utterance corpus; MFA does not need them)

    7. Collapse runs of whitespace, strip leading/trailing.

    Returns the cleaned string.  Caller checks for empty result.
    """
    # Step 1 — unicode punctuation normalisation
    text = text.replace("\u2019", "'").replace("\u2018", "'")   # curly apostrophes
    text = text.replace("\u2014", " ").replace("\u2013", " ")   # em/en dash
    text = text.replace("\u2026", " ")                          # ellipsis
    text = text.replace("\u00e9", "e").replace("\u00e8", "e")   # é è → e (common in loanwords)
    text = text.replace("\u00e0", "a").replace("\u00e2", "a")   # à â → a
    text = text.replace("\u00f4", "o").replace("\u00f6", "o")   # ô ö → o
    text = text.replace("\u00fc", "u").replace("\u00fb", "u")   # ü û → u
    text = text.replace("\u00ee", "i").replace("\u00ef", "i")   # î ï → i
    text = text.replace("\u00e7", "s")                          # ç → s (rough but better than OOV)

    # Step 2 — newlines → space
    text = text.replace("\n", " ").replace("\r", " ")

    # Step 3 — strip digits explicitly before the main pass
    text = re.sub(r"[0-9]+", " ", text)

    # Step 4 — keep only ASCII letters, apostrophes, hyphens, spaces
    text = re.sub(r"[^a-zA-Z'\- ]", " ", text)

    # Step 5 — mid-word apostrophe: strip apostrophes NOT flanked by letters
    #   Regex: apostrophe that is NOT preceded by [a-zA-Z] OR not followed by [a-zA-Z]
    text = re.sub(r"(?<![a-zA-Z])'|'(?![a-zA-Z])", " ", text)

    # Step 6 — mid-word hyphen: strip hyphens NOT flanked by letters
    text = re.sub(r"(?<![a-zA-Z])-|-(?![a-zA-Z])", " ", text)

    # Step 7 — collapse whitespace
    text = re.sub(r"\s+", " ", text).strip()

    return text.lower()   # MFA dictionary is lowercase


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.

    Parses the WAV exactly once and normalises in the same pass.
    Catching problems here gives the frontend an immediate 400 instead of
    a FAILED job after the full alignment cycle.
    """
    # 1. Base64 decode
    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.",
        })

    # 2. WAV parse — single open to read all metadata
    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}",
        })

    # 3. Format checks
    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).",
        })

    # 4. Duration checks
    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.",
        })

    # 5. Normalise to mono 16-bit PCM (stereo downmix + format conversion in one pass)
    wav_normalised = _normalise_wav(raw)
    return wav_normalised, duration

def _parse_textgrid(tg_path: Path) -> list:
    tg    = tgio.openTextgrid(str(tg_path), includeEmptyIntervals=False)
    names = tg.tierNames
    tier  = next((n for n in names if "word" in n.lower()), names[0] if names else None)
    if not tier:
        return []
    words = []
    for iv in tg.getTier(tier).entries:
        label = iv.label.strip()
        if not label or label.lower() in {"sp", "sil", "<eps>", "spn"}:
            continue
        words.append({
            "word":  label,
            "start": round(float(iv.start), 3),
            "end":   round(float(iv.end),   3),
        })
    return words

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}.
    slim=True omits word_timestamps from COMPLETED responses (use during polling).
    """
    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":         f"MFA/{MFA_ACOUSTIC}",
            "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,
        })
        # Only include the full payload if not in slim mode
        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


# ═══════════════════════════════════════════════════════════════════════════════
# PERSISTENT WORKER PROCESS
# ═══════════════════════════════════════════════════════════════════════════════

def _worker_main(work_q: MPQueue, result_q: MPQueue, work_root: str):
    """
    ═══════════════════════════════════════════════════════════════════════
    FIX v5.5-HOTFIX: The "Hello World" bug had 4 interlocking causes:

    1. Warm-up and real jobs shared the same corpus directory.
    2. PretrainedAligner.setup() caches corpus/utterance tables in memory.
       Overwriting utt.lab on disk does NOT update the in-memory table.
    3. _clear_dir() only deleted one level; Kaldi MFCC/lattice subdirs
       in TMP_DIR persisted and were reused.
    4. persistent_aligner reuse across jobs carried stale corpus state.

    THE FIX (all 4 addressed):
    ① Warm-up uses a SEPARATE _warmup/ directory, never shared with jobs.
    ② The warm-up aligner is explicitly del'd — its corpus state dies.
    ③ Each job uses shutil.rmtree (full recursive wipe) on OUTPUT and TMP.
    ④ Each job creates a brand-new PretrainedAligner instance (no reuse).
    ═══════════════════════════════════════════════════════════════════════
    """
    import logging as _lm
    import wave as _wave
    _lm.basicConfig(level=_lm.INFO)
    log = _lm.getLogger("mfa_worker")

    os.makedirs(work_root, exist_ok=True)

    # ── Job corpus paths (ONLY used for real jobs, never warm-up) ──────────
    CORPUS_ROOT = Path(work_root) / "_corpus"
    SPEAKER_DIR = CORPUS_ROOT / "corpus" / "speaker1"
    OUTPUT_DIR  = CORPUS_ROOT / "output"
    TMP_DIR     = CORPUS_ROOT / "tmp"
    WAV_PATH    = SPEAKER_DIR / "utt.wav"
    LAB_PATH    = SPEAKER_DIR / "utt.lab"
    for d in [SPEAKER_DIR, OUTPUT_DIR, TMP_DIR]:
        d.mkdir(parents=True, exist_ok=True)

    # ── Warm-up: ISOLATED directory + aligner, discarded after ─────────────
    # Uses _warmup/ which is NEVER touched by real jobs.
    # The warmup_aligner instance is del'd so its corpus tables are freed.
    log.info("Worker: starting warm-up (isolated — will not affect real jobs)...")
    try:
        WARMUP_ROOT    = Path(work_root) / "_warmup"
        WARMUP_SPEAKER = WARMUP_ROOT / "corpus" / "speaker1"
        WARMUP_OUT     = WARMUP_ROOT / "output"
        WARMUP_TMP     = WARMUP_ROOT / "tmp"
        for d in [WARMUP_SPEAKER, WARMUP_OUT, WARMUP_TMP]:
            d.mkdir(parents=True, exist_ok=True)

        # Write 0.5s silence + "hello world" text into the WARMUP corpus
        silent = np.zeros(8000, dtype=np.int16)
        with _wave.open(str(WARMUP_SPEAKER / "utt.wav"), "wb") as wf:
            wf.setnchannels(1)
            wf.setsampwidth(2)
            wf.setframerate(16000)
            wf.writeframes(silent.tobytes())
        (WARMUP_SPEAKER / "utt.lab").write_text("hello world", encoding="utf-8")

        warmup_aligner = PretrainedAligner(
            corpus_directory    = str(WARMUP_ROOT / "corpus"),
            dictionary_path     = MFA_DICTIONARY,
            acoustic_model_path = MFA_ACOUSTIC,
            output_directory    = str(WARMUP_OUT),
            temporary_directory = str(WARMUP_TMP),
            mfa_root_dir        = MFA_ROOT,
            fine_tune           = False,
            jobs                = 1,
            overwrite           = True,
        )
        warmup_aligner.setup()
        # Intentionally NOT calling warmup_aligner.align() —
        # setup() alone loads the acoustic model into memory (the slow part).
        # align() on silent audio would fail or produce garbage anyway.

        # Discard the warmup aligner — its corpus state ("hello world")
        # must NOT survive into job processing.
        del warmup_aligner

        # Clean up warmup corpus files — not needed anymore
        shutil.rmtree(str(WARMUP_ROOT), ignore_errors=True)

        log.info("Worker: warm-up complete — warmup aligner discarded.")
        result_q.put(("ready",))

    except Exception as e:
        log.warning(f"Worker: warm-up failed (non-fatal, first job will be slower): {e}")
        result_q.put(("ready",))   # always signal ready so service doesn't stall

    # ── Job loop ─────────────────────────────────────────────────────────────
    while True:
        try:
            msg = work_q.get()
            if msg is None:
                log.info("Worker: shutdown signal — exiting.")
                break

            cmd, job_id, payload = msg

            if cmd == "cancel":
                log.info(f"[{job_id}] Cancel received — skipping.")
                continue

            wav_path_str = payload["wav_path"]
            clean_text   = payload["text"]
            wav_path     = Path(wav_path_str)

            log.info(f"[{job_id}] Aligning: '{clean_text[:60]}...' (wav={wav_path_str})")
            t_start = time.monotonic()

            try:
                # ── Step 1: Write fresh corpus files ─────────────────────────
                shutil.copy2(wav_path_str, str(WAV_PATH))
                wav_path.unlink(missing_ok=True)   # clean up IPC temp file
                LAB_PATH.write_text(clean_text, encoding="utf-8")

                # ── Step 2: FULL recursive wipe of output + tmp ──────────────
                # _clear_dir() only removes top-level children.
                # Kaldi creates nested subdirs (split1/speaker1/mfcc/, etc.)
                # that must be fully destroyed so MFA can't reuse stale data.
                shutil.rmtree(str(OUTPUT_DIR), ignore_errors=True)
                shutil.rmtree(str(TMP_DIR),    ignore_errors=True)
                OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
                TMP_DIR.mkdir(parents=True,    exist_ok=True)

                # ── Step 3: Fresh aligner instance for this job ───────────────
                # CRITICAL: Do NOT reuse a PretrainedAligner across jobs.
                # The corpus/utterance tables are cached on the instance object.
                # setup() on a reused instance does NOT re-read corpus files.
                # A new instance + new setup() reads the current utt.lab/utt.wav.
                job_aligner = PretrainedAligner(
                    corpus_directory    = str(CORPUS_ROOT / "corpus"),
                    dictionary_path     = MFA_DICTIONARY,
                    acoustic_model_path = MFA_ACOUSTIC,
                    output_directory    = str(OUTPUT_DIR),
                    temporary_directory = str(TMP_DIR),
                    mfa_root_dir        = MFA_ROOT,
                    fine_tune           = False,
                    jobs                = 1,
                    overwrite           = True,
                )
                job_aligner.setup()           # reads current utt.wav + utt.lab
                job_aligner.align()
                job_aligner.export_files(str(OUTPUT_DIR))
                del job_aligner               # free memory immediately after use

                # ── Step 4: Parse TextGrid output ─────────────────────────────
                tg_files = list(OUTPUT_DIR.rglob("*.TextGrid"))
                if not tg_files:
                    raise RuntimeError("MFA produced no TextGrid output — "
                                       "check that text contains only dictionary words")

                words    = _parse_textgrid(tg_files[0])
                duration = round(time.monotonic() - t_start, 2)
                result_q.put(("success", job_id, words, duration))
                log.info(f"[{job_id}] Done — {len(words)} words in {duration}s.")

            except Exception as e:
                # Clean up IPC temp file if it still exists (e.g. copy failed)
                wav_path.unlink(missing_ok=True)
                log.exception(f"[{job_id}] Alignment error")
                result_q.put(("error", job_id, str(e), 0))
                # No aligner rebuild needed — next job always creates a fresh one

        except Exception as outer:
            log.error(f"Worker outer loop error (continuing): {outer}")


# ═══════════════════════════════════════════════════════════════════════════════
# WORKER LIFECYCLE
# ═══════════════════════════════════════════════════════════════════════════════

_worker_process: Optional[Process] = None

def _start_worker():
    global _worker_process, _worker_ready
    _worker_ready = False
    p = Process(
        target=_worker_main,
        args=(_work_queue, _result_queue, WORK_ROOT),
        daemon=False,   # REQUIRED — MFA spawns Kaldi child processes
    )
    p.start()
    logger.info(f"Worker process started (pid={p.pid})")
    _worker_process = p

def _restart_worker():
    """
    Kill current worker + start fresh.
    MUST be called OUTSIDE jobs_lock — terminate()+join() can block several
    seconds and would stall all concurrent requests if the lock was held.
    Always call via run_in_executor from async context.
    """
    global _worker_process, _worker_restarting, _worker_ready
    _worker_restarting = True
    _worker_ready      = False
    try:
        old = _worker_process
        if old and old.is_alive():
            old.terminate()
            old.join(timeout=3)
            if old.is_alive():
                old.kill()
                old.join(timeout=1)
            logger.info("Old worker terminated.")
        shutil.rmtree(str(Path(WORK_ROOT) / "_corpus"), ignore_errors=True)
        _metrics["worker_restarts"] += 1
        _start_worker()
    finally:
        _worker_restarting = False

@app.on_event("startup")
async def startup():
    _metrics["start_time"] = datetime.utcnow()
    os.makedirs(WORK_ROOT, exist_ok=True)
    logger.info(f"Work dir: {WORK_ROOT}  RAM free: {_shm_free_mb()} MB")
    _start_worker()
    asyncio.create_task(_collect_results())
    asyncio.create_task(_cleanup_loop())
    logger.info("MFA Aligner Service v5.5 ready.")

@app.on_event("shutdown")
async def shutdown():
    global _worker_process
    if _worker_process and _worker_process.is_alive():
        _work_queue.put(None)
        _worker_process.join(timeout=5)
        if _worker_process.is_alive():
            _worker_process.terminate()
            _worker_process.join(timeout=2)
        logger.info("Worker shut down.")


# ═══════════════════════════════════════════════════════════════════════════════
# RESULT COLLECTOR
# ═══════════════════════════════════════════════════════════════════════════════

async def _collect_results():
    """
    Drains result_queue in a non-blocking poll loop.
    Uses get_nowait() + asyncio.sleep — no thread permanently blocked on queue.
    """
    while True:
        try:
            try:
                msg = _result_queue.get_nowait()
            except _stdlib_queue.Empty:
                await asyncio.sleep(0.1)
                continue

            # Worker ready signal (warm-up complete)
            if msg[0] == "ready":
                global _worker_ready
                _worker_ready = True
                logger.info("Worker warm-up complete — worker_ready=True.")
                continue

            status, job_id, data, duration_s = msg

            async with jobs_lock:
                if job_id not in jobs:
                    logger.warning(f"Result for unknown/purged job {job_id} — discarded.")
                    continue
                now = datetime.utcnow()
                if status == "success":
                    jobs[job_id]["status"]     = JobStatus.COMPLETED
                    jobs[job_id]["result"]      = data
                    jobs[job_id]["terminal_at"] = now
                    _metrics["total_completed"] += 1
                    _recent_durations.append(duration_s)
                    logger.info(f"Job {job_id} completed — {len(data)} words in {duration_s}s.")
                else:
                    jobs[job_id]["status"]     = JobStatus.FAILED
                    jobs[job_id]["error"]       = data
                    jobs[job_id]["terminal_at"] = now
                    _metrics["total_failed"] += 1
                    logger.error(f"Job {job_id} failed: {data}")
                await _promote_queued()

        except Exception as e:
            logger.error(f"Result collector error: {e}")
            await asyncio.sleep(0.1)


# ═══════════════════════════════════════════════════════════════════════════════
# CLEANUP LOOP
# ═══════════════════════════════════════════════════════════════════════════════

async def _cleanup_loop():
    while True:
        await asyncio.sleep(CLEANUP_INTERVAL)
        need_restart = False

        async with jobs_lock:
            now              = datetime.utcnow()
            ttl_cutoff       = now - timedelta(seconds=JOB_TTL_SECONDS)

            # 2. Purge terminal jobs past TTL.
            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]

            if expired:
                logger.info(f"Cleanup: purged {len(expired)} jobs. Remaining: {len(jobs)}")

            await _promote_queued()

        # 3. Restart worker OUTSIDE jobs_lock.
        if need_restart:
            logger.info("Restarting worker (outside jobs_lock).")
            loop = asyncio.get_running_loop()
            await loop.run_in_executor(None, _restart_worker)


async def _promote_queued() -> Optional[str]:
    """
    Promote oldest queued job → RUNNING.
    Must be called with jobs_lock held.

    Grace period: last_heartbeat = now + HEARTBEAT_GRACE (+ WORKER_RESTART_GRACE
    if a restart is in progress) so the frontend has time to detect the
    transition and start heartbeating before the cleanup loop fires.
    """
    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.")
    _work_queue.put(("run", jid, info["_ipc_payload"]))
    return jid


# ═══════════════════════════════════════════════════════════════════════════════
# ENDPOINTS
# ═══════════════════════════════════════════════════════════════════════════════

@app.get("/")
async def root():
    return {
        "name":    "MFA Aligner v5.5",
        "version": "5.5.0",
        "status":  "ready",
        "model":   MFA_ACOUSTIC,
        "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":         "Worker health + job counts",
            "GET  /metrics":        "Aggregate metrics",
        },
    }


@app.get("/health")
async def health():
    worker_alive = _worker_process is not None and _worker_process.is_alive()
    shm_free     = _shm_free_mb()
    shm_ok       = shm_free is None or shm_free >= SHM_MIN_FREE_MB

    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 or _worker_restarting:
        overall = "degraded"
    if not shm_ok:
        overall = "degraded"

    return {
        "status":            overall,
        "worker_alive":      worker_alive,
        "worker_ready":      _worker_ready,     # False while warming up
        "worker_restarting": _worker_restarting,
        "model":             MFA_ACOUSTIC,
        "shm_free_mb":       shm_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():
    """Aggregate lifetime metrics — useful for dashboards and debugging."""
    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":   _metrics["worker_restarts"],
        "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 (audio format, duration, text) is performed here before
    the job enters the queue.  Invalid requests get an immediate HTTP 400.

    Response fields:
      job_id             — use for all subsequent calls
      status             — "running" | "queued"
      queue_position     — 0 = started now, 1 = queued behind running job
      poll_url           — GET here for status / result
      estimated_wait_s   — real rolling average, 0 if running
      duplicate_warning  — present if client_id already has an active job

    Frontend flow:
      queue_position==0: poll for "completed"
      queue_position==1: poll /job/{id} every 2 s until status=="running".
      503 QUEUE_FULL:    wait retry_after seconds, then retry
    """
    # ── 1. Text validation ────────────────────────────────────────────────────
    cleaned_text = _clean(req.text)
    if not cleaned_text:
        raise HTTPException(400, {
            "error":      "Invalid text",
            "error_code": "TEXT_EMPTY",
            "detail":     "Text is empty after removing unsupported characters.",
        })

    # ── 2. Audio validation (blocking 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   # re-raise validation errors as-is

    # ── 3. System checks ──────────────────────────────────────────────────────
    shm_free = _shm_free_mb()
    if shm_free is not None and shm_free < SHM_MIN_FREE_MB:
        raise HTTPException(503, {
            "error":      "Insufficient RAM",
            "error_code": "SHM_FULL",
            "detail":     f"Only {shm_free} MB free in /dev/shm (minimum {SHM_MIN_FREE_MB} MB).",
        })

    worker_alive = _worker_process is not None and _worker_process.is_alive()
    if not worker_alive and not _worker_restarting:
        raise HTTPException(503, {
            "error":      "Worker unavailable",
            "error_code": "WORKER_DOWN",
            "detail":     "Alignment worker is not running. Try again in a few seconds.",
        })

    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())

        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()))},
            )

        # ── 4. 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"],
                }

        # ── 5. Write audio to /dev/shm temp file ─────────────────────────────
        # Passes only a file path through MPQueue instead of pickling audio bytes.
        tmp_wav_path = Path(WORK_ROOT) / f"tmp_{uuid.uuid4().hex[:8]}.wav"
        try:
            tmp_wav_path.write_bytes(wav_normalised)
        except Exception as e:
            raise HTTPException(503, {
                "error":      "Storage error",
                "error_code": "SHM_WRITE_ERROR",
                "detail":     f"Could not write audio to /dev/shm: {e}",
            })

        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()

        # IPC payload: path + pre-cleaned text only — no audio bytes
        ipc_payload = {
            "wav_path": str(tmp_wav_path),
            "text":     cleaned_text,
        }

        try:
            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),
                "_ipc_payload":   ipc_payload,
            }

            _metrics["total_submitted"] += 1
            logger.info(f"Job {job_id} created — status={status}, duration={audio_duration:.1f}s, client={req.client_id}")

            if status == JobStatus.RUNNING:
                _work_queue.put(("run", job_id, ipc_payload))

        except Exception:
            # Prevent temp WAV leak if job registration fails unexpectedly
            tmp_wav_path.unlink(missing_ok=True)
            raise

    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 this during the polling loop; fetch without slim=true
                  once you see status=="completed" to retrieve the full result.

    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, consider resubmitting
      "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 — kept for backwards compatibility. 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, sends cancel signal to worker, restarts worker
             via run_in_executor (non-blocking — doesn't stall the event loop).
    QUEUED:  removes cleanly from queue, no restart.
    Terminal: idempotent 200.
    """
    need_restart = False

    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

        if status == JobStatus.RUNNING:
            _work_queue.put(("cancel", job_id, None))
            need_restart = True
            logger.info(f"Job {job_id} cancelled (RUNNING) — scheduling worker restart.")
        else:
            # Clean up the temp WAV file if it hasn't been consumed yet
            ipc = job.get("_ipc_payload", {})
            wav_path = ipc.get("wav_path")
            if wav_path:
                Path(wav_path).unlink(missing_ok=True)
            logger.info(f"Job {job_id} cancelled (QUEUED) — removed cleanly.")

        await _promote_queued()

    if need_restart:
        # Non-blocking: run_in_executor so the cancel response returns immediately
        loop = asyncio.get_running_loop()
        asyncio.ensure_future(loop.run_in_executor(None, _restart_worker))

    return {
        "cancelled":    True,
        "job_id":       job_id,
        "restarting":   need_restart,
        "message":      "Job cancelled." + (" Worker restart initiated." if need_restart else ""),
    }