File size: 51,414 Bytes
82efbf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1359
1360
1361
1362
1363
1364
"""Batch side-by-side inspector/editor for audio + two/three RTTM annotations.

Scans an experiment directory whose sub-directories each contain items of
the form  <id>.wav + <id>.rttm + <id>_3D.rttm [+ <id>_GT.rttm], and serves
a compare/edit page with prev/next navigation across all items. Panels:
GT = <id>_GT.rttm (parquet annotation, optional), A = <id>.rttm (DiariZen),
B = <id>_3D.rttm (3D-Speaker).

Speakers of every panel are auto-matched (by maximal overlap) against the
anchor annotation (GT when present, else A) so matched speakers share a
color, and a "diff" strip highlights every region where a selectable pair
of annotations disagree (speech only in one, or attributed to different
speakers). All annotations are editable (move/resize/reassign/split/
delete/create, undo/redo); each RTTM saves to "<original-stem>_new.rttm"
next to the original file.

Usage:
    python batch_double_rttm_viewer.py /workspace/comparison [--port 8766]
    open: http://127.0.0.1:8766
"""
import argparse
import io
import json
import mimetypes
import os
import re
import threading
import wave
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

AUDIO_EXTS = {".wav", ".flac", ".mp3", ".ogg", ".m4a", ".opus", ".aac"}


def parse_rttm(path):
    """Return (segments, file_id, channel) from SPEAKER lines of an RTTM."""
    segments = []
    file_id, chan = None, None
    with open(path, encoding="utf-8") as f:
        for ln, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith((";", "#")):
                continue
            parts = line.split()
            if parts[0] != "SPEAKER":
                continue
            if len(parts) < 8:
                raise ValueError(f"{path}:{ln}: malformed SPEAKER line")
            start, dur = float(parts[3]), float(parts[4])
            segments.append({"start": start, "end": start + dur,
                             "speaker": parts[7]})
            file_id = file_id or parts[1]
            chan = chan or parts[2]
    if not segments:
        raise ValueError(f"{path}: no SPEAKER lines found")
    segments.sort(key=lambda s: s["start"])
    return segments, file_id, chan


def load_audio(path):
    """Return (bytes, content-type, duration-or-None)."""
    with open(path, "rb") as f:
        data = f.read()
    if data[:4] == b"RIFF":
        with wave.open(io.BytesIO(data)) as w:
            return data, "audio/x-wav", w.getnframes() / w.getframerate()
    ctype = mimetypes.guess_type(path)[0] or "audio/mpeg"
    return data, ctype, None  # let the browser report the duration


def scan_items(root):
    """Collect audio + rttm items under root; _GT.rttm is optional."""
    items = []
    for ds in sorted(os.listdir(root)):
        d = os.path.join(root, ds)
        if not os.path.isdir(d):
            continue
        for fn in sorted(os.listdir(d)):
            stem, ext = os.path.splitext(fn)
            if ext.lower() not in AUDIO_EXTS:
                continue
            rttm_a = os.path.join(d, stem + ".rttm")
            rttm_b = os.path.join(d, stem + "_3D.rttm")
            rttm_gt = os.path.join(d, stem + "_GT.rttm")
            missing = [p for p in (rttm_a, rttm_b) if not os.path.isfile(p)]
            if missing:
                print(f"skip {ds}/{fn}: missing "
                      f"{', '.join(os.path.basename(m) for m in missing)}")
                continue
            item = {"dataset": ds, "id": stem,
                    "audio": os.path.join(d, fn),
                    "a": rttm_a, "b": rttm_b}
            if os.path.isfile(rttm_gt):
                item["gt"] = rttm_gt
            items.append(item)
    return items


class ItemStore:
    """Lazy per-item audio loading, caching the most recent item only."""

    def __init__(self, items):
        self.items = items
        self._cache = {}
        self._lock = threading.Lock()

    def audio(self, idx):
        with self._lock:
            if idx in self._cache:
                return self._cache[idx]
        entry = load_audio(self.items[idx]["audio"])
        with self._lock:
            self._cache.clear()
            self._cache[idx] = entry
        return entry

    def meta(self, idx):
        item = self.items[idx]
        _, _, duration = self.audio(idx)
        out = {"index": idx, "n_items": len(self.items),
               "dataset": item["dataset"], "id": item["id"],
               "audio_file": os.path.basename(item["audio"]),
               "files": {}}
        ends = []
        for key in ("gt", "a", "b"):
            if key not in item:
                continue
            segments, _, _ = parse_rttm(item[key])
            out_path = os.path.splitext(item[key])[0] + "_new.rttm"
            out["files"][key] = {
                "rttm_file": os.path.basename(item[key]),
                "out_file": os.path.basename(out_path),
                "segments": segments}
            ends.append(max(s["end"] for s in segments))
        out["duration"] = duration if duration is not None else max(ends)
        return out

    def save(self, idx, which, segments):
        item = self.items[idx]
        if which not in item or which not in ("gt", "a", "b"):
            raise ValueError(f"unknown rttm key: {which!r}")
        src = item[which]
        try:
            _, fid, chan = parse_rttm(src)
        except ValueError:
            fid, chan = None, None
        fid = fid or item["id"]
        chan = chan or "1"
        out_path = os.path.splitext(src)[0] + "_new.rttm"
        segs = sorted(segments, key=lambda s: float(s["start"]))
        lines = []
        for s in segs:
            start, end = float(s["start"]), float(s["end"])
            spk = re.sub(r"\s+", "_", str(s["speaker"]).strip())
            if not spk:
                raise ValueError("empty speaker label")
            if end <= start or start < 0:
                raise ValueError(f"invalid segment [{start}, {end}]")
            lines.append(f"SPEAKER {fid} {chan} {start:.3f} {end - start:.3f} "
                         f"<NA> <NA> {spk} <NA> <NA>\n")
        with open(out_path, "w", encoding="utf-8") as f:
            f.writelines(lines)
        return out_path, len(lines)


