File size: 59,180 Bytes
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
 
06347d3
 
 
 
 
 
9fca884
06347d3
 
 
 
9fca884
06347d3
9fca884
06347d3
 
 
 
 
 
 
 
9fca884
 
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
06347d3
 
9fca884
06347d3
 
 
 
 
9fca884
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
06347d3
 
 
 
 
 
9fca884
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1cea2
 
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1cea2
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1cea2
06347d3
 
 
 
3d1cea2
06347d3
 
3d1cea2
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1cea2
06347d3
 
3d1cea2
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1cea2
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1cea2
 
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
 
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
06347d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fca884
 
06347d3
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
# ─────────────────────────────────────────────
#  NINA — Neural Information & Narrative Abstraction
#  app.py  |  IRIS v0.80 | Made by Malina
# ─────────────────────────────────────────────
#
#  Precision MULTIMODAL video search + summarization pipeline.
#  Pipeline: video → audio → ASR segments → semantic chunking
#            → bi-encoder (text) ⨉ CLIP (vision) fusion → cross-encoder + entity overlap
#            → merge → confidence-gated precise re-transcribe → streaming LLM synthesis.
#
#  ─────────────────────────────────────────────────────────────────────────────
#  v0.80 — performance & modernisation pass over v0.71
#  ─────────────────────────────────────────────────────────────────────────────
#  Measured on Apple M1 (8 core / 16 GB), 39 s test clip:
#  cold first prompt 58.8 s → ~9 s, warm prompts ~1.5 s → sub-second to first token.
#
#  [P1] HARDWARE ACCELERATION
#       Torch models now auto-target the best device (CUDA → MPS → CPU). On
#       Apple Silicon CLIP runs ~1.8× and the cross-encoder ~1.4× faster on the
#       Metal (MPS) backend. CTranslate2 (Whisper) has no MPS backend, so it
#       stays on CPU but is tuned: int8 + cpu_threads, greedy decoding for the
#       cheap pass, and Silero VAD to skip non-speech.
#
#  [P2] NO MORE DOUBLE TRANSCRIPTION
#       v0.71 transcribed the whole video with `base`, then RE-transcribed every
#       sampled sector with the ~15× slower `large-v3-turbo` — even for a global
#       summary (≈24 s wasted on this clip). v0.80:
#         • GLOBAL summaries use the clean `base` transcript directly (no turbo).
#         • SPECIFIC queries re-transcribe with turbo ONLY on matched regions and
#           ONLY when the base pass was low-confidence (avg_logprob gate). On
#           clean audio turbo never runs; on hard audio it runs exactly where it
#           helps. Per-sector results are cached and persist across prompts.
#
#  [P3] PARALLEL COLD START
#       Audio transcription (CPU) and CLIP frame analysis (MPS) are independent
#       and now run concurrently on first sight of a video, overlapping the two
#       heaviest stages instead of summing them.
#
#  [P4] ZERO-COPY I/O
#       Audio is decoded straight from the container (PyAV) — no ffmpeg wav
#       temp file. Frames are streamed from one ffmpeg rawvideo pipe into NumPy —
#       no per-frame JPEG temp files.
#
#  [P5] PERSISTENT DISK CACHE
#       Transcript, chunk + visual embeddings and precise sectors are persisted
#       under a content fingerprint, so re-opening the same video — even after a
#       restart — skips transcription/chunking/CLIP entirely.
#
#  [P6] STREAMING + UX
#       LLM synthesis streams token-by-token; run() is a generator that shows
#       progress and writes the answer as it is produced.
#
#  [Q]  QUALITY FIXES
#       • Router no longer misreads "what does the video say about X" as a global
#         summary (the bare word "about"/"explain" no longer forces global mode).
#       • The illustrative "[2:30]" timestamp no longer leaks into answers.
#
#  Scoring formula (SPECIFIC/HYBRID mode):
#    audio = 0.6 * sigmoid(cross_encoder_logit) + 0.4 * entity_overlap
#    final = (1 - VISUAL_WEIGHT) * audio + VISUAL_WEIGHT * clip_visual_score
#
#  Entity extraction: regex + simple NP heuristic (no spacy dependency).
#  Works multilingually because it operates on surface forms, not POS tags.
# ─────────────────────────────────────────────

import os
import re
import json
import math
import base64
import hashlib
import hmac
import shutil
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor

import ffmpeg
import gradio as gr
import numpy as np
from PIL import Image
from faster_whisper import WhisperModel
from faster_whisper.audio import decode_audio
from sentence_transformers import SentenceTransformer, CrossEncoder
from huggingface_hub import InferenceClient
import warnings
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")


# ── Config ─────────────────────────────────────────────────────────────────────

WHISPER_FAST            = "base"
WHISPER_PRECISE         = "large-v3-turbo"
SAMPLE_RATE             = 16000
WHISPER_CPU_THREADS     = int(os.getenv("WHISPER_CPU_THREADS", "3"))
                                 # 3 threads × ~3 concurrent jobs ≈ an 8-vCPU Space.
                                 # Override via env. CTranslate2 is CPU-only.

RETRANSCRIBE_MAX        = 12     # per-prompt budget for NEW (uncached) sector transcriptions
PRECISE_LOGPROB_GATE    = -0.55  # only turbo-refine sectors whose base avg_logprob is below this
                                 # (clean audio scores high → turbo is correctly skipped)

CHUNK_SPLIT_THRESHOLD   = 0.45
CHUNK_MIN_DURATION      = 8.0
CHUNK_MAX_DURATION      = 90.0
CHUNK_WINDOW            = 5

BI_ENCODER_TOP_K        = 100
CROSS_ENCODER_TOP_K     = 10
RESULTS_TOP_N           = 6
REGION_MIN_DURATION     = 5.0
MERGE_GAP_SEC           = 6.0

# routing thresholds
BI_SCORE_GLOBAL_FLOOR   = 0.10   # below this → escalate to GLOBAL regardless
BI_SCORE_HYBRID_FLOOR   = 0.28   # below this → HYBRID (pad with neighbours)

# global mode: how many evenly-sampled chunks to retranscribe
GLOBAL_MAX_CHUNKS       = 12     # hard cap to keep latency sane

# ── CLIP / visual config ────────────────────────────────────────────────────────
CLIP_MODEL              = "clip-ViT-B-32"   # OpenAI CLIP ViT-B/32 (via sentence-transformers)
CLIP_MAX_FRAMES         = 96     # cap frames encoded per video (perf)
CLIP_MIN_FPS            = 0.1    # sample at least 1 frame / 10s
CLIP_MAX_FPS            = 0.5    # sample at most 1 frame / 2s
CLIP_FRAME_SIZE         = 224    # square fed to CLIP (matches ViT-B/32 input → no double resize)
VISUAL_WEIGHT           = 0.30   # fusion weight of visual vs audio in final score
VISUAL_TAGS_TOP_K       = 4      # max zero-shot tags surfaced per region
VISUAL_TAG_MIN_SIM      = 0.20   # min CLIP cosine for a tag to count

