File size: 42,369 Bytes
475d141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""DubLab โ€” short-video dubbing website. Upload video -> dubbed video."""
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import urllib.request
import uuid
from collections import deque
from pathlib import Path
from urllib.parse import urlparse

from flask import Flask, jsonify, render_template, request, send_file

from alerts import quota_alert, quota_ok
from dub import (blur_region, build_dub_track, cleanup_segments, configure_tts,
                 extract_audio, has_audio_stream, has_video_stream,
                 merge_segments, mux, probe_duration, probe_size, set_engine,
                 set_nara_voice, transcribe, valid_nara_voice, write_ass,
                 write_srt)
from gemini import translate_lines
from luna import translate_lines as luna_translate_lines
from gemini_tts import QuotaExhausted

# Gemini TTS key rotation (same 5-key pool style as the SRT site).
# GEMINI_TTS_API_KEYS is comma-separated; falls back to the single GEMINI_API_KEY.
_tts_keys = [k.strip() for k in
             os.environ.get("GEMINI_TTS_API_KEYS",
                            os.environ.get("GEMINI_API_KEY", "")).split(",")
             if k.strip()]
configure_tts(_tts_keys)

BASE = Path(__file__).parent
JOBS = BASE / "jobs"
JOBS.mkdir(exist_ok=True)
# Link-mode blur marking downloads the video here first so the user can
# pick a frame and draw the blur box; from-url then moves the file into
# the job instead of downloading twice. Swept after an hour.
STAGE = BASE / "stage"
STAGE.mkdir(exist_ok=True)
STAGE_TTL = 3600

MAX_DURATION = 600      # seconds (raised 5โ†’10 min 2026-11-07, his order)
MAX_MB = 250
TTL = 24 * 3600        # keep results a day

# ---- abuse protection (public site) ----
MAX_QUEUE = 15          # max jobs waiting in line
UPLOADS_PER_HOUR = 10   # per client IP
_ip_hits = {}
_ip_lock = threading.Lock()

# ---- maintenance mode (TTS outage) ----
# Turn True to pause new dub jobs; the home page shows the maintenance image.
MAINTENANCE = False
MAINTENANCE_MSG = ("๐Ÿ”ง DubLab แ€แ€ฑแ€แ€นแ€ แ€›แ€•แ€บแ€‘แ€ฌแ€ธแ€•แ€ซแ€แ€šแ€บ โ€” Microsoft แ€กแ€žแ€ถแ€‘แ€ฏแ€แ€บ service "
                   "แ€•แ€ปแ€€แ€บแ€”แ€ฑแ€œแ€ญแ€ฏแ€ท แ€•แ€ผแ€„แ€บแ€†แ€„แ€บแ€”แ€ฑแ€•แ€ซแ€แ€šแ€บแ‹ แ€•แ€ผแ€”แ€บแ€€แ€ฑแ€ฌแ€„แ€บแ€ธแ€แ€ฌแ€”แ€ฒแ€ท แ€กแ€€แ€ผแ€ฑแ€ฌแ€„แ€บแ€ธแ€€แ€ผแ€ฌแ€ธแ€™แ€šแ€บ ๐Ÿ™")

# ---- reviews ----
REVIEWS = BASE / "reviews.jsonl"
ADMIN_KEY = os.environ.get("DUBLAB_ADMIN_KEY", "")

# ---- usage counter (admin panel only) ----
# Job dirs are swept after a day, so without this append-only log the
# totals would be lost: one line per job created / done / failed.
USAGE = BASE / "usage.jsonl"
_usage_lock = threading.Lock()

VOICES = {
    "en2mm": {"female": "my-MM-NilarNeural", "male": "my-MM-ThihaNeural"},
    "mm2en": {"female": "en-US-AvaNeural", "male": "en-US-AndrewNeural"},
}
STAGE_LABEL = {
    "queue": "แ€แ€”แ€บแ€ธแ€…แ€ฎแ€”แ€ฑแ€แ€šแ€บ",
    "download": "แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏ แ€†แ€ฝแ€ฒแ€แ€ปแ€”แ€ฑแ€แ€šแ€บ",
    "blur": "แ€™แ€ฐแ€›แ€„แ€บแ€ธ แ€…แ€ฌแ€แ€”แ€บแ€ธ แ€–แ€ฏแ€ถแ€ธแ€”แ€ฑแ€แ€šแ€บ",
    "audio": "แ€กแ€žแ€ถแ€‘แ€ฏแ€แ€บแ€šแ€ฐแ€”แ€ฑแ€แ€šแ€บ",
    "transcribe": "แ€…แ€€แ€ฌแ€ธแ€•แ€ผแ€ฑแ€ฌแ€™แ€พแ€แ€บแ€”แ€ฑแ€แ€šแ€บ",
    "translate": "แ€˜แ€ฌแ€žแ€ฌแ€•แ€ผแ€”แ€บแ€”แ€ฑแ€แ€šแ€บ",
    "voice": "แ€กแ€žแ€ถแ€–แ€ฑแ€ฌแ€บแ€”แ€ฑแ€แ€šแ€บ",
    "mux": "แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€•แ€ฑแ€ซแ€„แ€บแ€ธแ€”แ€ฑแ€แ€šแ€บ",
    "done": "แ€•แ€ผแ€ฎแ€ธแ€•แ€ผแ€ฎ",
}

# ---- video link support (yt-dlp) ----
# Instead of uploading a file, users can paste a link from a social site.
# yt-dlp lives in the same venv as this app.
YTDLP = Path(sys.executable).parent / "yt-dlp"
LINK_HOSTS = ("youtube.com", "youtu.be", "tiktok.com", "instagram.com",
              "facebook.com", "fb.watch", "xiaohongshu.com", "xhslink.com",
              "rednote.com", "twitter.com", "x.com", "vimeo.com",
              "dailymotion.com", "bilibili.com")
# best mp4 up to 720p; the /b fallback covers sites with combined formats only
LINK_FMT = "bv*[height<=720]+ba/b[height<=720]/b"


def _host_ok(host):
    host = (host or "").lower()
    return any(host == h or host.endswith("." + h) for h in LINK_HOSTS)


def _link_log(url, stage, msg):
    """Keep link failures on disk so a bad link can be diagnosed later."""
    try:
        line = f"{time.strftime('%F %T')} [{stage}] {url} :: {msg}\n"
        with open(BASE / "link_check.log", "a") as fh:
            fh.write(line.replace("\n", " ")[:600] + "\n")
    except OSError:
        pass


SHORT_HOSTS = ("xhslink.com", "fb.watch", "vm.tiktok.com", "vt.tiktok.com")
_MOBILE_UA = ("Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) "
              "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
              "Mobile/15E148 Safari/604.1")


def resolve_link(url):
    """Follow a share short-link to its real URL.

    RedNote's xhslink lands on rednote.com, which yt-dlp can't read and
    which bounces anonymous visitors to a login page. The same URL on
    xiaohongshu.com (with its xsec_token kept) works, so the host is
    rewritten after resolving. Other short links pass through unchanged
    apart from the redirect itself.
    """
    host = (urlparse(url).hostname or "").lower()
    if host not in SHORT_HOSTS:
        return url
    req = urllib.request.Request(url, headers={"User-Agent": _MOBILE_UA})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            final = r.geturl()
    except Exception:  # noqa: BLE001 - fall back to the short link itself
        return url
    parts = urlparse(final)
    if (parts.hostname or "").lower() in ("rednote.com", "www.rednote.com"):
        final = parts._replace(netloc="www.xiaohongshu.com").geturl()
    return final


def check_link(url):
    """Check a pasted link looks safe to hand to yt-dlp. Returns the url.

    Share buttons often copy a whole sentence with the link inside, so the
    first http(s) URL in the pasted text is what counts. RedNote's
    international domain (rednote.com) is the same site as xiaohongshu.com
    but yt-dlp only knows the .com name, so it is rewritten here.
    """
    text = (url or "").strip()
    m = re.search(r"https?://[^\s\"'<>]+", text)
    url = (m.group(0).rstrip(").,๏ผŒใ€‚") if m else "")
    if len(url) > 2000 or not url:
        raise ValueError("link แ€™แ€พแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ โ€” http/https link แ€•แ€ฒ แ€‘แ€Šแ€ทแ€บแ€•แ€ซ")
    parts = urlparse(url)
    host = (parts.hostname or "").lower()
    if host in ("rednote.com", "www.rednote.com"):
        url = parts._replace(netloc="www.xiaohongshu.com").geturl()
        host = "www.xiaohongshu.com"
    if not _host_ok(host):
        raise ValueError("แ€’แ€ฎ site แ€€ link แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ โ€” YouTube / TikTok / RedNote / "
                         "Instagram / Facebook link แ€•แ€ฒ แ€›แ€แ€šแ€บ")
    url = resolve_link(url)
    if not _host_ok(urlparse(url).hostname):
        raise ValueError("แ€’แ€ฎ site แ€€ link แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ โ€” YouTube / TikTok / RedNote / "
                         "Instagram / Facebook link แ€•แ€ฒ แ€›แ€แ€šแ€บ")
    return url


def link_err(stderr):
    """Turn yt-dlp errors into short Burmese messages."""
    s = (stderr or "").lower()
    if "xiaohongshu" in s or "rednote" in s:
        return ("RedNote link แ€€แ€ญแ€ฏ server แ€€ แ€–แ€ฝแ€„แ€ทแ€บแ€™แ€›แ€˜แ€ฐแ€ธ โ€” app แ€‘แ€ฒแ€€ Share โ†’ "
                "Copy link แ€”แ€ฒแ€ท แ€›แ€แ€ฒแ€ท link แ€€แ€ญแ€ฏ แ€กแ€•แ€ผแ€Šแ€ทแ€บแ€กแ€…แ€ฏแ€ถ แ€•แ€ผแ€”แ€บ paste แ€œแ€ฏแ€•แ€บแ€€แ€ผแ€Šแ€ทแ€บแ€•แ€ซ")
    if ("private" in s or "login" in s or "cookies" in s or "sign in" in s
            or "log in" in s):
        return ("แ€’แ€ฎ video แ€€ private / login แ€œแ€ญแ€ฏแ€แ€šแ€บ โ€” video file แ€€แ€ญแ€ฏ "
                "แ€แ€ญแ€ฏแ€€แ€บแ€›แ€ญแ€ฏแ€€แ€บ แ€แ€„แ€บแ€•แ€ฑแ€ธแ€•แ€ซ")
    if "no video" in s:
        return "แ€’แ€ฎ link แ€™แ€พแ€ฌ video แ€™แ€แ€ฝแ€ฑแ€ทแ€˜แ€ฐแ€ธ"
    return "link แ€€ video แ€€แ€ญแ€ฏ แ€–แ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ โ€” link แ€™แ€พแ€”แ€บแ€›แ€ฒแ€ทแ€œแ€ฌแ€ธ แ€…แ€…แ€บแ€•แ€ผแ€ฎแ€ธ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"


def ytdlp_info(url):
    """Fetch link metadata with yt-dlp (no download)."""
    p = subprocess.run([str(YTDLP), "--no-playlist", "--no-warnings",
                        "--impersonate", "chrome", "-J", url],
                       capture_output=True, text=True, timeout=60)
    if p.returncode != 0:
        _link_log(url, "info", p.stderr.strip()[-300:])
        raise ValueError(link_err(p.stderr))
    try:
        return json.loads(p.stdout)
    except ValueError:
        raise ValueError("video แ€กแ€แ€ปแ€€แ€บแ€กแ€œแ€€แ€บ แ€–แ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ")


def fetch_link_info(url):
    info = ytdlp_info(url)
    if info.get("is_live"):
        raise ValueError("live video แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ")
    dur = info.get("duration") or 0
    if dur and dur > MAX_DURATION:
        raise ValueError("แแ€ แ€™แ€ญแ€”แ€…แ€บแ€‘แ€€แ€บ แ€›แ€พแ€Šแ€บแ€แ€ฒแ€ท แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏ แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ")
    return {"title": (info.get("title") or "")[:120],
            "duration": int(dur) if dur else None,
            "thumbnail": info.get("thumbnail") or "",
            "site": info.get("extractor_key") or info.get("extractor") or ""}


def download_link(url, d):
    """Download a pasted link into job dir d as input.<ext>. Returns ext."""
    p = subprocess.run([str(YTDLP), "--no-playlist", "--no-warnings",
                        "--impersonate", "chrome", "-f", LINK_FMT,
                        "--merge-output-format", "mp4",
                        "--max-filesize", f"{MAX_MB}M",
                        "--socket-timeout", "20", "--retries", "3",
                        "-o", str(d / "input.%(ext)s"), url],
                       capture_output=True, text=True, timeout=600)
    got = [f for f in d.glob("input.*")
           if f.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".m4v")]
    if p.returncode != 0 or not got:
        for f in got:  # drop partials from a failed download
            f.unlink(missing_ok=True)
        _link_log(url, "download", p.stderr.strip()[-300:])
        raise ValueError(link_err(p.stderr))
    return got[0].suffix.lower()


app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = MAX_MB * 1024 * 1024

jobs = {}
queue = []
lock = threading.Condition()


def jlog(job, msg):
    """Append a timestamped line to the job's live log file."""
    line = f"[{time.strftime('%H:%M:%S')}] {msg}\n"
    try:
        with open(job["dir"] / "job.log", "a") as fh:
            fh.write(line)
    except OSError:
        pass