PAGE = """<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>批量多 RTTM 对比编辑器</title>
<style>
  :root { --bg:#14161a; --panel:#1e2128; --text:#e6e6e6; --dim:#9aa0aa;
          --accent:#4da3ff; --sel:rgba(255,210,80,.25); --selborder:#ffd250;
          --aonly:#ffb020; --bonly:#3fd0ff; --mismatch:#ff5470;
          --labelw:210px; }
  * { box-sizing:border-box; }
  body { margin:0; background:var(--bg); color:var(--text);
         font:14px/1.5 system-ui,"Segoe UI",sans-serif; }
  header { display:flex; align-items:center; gap:10px; flex-wrap:wrap;
           padding:8px 16px; background:var(--panel);
           border-bottom:1px solid #000; position:sticky; top:0; z-index:6; }
  header .title { font-weight:600; }
  header .dim { color:var(--dim); font-size:12px; }
  button, input[type=text], input[type=number], select { background:#2a2e37;
      color:var(--text); border:1px solid #3a3f4a; border-radius:6px;
      padding:4px 10px; font-size:13px; cursor:pointer; }
  button:hover { border-color:var(--accent); }
  button:disabled { opacity:.4; cursor:default; }
  button.dirty { border-color:var(--selborder); color:var(--selborder); }
  input[type=text], input[type=number] { cursor:text;
      font-variant-numeric:tabular-nums; }
  input[type=text]:focus, input[type=number]:focus {
      border-color:var(--selborder); outline:none; }
  #itemidx { width:64px; }
  #controls { display:flex; align-items:center; gap:10px; flex-wrap:wrap;
              padding:6px 16px; }
  #audio { width:100%; }
  .selinfo { color:var(--dim); font-size:13px; }
  .selinfo b { color:var(--selborder); font-weight:600; }
  #zoomwrap { margin-left:auto; display:flex; align-items:center; gap:6px;
              color:var(--dim); font-size:12px; }
  #diffstats { font-size:13px; }
  #diffstats b { font-weight:600; }
  .sw { display:inline-block; width:9px; height:9px; border-radius:2px;
        margin:0 3px 0 10px; vertical-align:baseline; }
  #editbar { display:none; align-items:center; gap:8px; flex-wrap:wrap;
             margin:0 16px 6px; padding:6px 12px; background:#262b35;
             border:1px solid var(--selborder); border-radius:8px; }
  #editbar .tag { font-weight:600; color:var(--selborder); }
  #editbar input[type=text] { width:90px; }
  #editbar #ebspk { width:120px; }
  #tracks-outer { margin:0 16px 24px; border:1px solid #2a2e37;
                  border-radius:8px; overflow-x:auto; background:var(--panel); }
  #tracks { position:relative; min-width:100%; }
  #ruler { position:relative; height:26px; border-bottom:1px solid #2a2e37;
           cursor:crosshair; user-select:none; }
  .tick { position:absolute; top:0; height:100%; border-left:1px solid #333842;
          color:var(--dim); font-size:10px; padding:2px 0 0 3px; }
  .panel-sep { position:relative; height:28px; background:#171a20;
               border-bottom:1px solid #262a32; }
  .panel-sep .lane-label { font-size:12px; max-width:none; color:var(--dim);
                           pointer-events:auto; }
  .panel-sep b { color:var(--text); }
  .panel-sep button { padding:1px 8px; font-size:11px; }
  .lane { position:relative; height:34px; border-bottom:1px solid #262a32; }
  .lane-label { position:sticky; left:0; z-index:5; display:inline-flex;
      align-items:center; gap:6px; height:100%; padding:0 8px;
      width:var(--labelw); background:var(--panel);
      border-right:1px solid #2a2e37;
      font-size:12px; white-space:nowrap;
      overflow:hidden; text-overflow:ellipsis; pointer-events:none; }
  .panel-sep .lane-label { width:auto; min-width:var(--labelw); }
  .gutter-mask { position:sticky; left:0; z-index:5; display:inline-block;
      width:var(--labelw); height:100%; background:var(--panel);
      border-right:1px solid #2a2e37; }
  .lane-label .swatch { width:10px; height:10px; border-radius:2px; flex:none; }
  .lane-label button { pointer-events:auto; padding:0 6px; font-size:11px; }
  .seg { position:absolute; top:7px; height:20px; border-radius:3px;
         opacity:.85; cursor:grab; min-width:2px; }
  .seg:hover { opacity:1; outline:1px solid #fff; z-index:2; }
  .seg.selected { opacity:1; outline:2px solid #fff; z-index:3; }
  .difflane { position:relative; height:26px; background:#101216;
              border-bottom:1px solid #262a32; }
  .difflane .lane-label { font-size:11px; }
  .diffseg { position:absolute; top:6px; height:14px; border-radius:2px;
             opacity:.9; cursor:pointer; min-width:2px; }
  .diffseg:hover { opacity:1; outline:1px solid #fff; z-index:2; }
  #playhead { position:absolute; top:0; bottom:0; width:1px;
              background:#ff5555; z-index:4; pointer-events:none; }
  #selbox { position:absolute; top:0; bottom:0; background:var(--sel);
            border-left:1px solid var(--selborder);
            border-right:1px solid var(--selborder);
            z-index:1; pointer-events:none; display:none; }
  #hint { padding:0 16px 12px; color:var(--dim); font-size:12px; }
  #err { color:#ff7070; padding:8px 16px; display:none; }
  #savemsg { font-size:12px; color:#7ddf8f; }
</style>
</head>
<body>
<header>
  <span class="title">批量多 RTTM 对比</span>
  <button id="previtem">◀ 上一条</button>
  <input type="number" id="itemidx" min="0" value="0">
  <span class="dim" id="itemcount"></span>
  <button id="nextitem">下一条 ▶</button>
  <span class="dim" id="fname"></span>
  <span class="dim" id="rowinfo"></span>
  <span style="margin-left:auto"></span>
  <button id="savegt"></button>
  <button id="savea"></button>
  <button id="saveb"></button>
  <span id="savemsg"></span>
</header>
<div id="err"></div>
<div id="controls">
  <audio id="audio" controls preload="auto"></audio>
</div>
<div id="controls">
  <button id="playsel" disabled>▶ 播放选区</button>
  <label class="dim"><input type="checkbox" id="loop"> 循环</label>
  <button id="clearsel" disabled>清除选区</button>
  <span class="dim">选区</span>
  <input type="text" id="selstart" placeholder="起 (秒或分:秒)" style="width:110px">
  <span class="dim">→</span>
  <input type="text" id="selend" placeholder="止 (秒或分:秒)" style="width:110px">
  <button id="applysel">应用</button>
  <span class="selinfo" id="selinfo">拖动空白选择区间;单击色块选中编辑</span>
  <label class="dim" style="margin-left:auto"><input type="checkbox" id="follow" checked> 跟随播放</label>
  <span id="zoomwrap" style="margin-left:0">缩放
    <input type="range" id="zoom" min="0" max="100" value="0" style="width:140px">
    <span id="zoomval">1×</span>
  </span>
</div>
<div id="controls">
  <span class="dim">差异对比</span>
  <select id="diffpair"></select>
  <span id="diffstats" class="dim">…</span>
  <span class="dim" style="margin-left:auto">忽略短于</span>
  <input type="number" id="mindiff" value="0.25" min="0" step="0.05" style="width:70px">
  <span class="dim">s 的差异</span>
  <button id="remap" title="按当前标注重新计算说话人配对与配色">重算说话人配对</button>
</div>
<div id="editbar">
  <span class="tag" id="ebtitle"></span>
  <span class="dim">说话人</span><input type="text" id="ebspk" list="spklist">
  <datalist id="spklist"></datalist>
  <span class="dim">起</span><input type="text" id="ebstart">
  <span class="dim">止</span><input type="text" id="ebend">
  <span class="dim" id="ebdur"></span>
  <button id="ebapply">应用 (Enter)</button>
  <button id="ebplay">▶ 播放该段</button>
  <button id="ebsplit">✂ 在播放头拆分 (S)</button>
  <button id="ebdel">🗑 删除 (Del)</button>
  <button id="ebclose">取消 (Esc)</button>
</div>
<div id="tracks-outer"><div id="tracks">
  <div id="ruler"></div>
  <div id="lanes"></div>
  <div id="selbox"></div>
  <div id="playhead" style="left:0"></div>
</div></div>
<div id="hint">PgUp/PgDn=上一条/下一条 · 面板顺序 GT(parquet 标注)/A(DiariZen)/B(3D-Speaker) ·
差异带在最上方,可切换对比对 · 单击色块=选中编辑 · 双击色块=播放该段 ·
拖动色块=移动 · 拖边缘=调整边界 · Alt+空白拖动=新建段 · 泳道"+段"=把选区加为该说话人的段 ·
Del=删除 S=拆分 Ctrl+Z/Ctrl+Shift+Z=撤销/重做 · 空格=播放/暂停 ←/→=±5s Shift+←/→=±0.5s Esc=取消</div>
<script>
const $ = id => document.getElementById(id);
const audio = $('audio');
const PALETTE = ['#4da3ff','#ff9f43','#2ecc71','#e74c3c','#a55eea','#f1c40f',
                 '#1abc9c','#fd79a8','#74b9ff','#e17055','#81ecec','#b8e994',
                 '#ffbe76','#badc58','#7ed6df','#e056fd','#f8a5c2','#63cdda'];
const ALL_KEYS = ['gt', 'a', 'b'];
const NAME = {gt: 'GT', a: 'A', b: 'B'};
let meta = null, dur = 0, zoomFactor = 1;
let fileKeys = [];           // present file keys of the current item
let sel = null;              // {start, end} seconds
let dragging = null;         // select | create | move | resize-l | resize-r
let selected = null;         // {file, id}
let mapping = null;          // {assign:{'x|y':[[sx,sy],..]}, colorOf, nextColor}
let diffPair = null;         // [x, y] file keys being compared
let diffRegions = [], diffStats = null;
let nextId = 1;
let undoStack = {}, redoStack = {}, dirty = {};

function fmt(t) {
  const h = Math.floor(t/3600), m = Math.floor(t%3600/60), s = t%60;
  return (h? h+':' : '') + String(m).padStart(2,'0') + ':' +
         s.toFixed(2).padStart(5,'0');
}
const LABEL_W = 210;  // keep in sync with --labelw
function pxPerSec() {
  const w = $('tracks-outer').clientWidth - LABEL_W - 2;
  return (w / dur) * zoomFactor;
}
// content x-position of time t (timeline starts right of the label gutter)
function tX(t) { return LABEL_W + t * pxPerSec(); }
function xToTime(clientX) {
  const r = $('tracks').getBoundingClientRect();
  return Math.min(dur, Math.max(0,
      (clientX - r.left - LABEL_W) / pxPerSec()));
}
const natCmp = (a, b) => a.localeCompare(b, undefined, {numeric:true});
function findSeg(file, id) {
  return meta.files[file].segments.find(s => s.id === id);
}
function anchorKey() { return fileKeys.includes('gt') ? 'gt' : 'a'; }
function pairCombos() {
  const combos = [];
  for (let i = 0; i < fileKeys.length; i++)
    for (let j = i + 1; j < fileKeys.length; j++)
      combos.push([fileKeys[i], fileKeys[j]]);
  return combos;
}

/* ---------- speaker mapping and colors ---------- */

function speakerList(file) {
  const f = meta.files[file];
  const spks = new Set(f.segments.map(s => s.speaker));
  f.extraSpeakers.forEach(s => spks.add(s));
  return [...spks];
}

// pair X/Y speakers maximizing total overlap duration; exact bitmask DP
// over the smaller side (fallback: greedy when both sides are large)
function bestPairs(ov, nA, nB) {
  let flip = false;
  if (nB > nA) {  // make B (mask side) the smaller one
    flip = true;
    const t = [];
    for (let j = 0; j < nB; j++) { t.push(ov.map(row => row[j])); }
    ov = t; [nA, nB] = [nB, nA];
  }
  let pairs = [];
  if (nB > 14) {  // greedy fallback
    const all = [];
    for (let i = 0; i < nA; i++)
      for (let j = 0; j < nB; j++)
        if (ov[i][j] > 0) all.push([ov[i][j], i, j]);
    all.sort((x, y) => y[0] - x[0]);
    const ua = new Set(), ub = new Set();
    for (const [, i, j] of all) {
      if (ua.has(i) || ub.has(j)) continue;
      ua.add(i); ub.add(j); pairs.push([i, j]);
    }
  } else {
    const FULL = 1 << nB;
    let dp = new Float64Array(FULL).fill(-1); dp[0] = 0;
    const choice = [];
    for (let i = 0; i < nA; i++) {
      const ndp = new Float64Array(FULL).fill(-1);
      const ch = new Int8Array(FULL).fill(-2);
      for (let mask = 0; mask < FULL; mask++) {
        if (dp[mask] < 0) continue;
        if (dp[mask] > ndp[mask]) { ndp[mask] = dp[mask]; ch[mask] = -1; }
        for (let j = 0; j < nB; j++) {
          if (mask & (1 << j) || ov[i][j] <= 0) continue;
          const nm = mask | (1 << j), v = dp[mask] + ov[i][j];
          if (v > ndp[nm]) { ndp[nm] = v; ch[nm] = j; }
        }
      }
      dp = ndp; choice.push(ch);
    }
    let best = 0;
    for (let m = 0; m < FULL; m++) if (dp[m] > dp[best]) best = m;
    let mask = best;
    for (let i = nA - 1; i >= 0; i--) {
      const j = choice[i][mask];
      if (j >= 0) { pairs.push([i, j]); mask ^= 1 << j; }
    }
  }
  if (flip) pairs = pairs.map(([i, j]) => [j, i]);
  return pairs;
}

function overlapMatrix(x, y) {
  const X = speakerList(x).sort(natCmp), Y = speakerList(y).sort(natCmp);
  const xBy = new Map(X.map((s, i) => [s, i]));
  const yBy = new Map(Y.map((s, j) => [s, j]));
  const ov = X.map(() => Y.map(() => 0));
  const ySegs = meta.files[y].segments;
  for (const sx of meta.files[x].segments) {
    const i = xBy.get(sx.speaker);
    for (const sy of ySegs) {
      const o = Math.min(sx.end, sy.end) - Math.max(sx.start, sy.start);
      if (o > 0) ov[i][yBy.get(sy.speaker)] += o;
    }
  }
  return {X, Y, ov};
}

function computeMapping() {
  mapping = {assign: {}, colorOf: new Map(), nextColor: 0};
  for (const [x, y] of pairCombos()) {
    const {X, Y, ov} = overlapMatrix(x, y);
    const idx = bestPairs(ov, X.length, Y.length);
    idx.sort((p, q) => ov[q[0]][q[1]] - ov[p[0]][p[1]]);  // strongest first
    mapping.assign[x + '|' + y] = idx.map(([i, j]) => [X[i], Y[j]]);
  }
  // colors anchored on the anchor file's speakers
  const anchor = anchorKey();
  for (const spk of speakerList(anchor).sort(natCmp))
    mapping.colorOf.set(anchor + '|' + spk, mapping.nextColor++);
  for (const file of fileKeys) {
    if (file === anchor) continue;
    const partner = partnerMap(file, anchor);
    for (const spk of speakerList(file).sort(natCmp)) {
      const key = file + '|' + spk;
      const p = partner.get(spk);
      if (p !== undefined && mapping.colorOf.has(anchor + '|' + p))
        mapping.colorOf.set(key, mapping.colorOf.get(anchor + '|' + p));
      else
        mapping.colorOf.set(key, mapping.nextColor++);
    }
  }
}

// map speakers of `file` to their partner in `other` (if paired)
function partnerMap(file, other) {
  const key = fileKeys.indexOf(file) < fileKeys.indexOf(other)
      ? file + '|' + other : other + '|' + file;
  const pairs = mapping.assign[key] || [];
  const m = new Map();
  for (const [sx, sy] of pairs) {
    if (key.startsWith(file + '|')) m.set(sx, sy);
    else m.set(sy, sx);
  }
  return m;
}

function colorFor(file, spk) {
  const key = file + '|' + spk;
  if (!mapping.colorOf.has(key))
    mapping.colorOf.set(key, mapping.nextColor++);
  return PALETTE[mapping.colorOf.get(key) % PALETTE.length];
}
function laneOrder(file) {
  const spks = new Set(speakerList(file));
  const anchor = anchorKey();
  if (file === anchor) return [...spks].sort(natCmp);
  const partner = partnerMap(file, anchor);
  const anchorOrder = speakerList(anchor).sort(natCmp);
  const paired = [];
  for (const aSpk of anchorOrder)
    for (const [spk, p] of partner)
      if (p === aSpk && spks.has(spk)) paired.push(spk);
  const rest = [...spks].filter(s => !paired.includes(s)).sort(natCmp);
  return [...paired, ...rest];
}

/* ---------- diff computation (between diffPair files) ---------- */

function computeDiff() {
  const [fx, fy] = diffPair;
  // mapped id: paired speakers share 'P<k>' ids, unpaired get unique ids
  const key = fileKeys.indexOf(fx) < fileKeys.indexOf(fy)
      ? fx + '|' + fy : fy + '|' + fx;
  const pairs = mapping.assign[key] || [];
  const idOf = {[fx]: new Map(), [fy]: new Map()};
  pairs.forEach(([sx, sy], k) => {
    if (key.startsWith(fx + '|')) {
      idOf[fx].set(sx, 'P' + k); idOf[fy].set(sy, 'P' + k);
    } else {
      idOf[fy].set(sx, 'P' + k); idOf[fx].set(sy, 'P' + k);
    }
  });
  const mid = (f, spk) => idOf[f].get(spk) ?? (f + '#' + spk);

  const bounds = new Set();
  const evts = {[fx]: [], [fy]: []};
  for (const file of [fx, fy])
    for (const s of meta.files[file].segments) {
      bounds.add(s.start); bounds.add(s.end);
      evts[file].push([s.start, 1, s.speaker], [s.end, -1, s.speaker]);
    }
  const ts = [...bounds].sort((p, q) => p - q);
  for (const file of [fx, fy])
    evts[file].sort((p, q) => p[0] - q[0] || p[1] - q[1]);
  const act = {[fx]: new Map(), [fy]: new Map()};
  const ptr = {[fx]: 0, [fy]: 0};
  const raw = [];
  for (let k = 0; k + 1 < ts.length; k++) {
    const t0 = ts[k], t1 = ts[k + 1];
    for (const file of [fx, fy]) {
      const e = evts[file], m = act[file];
      while (ptr[file] < e.length && e[ptr[file]][0] <= t0 + 1e-9) {
        const [, d, spk] = e[ptr[file]++];
        m.set(spk, (m.get(spk) || 0) + d);
        if (m.get(spk) <= 0) m.delete(spk);
      }
    }
    const xSpk = [...act[fx].keys()], ySpk = [...act[fy].keys()];
    if (!xSpk.length && !ySpk.length) continue;
    const sx = xSpk.map(s => mid(fx, s)).sort().join(',');
    const sy = ySpk.map(s => mid(fy, s)).sort().join(',');
    const cat = sx === sy ? 'same' : !xSpk.length ? 'bonly'
              : !ySpk.length ? 'aonly' : 'mismatch';
    raw.push({t0, t1, cat, sx, sy,
              xSpk: xSpk.sort(natCmp), ySpk: ySpk.sort(natCmp)});
  }
  // merge contiguous regions with identical category and speaker sets
  const merged = [];
  for (const r of raw) {
    const last = merged[merged.length - 1];
    if (last && last.cat === r.cat && last.sx === r.sx && last.sy === r.sy &&
        Math.abs(last.t1 - r.t0) < 1e-6) last.t1 = r.t1;
    else merged.push({...r});
  }
  diffStats = {union: 0, same: 0, aonly: 0, bonly: 0, mismatch: 0};
  for (const r of merged) {
    const d = r.t1 - r.t0;
    diffStats.union += d;
    diffStats[r.cat] += d;
  }
  diffRegions = merged.filter(r => r.cat !== 'same');
  renderStats();
}

function renderStats() {
  const s = diffStats;
  const [fx, fy] = diffPair;
  const pct = s.union ? (100 * s.same / s.union).toFixed(1) : '100.0';
  $('diffstats').innerHTML =
    `一致 <b>${pct}%</b>(按语音时长)` +
    `<span class="sw" style="background:var(--aonly)"></span>仅${NAME[fx]} ${s.aonly.toFixed(1)}s` +
    `<span class="sw" style="background:var(--bonly)"></span>仅${NAME[fy]} ${s.bonly.toFixed(1)}s` +
    `<span class="sw" style="background:var(--mismatch)"></span>不一致 ${s.mismatch.toFixed(1)}s`;
}

/* ---------- rendering ---------- */

function render() {
  const pps = pxPerSec(), width = Math.ceil(LABEL_W + dur * pps);
  $('tracks').style.width = width + 'px';

  const ruler = $('ruler');
  ruler.innerHTML = '';
  const mask = document.createElement('div');
  mask.className = 'gutter-mask';
  ruler.appendChild(mask);
  const steps = [0.1,0.2,0.5,1,2,5,10,15,30,60,120,300,600,1200,1800,3600];
  const step = steps.find(s => s*pps >= 90) || 3600;
  for (let t = 0; t <= dur; t += step) {
    if (tX(t) + 60 > width) break;  // skip ticks whose text would overflow
    const d = document.createElement('div');
    d.className = 'tick';
    d.style.left = tX(t) + 'px';
    d.textContent = fmt(t);
    ruler.appendChild(d);
  }

  const lanes = $('lanes');
  lanes.innerHTML = '';
  buildDiffLane(lanes, pps);
  for (const file of fileKeys) buildPanel(lanes, file, pps);
  updateSaveBtns();
  updateInfo();
  drawSel();
  movePlayhead();
}

function buildPanel(parent, file, pps) {
  const f = meta.files[file];
  const sep = document.createElement('div');
  sep.className = 'panel-sep';
  const spkN = new Set(f.segments.map(s => s.speaker)).size;
  sep.innerHTML =
    `<span class="lane-label"><b>${NAME[file]}</b>·${f.rttm_file}` +
    ` · ${f.segments.length} 段 · ${spkN} 人 ` +
    `<button data-addspk="${file}">+新说话人</button></span>`;
  parent.appendChild(sep);

  const anchor = anchorKey();
  const partner = file === anchor ? null : partnerMap(file, anchor);
  for (const spk of laneOrder(file)) {
    const lane = document.createElement('div');
    lane.className = 'lane';
    lane.dataset.file = file;
    lane.dataset.speaker = spk;
    const color = colorFor(file, spk);
    const segs = f.segments.filter(s => s.speaker === spk);
    const p = partner ? partner.get(spk) : undefined;
    const label = document.createElement('span');
    label.className = 'lane-label';
    label.innerHTML =
      `<span class="swatch" style="background:${color}"></span>${spk} ` +
      `<span style="color:var(--dim)">(${segs.length}` +
      (p !== undefined ? ` ⇄ ${NAME[anchor]}:${p}` : '') +
      `)</span> <button data-addseg title="把当前选区加为该说话人的段">+段</button>`;
    lane.appendChild(label);
    for (const s of segs) {
      const d = document.createElement('div');
      d.className = 'seg';
      d.dataset.file = file;
      d.dataset.segId = s.id;
      if (selected && selected.file === file && selected.id === s.id)
        d.classList.add('selected');
      d.style.left = tX(s.start) + 'px';
      d.style.width = Math.max(2, (s.end-s.start)*pps) + 'px';
      d.style.background = color;
      d.title = `${NAME[file]}:${spk}\\n${fmt(s.start)} → ${fmt(s.end)}` +
                `  (${(s.end-s.start).toFixed(2)}s)`;
      lane.appendChild(d);
    }
    parent.appendChild(lane);
  }
}

function buildDiffLane(parent, pps) {
  const [fx, fy] = diffPair;
  const CATNAME = {aonly: `仅${NAME[fx]}有语音`, bonly: `仅${NAME[fy]}有语音`,
                   mismatch: '说话人不一致'};
  const CATCOLOR = {aonly: 'var(--aonly)', bonly: 'var(--bonly)',
                    mismatch: 'var(--mismatch)'};
  const lane = document.createElement('div');
  lane.className = 'difflane';
  const minDiff = parseFloat($('mindiff').value) || 0;
  const shown = diffRegions.filter(r => r.t1 - r.t0 >= minDiff);
  lane.innerHTML = `<span class="lane-label">差异 ${NAME[fx]}↔${NAME[fy]} ` +
    `<span style="color:var(--dim)">(${shown.length})</span></span>`;
  for (const r of shown) {
    const d = document.createElement('div');
    d.className = 'diffseg';
    d.dataset.t0 = r.t0;
    d.dataset.t1 = r.t1;
    d.style.left = tX(r.t0) + 'px';
    d.style.width = Math.max(2, (r.t1-r.t0)*pps) + 'px';
    d.style.background = CATCOLOR[r.cat];
    d.title = `${CATNAME[r.cat]}  ${fmt(r.t0)} → ${fmt(r.t1)}` +
              ` (${(r.t1-r.t0).toFixed(2)}s)\\n` +
              `${NAME[fx]}: ${r.xSpk.join(', ') || '-'}\\n` +
              `${NAME[fy]}: ${r.ySpk.join(', ') || '-'}`;
    lane.appendChild(d);
  }
  parent.appendChild(lane);
}

function updateInfo() {
  $('rowinfo').textContent = `时长 ${fmt(dur)}`;
}
function updateSaveBtns() {
  for (const file of ALL_KEYS) {
    const b = $('save' + file);
    if (!fileKeys.includes(file)) { b.style.display = 'none'; continue; }
    b.style.display = '';
    b.textContent = `保存${NAME[file]} → ${meta.files[file].out_file}` +
                    (dirty[file] ? ' *' : '');
    b.classList.toggle('dirty', !!dirty[file]);
  }
}
function updateDiffPairSelect() {
  const sel_ = $('diffpair');
  sel_.innerHTML = '';
  for (const [x, y] of pairCombos()) {
    const o = document.createElement('option');
    o.value = x + '|' + y;
    o.textContent = `${NAME[x]} ↔ ${NAME[y]}`;
    sel_.appendChild(o);
  }
  sel_.value = diffPair.join('|');
}

/* ---------- selection & playback (interval) ---------- */

function setSel(a, b, keepInputs) {
  if (b < a) [a, b] = [b, a];
  sel = {start: a, end: b};
  $('playsel').disabled = $('clearsel').disabled = false;
  $('selinfo').innerHTML =
    `选区 <b>${fmt(a)}</b> → <b>${fmt(b)}</b> (${(b-a).toFixed(2)}s)`;
  if (!keepInputs) {
    $('selstart').value = a.toFixed(3);
    $('selend').value = b.toFixed(3);
  }
  drawSel();
}
function clearSel() {
  sel = null;
  $('playsel').disabled = $('clearsel').disabled = true;
  $('selstart').value = $('selend').value = '';
  $('selinfo').textContent = '拖动空白选择区间;单击色块选中编辑';
  drawSel();
}
function parseTime(str) {
  str = str.trim();
  if (!str) return null;
  const parts = str.split(':');
  if (parts.some(p => p.trim() === '' || isNaN(p))) return null;
  return parts.reduce((t, p) => t * 60 + parseFloat(p), 0);
}
function applyManualSel() {
  const a = parseTime($('selstart').value);
  const b = parseTime($('selend').value);
  if (a === null || b === null || a < 0 || b <= a || a >= dur) {
    $('selinfo').innerHTML = '<span style="color:#ff7070">无效区间:' +
      '支持 秒 或 分:秒 格式,需满足 0 ≤ 起 &lt; 止</span>';
    return;
  }
  setSel(a, Math.min(b, dur), true);
  playSel();
}
function drawSel() {
  const box = $('selbox');
  if (!sel) { box.style.display = 'none'; return; }
  box.style.display = 'block';
  box.style.left = tX(sel.start) + 'px';
  box.style.width = ((sel.end-sel.start)*pxPerSec()) + 'px';
}
function playSel() {
  if (!sel) return;
  audio.currentTime = sel.start;
  audio.play();
}
audio.addEventListener('timeupdate', () => {
  if (sel && !audio.paused && audio.currentTime >= sel.end) {
    if ($('loop').checked) audio.currentTime = sel.start;
    else audio.pause();
  }
});

function movePlayhead() {
  $('playhead').style.left = tX(audio.currentTime) + 'px';
}
let progScroll = false;
function followPlayhead(force) {
  if (!$('follow').checked || !dur) return;
  const outer = $('tracks-outer');
  if (outer.scrollWidth <= outer.clientWidth + 1) return;
  const x = tX(audio.currentTime);
  const lo = outer.scrollLeft + LABEL_W + 10;
  const hi = outer.scrollLeft + outer.clientWidth - 40;
  if (force || x < lo || x > hi) {
    progScroll = true;
    outer.scrollLeft = Math.max(0,
        x - LABEL_W - (outer.clientWidth - LABEL_W) * 0.15);
  }
}
$('tracks-outer').addEventListener('scroll', () => {
  if (progScroll) { progScroll = false; return; }
  if (!audio.paused) $('follow').checked = false;
});
$('follow').onchange = () => followPlayhead(true);
audio.addEventListener('seeked', () => followPlayhead(true));
(function raf() {
  movePlayhead();
  if (!audio.paused) followPlayhead();
  requestAnimationFrame(raf);
})();

/* ---------- editing ---------- */

function pushUndo(file) {
  const f = meta.files[file];
  undoStack[file].push(JSON.stringify(
      {segments: f.segments, extraSpeakers: [...f.extraSpeakers]}));
  if (undoStack[file].length > 200) undoStack[file].shift();
  redoStack[file].length = 0;
}
function restore(file, snap) {
  const f = meta.files[file];
  const o = JSON.parse(snap);
  f.segments = o.segments;
  f.extraSpeakers = new Set(o.extraSpeakers);
}
function snapshot(file) {
  const f = meta.files[file];
  return JSON.stringify(
      {segments: f.segments, extraSpeakers: [...f.extraSpeakers]});
}
function undo(file) {
  if (!undoStack[file].length) return;
  redoStack[file].push(snapshot(file));
  restore(file, undoStack[file].pop());
  afterEdit(file, true);
}
function redo(file) {
  if (!redoStack[file].length) return;
  undoStack[file].push(snapshot(file));
  restore(file, redoStack[file].pop());
  afterEdit(file, true);
}
// after any data mutation: mark dirty, recompute diff, redraw
function afterEdit(file, checkSelection) {
  dirty[file] = true;
  if (checkSelection && selected && selected.file === file &&
      !findSeg(file, selected.id)) deselectSeg();
  computeDiff();
  render();
  refreshEditbar();
}
function lastEditedFile() {
  return selected ? selected.file : null;
}

function selectSeg(file, id) {
  selected = {file, id};
  document.querySelectorAll('.seg.selected')
      .forEach(e => e.classList.remove('selected'));
  const el = document.querySelector(
      `.seg[data-file="${file}"][data-seg-id="${id}"]`);
  if (el) el.classList.add('selected');
  refreshEditbar();
}
function deselectSeg() {
  selected = null;
  document.querySelectorAll('.seg.selected')
      .forEach(e => e.classList.remove('selected'));
  refreshEditbar();
}
function refreshEditbar() {
  const bar = $('editbar');
  if (!selected) { bar.style.display = 'none'; return; }
  const s = findSeg(selected.file, selected.id);
  if (!s) { bar.style.display = 'none'; return; }
  bar.style.display = 'flex';
  $('ebtitle').textContent =
      `${NAME[selected.file]} · ${s.speaker}`;
  $('ebspk').value = s.speaker;
  $('ebstart').value = s.start.toFixed(3);
  $('ebend').value = s.end.toFixed(3);
  $('ebdur').textContent = `(${(s.end - s.start).toFixed(2)}s)`;
  const dl = $('spklist');
  dl.innerHTML = '';
  for (const spk of laneOrder(selected.file)) {
    const o = document.createElement('option');
    o.value = spk;
    dl.appendChild(o);
  }
}
function applyEditbar() {
  if (!selected) return;
  const s = findSeg(selected.file, selected.id);
  const start = parseTime($('ebstart').value);
  const end = parseTime($('ebend').value);
  const spk = $('ebspk').value.trim();
  if (start === null || end === null || !spk ||
      start < 0 || end <= start || start >= dur) {
    $('ebdur').textContent = '(无效输入)';
    return;
  }
  pushUndo(selected.file);
  s.start = start; s.end = Math.min(end, dur); s.speaker = spk;
  afterEdit(selected.file);
}
function splitSelected() {
  if (!selected) return;
  const s = findSeg(selected.file, selected.id);
  const t = audio.currentTime;
  if (t <= s.start + 0.02 || t >= s.end - 0.02) {
    $('ebdur').textContent = '(播放头不在段内,无法拆分)';
    return;
  }
  pushUndo(selected.file);
  const right = {id: nextId++, start: t, end: s.end, speaker: s.speaker};
  s.end = t;
  meta.files[selected.file].segments.push(right);
  afterEdit(selected.file);
}
function deleteSelected() {
  if (!selected) return;
  const f = meta.files[selected.file];
  pushUndo(selected.file);
  f.segments = f.segments.filter(s => s.id !== selected.id);
  const file = selected.file;
  deselectSeg();
  afterEdit(file);
}
function addSegFromSel(file, spk) {
  if (!sel) {
    $('selinfo').innerHTML =
        '<span style="color:#ff7070">先拖动选择一个区间,再点 +段</span>';
    return;
  }
  pushUndo(file);
  const s = {id: nextId++, start: sel.start, end: sel.end, speaker: spk};
  meta.files[file].segments.push(s);
  afterEdit(file);
  selectSeg(file, s.id);
}
function addSpeaker(file) {
  const name = prompt('新说话人标签(仅用于本页;保存时无段的说话人不会写入 RTTM):');
  if (!name || !name.trim()) return;
  meta.files[file].extraSpeakers.add(name.trim());
  render();
}

/* ---------- mouse interactions on tracks ---------- */

const tracksEl = $('tracks');
tracksEl.addEventListener('mousedown', ev => {
  const segEl = ev.target.closest('.seg');
  if (segEl) {
    const file = segEl.dataset.file, id = +segEl.dataset.segId;
    const r = segEl.getBoundingClientRect();
    const x = ev.clientX - r.left;
    const edge = Math.min(6, r.width / 3);
    const mode = r.width >= 12 && x < edge ? 'resize-l'
               : r.width >= 12 && x > r.width - edge ? 'resize-r' : 'move';
    const s = findSeg(file, id);
    dragging = {mode, file, id, el: segEl, moved: false, pushed: false,
                grabOffset: xToTime(ev.clientX) - s.start};
    ev.preventDefault();
    return;
  }
  const diffEl = ev.target.closest('.diffseg');
  if (diffEl) {
    dragging = {mode: 'select', anchor: xToTime(ev.clientX), moved: false,
                diffEl};
    ev.preventDefault();
    return;
  }
  const lane = ev.target.closest('.lane');
  if (ev.altKey && lane) {
    dragging = {mode: 'create', file: lane.dataset.file,
                spk: lane.dataset.speaker, lane,
                anchor: xToTime(ev.clientX), t0: null, t1: null,
                el: null, moved: false};
    ev.preventDefault();
    return;
  }
  dragging = {mode: 'select', anchor: xToTime(ev.clientX), moved: false};
  ev.preventDefault();
});

window.addEventListener('mousemove', ev => {
  if (!dragging) return;
  const t = xToTime(ev.clientX);
  const pps = pxPerSec();
  if (dragging.mode === 'select') {
    if (Math.abs(t - dragging.anchor) * pps > 3) {
      dragging.moved = true;
      setSel(dragging.anchor, t);
    }
  } else if (dragging.mode === 'create') {
    if (Math.abs(t - dragging.anchor) * pps > 3) {
      dragging.moved = true;
      dragging.t0 = Math.min(dragging.anchor, t);
      dragging.t1 = Math.max(dragging.anchor, t);
      if (!dragging.el) {
        dragging.el = document.createElement('div');
        dragging.el.className = 'seg';
        dragging.el.style.background =
            colorFor(dragging.file, dragging.spk);
        dragging.el.style.opacity = '0.6';
        dragging.lane.appendChild(dragging.el);
      }
      dragging.el.style.left = tX(dragging.t0) + 'px';
      dragging.el.style.width = Math.max(2, (dragging.t1-dragging.t0)*pps) + 'px';
    }
  } else {  // move / resize
    const s = findSeg(dragging.file, dragging.id);
    if (!s) { dragging = null; return; }
    if (!dragging.pushed) { pushUndo(dragging.file); dragging.pushed = true; }
    dragging.moved = true;
    if (dragging.mode === 'move') {
      const len = s.end - s.start;
      const ns = Math.min(Math.max(t - dragging.grabOffset, 0), dur - len);
      s.start = ns; s.end = ns + len;
    } else if (dragging.mode === 'resize-l') {
      s.start = Math.min(Math.max(t, 0), s.end - 0.02);
    } else {
      s.end = Math.max(Math.min(t, dur), s.start + 0.02);
    }
    dragging.el.style.left = tX(s.start) + 'px';
    dragging.el.style.width = Math.max(2, (s.end-s.start)*pps) + 'px';
    if (selected && selected.file === dragging.file &&
        selected.id === dragging.id) {
      $('ebstart').value = s.start.toFixed(3);
      $('ebend').value = s.end.toFixed(3);
      $('ebdur').textContent = `(${(s.end - s.start).toFixed(2)}s)`;
    }
  }
});

window.addEventListener('mouseup', ev => {
  if (!dragging) return;
  const d = dragging;
  dragging = null;
  if (d.mode === 'select') {
    if (!d.moved) {
      if (d.diffEl) {  // click on a diff region: select it and play
        setSel(+d.diffEl.dataset.t0, +d.diffEl.dataset.t1);
        playSel();
      } else {
        audio.currentTime = xToTime(ev.clientX);
      }
    }
  } else if (d.mode === 'create') {
    if (d.el) d.el.remove();
    if (d.moved && d.t1 - d.t0 >= 0.05) {
      pushUndo(d.file);
      const s = {id: nextId++, start: d.t0, end: d.t1, speaker: d.spk};
      meta.files[d.file].segments.push(s);
      afterEdit(d.file);
      selectSeg(d.file, s.id);
    }
  } else {  // move / resize finished (or plain click on a segment)
    if (d.moved) {
      afterEdit(d.file);
      selectSeg(d.file, d.id);
    } else {
      selectSeg(d.file, d.id);
    }
  }
});

tracksEl.addEventListener('dblclick', ev => {
  const segEl = ev.target.closest('.seg');
  if (!segEl) return;
  const s = findSeg(segEl.dataset.file, +segEl.dataset.segId);
  if (s) { setSel(s.start, s.end); playSel(); }
});

// lane-label "+seg" / panel "+speaker" buttons (delegated)
$('lanes').addEventListener('click', ev => {
  const t = ev.target;
  if (t.dataset && 'addseg' in t.dataset) {
    const lane = t.closest('.lane');
    addSegFromSel(lane.dataset.file, lane.dataset.speaker);
  } else if (t.dataset && t.dataset.addspk) {
    addSpeaker(t.dataset.addspk);
  }
});

/* ---------- save ---------- */

async function save(which) {
  const f = meta.files[which];
  $('savemsg').textContent = '保存中…';
  try {
    const r = await fetch('/api/save', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({which, index: meta.index, segments: f.segments.map(
          ({start, end, speaker}) => ({start, end, speaker}))}),
    });
    if (!r.ok) throw new Error(await r.text());
    const res = await r.json();
    dirty[which] = false;
    updateSaveBtns();
    $('savemsg').textContent = `已保存 ${res.n} 段 → ${res.path}`;
  } catch (e) {
    $('savemsg').textContent = '';
    $('err').textContent = '保存失败: ' + e;
    $('err').style.display = 'block';
  }
}
$('savegt').onclick = () => save('gt');
$('savea').onclick = () => save('a');
$('saveb').onclick = () => save('b');
window.addEventListener('beforeunload', ev => {
  if (fileKeys.some(k => dirty[k])) { ev.preventDefault(); ev.returnValue = ''; }
});

/* ---------- item navigation ---------- */

function confirmLeave() {
  if (!fileKeys.some(k => dirty[k])) return true;
  return confirm('当前条目有未保存的修改,切换后将丢失。确定切换?');
}

async function loadItem(idx) {
  if (meta && (idx < 0 || idx >= meta.n_items)) return;
  if (meta && idx === meta.index) return;
  if (meta && !confirmLeave()) {
    $('itemidx').value = meta.index;
    return;
  }
  $('err').style.display = 'none';
  let m;
  try {
    const r = await fetch('/api/meta/' + idx);
    if (!r.ok) throw new Error(await r.text());
    m = await r.json();
  } catch (e) {
    $('err').textContent = '加载失败: ' + e;
    $('err').style.display = 'block';
    return;
  }
  // reset all per-item state
  meta = {index: m.index, n_items: m.n_items, dataset: m.dataset, id: m.id,
          audio_file: m.audio_file, duration: m.duration, files: m.files};
  fileKeys = ALL_KEYS.filter(k => meta.files[k]);
  nextId = 1;
  undoStack = {}; redoStack = {}; dirty = {};
  for (const file of fileKeys) {
    const f = meta.files[file];
    f.extraSpeakers = new Set();
    f.segments.forEach(s => { s.id = nextId++; });
    undoStack[file] = []; redoStack[file] = []; dirty[file] = false;
  }
  const prevPair = diffPair;
  diffPair = prevPair && fileKeys.includes(prevPair[0]) &&
             fileKeys.includes(prevPair[1])
      ? prevPair : pairCombos()[0];
  selected = null;
  dur = meta.duration;
  clearSel();
  $('savemsg').textContent = '';
  audio.src = '/api/audio/' + idx;
  $('itemidx').value = idx;
  $('itemidx').max = meta.n_items - 1;
  $('itemcount').textContent = '/ ' + (meta.n_items - 1);
  $('previtem').disabled = idx === 0;
  $('nextitem').disabled = idx === meta.n_items - 1;
  $('fname').textContent = `${meta.dataset} / ${meta.audio_file}` +
      fileKeys.map(k => ` · ${NAME[k]}=${meta.files[k].rttm_file}`).join('');
  document.title = `批量多 RTTM 对比 – ${meta.dataset}/${meta.id}`;
  computeMapping();
  updateDiffPairSelect();
  computeDiff();
  render();
  refreshEditbar();
}

$('previtem').onclick = () => loadItem(meta.index - 1);
$('nextitem').onclick = () => loadItem(meta.index + 1);
$('itemidx').onchange = () => loadItem(parseInt($('itemidx').value || 0));

/* ---------- top-level controls & keys ---------- */

$('zoom').oninput = () => {
  zoomFactor = Math.pow(2, $('zoom').value / 12.5);  // 1x .. 256x
  $('zoomval').textContent = zoomFactor < 10 ?
      zoomFactor.toFixed(1)+'×' : Math.round(zoomFactor)+'×';
  render();
};
$('playsel').onclick = playSel;
$('clearsel').onclick = clearSel;
$('applysel').onclick = applyManualSel;
$('mindiff').oninput = () => render();
$('diffpair').onchange = () => {
  diffPair = $('diffpair').value.split('|');
  computeDiff();
  render();
};
$('remap').onclick = () => { computeMapping(); computeDiff(); render(); };
$('ebapply').onclick = applyEditbar;
$('ebplay').onclick = () => {
  if (!selected) return;
  const s = findSeg(selected.file, selected.id);
  if (s) { setSel(s.start, s.end); playSel(); }
};
$('ebsplit').onclick = splitSelected;
$('ebdel').onclick = deleteSelected;
$('ebclose').onclick = deselectSeg;
['selstart', 'selend'].forEach(id => $(id).addEventListener('keydown',
  ev => { if (ev.key === 'Enter') applyManualSel(); }));
['ebspk', 'ebstart', 'ebend'].forEach(id => $(id).addEventListener('keydown',
  ev => { if (ev.key === 'Enter') applyEditbar(); }));

document.addEventListener('keydown', ev => {
  const typing = ev.target.tagName === 'INPUT' &&
                 ev.target.type !== 'checkbox' &&
                 ev.target.type !== 'range';
  if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 'z') {
    ev.preventDefault();
    const f = lastEditedFile() ||
        fileKeys.find(k => undoStack[k] && undoStack[k].length) || null;
    if (f) ev.shiftKey ? redo(f) : undo(f);
    return;
  }
  if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 'y') {
    ev.preventDefault();
    const f = lastEditedFile() ||
        fileKeys.find(k => redoStack[k] && redoStack[k].length) || null;
    if (f) redo(f);
    return;
  }
  if (ev.key === 'PageUp') { ev.preventDefault(); loadItem(meta.index - 1); return; }
  if (ev.key === 'PageDown') { ev.preventDefault(); loadItem(meta.index + 1); return; }
  if (typing) return;
  const jump = ev.shiftKey ? 0.5 : 5;
  if (ev.key === 'ArrowLeft')
    audio.currentTime = Math.max(0, audio.currentTime - jump);
  else if (ev.key === 'ArrowRight')
    audio.currentTime = Math.min(dur, audio.currentTime + jump);
  else if (ev.key === 'Escape') selected ? deselectSeg() : clearSel();
  else if (ev.key === 'Delete' || ev.key === 'Backspace') deleteSelected();
  else if (ev.key.toLowerCase() === 's') splitSelected();
  else if (ev.key === ' ') { ev.preventDefault();
    audio.paused ? audio.play() : audio.pause(); }
});
window.addEventListener('resize', render);

// non-WAV audio: the server may only estimate the duration from the last
// segment end, so refine it once the browser has decoded the metadata
audio.addEventListener('loadedmetadata', () => {
  if (isFinite(audio.duration) && Math.abs(audio.duration - dur) > 0.05) {
    dur = audio.duration;
    render();
  }
});

loadItem(0);
</script>
</body>
</html>
"""