# vocabulary for zero-shot "what is on screen" tagging
VISUAL_CONCEPTS = [
    "a person talking to the camera", "a group of people", "a presentation with slides",
    "a lecture or classroom", "an interview", "a news broadcast",
    "a screen recording of software", "source code in a text editor",
    "a webpage in a browser", "a chart or graph", "text on screen",
    "a product demonstration", "hands demonstrating something",
    "a cooking or food scene", "a kitchen", "an office", "a laboratory",
    "a factory or machinery", "a construction site", "an outdoor nature landscape",
    "a forest", "mountains", "a beach or ocean", "a city street",
    "buildings and architecture", "a car or vehicle driving", "an airplane", "a train",
    "a sports event", "people exercising", "a concert or live music",
    "a video game gameplay", "an animation or cartoon", "a medical or hospital scene",
    "a doctor or patient", "an animal", "a dog", "a cat", "a crowd of people",
    "a map", "a whiteboard with diagrams", "a scientific diagram",
    "a phone or mobile device", "a computer or laptop", "money or finance",
    "a meeting or conference room", "a stage with a speaker",
    "a dark scene at night", "a daytime scene",
]

LLM_MODEL               = "Qwen/Qwen2.5-7B-Instruct"
LLM_MAX_TOKENS          = 600
LLM_TIMEOUT             = 60

CACHE_DIR               = os.path.join(tempfile.gettempdir(), "nina_cache")
DISK_CACHE              = True

DEBUG                   = False


# ── Usage-token gate ──────────────────────────────────────────────────────────────
#  The Space is public, so to enforce the per-account 10/5h limit set on the
#  website, each request must carry a short-lived HMAC token issued by the
#  Cloudflare Worker (app.nnlabs.pl) after it counts the use. Without a valid,
#  unexpired, not-yet-seen token the model refuses to run. Same secret on both
#  sides (NINA_SIGNING_SECRET). If the secret is unset the gate is open (dev).
SIGNING_SECRET = os.getenv("NINA_SIGNING_SECRET", "")
_used_jti      = {}                 # jti -> exp epoch (single-use, replay-proof within a container)
_jti_lock      = threading.Lock()

def _b64url_decode(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def _b64url_encode(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).decode().rstrip("=")

def _verify_usage_token(token: str) -> bool:
    if not SIGNING_SECRET:
        return True                 # not configured → open (local/dev)
    if not token or "." not in token:
        return False
    try:
        msg, sig = token.split(".", 1)
        expected = _b64url_encode(hmac.new(SIGNING_SECRET.encode(), msg.encode(), hashlib.sha256).digest())
        if not hmac.compare_digest(expected, sig):
            return False
        payload = json.loads(_b64url_decode(msg))
        now = int(time.time())
        if int(payload.get("e", 0)) < now:
            return False            # expired
        jti = payload.get("j", "")
        if not jti:
            return False
        with _jti_lock:
            for k in [k for k, e in _used_jti.items() if e < now]:
                _used_jti.pop(k, None)
            if jti in _used_jti:
                return False        # replay
            _used_jti[jti] = int(payload.get("e", now + 120))
        return True
    except Exception:
        return False


# ── Device selection ─────────────────────────────────────────────────────────────
#  CTranslate2 (Whisper) is CPU-only here; the torch models (bi/cross/CLIP) can
#  use Metal (MPS) on Apple Silicon or CUDA on a GPU box.

def _best_torch_device() -> str:
    try:
        import torch
        if torch.cuda.is_available():
            return "cuda"
        if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
            return "mps"
    except Exception:
        pass
    return "cpu"

TORCH_DEVICE = _best_torch_device()


# ── Model load ─────────────────────────────────────────────────────────────────

print(f"[NINA] Torch device: {TORCH_DEVICE}  |  Whisper: CPU int8 (x{WHISPER_CPU_THREADS})")

print("[NINA] Loading Whisper base (faster-whisper)...")
_whisper_fast = WhisperModel(WHISPER_FAST, device="cpu", compute_type="int8",
                             cpu_threads=WHISPER_CPU_THREADS)

# Bi-encoder stays on CPU: it is tiny (sub-100 ms) and MPS transfer overhead is a
# wash, and this keeps the MPS device free for CLIP during the parallel cold start.
print("[NINA] Loading bi-encoder...")
bi_encoder = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")

print(f"[NINA] Loading cross-encoder ({TORCH_DEVICE})...")
cross_encoder = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device=TORCH_DEVICE)


HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
    _token_file = os.path.expanduser("~/.cache/huggingface/token")
    if os.path.exists(_token_file):
        HF_TOKEN = open(_token_file).read().strip()

if HF_TOKEN:
    print(f"[NINA] HF_TOKEN loaded — LLM calls enabled.")
else:
    print("[NINA] HF_TOKEN not set — LLM calls will fail.")

llm_client = InferenceClient(
    token=HF_TOKEN,
    timeout=LLM_TIMEOUT,
)


_whisper_precise      = None
_whisper_precise_lock = threading.Lock()

def get_whisper_precise():
    global _whisper_precise
    with _whisper_precise_lock:
        if _whisper_precise is None:
            print(f"[NINA] Loading Whisper {WHISPER_PRECISE} (faster-whisper)...")
            _whisper_precise = WhisperModel(WHISPER_PRECISE, device="cpu",
                                            compute_type="int8",
                                            cpu_threads=WHISPER_CPU_THREADS)
            print(f"[NINA] Whisper {WHISPER_PRECISE} ready.")
    return _whisper_precise


# ── CLIP (OpenAI ViT-B/32) — lazy, warmed in background ──────────────────────────
_clip_model       = None
_clip_lock        = threading.Lock()
_concept_embs     = None
_concept_lock     = threading.Lock()

def get_clip():
    global _clip_model
    with _clip_lock:
        if _clip_model is None:
            print(f"[NINA] Loading CLIP ({CLIP_MODEL}, {TORCH_DEVICE})...")
            _clip_model = SentenceTransformer(CLIP_MODEL, device=TORCH_DEVICE)
            print(f"[NINA] CLIP ready.")
    return _clip_model

def _get_concept_embs() -> np.ndarray:
    """Encode (once) the zero-shot vocabulary, L2-normalised."""
    global _concept_embs
    with _concept_lock:
        if _concept_embs is None:
            embs = get_clip().encode(VISUAL_CONCEPTS, convert_to_numpy=True,
                                     show_progress_bar=False)
            _concept_embs = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
    return _concept_embs


# Warm the lazy models in the background; CLIP loads on the (free) MPS device,
# turbo loads on CPU. Both finish before they are first needed in most cases.
threading.Thread(target=get_whisper_precise, daemon=True).start()
threading.Thread(target=get_clip, daemon=True).start()
print(f"[NINA] Ready. ( {WHISPER_PRECISE} + CLIP warming up...)")

# ── Transcript + visual cache (in-memory) ─────────────────────────────────────────
# Stores segments, chunks (with embeddings), visual frame embeddings, the decoded
# waveform, and a per-sector precise-transcription cache, keyed by video path.
# Second prompt on same video skips transcription, chunking and CLIP entirely.
_cache: dict = {}   # { video_path: {"segments","chunks","visual","audio","precise","_atime"} }