def _is_quota(e):
    """True when a job died because a Gemini key ran out of quota."""
    if isinstance(e, QuotaExhausted):
        return True
    s = str(e).lower()
    return "resource_exhausted" in s or "quota" in s or "429" in s


def clean_err(e):
    """User-facing error text โ€” never leak server paths."""
    s = str(e)
    if ("speech.platform.bing.com" in s or "WSServerHandshakeError" in s
            or "Invalid response status" in s):
        return ("แ€กแ€žแ€ถแ€‘แ€ฏแ€แ€บแ€แ€ฒแ€ท service (Microsoft) แ€แ€ฑแ€แ€นแ€ แ€•แ€ปแ€€แ€บแ€”แ€ฑแ€แ€šแ€บ โ€” "
                "แ€•แ€ผแ€”แ€บแ€€แ€ฑแ€ฌแ€„แ€บแ€ธแ€กแ€ฑแ€ฌแ€„แ€บ แ€•แ€ผแ€„แ€บแ€”แ€ฑแ€•แ€ซแ€แ€šแ€บแ‹ แ€แ€แ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ ๐Ÿ™")
    return s.replace(str(BASE), "[app]").replace(str(JOBS), "[jobs]")[:300]


def _client_ip():
    # nginx on this box sets X-Real-IP. X-Forwarded-For alone is not
    # reliable here: Waitress strips it unless the proxy is trusted,
    # which left every logged IP as 127.0.0.1 until 2026-11-08.
    real = request.headers.get("X-Real-IP", "").strip()
    if real:
        return real
    fwd = request.headers.get("X-Forwarded-For", "")
    return (fwd.split(",")[0].strip() or request.remote_addr or "?")