class Handler(BaseHTTPRequestHandler):
    store = None

    def log_message(self, *args):
        pass

    def _send(self, code, body, ctype="application/json", extra=None):
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        for k, v in (extra or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        try:
            self._route()
        except BrokenPipeError:
            pass
        except IndexError:
            self._send(404, b"item index out of range", "text/plain")
        except Exception as e:  # surface errors to the page
            self._send(500, str(e).encode(), "text/plain; charset=utf-8")

    def do_POST(self):
        try:
            if self.path == "/api/save":
                length = int(self.headers.get("Content-Length", 0))
                payload = json.loads(self.rfile.read(length))
                path, n = self.store.save(int(payload["index"]),
                                          payload["which"],
                                          payload["segments"])
                self._send(200, json.dumps({"path": path, "n": n}).encode())
            else:
                self._send(404, b"not found", "text/plain")
        except BrokenPipeError:
            pass
        except Exception as e:
            self._send(500, str(e).encode(), "text/plain; charset=utf-8")

    def _route(self):
        if self.path in ("/", "/index.html"):
            self._send(200, PAGE.encode(), "text/html; charset=utf-8")
        elif m := re.fullmatch(r"/api/meta/(\d+)", self.path):
            self._send(200, json.dumps(self.store.meta(int(m.group(1)))).encode())
        elif m := re.fullmatch(r"/api/audio/(\d+)", self.path):
            data, ctype, _ = self.store.audio(int(m.group(1)))
            self._serve_audio(data, ctype)
        else:
            self._send(404, b"not found", "text/plain")

    def _serve_audio(self, data, ctype):
        """Serve audio bytes with Range support so the player can seek."""
        rng = self.headers.get("Range")
        total = len(data)
        if rng and (m := re.fullmatch(r"bytes=(\d*)-(\d*)", rng.strip())):
            start = int(m.group(1)) if m.group(1) else 0
            end = int(m.group(2)) if m.group(2) else total - 1
            end = min(end, total - 1)
            if start > end:
                self._send(416, b"", ctype,
                           {"Content-Range": f"bytes */{total}"})
                return
            chunk = data[start:end + 1]
            self._send(206, chunk, ctype, {
                "Content-Range": f"bytes {start}-{end}/{total}",
                "Accept-Ranges": "bytes"})
        else:
            self._send(200, data, ctype, {"Accept-Ranges": "bytes"})


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("experiment_dir",
                    help="directory whose sub-dirs hold <id>.wav + <id>.rttm "
                         "+ <id>_3D.rttm [+ <id>_GT.rttm] items")
    ap.add_argument("--port", type=int, default=8766)
    ap.add_argument("--host", default="127.0.0.1")
    args = ap.parse_args()

    items = scan_items(args.experiment_dir)
    if not items:
        raise SystemExit(f"no complete items found under {args.experiment_dir}")

    n_gt = sum(1 for it in items if "gt" in it)
    Handler.store = ItemStore(items)
    srv = ThreadingHTTPServer((args.host, args.port), Handler)
    print(f"Serving {len(items)} items ({n_gt} with GT) from "
          f"{args.experiment_dir} at http://{args.host}:{args.port}")
    for i, it in enumerate(items[:10]):
        print(f"  [{i}] {it['dataset']}/{it['id']}"
              f"{'' if 'gt' in it else '  (no GT)'}")
    if len(items) > 10:
        print(f"  ... and {len(items) - 10} more")
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()