# Data lifecycle / privacy:
#   • The uploaded video itself is purged by Gradio's own temp cleaner
#     (Interface(delete_cache=...)) — see the bottom of this file — so a file is
#     removed shortly after the user's session goes idle. One upload still serves
#     MANY prompts: the decoded audio + transcript live in RAM (below), so the
#     file is no longer needed once processed.
#   • This in-memory state and the derived on-disk cache are TTL-evicted here so
#     nothing lingers indefinitely.
CACHE_IDLE_TTL = 1200    # drop in-memory video state idle for > 20 min
CACHE_DISK_TTL = 1800    # delete on-disk transcript/embedding cache > 30 min old

def _evict_stale() -> None:
    now = time.time()
    for vp in [k for k, e in _cache.items() if now - e.get("_atime", now) > CACHE_IDLE_TTL]:
        _cache.pop(vp, None)
    try:
        if os.path.isdir(CACHE_DIR):
            for name in os.listdir(CACHE_DIR):
                d = os.path.join(CACHE_DIR, name)
                if os.path.isdir(d) and now - os.path.getmtime(d) > CACHE_DISK_TTL:
                    shutil.rmtree(d, ignore_errors=True)
    except Exception:
        pass


# ── Audio ──────────────────────────────────────────────────────────────────────

def load_audio(media_path: str) -> np.ndarray:
    """Decode any container straight to a float32 mono 16k waveform (PyAV, no temp file)."""
    return decode_audio(media_path, sampling_rate=SAMPLE_RATE)


def media_duration(media_path: str) -> float:
    try:
        info = ffmpeg.probe(media_path)
        return float(info["format"]["duration"])
    except Exception:
        return 0.0


# ── Frames (CLIP input) — streamed from one ffmpeg pipe, no temp files ────────────

def extract_frames(video_path: str, duration: float):
    """
    Sample frames evenly across the video and stream them as raw RGB straight
    into NumPy via a single ffmpeg pipe (no per-frame JPEG temp files).
    fps is chosen so total frames ≈ CLIP_MAX_FRAMES (bounded by MIN/MAX fps).
    Returns (frames_rgb, times) where frames_rgb is (N, S, S, 3) uint8.
    """
    fps = CLIP_MAX_FPS
    if duration and duration > 0:
        fps = min(CLIP_MAX_FPS, max(CLIP_MIN_FPS, CLIP_MAX_FRAMES / duration))

    S = CLIP_FRAME_SIZE
    try:
        out, _ = (
            ffmpeg.input(video_path)
            .filter("fps", fps=fps)
            # cover-then-centre-crop to a square so portrait/landscape both work
            .filter("scale", S, S, force_original_aspect_ratio="increase")
            .filter("crop", S, S)
            .output("pipe:", format="rawvideo", pix_fmt="rgb24")
            .run(capture_stdout=True, capture_stderr=True)
        )
    except ffmpeg.Error:
        return np.zeros((0, S, S, 3), dtype=np.uint8), np.zeros((0,))

    if not out:
        return np.zeros((0, S, S, 3), dtype=np.uint8), np.zeros((0,))

    frames = np.frombuffer(out, np.uint8).reshape(-1, S, S, 3)[:CLIP_MAX_FRAMES]
    times  = np.array([(i + 0.5) / fps for i in range(len(frames))])
    return frames, times


# ── Stage 2: transcription ─────────────────────────────────────────────────────

def transcribe_fast(audio: np.ndarray) -> list[dict]:
    """
    Cheap full-video pass: base model, greedy decoding, Silero VAD.
    Keeps per-segment avg_logprob so we can later refine ONLY weak sectors.
    """
    segments_gen, _ = _whisper_fast.transcribe(
        audio, beam_size=1, vad_filter=True, word_timestamps=False,
    )
    return [
        {
            "text":       seg.text.strip(),
            "start":      round(seg.start, 2),
            "end":        round(seg.end,   2),
            "logprob":    round(float(getattr(seg, "avg_logprob", 0.0) or 0.0), 3),
        }
        for seg in segments_gen
        if seg.text.strip()
    ]


# ── Stage 3a: visual analysis (CLIP) ─────────────────────────────────────────────

def analyze_visual(video_path: str, duration: float) -> dict:
    """
    Sample → encode frames with CLIP. Cached per video.
    Returns {"emb": (N, D) float32, "time": (N,) float}.
    Empty arrays when the video has no usable visual stream (audio-only).
    """
    frames, times = extract_frames(video_path, duration)
    if len(frames) == 0:
        print("[NINA] No video frames (audio-only?) — visual analysis skipped.")
        return {"emb": np.zeros((0, 512), dtype=np.float32), "time": np.zeros((0,))}

    images = [Image.fromarray(f) for f in frames]
    embs = get_clip().encode(images, convert_to_numpy=True,
                             batch_size=32, show_progress_bar=False)

    print(f"[NINA] CLIP encoded {len(images)} frames ({TORCH_DEVICE}).")
    return {"emb": np.asarray(embs, dtype=np.float32), "time": np.asarray(times)}


# ── semantic chunking ─────────────────────────────────────────────────

def semantic_chunk(segments: list[dict]) -> list[dict]:
    if not segments:
        return []
    texts      = [s["text"] for s in segments]
    embeddings = bi_encoder.encode(texts, convert_to_numpy=True, batch_size=64)
    chunks, current, cur_emb = [], [segments[0]], [embeddings[0]]

    for i in range(1, len(segments)):
        chunk_dur   = segments[i]["end"] - current[0]["start"]
        window_mean = np.mean(cur_emb[-CHUNK_WINDOW:], axis=0)
        sim         = max(_cosine(embeddings[i], window_mean),
                          _cosine(embeddings[i], cur_emb[-1]))
        long_enough = (current[-1]["end"] - current[0]["start"]) >= CHUNK_MIN_DURATION

        if (sim < CHUNK_SPLIT_THRESHOLD or chunk_dur >= CHUNK_MAX_DURATION) and long_enough:
            chunks.append(_build_chunk(current, cur_emb))
            current, cur_emb = [segments[i]], [embeddings[i]]
        else:
            current.append(segments[i])
            cur_emb.append(embeddings[i])

    if current:
        chunks.append(_build_chunk(current, cur_emb))

    print(f"[NINA] {len(segments)} segments → {len(chunks)} chunks.")
    return chunks


# ── Entity extraction ──────────────────────────────────────────────────────────

_STOPWORDS = {
    "the","a","an","and","or","but","in","on","at","to","for","of","is","are",
    "was","were","be","been","that","this","it","he","she","they","we","i",
    "w","z","i","że","na","do","się","nie","to","jest","są","by","przez","po",
    "le","la","les","un","une","des","du","et","en","à","de","est","il","elle",
    "ein","eine","der","die","das","und","ist","in","zu","mit","von","dem",
}