def _usage(event, **kw):
    """Append one usage event for the admin panel counter."""
    try:
        rec = {"ts": time.time(), "event": event, **kw}
        with _usage_lock:
            with open(USAGE, "a", encoding="utf-8") as fh:
                fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
    except OSError:
        pass  # counting must never break a job


def _rate_ok(ip):
    now = time.time()
    with _ip_lock:
        dq = _ip_hits.get(ip)
        if dq is None:
            dq = _ip_hits[ip] = deque()
        while dq and now - dq[0] > 3600:
            dq.popleft()
        if len(dq) >= UPLOADS_PER_HOUR:
            return False
        dq.append(now)
        if len(_ip_hits) > 5000:  # don't let the table grow forever
            _ip_hits.clear()
        return True


# drop leftover job dirs from before a restart
for _old in JOBS.iterdir():
    try:
        if _old.is_dir() and time.time() - _old.stat().st_mtime > TTL:
            shutil.rmtree(_old, ignore_errors=True)
    except OSError:
        pass


def sweep_old():
    now = time.time()
    for jid, job in list(jobs.items()):
        if now - job["created"] > TTL and job["status"] in ("done", "failed"):
            shutil.rmtree(job["dir"], ignore_errors=True)
            jobs.pop(jid, None)
    for sdir in STAGE.iterdir():
        try:
            if sdir.is_dir() and now - sdir.stat().st_mtime > STAGE_TTL:
                shutil.rmtree(sdir, ignore_errors=True)
        except OSError:
            pass


def _parse_box(raw):
    """'x,y,w,h' blur box as 0..1 fractions of the frame -> tuple or None."""
    try:
        parts = [float(v) for v in str(raw or "").split(",")]
    except ValueError:
        return None
    if len(parts) != 4:
        return None
    x, y, w, h = parts
    if w < 0.02 or h < 0.02:
        return None
    x = min(max(x, 0.0), 0.98)
    y = min(max(y, 0.0), 0.98)
    return (x, y, min(w, 1.0 - x), min(h, 1.0 - y))


def _sub_opts(get):
    """Subtitle choices shared by the upload form and the JSON link API."""
    subs = str(get("subs") or "") in ("1", "on", "true")
    bg = str(get("sub_bg") or "box")
    return subs, (bg if bg in ("box", "none") else "box")