def extract_entities(text: str) -> set[str]:
    """
    Extract surface-form entities from text.
    Returns a set of normalised lowercase strings for overlap comparison.
    """
    entities: set[str] = set()

    # 1. quoted phrases — high precision
    for match in re.finditer(r'"([^"]{2,40})"', text):
        entities.add(match.group(1).lower().strip())

    # 2. capitalised multi-word sequences (proper nouns)
    for match in re.finditer(r'\b([A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-záéíóúàâêîôùäëïöüąćęłńóśźż]+(?:\s[A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-zÀ-žąćęłńóśźż]+)*)\b', text):
        token = match.group(1).lower().strip()
        if token not in _STOPWORDS and len(token) > 2:
            entities.add(token)

    # 3. single capitalised tokens (names, brands)
    for token in re.findall(r'\b[A-ZÁÉÍÓÚÀÂÊÎÔÙÄËÏÖÜĄĆĘŁŃÓŚŹŻ][a-zÀ-žąćęłńóśźż]{2,}\b', text):
        t = token.lower()
        if t not in _STOPWORDS:
            entities.add(t)

    # 4. numbers with context
    for match in re.finditer(r'\b([A-Za-z]+[-\s]?\d+[\w]*)\b', text):
        entities.add(match.group(1).lower())

    return entities


def entity_overlap_score(prompt_entities: set[str],
                          chunk_entities: set[str],
                          chunk_text: str = "") -> float:

    if not prompt_entities:
        return 0.0

    chunk_text_lower = chunk_text.lower()
    matched = 0
    for pe in prompt_entities:
        # pass 1: extracted entity overlap
        entity_hit = any(pe in ce or ce in pe for ce in chunk_entities)
        # pass 2: raw text substring (handles lowercase ASR output)
        text_hit   = len(pe) > 3 and pe in chunk_text_lower
        if entity_hit or text_hit:
            matched += 1
    return matched / len(prompt_entities)


def add_entities_to_chunks(chunks: list[dict]) -> list[dict]:
    for chunk in chunks:
        chunk["entities"] = extract_entities(chunk["text"])
    return chunks


# ── Query router ───────────────────────────────────────────────────────────────
#
#  Classifies prompt into one of three modes before retrieval runs.
#
#  GLOBAL  — user wants a summary / overview of the whole video.
#            Retrieval is the wrong tool here because no single chunk is "about"
#            summarization. → skip retrieval, sample chunks evenly, synthesize.
#
#  HYBRID  — user has a topic but signal is weak (bi-score 0.10–0.28).
#            → run retrieval, but pad results with adjacent chunks.
#
#  SPECIFIC — normal focused query, retrieval works well (bi-score > 0.28).
#            → standard pipeline unchanged.
#
#  Router runs in two passes:
#    Pass 1: regex pattern match on prompt text (zero-cost, runs before encoding)
#    Pass 2: bi-encoder score after retrieval (upgrades SPECIFIC → GLOBAL if
#            retrieval actually fails)

# Global ONLY when the user asks for a whole-video overview. Critically, this no
# longer fires on "what does the video say ABOUT <topic>" — a bare "about" or
# "explain" used to force global and swallow specific questions.
_GLOBAL_PATTERNS = re.compile(
    r'\b('
    r'summari[sz]e|summary|overview|recap|tl;?dr|key\s+points?|main\s+points?|'
    r'key\s+takeaways?|main\s+idea|gist|'
    r'what(?:\'s| is| was)\s+(?:this|the|it)\s+(?:video|recording|clip|all\s+)?\s*about|'
    r'what(?:\'s| is| was)\s+(?:this|the)\s+(?:video|recording|clip)|'
    r'describe\s+(?:the|this)\s+(?:video|recording|clip)|'
    r'streszcz\w*|podsumuj\w*|podsumowanie|'
    r'o\s+czym\s+(?:jest|to|opowiada|mówi)|czego\s+dotyczy|'
    r'gł[oó]wn\w+\s+(?:punkt\w*|my[sś]l\w*|tez\w*)|og[oó]ln\w+\s+zarys'
    r')\b',
    re.IGNORECASE
)

def classify_query(prompt: str) -> str:
    """
    Pass 1 router — pattern-based, runs before any encoding.
    Returns "global" or "specific".
    Pass 2 (bi-score based upgrade) happens inside run() after retrieval.
    """
    if _GLOBAL_PATTERNS.search(prompt):
        return "global"
    return "specific"


# ── Stage 4: bi-encoder retrieval (top-100) ───────────────────────────────────

def bi_encode_retrieve(chunks: list[dict], prompt: str) -> tuple[list[dict], float]:
    # chunk embeddings were computed once at chunking time and cached on the
    # chunk dict ("emb"); here we only encode the prompt.
    prompt_emb = bi_encoder.encode([prompt], convert_to_numpy=True)[0]
    scores     = [_cosine(prompt_emb, c["emb"]) for c in chunks]

    top_k   = min(BI_ENCODER_TOP_K, len(chunks))
    top_idx = np.argsort(scores)[::-1][:top_k]

    if DEBUG:
        print(f"[DEBUG] Bi top-3 scores: " +
              ", ".join(f"{scores[i]:.3f}" for i in top_idx[:3]))

    best = scores[top_idx[0]] if len(top_idx) else 0.0
    return (
        [{**chunks[i], "bi_score": round(scores[i], 3)} for i in top_idx],
        best
    )


# ── Stage 4b: visual relevance (CLIP) ─────────────────────────────────────────

def visual_scores(visual: dict, prompt: str) -> tuple[np.ndarray, np.ndarray]:
    """
    Cosine of prompt↔each frame in CLIP space, plus a min-max normalised copy.
    Normalisation makes CLIP sims (typically ~0.2–0.35) comparable to the
    audio score's 0–1 range before fusion. Returns (raw, norm); empty when
    there are no frames.
    """
    embs = visual.get("emb")
    if embs is None or len(embs) == 0:
        if DEBUG:
            print("[DEBUG] Visual: no frames (audio-only) — visual weight = 0.")
        return np.array([]), np.array([])
    q  = get_clip().encode([prompt], convert_to_numpy=True, show_progress_bar=False)[0]
    qn = q / (np.linalg.norm(q) + 1e-9)
    en = embs / (np.linalg.norm(embs, axis=1, keepdims=True) + 1e-9)
    sims = en @ qn
    lo, hi = float(sims.min()), float(sims.max())
    norm = (sims - lo) / (hi - lo + 1e-9)
    if DEBUG:
        times = visual.get("time")
        order = np.argsort(sims)[::-1][:3]
        tops  = ", ".join(f"{fmt_time(times[i])}={sims[i]:.3f}" for i in order)
        print(f"[DEBUG] Visual: {len(sims)} frames; raw sim "
              f"min/mean/max={sims.min():.3f}/{sims.mean():.3f}/{sims.max():.3f}; "
              f"top moments: {tops}")
    return sims, norm


def span_visual_score(times: np.ndarray, norm: np.ndarray,
                      start: float, end: float) -> float:
    """Best (normalised) visual relevance among frames inside [start, end]."""
    if len(times) == 0:
        return 0.0
    mask = (times >= start - 0.5) & (times <= end + 0.5)
    if not mask.any():
        idx = int(np.argmin(np.abs(times - (start + end) / 2)))
        return float(norm[idx])
    return float(norm[mask].max())


def region_visual_tags(visual: dict, start: float, end: float) -> list[str]:
    """Zero-shot CLIP tags describing what is on screen during [start, end]."""
    embs  = visual.get("emb")
    times = visual.get("time")
    if embs is None or len(embs) == 0:
        return []

    mask = (times >= start - 0.5) & (times <= end + 0.5)
    if mask.any():
        sel = embs[mask]
    else:
        idx = int(np.argmin(np.abs(times - (start + end) / 2)))
        sel = embs[idx:idx + 1]

    region_emb = sel.mean(axis=0)
    region_emb = region_emb / (np.linalg.norm(region_emb) + 1e-9)
    sims = _get_concept_embs() @ region_emb

    order = np.argsort(sims)[::-1][:VISUAL_TAGS_TOP_K]
    return [VISUAL_CONCEPTS[i] for i in order if sims[i] >= VISUAL_TAG_MIN_SIM]


def add_visual_tags(regions: list[dict], visual: dict) -> list[dict]:
    for r in regions:
        r["visual_tags"] = region_visual_tags(visual, r["start"], r["end"])
    return regions


# ── Stage 5: cross-encoder rerank + audio/visual fusion (top-100 → top-10) ─────

def rerank_and_score(candidates: list[dict], prompt: str,
                     times: np.ndarray, norm: np.ndarray) -> list[dict]:
    # cross-encoder
    pairs  = [[prompt, c["text"]] for c in candidates]
    logits = cross_encoder.predict(pairs)

    # entity overlap
    prompt_entities = extract_entities(prompt)
    prompt_words = {w.lower() for w in re.findall(r'[\wÀ-ž]{3,}', prompt)
                    if w.lower() not in _STOPWORDS}
    all_prompt_tokens = prompt_entities | prompt_words

    if DEBUG and all_prompt_tokens:
        print(f"[DEBUG] Prompt tokens for entity match: {all_prompt_tokens}")

    vw = VISUAL_WEIGHT if len(norm) else 0.0   # no frames → pure audio

    scored = []
    for candidate, logit in zip(candidates, logits):
        chunk_entities = candidate.get("entities", set())
        chunk_text     = candidate.get("text", "")
        overlap        = entity_overlap_score(all_prompt_tokens, chunk_entities, chunk_text)

        ce_conf      = _sigmoid(float(logit))
        audio_score  = 0.6 * ce_conf + 0.4 * overlap
        visual_score = span_visual_score(times, norm, candidate["start"], candidate["end"])
        final        = (1.0 - vw) * audio_score + vw * visual_score

        scored.append({
            **candidate,
            "ce_logit":       round(float(logit), 3),
            "entity_overlap": round(overlap, 3),
            "visual_score":   round(visual_score, 3),
            "confidence":     round(min(1.0, final), 3),
        })

    # sort by fused multimodal score
    ranked = sorted(scored, key=lambda x: x["confidence"], reverse=True)

    if DEBUG:
        print(f"[DEBUG] Top-3 after reranking (audio+visual):")
        for r in ranked[:3]:
            print(f"  ce_logit={r['ce_logit']:.2f}  "
                  f"bi={r['bi_score']:.3f}  "
                  f"entity={r['entity_overlap']:.3f}  "
                  f"visual={r['visual_score']:.3f}  "
                  f"conf={r['confidence']:.3f}  "
                  f"\"{r['text'][:60]}\"")

    return ranked[:CROSS_ENCODER_TOP_K]


# ── Hybrid padding ─────────────────────────────────────────────────────────────

def pad_with_neighbours(results: list[dict], chunks: list[dict]) -> list[dict]:
    """
    HYBRID mode: for each retrieved chunk, include its immediate neighbours
    from the full chunk list. Helps when the relevant content slightly
    overflows the chunk boundary. Deduplicates by start timestamp.
    """
    result_starts = {r["start"] for r in results}
    padded = list(results)

    for r in results:
        for i, c in enumerate(chunks):
            if abs(c["start"] - r["start"]) < 0.5:   # found matching chunk
                for neighbour_i in [i - 1, i + 1]:
                    if 0 <= neighbour_i < len(chunks):
                        nb = chunks[neighbour_i]
                        if nb["start"] not in result_starts:
                            padded.append({
                                **nb,
                                "bi_score":       0.0,
                                "ce_logit":       -9.0,
                                "entity_overlap": 0.0,
                                "visual_score":   0.0,
                                "confidence":     nb.get("confidence", 0.1),
                            })
                            result_starts.add(nb["start"])
                break

    return sorted(padded, key=lambda x: x["start"])


# ── Global mode: even sampling ────────────────────────────────────────────────

def sample_chunks_for_global(chunks: list[dict], n_target: int) -> list[dict]:
    """
    For global summarization, pick `n_target` chunks evenly distributed across
    the video, so the summary covers the whole thing, not just the beginning.
    """
    n_target = max(3, min(n_target, len(chunks)))
    if n_target >= len(chunks):
        return chunks

    # evenly spaced indices
    indices = [int(i * (len(chunks) - 1) / (n_target - 1)) for i in range(n_target)]
    return [chunks[i] for i in indices]


# ── Stage 6: merge regions ─────────────────────────────────────────────────────

def merge_regions(results: list[dict]) -> list[dict]:
    if not results:
        return []
    sorted_r = sorted(results, key=lambda x: x["start"])
    merged, current = [], sorted_r[0].copy()
    current["_frags"] = [sorted_r[0]]

    for nxt in sorted_r[1:]:
        if nxt["start"] - current["end"] <= MERGE_GAP_SEC:
            current["end"]   = max(current["end"], nxt["end"])
            current["text"] += " " + nxt["text"]
            current["_frags"].append(nxt)
        else:
            merged.append(_finalize_region(current))
            current = nxt.copy()
            current["_frags"] = [nxt]

    merged.append(_finalize_region(current))
    return [r for r in merged if (r["end"] - r["start"]) >= REGION_MIN_DURATION]


def _finalize_region(region: dict) -> dict:
    frags     = region.pop("_frags")
    total_dur = sum(max(f["end"] - f["start"], 0.1) for f in frags)
    w_conf    = sum(f["confidence"] * max(f["end"] - f["start"], 0.1)
                    for f in frags) / total_dur
    duration  = region["end"] - region["start"]
    w_conf   *= min(1.0, duration / 20.0)
    visual    = max((f.get("visual_score", 0.0) for f in frags), default=0.0)
    return {**region, "confidence": round(w_conf, 3), "visual_score": round(visual, 3)}


# ── Stage 7: precise re-transcription (confidence-gated) ──────────────────────

def retranscribe_region(audio: np.ndarray, region: dict) -> str:
    """Slice the in-memory waveform (no per-region ffmpeg) and run precise ASR."""
    s = max(0, int(region["start"] * SAMPLE_RATE))
    e = min(len(audio), int(region["end"] * SAMPLE_RATE))
    clip = audio[s:e]
    if len(clip) < SAMPLE_RATE * 0.2:          # < 0.2s → nothing to gain
        return region.get("text", "")
    model = get_whisper_precise()
    segments_gen, _ = model.transcribe(clip, beam_size=1)
    return " ".join(seg.text.strip() for seg in segments_gen).strip()