def process_job(jid):
    job = jobs[jid]
    d = job["dir"]
    try:
        api_key = os.environ.get("GEMINI_API_KEY")
        if not api_key:
            raise RuntimeError("server config missing (GEMINI_API_KEY)")
        direction, voice_name = job["direction"], VOICES[job["direction"]][job["voice"]]
        lang_hint = "en" if direction == "en2mm" else "my"
        engine = job.get("engine") or "nara"
        set_engine(engine)
        set_nara_voice(job.get("nara_voice"))
        start_msg = (f"job {jid} started ยท {direction} ยท {job['voice']} voice "
                     f"ยท {engine} engine")
        if engine == "nara" and job.get("nara_voice"):
            start_msg += f" ยท {job['nara_voice']}"
        jlog(job, start_msg)
        if job.get("url"):
            job.update(stage="download", pct=2)
            jlog(job, f"downloading link: {job['url'][:100]}")
            job["ext"] = download_link(job["url"], d)
            mb = (d / ("input" + job["ext"])).stat().st_size / 1048576
            jlog(job, f"downloaded ({mb:.1f} MB)")
        src = d / ("input" + job["ext"])
        total = probe_duration(src)
        jlog(job, f"video duration: {total:.1f}s")
        if total > MAX_DURATION:
            raise ValueError("แแ€ แ€™แ€ญแ€”แ€…แ€บแ€‘แ€€แ€บ แ€›แ€พแ€Šแ€บแ€แ€ฒแ€ท แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏ แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ")
        if not has_video_stream(src):
            raise ValueError("แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€–แ€ญแ€ฏแ€„แ€บ แ€™แ€Ÿแ€ฏแ€แ€บแ€˜แ€ฐแ€ธ")
        if not has_audio_stream(src):
            raise ValueError("แ€’แ€ฎแ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€™แ€พแ€ฌ แ€กแ€žแ€ถแ€™แ€•แ€ซแ€˜แ€ฐแ€ธ โ€” แ€กแ€žแ€ถแ€•แ€ซแ€แ€ฒแ€ท แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€™แ€พ dub แ€œแ€ญแ€ฏแ€ทแ€›แ€™แ€šแ€บ")

        if job.get("blur"):
            # Hide the source video's own burned-in subtitles before
            # anything else reads the picture; the box the user drew is
            # stored as frame fractions, so scale it to real pixels here
            job.update(stage="blur", pct=3)
            vw, vh = probe_size(src)
            fx, fy, fw, fh = job["blur"]
            px = (int(fx * vw) // 2 * 2, int(fy * vh) // 2 * 2,
                  max(2, int(fw * vw) // 2 * 2), max(2, int(fh * vh) // 2 * 2))
            jlog(job, f"blurring original subtitle area {px} of {vw}x{vh}โ€ฆ")
            work = d / "work.mp4"
            blur_region(src, work, px)
            src = work

        job.update(stage="audio", pct=4)
        jlog(job, "extracting audioโ€ฆ")
        wav = d / "audio.wav"
        extract_audio(src, wav)

        job.update(stage="transcribe", pct=8)
        jlog(job, "transcribing with whisperโ€ฆ")
        segs = transcribe(wav, lang_hint)
        if not segs:
            raise ValueError("แ€กแ€žแ€ถแ€‘แ€ฒแ€™แ€พแ€ฌ แ€…แ€€แ€ฌแ€ธแ€•แ€ผแ€ฑแ€ฌแ€žแ€ถ แ€™แ€แ€ฝแ€ฑแ€ทแ€˜แ€ฐแ€ธ")
        utter = merge_segments(segs)
        jlog(job, f"transcribed {len(segs)} segments โ†’ {len(utter)} utterances")

        job.update(stage="translate", pct=45)
        # HF Spaces has no OpenCode agent, so Luna is skipped there
        # (DUBLAB_NO_LUNA=1) and Gemini translates directly.
        if os.environ.get("DUBLAB_NO_LUNA"):
            jlog(job, "translating with geminiโ€ฆ")
            texts = translate_lines([u["text"] for u in utter], direction, api_key)
            jlog(job, "translated with gemini")
        else:
            jlog(job, "translating with lunaโ€ฆ")
            try:
                texts = luna_translate_lines([u["text"] for u in utter], direction)
                jlog(job, "translated with luna")
            except Exception as e:  # noqa: BLE001 - Luna down/quota: Gemini next
                jlog(job, f"Luna แ€แ€แ€™แ€›แ€œแ€ญแ€ฏแ€ท ({clean_err(e)}) โ€” Gemini แ€”แ€ฒแ€ท แ€†แ€€แ€บแ€˜แ€ฌแ€žแ€ฌแ€•แ€ผแ€”แ€บแ€แ€šแ€บ")
                try:
                    texts = translate_lines([u["text"] for u in utter], direction, api_key)
                except Exception as e2:  # noqa: BLE001 - Gemini down/quota: local fallback
                    jlog(job, f"Gemini แ€แ€แ€™แ€›แ€œแ€ญแ€ฏแ€ท ({clean_err(e2)}) โ€” NLLB (local) แ€”แ€ฒแ€ท แ€†แ€€แ€บแ€˜แ€ฌแ€žแ€ฌแ€•แ€ผแ€”แ€บแ€แ€šแ€บ")
                    try:
                        from nllb_translate import translate_lines as nllb_translate_lines
                        texts = nllb_translate_lines([u["text"] for u in utter], direction)
                    except Exception:
                        # HF build ships no NLLB model: surface the Gemini
                        # error instead of masking it with a missing-model one.
                        raise e2
                    jlog(job, "translated with NLLB (local)")
        for u, t in zip(utter, texts):
            u["text"] = t or u["text"]
        jlog(job, f"translated {len(texts)} lines")

        job.update(stage="voice", pct=58)
        jlog(job, f"synthesizing {len(utter)} utterances ({voice_name})โ€ฆ")
        def tts_prog(i, n):
            job.update(pct=58 + int(32 * i / max(n, 1)))
            if i % 5 == 0 or i == n:
                jlog(job, f"tts {i}/{n}")
        dub_wav, warp, cues = build_dub_track(utter, voice_name, d, total, tts_prog)
        slowed = [f for (_a, _b, f) in warp if f > 1.001]
        if slowed:
            jlog(job, f"slowed {len(slowed)} scene part(s) in the picture "
                      f"(max {max(slowed):.2f}x) so speech stays natural")

        job.update(stage="mux", pct=93)
        jlog(job, "muxing dubbed audio with videoโ€ฆ")
        ass_path = None
        if job.get("subs"):
            # Cues sit on the output timeline (build_dub_track placed
            # them after stretch/cascade), so the ASS matches the final
            # picture; the .srt twin is offered as a download
            vw, vh = probe_size(src)
            write_ass(cues, d / "subs.ass", vw, vh, job.get("sub_bg") or "box")
            write_srt(cues, d / "subs.srt")
            ass_path = d / "subs.ass"
            jlog(job, f"burning in {len(cues)} subtitle lines "
                      f"(bg={job.get('sub_bg') or 'box'})โ€ฆ")
        mux(src, dub_wav, d / "dubbed.mp4", warp, ass_path)
        try:
            cleanup_segments(d)
        except OSError:
            pass

        job.update(status="done", stage="done", pct=100)
        jlog(job, "done โœ…")
        _usage("done", job_id=jid, ip=job.get("ip", "?"),
               secs=round(time.time() - job["created"]), dur=round(total))
        quota_ok()
    except Exception as e:  # noqa: BLE001 - surfaced to UI
        err = clean_err(e)
        jlog(job, f"FAILED: {type(e).__name__}: {err}")
        _usage("fail", job_id=jid, ip=job.get("ip", "?"), error=err[:80])
        job.update(status="failed", error=err)
        if _is_quota(e):
            where = STAGE_LABEL.get(job["stage"], job["stage"])
            quota_alert(f"{where} (job {jid})", err)


def worker():
    while True:
        with lock:
            while not queue:
                lock.wait()
            jid = queue.pop(0)
        jobs[jid]["status"] = "processing"
        process_job(jid)
        sweep_old()


threading.Thread(target=worker, daemon=True).start()


@app.get("/")
def index():
    return render_template("index.html",
                           maintenance=MAINTENANCE,
                           maintenance_msg=MAINTENANCE_MSG)


@app.get("/health")
def health():
    return {"ok": True}


@app.post("/api/jobs")
def create_job():
    if MAINTENANCE:
        return jsonify(error=MAINTENANCE_MSG), 503
    if len(queue) >= MAX_QUEUE:
        return jsonify(error="แ€œแ€ฐแ€™แ€ปแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ โ€” แ€แ€แ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    if not _rate_ok(_client_ip()):
        return jsonify(error="แ€แ€แ€แ€ แ€แ€„แ€บแ€”แ€ฑแ€แ€šแ€บ โ€” แ แ€”แ€ฌแ€›แ€ฎแ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    f = request.files.get("video")
    direction = request.form.get("direction", "en2mm")
    voice = request.form.get("voice", "female")
    engine = request.form.get("engine", "nara")
    if engine not in ("edge", "gemini", "nara"):
        engine = "nara"
    nara_voice = valid_nara_voice(request.form.get("nara_voice"))
    subs, sub_bg = _sub_opts(request.form.get)
    blur = _parse_box(request.form.get("blur"))
    if not f or not f.filename:
        return jsonify(error="แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€–แ€ญแ€ฏแ€„แ€บ แ€›แ€ฝแ€ฑแ€ธแ€•แ€ฑแ€ธแ€•แ€ซ"), 400
    ext = os.path.splitext(f.filename)[1].lower()
    if ext not in (".mp4", ".mov", ".mkv", ".webm", ".m4v"):
        return jsonify(error="MP4/MOV แ€–แ€ญแ€ฏแ€„แ€บแ€•แ€ฒ แ€œแ€€แ€บแ€แ€ถแ€แ€šแ€บ"), 400
    if direction not in VOICES or voice not in ("female", "male"):
        return jsonify(error="แ€›แ€ฝแ€ฑแ€ธแ€แ€ปแ€šแ€บแ€™แ€พแ€ฏ แ€™แ€พแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ"), 400
    jid = uuid.uuid4().hex[:12]
    d = JOBS / jid
    try:
        d.mkdir(parents=True)
        src = d / ("input" + ext)
        f.save(src)
        # fail fast on bad files โ€” nothing reaches the worker queue
        if probe_duration(src) > MAX_DURATION:
            raise ValueError("แแ€ แ€™แ€ญแ€”แ€…แ€บแ€‘แ€€แ€บ แ€›แ€พแ€Šแ€บแ€แ€ฒแ€ท แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏ แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ")
        if not has_video_stream(src):
            raise ValueError("แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€–แ€ญแ€ฏแ€„แ€บ แ€™แ€Ÿแ€ฏแ€แ€บแ€˜แ€ฐแ€ธ")
    except Exception as e:  # noqa: BLE001
        shutil.rmtree(d, ignore_errors=True)
        if isinstance(e, ValueError):
            return jsonify(error=clean_err(e)), 400
        return jsonify(error="แ€–แ€ญแ€ฏแ€„แ€บแ€…แ€…แ€บแ€›แ€„แ€บแ€ธ แ€กแ€™แ€พแ€ฌแ€ธแ€›แ€พแ€ญแ€แ€šแ€บ"), 500
    jobs[jid] = {"status": "queued", "stage": "queue", "pct": 0, "error": "",
                 "dir": d, "ext": ext, "direction": direction,
                 "voice": voice, "engine": engine, "nara_voice": nara_voice, "created": time.time(),
                 "subs": subs, "sub_bg": sub_bg, "blur": blur,
                 "ip": _client_ip()}
    _usage("job", job_id=jid, ip=jobs[jid]["ip"], kind="file",
           direction=direction, voice=voice, engine=engine)
    fname = re.sub(r"[\r\n]", " ", f.filename or "?")[:80]
    jlog(jobs[jid], f"uploaded {fname} ({src.stat().st_size / 1048576:.1f} MB)")
    with lock:
        queue.append(jid)
        lock.notify()
    return jsonify(job_id=jid)


@app.post("/api/jobs/check-url")
def check_url():
    """Look up a pasted link so the user sees title/duration before dubbing."""
    if MAINTENANCE:
        return jsonify(error=MAINTENANCE_MSG), 503
    data = request.get_json(force=True, silent=True) or {}
    try:
        url = check_link(str(data.get("url") or ""))
        info = fetch_link_info(url)
    except ValueError as e:
        return jsonify(error=str(e)), 400
    except subprocess.TimeoutExpired:
        return jsonify(error="site แ€€ แ€แ€ฏแ€ถแ€ทแ€•แ€ผแ€”แ€บแ€แ€ฌ แ€€แ€ผแ€ฌแ€”แ€ฑแ€แ€šแ€บ โ€” แ€แ€แ€”แ€ฑ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 400
    return jsonify(ok=True, url=url, **info)


def _extract_frames(sdir, sid, src, dur):
    """Five sample frames (720px wide) for the blur-box picker."""
    frames = []
    for i, frac in enumerate((0.08, 0.27, 0.46, 0.65, 0.84)):
        out = sdir / f"frame{i}.jpg"
        p = subprocess.run(
            ["ffmpeg", "-y", "-v", "error", "-ss", f"{dur * frac:.2f}",
             "-i", str(src), "-frames:v", "1",
             "-vf", "scale=720:-2", str(out)],
            capture_output=True, text=True, timeout=60)
        if p.returncode == 0 and out.exists():
            frames.append(f"/api/stage/{sid}/frame{i}.jpg")
    return frames


def _make_preview(sdir, src):
    """Small H.264 copy of the staged input for in-browser preview.

    Safari's <video> cannot play some codecs a phone file may carry
    (AV1 in an .mp4, seen 2026-11-07 โ€” black preview, codec error
    icon), while ffmpeg reads them fine. A 720px H.264/AAC faststart
    copy plays everywhere, so the user can watch and scrub it while
    marking the blur box.
    """
    out = sdir / "preview.mp4"
    p = subprocess.run(
        ["ffmpeg", "-y", "-v", "error", "-i", str(src),
         "-vf", "scale='min(720,iw)':-2",
         "-c:v", "libx264", "-preset", "veryfast", "-crf", "25",
         "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "96k",
         "-movflags", "+faststart", str(out)],
        capture_output=True, text=True, timeout=600)
    if p.returncode != 0 or not out.exists():
        raise ValueError("preview แ€‘แ€ฏแ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ")
    return out


@app.post("/api/jobs/link-frames")
def link_frames():
    """Download a link once and return sample frames for blur marking.

    The download lands in a stage dir keyed by a session id; the client
    draws the blur box over one of the frames, and from-url with the
    same sid reuses this file instead of downloading again.
    """
    if MAINTENANCE:
        return jsonify(error=MAINTENANCE_MSG), 503
    if not _rate_ok(_client_ip()):
        return jsonify(error="แ€แ€แ€แ€ แ€แ€„แ€บแ€”แ€ฑแ€แ€šแ€บ โ€” แ แ€”แ€ฌแ€›แ€ฎแ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    data = request.get_json(force=True, silent=True) or {}
    try:
        url = check_link(str(data.get("url") or ""))
    except ValueError as e:
        return jsonify(error=str(e)), 400
    sid = uuid.uuid4().hex[:12]
    sdir = STAGE / sid
    sdir.mkdir(parents=True)
    try:
        ext = download_link(url, sdir)
        src = sdir / ("input" + ext)
        dur = probe_duration(src)
        if dur > MAX_DURATION:
            raise ValueError("แแ€ แ€™แ€ญแ€”แ€…แ€บแ€‘แ€€แ€บ แ€›แ€พแ€Šแ€บแ€แ€ฒแ€ท แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏ แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ")
        w, h = probe_size(src)
        frames = _extract_frames(sdir, sid, src, dur)
        if not frames:
            raise ValueError("frame แ€‘แ€ฏแ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ โ€” file แ€แ€ญแ€ฏแ€€แ€บแ€›แ€ญแ€ฏแ€€แ€บ แ€แ€„แ€บแ€•แ€ฑแ€ธแ€•แ€ซ")
    except ValueError as e:
        shutil.rmtree(sdir, ignore_errors=True)
        return jsonify(error=str(e)), 400
    except Exception:  # noqa: BLE001
        shutil.rmtree(sdir, ignore_errors=True)
        return jsonify(error="frame แ€‘แ€ฏแ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ โ€” file แ€แ€ญแ€ฏแ€€แ€บแ€›แ€ญแ€ฏแ€€แ€บ แ€แ€„แ€บแ€•แ€ฑแ€ธแ€•แ€ซ"), 400
    return jsonify(sid=sid, w=w, h=h, duration=int(dur), frames=frames)


@app.get("/api/stage/<sid>/frame<int:i>.jpg")
def stage_frame(sid, i):
    if not re.fullmatch(r"[0-9a-f]{12}", sid or "") or not 0 <= i < 5:
        return jsonify(error="not found"), 404
    p = STAGE / sid / f"frame{i}.jpg"
    if not p.exists():
        return jsonify(error="not found"), 404
    return send_file(p)


@app.get("/api/stage/<sid>/preview.mp4")
def stage_preview(sid):
    if not re.fullmatch(r"[0-9a-f]{12}", sid or ""):
        return jsonify(error="not found"), 404
    p = STAGE / sid / "preview.mp4"
    if not p.exists():
        return jsonify(error="not found"), 404
    # conditional=True so Safari gets Range support and can scrub
    return send_file(p, mimetype="video/mp4", conditional=True)


@app.post("/api/jobs/file-frames")
def file_frames():
    """Stage an uploaded file and build a playable preview from it.

    Used when the browser cannot play the picked file itself (e.g. an
    AV1 .mp4 in Safari): the file lands in a stage dir, we return
    sample frames plus an H.264 preview the user can watch/scrub, and
    from-file with the same sid reuses the upload as the job input โ€”
    no second upload.
    """
    if MAINTENANCE:
        return jsonify(error=MAINTENANCE_MSG), 503
    if not _rate_ok(_client_ip()):
        return jsonify(error="แ€แ€แ€แ€ แ€แ€„แ€บแ€”แ€ฑแ€แ€šแ€บ โ€” แ แ€”แ€ฌแ€›แ€ฎแ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    f = request.files.get("video")
    if not f or not f.filename:
        return jsonify(error="แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€–แ€ญแ€ฏแ€„แ€บ แ€›แ€ฝแ€ฑแ€ธแ€•แ€ฑแ€ธแ€•แ€ซ"), 400
    ext = os.path.splitext(f.filename)[1].lower()
    if ext not in (".mp4", ".mov", ".mkv", ".webm", ".m4v"):
        return jsonify(error="MP4/MOV แ€–แ€ญแ€ฏแ€„แ€บแ€•แ€ฒ แ€œแ€€แ€บแ€แ€ถแ€แ€šแ€บ"), 400
    sid = uuid.uuid4().hex[:12]
    sdir = STAGE / sid
    sdir.mkdir(parents=True)
    try:
        src = sdir / ("input" + ext)
        f.save(src)
        dur = probe_duration(src)
        if dur > MAX_DURATION:
            raise ValueError("แแ€ แ€™แ€ญแ€”แ€…แ€บแ€‘แ€€แ€บ แ€›แ€พแ€Šแ€บแ€แ€ฒแ€ท แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏ แ€œแ€€แ€บแ€™แ€แ€ถแ€˜แ€ฐแ€ธ")
        if not has_video_stream(src):
            raise ValueError("แ€—แ€ฎแ€’แ€ฎแ€šแ€ญแ€ฏแ€–แ€ญแ€ฏแ€„แ€บ แ€™แ€Ÿแ€ฏแ€แ€บแ€˜แ€ฐแ€ธ")
        w, h = probe_size(src)
        frames = _extract_frames(sdir, sid, src, dur)
        if not frames:
            raise ValueError("frame แ€‘แ€ฏแ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ")
        _make_preview(sdir, src)
    except ValueError as e:
        shutil.rmtree(sdir, ignore_errors=True)
        return jsonify(error=clean_err(e)), 400
    except Exception:  # noqa: BLE001
        shutil.rmtree(sdir, ignore_errors=True)
        return jsonify(error="preview แ€‘แ€ฏแ€แ€บแ€™แ€›แ€˜แ€ฐแ€ธ"), 400
    return jsonify(sid=sid, w=w, h=h, duration=int(dur), frames=frames,
                   preview=f"/api/stage/{sid}/preview.mp4")


@app.post("/api/jobs/from-file")
def create_job_from_file():
    """Create a job from a file already staged by file-frames."""
    if MAINTENANCE:
        return jsonify(error=MAINTENANCE_MSG), 503
    if len(queue) >= MAX_QUEUE:
        return jsonify(error="แ€œแ€ฐแ€™แ€ปแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ โ€” แ€แ€แ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    if not _rate_ok(_client_ip()):
        return jsonify(error="แ€แ€แ€แ€ แ€แ€„แ€บแ€”แ€ฑแ€แ€šแ€บ โ€” แ แ€”แ€ฌแ€›แ€ฎแ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    data = request.get_json(force=True, silent=True) or {}
    direction = str(data.get("direction") or "en2mm")
    voice = str(data.get("voice") or "female")
    engine = str(data.get("engine") or "nara")
    if engine not in ("edge", "gemini", "nara"):
        engine = "nara"
    nara_voice = valid_nara_voice(data.get("nara_voice"))
    subs, sub_bg = _sub_opts(data.get)
    blur = _parse_box(data.get("blur"))
    if direction not in VOICES or voice not in ("female", "male"):
        return jsonify(error="แ€›แ€ฝแ€ฑแ€ธแ€แ€ปแ€šแ€บแ€™แ€พแ€ฏ แ€™แ€พแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ"), 400
    sid = re.sub(r"[^0-9a-f]", "", str(data.get("sid") or ""))[:12]
    staged = None
    if sid:
        sdir = STAGE / sid
        if sdir.is_dir():
            got = [f for f in sdir.glob("input.*")
                   if f.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".m4v")]
            if got:
                staged = got[0]
    if staged is None:
        return jsonify(error="preview session แ€€แ€ฏแ€”แ€บแ€žแ€ฝแ€ฌแ€ธแ€•แ€ผแ€ฎ โ€” file แ€•แ€ผแ€”แ€บแ€›แ€ฝแ€ฑแ€ธแ€•แ€ฑแ€ธแ€•แ€ซ"), 400
    jid = uuid.uuid4().hex[:12]
    d = JOBS / jid
    d.mkdir(parents=True)
    ext = staged.suffix.lower()
    shutil.move(str(staged), str(d / ("input" + ext)))
    shutil.rmtree(STAGE / sid, ignore_errors=True)
    jobs[jid] = {"status": "queued", "stage": "queue", "pct": 0, "error": "",
                 "dir": d, "ext": ext, "direction": direction,
                 "voice": voice, "engine": engine, "nara_voice": nara_voice, "created": time.time(),
                 "subs": subs, "sub_bg": sub_bg, "blur": blur,
                 "ip": _client_ip()}
    _usage("job", job_id=jid, ip=jobs[jid]["ip"], kind="file",
           direction=direction, voice=voice, engine=engine)
    jlog(jobs[jid], "file job (staged preview session)")
    with lock:
        queue.append(jid)
        lock.notify()
    return jsonify(job_id=jid)


@app.post("/api/jobs/from-url")
def create_job_from_url():
    if MAINTENANCE:
        return jsonify(error=MAINTENANCE_MSG), 503
    if len(queue) >= MAX_QUEUE:
        return jsonify(error="แ€œแ€ฐแ€™แ€ปแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ โ€” แ€แ€แ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    if not _rate_ok(_client_ip()):
        return jsonify(error="แ€แ€แ€แ€ แ€แ€„แ€บแ€”แ€ฑแ€แ€šแ€บ โ€” แ แ€”แ€ฌแ€›แ€ฎแ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    data = request.get_json(force=True, silent=True) or {}
    direction = str(data.get("direction") or "en2mm")
    voice = str(data.get("voice") or "female")
    engine = str(data.get("engine") or "nara")
    if engine not in ("edge", "gemini", "nara"):
        engine = "nara"
    nara_voice = valid_nara_voice(data.get("nara_voice"))
    subs, sub_bg = _sub_opts(data.get)
    blur = _parse_box(data.get("blur"))
    if direction not in VOICES or voice not in ("female", "male"):
        return jsonify(error="แ€›แ€ฝแ€ฑแ€ธแ€แ€ปแ€šแ€บแ€™แ€พแ€ฏ แ€™แ€พแ€ฌแ€ธแ€”แ€ฑแ€แ€šแ€บ"), 400
    # A blur-marking session (link-frames) may already hold the download;
    # if so the job reuses that file instead of downloading a second time
    sid = re.sub(r"[^0-9a-f]", "", str(data.get("sid") or ""))[:12]
    staged = None
    if sid:
        sdir = STAGE / sid
        if sdir.is_dir():
            got = [f for f in sdir.glob("input.*")
                   if f.suffix.lower() in (".mp4", ".mov", ".mkv", ".webm", ".m4v")]
            if got:
                staged = got[0]
    try:
        url = check_link(str(data.get("url") or ""))
        if staged is None:
            # fail fast: bad/private/too-long links never reach the queue
            fetch_link_info(url)
    except ValueError as e:
        return jsonify(error=str(e)), 400
    except subprocess.TimeoutExpired:
        return jsonify(error="site แ€€ แ€แ€ฏแ€ถแ€ทแ€•แ€ผแ€”แ€บแ€แ€ฌ แ€€แ€ผแ€ฌแ€”แ€ฑแ€แ€šแ€บ โ€” แ€แ€แ€”แ€ฑ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 400
    jid = uuid.uuid4().hex[:12]
    d = JOBS / jid
    d.mkdir(parents=True)
    jobs[jid] = {"status": "queued", "stage": "queue", "pct": 0, "error": "",
                 "dir": d, "ext": ".mp4", "direction": direction,
                 "voice": voice, "engine": engine, "nara_voice": nara_voice, "created": time.time(),
                 "subs": subs, "sub_bg": sub_bg, "blur": blur,
                 "ip": _client_ip()}
    _usage("job", job_id=jid, ip=jobs[jid]["ip"], kind="link",
           direction=direction, voice=voice, engine=engine)
    if staged is not None:
        ext = staged.suffix.lower()
        shutil.move(str(staged), str(d / ("input" + ext)))
        jobs[jid]["ext"] = ext
        shutil.rmtree(STAGE / sid, ignore_errors=True)
    else:
        jobs[jid]["url"] = url
    title = re.sub(r"[\r\n]", " ", str(data.get("title") or ""))[:80]
    jlog(jobs[jid], f"link job: {title or url[:80]}")
    with lock:
        queue.append(jid)
        lock.notify()
    return jsonify(job_id=jid)


@app.get("/api/jobs/<jid>")
def job_status(jid):
    job = jobs.get(jid)
    if not job:
        if re.fullmatch(r"[0-9a-f]{12}", jid or "") and (JOBS / jid / "dubbed.mp4").exists():
            return jsonify(status="done", stage="done", pct=100,
                           label=STAGE_LABEL.get("done", "done"), error="",
                           has_srt=(JOBS / jid / "subs.srt").exists())
        return jsonify(error="job แ€™แ€แ€ฝแ€ฑแ€ทแ€˜แ€ฐแ€ธ"), 404
    return jsonify(status=job["status"], stage=job["stage"], pct=job["pct"],
                   label=STAGE_LABEL.get(job["stage"], job["stage"]),
                   error=job["error"], has_srt=bool(job.get("subs")))


@app.get("/api/jobs/<jid>/srt")
def job_srt(jid):
    if not re.fullmatch(r"[0-9a-f]{12}", jid or ""):
        return jsonify(error="not found"), 404
    p = JOBS / jid / "subs.srt"
    if not p.exists():
        return jsonify(error="แ€…แ€ฌแ€แ€”แ€บแ€ธ แ€™แ€›แ€พแ€ญแ€˜แ€ฐแ€ธ"), 404
    return send_file(p, as_attachment=True, download_name="dublab-subs.srt")


@app.get("/api/jobs/<jid>/log")
def job_log(jid):
    job = jobs.get(jid)
    if not job:
        return jsonify(error="job แ€™แ€แ€ฝแ€ฑแ€ทแ€˜แ€ฐแ€ธ"), 404
    p = job["dir"] / "job.log"
    return jsonify(log=p.read_text() if p.exists() else "")


@app.post("/api/reviews")
def add_review():
    if not _rate_ok(_client_ip()):
        return jsonify(error="แ€แ€แ€”แ€ฑแ€™แ€พ แ€•แ€ผแ€”แ€บแ€…แ€™แ€บแ€ธแ€•แ€ซ"), 429
    data = request.get_json(force=True, silent=True) or {}
    try:
        stars = int(data.get("stars", 0))
    except (TypeError, ValueError):
        stars = 0
    msg = re.sub(r"\s+", " ", str(data.get("message") or "")).strip()[:500]
    jid = re.sub(r"[^0-9a-f]", "", str(data.get("job_id") or ""))[:12]
    if not (1 <= stars <= 5) and not msg:
        return jsonify(error="star แ€’แ€ซแ€™แ€พแ€™แ€Ÿแ€ฏแ€แ€บ แ€…แ€ฌแ€แ€…แ€บแ€แ€ฏแ€แ€ฏ แ€•แ€ฑแ€ธแ€•แ€ซ"), 400
    rec = {"id": uuid.uuid4().hex[:8], "ts": time.time(), "ip": _client_ip(),
           "stars": stars if 1 <= stars <= 5 else 0,
           "message": msg, "job_id": jid}
    try:
        with open(REVIEWS, "a", encoding="utf-8") as fh:
            fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
    except OSError:
        return jsonify(error="แ€žแ€ญแ€™แ€บแ€ธแ€™แ€›แ€˜แ€ฐแ€ธ"), 500
    return jsonify(ok=True)


@app.get("/admin/reviews")
def admin_reviews():
    if not ADMIN_KEY or request.args.get("key") != ADMIN_KEY:
        return "not found", 404
    return render_template("admin.html")


def _read_reviews():
    rows = []
    if REVIEWS.exists():
        for line in REVIEWS.read_text(encoding="utf-8").splitlines():
            try:
                rows.append(json.loads(line))
            except ValueError:
                pass
    rows.sort(key=lambda r: r.get("ts", 0), reverse=True)
    return rows


def _admin_ok():
    return bool(ADMIN_KEY) and request.args.get("key") == ADMIN_KEY


def _read_usage():
    rows = []
    if USAGE.exists():
        for line in USAGE.read_text(encoding="utf-8").splitlines():
            try:
                rows.append(json.loads(line))
            except ValueError:
                pass
    rows.sort(key=lambda r: r.get("ts", 0))
    return rows


@app.get("/admin/api/reviews")
def admin_api_reviews():
    if not _admin_ok():
        return jsonify(error="not found"), 404
    rows = _read_reviews()
    dist = {str(i): 0 for i in range(1, 6)}
    total_stars = rated = 0
    for r in rows:
        s = r.get("stars", 0)
        if 1 <= s <= 5:
            dist[str(s)] += 1
            total_stars += s
            rated += 1
    # usage counter: jobs ever created, outcomes, distinct user IPs
    urows = _read_usage()
    now = time.time()
    made = [r for r in urows if r.get("event") == "job"]
    users = {r.get("ip") for r in urows if r.get("ip")}
    users |= {r.get("ip") for r in rows
              if r.get("ip") and r.get("ip") != "127.0.0.1"}
    users.discard(None)
    usage = {
        "jobs": len(made),
        "done": sum(1 for r in urows if r.get("event") == "done"),
        "fail": sum(1 for r in urows if r.get("event") == "fail"),
        "users": len(users),
        "today": sum(1 for r in made if now - r.get("ts", 0) < 86400),
        "week": sum(1 for r in made if now - r.get("ts", 0) < 7 * 86400),
        "recent": [{"ts": r.get("ts", 0), "ip": r.get("ip", "?"),
                    "kind": r.get("kind", ""), "event": r.get("event", ""),
                    "dur": r.get("dur"), "job_id": r.get("job_id", "")}
                   for r in urows[-60:]][::-1]}
    return jsonify(reviews=rows[:300], stats={
        "total": len(rows), "rated": rated,
        "avg": round(total_stars / rated, 1) if rated else 0,
        "dist": dist}, usage=usage)


@app.delete("/admin/api/reviews/<rid>")
def admin_del_review(rid):
    if not _admin_ok():
        return jsonify(error="not found"), 404
    rid = re.sub(r"[^0-9a-f]", "", rid)[:8]
    rows = _read_reviews()
    kept = [r for r in rows if r.get("id") != rid]
    if len(kept) == len(rows):
        return jsonify(error="not found"), 404
    try:
        with open(REVIEWS, "w", encoding="utf-8") as fh:
            for r in kept:
                fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    except OSError:
        return jsonify(error="write failed"), 500
    return jsonify(ok=True)


@app.get("/r/<jid>")
def result(jid):
    job = jobs.get(jid)
    if job and job["status"] == "done":
        f = job["dir"] / "dubbed.mp4"
    elif re.fullmatch(r"[0-9a-f]{12}", jid or "") and (JOBS / jid / "dubbed.mp4").exists():
        f = JOBS / jid / "dubbed.mp4"
    else:
        return jsonify(error="แ€กแ€†แ€„แ€บแ€žแ€„แ€ทแ€บ แ€™แ€–แ€ผแ€…แ€บแ€žแ€ฑแ€ธแ€˜แ€ฐแ€ธ"), 404
    return send_file(f, as_attachment=True,
                     download_name="dublab-dubbed.mp4")