def fill_precise(audio: np.ndarray, regions: list[dict], all_chunks: list[dict],
                 precise_cache: dict, budget: int) -> int:
    """
    Ensure every region has `precise_text`. A sector is turbo-refined ONLY when:
      • it is not already cached, AND
      • the base pass for that sector was low-confidence (avg_logprob < gate), AND
      • we are still within `budget` NEW transcriptions this call.
    Clean/high-confidence sectors keep the (already accurate) base text for free,
    so on clean audio the slow turbo model never runs. `precise_cache` persists
    per video, so later prompts reuse earlier work. Returns remaining budget.
    """
    reused = new = skipped = 0
    for region in regions:
        # the chunk sectors this region spans (chunks are non-overlapping)
        comp = [c for c in all_chunks
                if c["start"] < region["end"] - 1e-3 and c["end"] > region["start"] + 1e-3]
        if not comp:
            comp = [region]

        for ch in comp:
            key = round(ch["start"], 2)
            if key in precise_cache:
                reused += 1
                continue
            weak = ch.get("logprob", 0.0) < PRECISE_LOGPROB_GATE
            if not weak:
                skipped += 1                  # base was confident → trust it
                continue
            if budget <= 0:
                continue                      # over budget → fall back to fast text
            print(f"[NINA] Re-transcribing weak sector "
                  f"[{fmt_time(ch['start'])} → {fmt_time(ch['end'])}] "
                  f"(logprob {ch.get('logprob', 0.0):.2f})")
            precise_cache[key] = retranscribe_region(audio, ch)
            if DEBUG:
                snip = precise_cache[key]
                print(f"[DEBUG] Precise sector [{fmt_time(ch['start'])}→{fmt_time(ch['end'])}]: "
                      f"{snip[:200]}{'…' if len(snip) > 200 else ''}")
            new += 1
            budget -= 1

        region["precise_text"] = " ".join(
            (precise_cache.get(round(ch["start"], 2)) or ch.get("text", ""))
            for ch in comp
        ).strip() or region.get("text", "")

    print(f"[NINA] Precise sectors — {new} refined, {reused} cached, {skipped} trusted (base).")
    return budget


# ── Stage 8: synthesis ─────────────────────────────────────────────────────────

# ── Output sizing — inferred from the PROMPT (no slider) ─────────────────────────

_BRIEF_CUES = (
    "brief", "briefly", "short", "shortly", "quick", "quickly", "concise",
    "in a sentence", "one sentence", "one-liner", "tl;dr", "tldr",
    "krótko", "w skrócie", "zwięźle", "jednym zdaniem", "w jednym zdaniu",
)
_DETAIL_CUES = (
    "in detail", "detailed", "in-depth", "in depth", "thorough", "thoroughly",
    "comprehensive", "exhaustive", "everything", "full summary", "elaborate",
    "step by step", "step-by-step", "deep dive", "as much as possible",
    "szczegółowo", "dokładnie", "wyczerpująco", "wszystko", "krok po kroku",
    "dogłębnie", "obszernie",
)
_FACTUAL_START = re.compile(
    r'^\s*(what|who|whom|whose|when|where|which|how many|how much|how long|'
    r'is|are|was|were|does|do|did|can|could|will|would|'
    r'czy|kiedy|kto|kogo|gdzie|ile|jaki|jaka|jakie|który|która|które)\b',
    re.IGNORECASE,
)

def _summary_tier(max_words: int) -> str:
    """Human-readable label for the chosen output length."""
    if max_words <= 60:  return "brief / one-liner"
    if max_words <= 110: return "short"
    if max_words <= 250: return "standard"
    if max_words <= 400: return "detailed"
    return "exhaustive"


def _prompt_to_words(prompt: str) -> int:
    """
    Infer the answer's word budget from the prompt itself (replaces the slider):
      - explicit brevity cues  → ~40 words
      - explicit detail cues   → ~450 words
      - factual wh-/yes-no Q    → ~80 words
      - otherwise scale gently with prompt length (longer ask → longer answer)
    Clamped to [30, 500].
    """
    p = prompt.lower()
    if any(c in p for c in _DETAIL_CUES):
        base, reason = 450, "explicit detail cue"
    elif any(c in p for c in _BRIEF_CUES):
        base, reason = 40, "explicit brevity cue"
    elif _FACTUAL_START.match(p):
        base, reason = 80, "factual question"
    else:
        n_words = len(re.findall(r'\w+', p))
        base, reason = 120 + min(180, n_words * 8), f"length-scaled ({n_words} prompt words)"

    out = int(max(30, min(500, base)))
    if DEBUG:
        print(f"[DEBUG] Summary sizing: {reason} → {out} words [{_summary_tier(out)}]")
    return out


def _words_to_global_chunks(max_words: int) -> int:
    """More requested words → sample more chunks for the global overview."""
    return max(3, min(GLOBAL_MAX_CHUNKS, round(max_words / 40)))


def _fallback_summary(regions: list[dict]) -> str:
    snippets = [
        f"[{fmt_time(r['start'])}] {r.get('precise_text', r['text'])[:200]}"
        for r in regions[:2]
    ]
    return "(LLM unavailable — raw excerpts:)\n" + "\n".join(snippets)


def _build_synth_prompt(regions: list[dict], prompt: str,
                        max_words: int, mode: str) -> str:
    # Each fragment carries BOTH modalities: what is SAID (audio) and what is
    # SHOWN (CLIP visual cues). The LLM is asked to fuse them.
    blocks = []
    for r in regions:
        spoken = (r.get("precise_text", r["text"]) or "").strip()
        tags   = r.get("visual_tags", [])
        block  = (f"[{fmt_time(r['start'])} → {fmt_time(r['end'])}]\n"
                  f"  Spoken (audio): {spoken or '(no speech)'}")
        if tags:
            block += f"\n  On screen (video): {', '.join(tags)}"
        blocks.append(block)
    fragments = "\n\n".join(blocks)

    if mode == "global":
        task_line = "Task: Give a complete overview of what this video is about."
    else:
        task_line = f'Task: Summarize what the video says/shows about "{prompt}".'

    return (
        f"You are analyzing a video. Each fragment below contains what is SPOKEN "
        f"(audio transcript) and what is SHOWN (visual cues detected in the frames).\n"
        f'The user is looking for: "{prompt}"\n\n'
        f"Fragments:\n\n{fragments}\n\n"
        f"{task_line}\n\n"
        f"Output format:\n"
        f"- Combine BOTH the spoken content and the on-screen visuals into one coherent answer\n"
        f"- After each statement, append the timestamp it came from, taken from the "
        f"bracketed start time of the relevant fragment above (use that exact value)\n"
        f"- Maximum {max_words} words total\n"
        f"- IMPORTANT: Write in the same language as the prompt given by the user\n"
        f"- Only use information from the fragments (audio + visual) — do not invent details\n"
        f"- If fragments contain no real information about the topic, say so clearly, "
        f"without further explanation\n"
    )


def llm_synthesize_stream(regions: list[dict], prompt: str,
                          max_words: int = 150, mode: str = "specific"):
    """
    Generator: yields the answer incrementally as the LLM streams tokens.
    On any error, yields a single fallback string.
    """
    if not regions:
        yield "(No relevant regions to summarize.)"
        return

    synth_prompt = _build_synth_prompt(regions, prompt, max_words, mode)

    if DEBUG:
        print(f"[DEBUG] Synthesis [{mode}] — {len(regions)} region(s), "
              f"max_words={max_words} [{_summary_tier(max_words)}].")

    try:
        acc = ""
        stream = llm_client.chat_completion(
            model=LLM_MODEL,
            messages=[{"role": "user", "content": synth_prompt}],
            max_tokens=LLM_MAX_TOKENS,
            temperature=0.3,
            stream=True,
        )
        for ev in stream:
            delta = ev.choices[0].delta.content or ""
            if delta:
                acc += delta
                yield acc.strip()
        if not acc.strip():
            yield _fallback_summary(regions)
    except Exception as e:
        print(f"[NINA] Synthesis error: {e}")
        yield _fallback_summary(regions)


def llm_synthesize(regions: list[dict], prompt: str,
                   max_words: int = 150, mode: str = "specific") -> str:
    """Non-streaming convenience wrapper (kept for API compatibility / testing)."""
    out = ""
    for out in llm_synthesize_stream(regions, prompt, max_words, mode):
        pass
    return out


# ── Helpers ────────────────────────────────────────────────────────────────────

def _build_chunk(segs: list[dict], embs: list[np.ndarray]) -> dict:
    total = sum(max(s["end"] - s["start"], 0.1) for s in segs)
    logp  = sum(s.get("logprob", 0.0) * max(s["end"] - s["start"], 0.1)
                for s in segs) / total          # duration-weighted base confidence
    return {"text":    " ".join(s["text"] for s in segs),
            "start":   segs[0]["start"],
            "end":     segs[-1]["end"],
            "logprob": round(logp, 3),
            "emb":     np.mean(np.stack(embs), axis=0)}   # cached chunk embedding

def _cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))

def _sigmoid(x: float) -> float:
    return 1.0 / (1.0 + math.exp(-float(x)))

def fmt_time(s: float) -> str:
    m = int(s) // 60
    return f"{m}:{s % 60:05.2f}"

def conf_bar(c: float) -> str:
    f = round(c * 10)
    return "█" * f + "░" * (10 - f)


# ── Persistent disk cache ────────────────────────────────────────────────────────
#  Keyed by a content fingerprint (size + head + tail bytes), so the same video
#  re-uploaded to a fresh temp path — or opened after a restart — is recognised
#  and its transcript / embeddings / precise sectors are loaded instead of
#  recomputed. Best-effort: any failure silently falls back to recomputation.

def _fingerprint(path: str) -> str:
    h  = hashlib.sha1()
    st = os.stat(path)
    h.update(str(st.st_size).encode())
    with open(path, "rb") as f:
        h.update(f.read(1 << 20))               # first 1 MB
        if st.st_size > (1 << 20):
            f.seek(-(1 << 20), os.SEEK_END)
            h.update(f.read(1 << 20))            # last 1 MB
    return h.hexdigest()[:16]


def _disk_load(fp: str) -> dict | None:
    if not DISK_CACHE:
        return None
    d = os.path.join(CACHE_DIR, fp)
    try:
        with open(os.path.join(d, "meta.json"), encoding="utf-8") as f:
            meta = json.load(f)
        arr = np.load(os.path.join(d, "emb.npz"))
        chunk_emb = arr["chunk_emb"]
        chunks = []
        for i, c in enumerate(meta["chunks"]):
            chunks.append({
                "text": c["text"], "start": c["start"], "end": c["end"],
                "logprob": c.get("logprob", 0.0),
                "entities": set(c.get("entities", [])),
                "emb": chunk_emb[i],
            })
        visual = {"emb": arr["visual_emb"], "time": arr["visual_time"]}
        print(f"[NINA] Disk cache hit ({fp}) — loaded {len(chunks)} chunks.")
        return {"segments": meta["segments"], "chunks": chunks,
                "visual": visual, "precise": {float(k): v for k, v in meta["precise"].items()}}
    except Exception:
        return None


def _disk_save(fp: str, entry: dict) -> None:
    if not DISK_CACHE:
        return
    d = os.path.join(CACHE_DIR, fp)
    try:
        os.makedirs(d, exist_ok=True)
        chunks = entry["chunks"]
        meta = {
            "segments": entry["segments"],
            "precise":  entry["precise"],
            "chunks": [{"text": c["text"], "start": c["start"], "end": c["end"],
                        "logprob": c.get("logprob", 0.0),
                        "entities": sorted(c.get("entities", []))}
                       for c in chunks],
        }
        chunk_emb = (np.stack([c["emb"] for c in chunks]) if chunks
                     else np.zeros((0, 384), dtype=np.float32))
        with open(os.path.join(d, "meta.json"), "w", encoding="utf-8") as f:
            json.dump(meta, f)
        np.savez(os.path.join(d, "emb.npz"),
                 chunk_emb=chunk_emb,
                 visual_emb=entry["visual"]["emb"],
                 visual_time=entry["visual"]["time"])
    except Exception as e:
        if DEBUG:
            print(f"[DEBUG] disk cache save failed: {e}")


def _disk_update_precise(fp: str, precise: dict) -> None:
    """Persist newly-refined precise sectors without rewriting embeddings."""
    if not DISK_CACHE:
        return
    p = os.path.join(CACHE_DIR, fp, "meta.json")
    try:
        with open(p, encoding="utf-8") as f:
            meta = json.load(f)
        meta["precise"] = precise
        with open(p, "w", encoding="utf-8") as f:
            json.dump(meta, f)
    except Exception:
        pass


# ── Formatter ──────────────────────────────────────────────────────────────────

def format_output(regions: list[dict], prompt: str, summary: str,
                  mode: str = "specific") -> str:
    if not regions:
        return (
            f'    Topic not found in this video.\n\n'
            f'    Prompt : "{prompt}"\n\n'
            f'    No relevant segments found.\n'
            f'    Try a broader or differently worded prompt.'
        )

    mode_tag = {"global": "🌐 global", "hybrid": "⚡ hybrid", "specific": "🎯 specific"}.get(mode, "")
    lines = [f' {len(regions)} region(s) found for: "{prompt}"  [{mode_tag} · audio+video]\n']

    if DEBUG:
        for i, r in enumerate(regions, 1):
            dur  = round(r["end"] - r["start"], 1)
            text = r.get("precise_text", r["text"])
            ent  = r.get("entity_overlap", 0)
            bi   = r.get("bi_score", 0)
            vis  = r.get("visual_score", 0)
            tags = ", ".join(r.get("visual_tags", []))
            lines += [
                f'\n  [{i}]  {fmt_time(r["start"])} → {fmt_time(r["end"])}  ({dur}s)',
                f'       {conf_bar(r["confidence"])}  {r["confidence"]:.0%} '
                f'(embed {bi:.0%} · entity {ent:.0%} · visual {vis:.0%})',
                f'       👁  {tags}' if tags else '       👁  (no visual tags)',
                f'       "{text[:220]}{"…" if len(text) > 220 else ""}"',
            ]

    lines += [
        f'  🧠  Based on uploaded video (audio + video):  —  "{prompt}"',
        summary,
        f'\n  Sources: ' + ',  '.join(
            f'[{fmt_time(r["start"])} → {fmt_time(r["end"])}]' for r in regions
        ),
    ]
    return "\n".join(lines)


# ── Cold-start ingestion (transcription + chunking + CLIP, in parallel) ───────────

def ingest_video(video_path: str) -> dict:
    """
    First sight of a video: decode audio, then run the two heavy independent
    stages concurrently —
        • CPU thread : base transcription → semantic chunking → entities
        • MPS thread : frame extraction → CLIP encoding
    Returns the cache entry dict.
    """
    audio    = load_audio(video_path)
    duration = media_duration(video_path) or (len(audio) / SAMPLE_RATE)

    result = {}

    def _audio_branch():
        segments = transcribe_fast(audio)
        result["segments"] = segments
        if segments:
            result["chunks"] = add_entities_to_chunks(semantic_chunk(segments))
        else:
            result["chunks"] = []

    def _visual_branch():
        result["visual"] = analyze_visual(video_path, duration)

    with ThreadPoolExecutor(max_workers=2) as ex:
        fa = ex.submit(_audio_branch)
        fv = ex.submit(_visual_branch)
        fa.result()
        fv.result()

    return {
        "segments": result["segments"],
        "chunks":   result["chunks"],
        "visual":   result["visual"],
        "audio":    audio,
        "precise":  {},
    }


# ── Global path (shared by GLOBAL mode + every escalation/fallback) ───────────────
#  Global summaries run on the clean base transcript — no whole-video turbo pass.

def _run_global(chunks: list[dict], visual: dict,
                prompt: str, max_words: int) -> list[dict]:
    sampled = sample_chunks_for_global(chunks, _words_to_global_chunks(max_words))
    print(f"[NINA] Global mode — sampled {len(sampled)} chunks evenly (base transcript).")
    for c in sampled:
        c.setdefault("confidence", 0.5)
        c.setdefault("bi_score", 0.0)
        c.setdefault("entity_overlap", 0.0)
        c.setdefault("visual_score", 0.0)
        c["precise_text"] = c.get("text", "")     # base text is enough for an overview
    return add_visual_tags(sampled, visual)


# ── Main pipeline (generator: streams progress + answer) ─────────────────────────

def format_iris(regions, prompt, best_bi):
    if not regions:
        return (f'No clear moments about "{prompt}" were found in this video.\n\n'
                f'Try broader or differently-worded keywords.')
    lines = [f'IRIS - moments matching: "{prompt}"\n']
    for i, r in enumerate(sorted(regions, key=lambda x: x["start"]), 1):
        txt  = (r.get("precise_text", r.get("text", "")) or "").strip()
        tags = ", ".join(r.get("visual_tags", []))
        lines.append(f'  {i}.  [{fmt_time(r["start"])} -> {fmt_time(r["end"])}]   {r.get("confidence", 0):.0%} match')
        lines.append(f'      "{txt[:260]}{"..." if len(txt) > 260 else ""}"')
        if tags:
            lines.append(f'      on screen: {tags}')
        lines.append("")
    lines.append(f'  {len(regions)} moment(s) - ranked by relevance, shown in order of appearance.')
    return "\n".join(lines)


def run(video_path: str, prompt: str, token: str = ""):
    if not _verify_usage_token(token):
        yield ("This request is not authorized.\n\n"
               "Please use IRIS at https://app.nnlabs.pl/iris (sign in first). "
               "Direct API access is disabled, and each account has a usage limit.")
        return
    if video_path is None:
        yield "Please upload a video."
        return
    if not prompt or not prompt.strip():
        yield "Please type what you want to find."
        return
    prompt = prompt.strip()
    print(f'\n[IRIS] -- Find -- "{prompt}"')
    _evict_stale()

    fp = None
    if video_path in _cache:
        entry = _cache[video_path]
    else:
        try: fp = _fingerprint(video_path)
        except Exception: fp = None
        disk = _disk_load(fp) if fp else None
        if disk is not None:
            disk["audio"] = load_audio(video_path)
            entry = disk; _cache[video_path] = entry
        else:
            yield "Reading video - transcribing audio and scanning frames..."
            entry = ingest_video(video_path)
            if not entry["segments"]:
                yield "No speech detected."
                return
            _cache[video_path] = entry
            if fp: _disk_save(fp, entry)

    entry["_atime"] = time.time()
    segments, chunks, visual = entry["segments"], entry["chunks"], entry["visual"]
    precise_cache, audio = entry["precise"], entry["audio"]
    if fp is None:
        try: fp = _fingerprint(video_path)
        except Exception: fp = None
    if not chunks:
        yield "No speech detected."
        return

    candidates, best_bi = bi_encode_retrieve(chunks, prompt)
    _, v_norm = visual_scores(visual, prompt)
    results = rerank_and_score(candidates, prompt, visual["time"], v_norm)
    regions = merge_regions(results)
    if not regions:
        yield format_iris([], prompt, best_bi)
        return
    before = dict(precise_cache)
    fill_precise(audio, regions, chunks, precise_cache, RETRANSCRIBE_MAX)
    if fp and precise_cache != before:
        _disk_update_precise(fp, precise_cache)
    regions = add_visual_tags(regions, visual)
    regions = sorted(regions, key=lambda r: r.get("confidence", 0), reverse=True)[:RESULTS_TOP_N]
    print(f"[IRIS] Done - {len(regions)} moment(s).")
    yield format_iris(regions, prompt, best_bi)


def _synthesize_streaming(regions: list[dict], prompt: str, max_words: int, mode: str):
    """Stream the formatted answer to the UI as the LLM produces it."""
    print(f"[NINA] Running synthesis [{mode}]...")
    yield format_output(regions, prompt, "✍️  …", mode)
    last = ""
    for partial in llm_synthesize_stream(regions, prompt, max_words, mode):
        last = partial
        yield format_output(regions, prompt, partial, mode)
    if not last:
        yield format_output(regions, prompt, _fallback_summary(regions), mode)


# ── Gradio UI ──────────────────────────────────────────────────────────────────

demo = gr.Interface(
    fn=run,
    inputs=[
        gr.Video(label="Upload video "),
        gr.Textbox(
            label="What moment do you want to find?",
            placeholder='e.g. "What does the video say about...?"  '
                        '(add "briefly" or "in detail" to size the answer)',
        ),
        # Issued by app.nnlabs.pl after it counts the use; required to run.
        gr.Textbox(label="access token (set automatically by the website)", value=""),
    ],
    outputs=gr.Textbox(label="Results", lines=38),
    title="IRIS v0.80 — Intelligent Retrieval & Indexing (find the moment)",
    description=(
        "video -> find the exact moments a topic is mentioned or shown. "
        "Use it at https://app.nnlabs.pl/iris."
    ),
    flagging_mode="never",
    # Privacy: Gradio purges uploaded files older than 5 min, every 5 min. One
    # upload still serves many prompts (audio/transcript are cached in RAM), and
    # the file is cleaned shortly after the session goes idle.
    delete_cache=(300, 300),
)

# Concurrency for ~5-10 simultaneous users on an 8-vCPU Space: run a few jobs in
# parallel, queue the rest (CTranslate2 is CPU-bound). Tune with the env var.
demo.queue(
    default_concurrency_limit=int(os.getenv("NINA_CONCURRENCY", "3")),
    max_size=int(os.getenv("NINA_QUEUE_MAX", "40")),
)

if __name__ == "__main__":
    demo.launch()