File size: 50,043 Bytes
cb8518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
#!/usr/bin/env python3


from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import pickle
import re
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable

import cv2
import numpy as np
from PIL import Image
from scipy.optimize import linear_sum_assignment


SCENE_EXTS = (".blend", ".glb", ".gltf")
IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
DEPTH_NAMES = ("depth.npy", "depth.npz", "depth.png", "depth.exr")
CAMERA_NAMES = (
    "camera.json",
    "cameras.json",
    "poses.json",
    "camera_poses.json",
    "transforms.json",
    "extrinsics.npy",
    "extrinsics.npz",
    "poses.npy",
    "poses.npz",
    "cameras.npz",
)
EPS = 1e-9
OBJECT_NAME_STOPWORDS = {
    "object",
    "geometry",
    "mesh",
    "model",
    "shape",
    "textured",
    "scene",
    "gt",
    "pred",
}


def lower_is_better_to_score(value: float, bad_value: float = 1.0) -> float:
    if bad_value <= 0:
        raise ValueError("bad_value must be > 0")
    normalized = max(0.0, min(1.0, value / bad_value))
    return 100.0 * (1.0 - normalized)


@dataclass(frozen=True)
class AssetBundle:
    key: str
    base: Path
    scene: Path
    images: tuple[Path, ...]
    text: Path | None
    depth: Path | None
    camera: Path | None
    generated_meta: Path | None


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Run full eval for one sample id across multiple models")
    p.add_argument("--sample_id", required=True)
    p.add_argument("--data_root", default="data")
    p.add_argument("--gt_key", default="gt")
    p.add_argument(
        "--models",
        required=True,
        help="Comma-separated model keys under data_root",
    )
    p.add_argument("--blender_bin", required=True)
    p.add_argument("--clip_model_path", required=True)
    p.add_argument("--clip_batch_size", type=int, default=32)
    p.add_argument("--out_json", required=True)
    p.add_argument(
        "--alignment",
        choices=["identity", "bbox", "object_bbox", "depth_bbox", "depth_camera"],
        default="bbox",
        help=(
            "Transform pred geometry into GT coordinates before IoU. "
            "object_bbox anchors on the best first-frame object IoU match; "
            "depth_camera uses depth median scale plus first-camera canonicalization."
        ),
    )
    p.add_argument(
        "--ground_policy",
        choices=["exclude", "include"],
        default="exclude",
        help=(
            "Whether to exclude detected ground/floor/large planes from bbox alignment "
            "and scene/object IoU. Use include to benchmark with ground from alignment onward."
        ),
    )
    p.add_argument(
        "--camera_convention",
        choices=["auto", "world_to_camera", "camera_to_world"],
        default="auto",
        help="Convention for camera matrices used by --alignment depth_camera.",
    )
    p.add_argument(
        "--camera_rotation_only",
        action="store_true",
        help="For --alignment depth_camera, use only first-frame camera rotation and ignore camera translation.",
    )
    p.add_argument(
        "--auto_scene_meta",
        action=argparse.BooleanOptionalAction,
        default=True,
        help="Auto-extract camera.json/depth.npy from scene.blend/glb when missing.",
    )
    p.add_argument(
        "--scene_meta_dir",
        default=None,
        help="Cache directory for auto-extracted scene camera/depth metadata.",
    )
    p.add_argument(
        "--alignment_dir",
        default=None,
        help="Directory for per-model alignment_transform.json files (default: out_json parent/alignments)",
    )
    p.add_argument(
        "--geometry_frame_mode",
        default="first_mid_last",
        help="Geometry frames used for IoU-B extraction: first_only, first_mid_last, last_only, or exact:<frame>.",
    )
    p.add_argument(
        "--image_glob",
        default="frames/*,selected_frames/*,eval_frames/*,scene.png",
        help="Comma-separated image globs relative to each asset directory",
    )
    p.add_argument(
        "--scene_filename",
        default=None,
        help="Optional fixed scene filename, e.g. scene.glb. Otherwise auto-detect scene.*",
    )
    p.add_argument(
        "--allow_missing_images",
        action="store_true",
        help="Skip PL/N-CLIP for models without selected images instead of failing",
    )
    p.add_argument(
        "--skip_selected_image_metrics",
        action="store_true",
        help="Skip selected-frame PL/N-CLIP in this stage. Useful when rendered metrics are computed later.",
    )
    args = p.parse_args()
    _validate_frame_mode(args.geometry_frame_mode)
    return args


def _validate_frame_mode(mode: str) -> None:
    if mode in {"first_only", "first_mid_last", "last_only"}:
        return
    if mode.startswith("exact:"):
        raw = mode.split(":", 1)[1].strip()
        if raw and raw.lstrip("-").isdigit():
            return
    raise ValueError(
        f"Unsupported --geometry_frame_mode {mode!r}; expected first_only, "
        "first_mid_last, last_only, or exact:<frame>."
    )


def _project_root() -> Path:
    return Path(__file__).resolve().parents[1]


def _resolve_data_root(project_root: Path, raw: str) -> Path:
    path = Path(raw)
    if path.is_absolute():
        return path
    return (project_root / path).resolve()


def _first_existing(paths: Iterable[Path]) -> Path | None:
    for path in paths:
        if path.exists():
            return path
    return None


def _find_scene(base: Path, scene_filename: str | None) -> Path:
    if scene_filename:
        scene = base / scene_filename
        if scene.exists():
            return scene
        raise FileNotFoundError(f"Missing scene asset: {scene}")

    for ext in SCENE_EXTS:
        scene = base / f"scene{ext}"
        if scene.exists():
            return scene

    candidates: list[Path] = []
    for ext in SCENE_EXTS:
        candidates.extend(sorted(base.glob(f"*{ext}")))
    if candidates:
        return candidates[0]
    raise FileNotFoundError(f"No scene asset found under {base} ({', '.join(SCENE_EXTS)})")


def _find_images(base: Path, image_glob: str) -> tuple[Path, ...]:
    out: list[Path] = []
    seen: set[Path] = set()
    patterns = [x.strip() for x in image_glob.split(",") if x.strip()]
    for pattern in patterns:
        for path in sorted(base.glob(pattern)):
            if not path.is_file():
                continue
            if path.suffix.lower() not in IMAGE_EXTS:
                continue
            resolved = path.resolve()
            if resolved in seen:
                continue
            seen.add(resolved)
            out.append(resolved)
    return tuple(out)


def _find_depth(base: Path) -> Path | None:
    direct = _first_existing(base / name for name in DEPTH_NAMES)
    if direct is not None:
        return direct
    depth_dir = base / "depth"
    if depth_dir.is_dir():
        for ext in (".npy", ".npz", ".png", ".exr"):
            cands = sorted(depth_dir.glob(f"*{ext}"))
            if cands:
                return cands[0]
    return None


def _find_camera(base: Path) -> Path | None:
    direct = _first_existing(base / name for name in CAMERA_NAMES)
    if direct is not None:
        return direct
    camera_dir = base / "camera"
    if camera_dir.is_dir():
        for name in CAMERA_NAMES:
            candidate = camera_dir / name
            if candidate.exists():
                return candidate
        for pattern in ("*.json", "*.npy", "*.npz", "*.txt"):
            cands = sorted(camera_dir.glob(pattern))
            if cands:
                return cands[0]
    cameras_dir = base / "cameras"
    if cameras_dir.is_dir():
        for pattern in ("*.json", "*.npy", "*.npz", "*.txt"):
            cands = sorted(cameras_dir.glob(pattern))
            if cands:
                return cands[0]
    return None


def _scene_meta_script_path(project_root: Path) -> Path:
    script = project_root / "scripts" / "extract_scene_camera_depth.py"
    if not script.exists():
        raise FileNotFoundError(f"Missing scene meta extraction script: {script}")
    return script


def _scene_meta_cache_dir(root: Path, asset: AssetBundle) -> Path:
    stat = asset.scene.stat()
    key = f"{asset.scene.resolve()}::{stat.st_mtime_ns}::scene_meta_v1"
    digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:12]
    return root / asset.key / asset.scene.stem / digest


def ensure_scene_meta(
    asset: AssetBundle,
    *,
    project_root: Path,
    blender_bin: str,
    scene_meta_dir: Path,
    force: bool = False,
) -> AssetBundle:
    if asset.depth is not None and asset.camera is not None:
        return asset

    out_dir = _scene_meta_cache_dir(scene_meta_dir, asset)
    camera_path = out_dir / "camera.json"
    depth_path = out_dir / "depth.npy"
    if force or not camera_path.exists() or not depth_path.exists():
        out_dir.mkdir(parents=True, exist_ok=True)
        cmd = [
            blender_bin,
            "--factory-startup",
            "--background",
            "--python",
            str(_scene_meta_script_path(project_root)),
            "--",
            "--input",
            str(asset.scene),
            "--output_dir",
            str(out_dir),
        ]
        proc = subprocess.run(cmd, capture_output=True, text=True)
        if proc.returncode != 0 or not camera_path.exists() or not depth_path.exists():
            raise RuntimeError(
                "Scene camera/depth metadata extraction failed\n"
                f"scene={asset.scene}\n"
                f"code={proc.returncode}\n"
                f"stdout_tail={proc.stdout[-1000:]}\n"
                f"stderr_tail={proc.stderr[-1000:]}"
            )

    return AssetBundle(
        key=asset.key,
        base=asset.base,
        scene=asset.scene,
        images=asset.images,
        text=asset.text,
        depth=asset.depth or depth_path,
        camera=asset.camera or camera_path,
        generated_meta=out_dir,
    )


def load_assets(
    data_root: Path,
    model_key: str,
    sample_id: str,
    *,
    image_glob: str,
    scene_filename: str | None,
) -> AssetBundle:
    base = data_root / model_key / sample_id
    scene = _find_scene(base, scene_filename)
    text = _first_existing([base / "description.txt", base / "prompt.txt", base / "text.txt"])
    return AssetBundle(
        key=model_key,
        base=base,
        scene=scene.resolve(),
        images=_find_images(base, image_glob),
        text=text.resolve() if text is not None else None,
        depth=_find_depth(base),
        camera=_find_camera(base),
        generated_meta=None,
    )


def import_bbox_helpers(project_root: Path):
    bbox_script = project_root / "scripts" / "eval_bbox_iou_blend.py"
    spec = importlib.util.spec_from_file_location("eval_bbox_iou_blend", bbox_script)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to import {bbox_script}")
    mod = importlib.util.module_from_spec(spec)
    import sys

    sys.modules[spec.name] = mod
    spec.loader.exec_module(mod)
    return mod


def run_extract(
    blender_bin: str,
    extract_script: Path,
    scene_path: Path,
    out_path: Path,
    *,
    frame_mode: str,
) -> None:
    cmd = [
        blender_bin,
        "--factory-startup",
        "--background",
        "--python",
        str(extract_script),
        "--",
        "--input",
        str(scene_path),
        "--output",
        str(out_path),
        "--frame_mode",
        frame_mode,
    ]
    proc = subprocess.run(cmd, capture_output=True, text=True)
    if proc.returncode != 0 or not out_path.exists():
        raise RuntimeError(
            "Scene extraction failed\n"
            f"scene={scene_path}\n"
            f"code={proc.returncode}\n"
            f"stdout_tail={proc.stdout[-1000:]}\n"
            f"stderr_tail={proc.stderr[-1000:]}"
        )


def _load_payload(
    scene_path: Path,
    *,
    blender_bin: str,
    extract_script: Path,
    frame_mode: str,
    payload_cache: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    k = f"{scene_path.resolve()}::{frame_mode}"
    if k in payload_cache:
        return payload_cache[k]
    with tempfile.TemporaryDirectory(prefix="big_eval_extract_") as td:
        p = Path(td) / "mesh.pkl"
        run_extract(blender_bin, extract_script, scene_path, p, frame_mode=frame_mode)
        payload = pickle.loads(p.read_bytes())
        payload_cache[k] = payload
        return payload


def _aligned_indices(total: int, target: int) -> list[int]:
    if total <= 0 or target <= 0:
        return []
    if target >= total:
        return list(range(total))
    return np.linspace(0, total - 1, num=target, dtype=int).tolist()


def _stack_frame_vertices(bbox_mod: Any, frame: dict[str, Any]) -> np.ndarray:
    return bbox_mod._stack_vertices(bbox_mod._to_mesh_map(frame))


_GROUND_NAME_TOKENS = ("ground", "floor", "plane", "table_plane", "backdrop", "wall")


def _is_ground_object(name: str, vertices: np.ndarray, scene_diag: float) -> bool:
    low = name.lower()
    if any(tok in low for tok in _GROUND_NAME_TOKENS):
        return True
    if vertices.size == 0:
        return False
    ext = vertices.max(axis=0) - vertices.min(axis=0)
    xy = float(np.hypot(ext[0], ext[1]))
    z = float(ext[2])

    if scene_diag > 0 and xy >= 0.55 * scene_diag and z <= 0.06 * max(xy, EPS):
        return True
    return False


def _stack_frame_vertices_no_ground(bbox_mod: Any, frame: dict[str, Any]) -> np.ndarray:
    mesh_map = bbox_mod._to_mesh_map(frame)
    full = bbox_mod._stack_vertices(mesh_map)
    if full.size == 0:
        return full
    scene_diag = float(np.linalg.norm(full.max(axis=0) - full.min(axis=0)))
    kept = {
        name: md
        for name, md in mesh_map.items()
        if not _is_ground_object(name, md.vertices, scene_diag)
    }
    if not kept:
        return full
    stacked = bbox_mod._stack_vertices(kept)
    return stacked if stacked.size else full


def _drop_ground_from_map(mesh_map: dict[str, Any]) -> dict[str, Any]:
    if not mesh_map:
        return mesh_map
    full = _stack_mesh_map_safe(mesh_map)
    scene_diag = float(np.linalg.norm(full.max(axis=0) - full.min(axis=0))) if full.size else 0.0
    kept = {
        name: md
        for name, md in mesh_map.items()
        if not _is_ground_object(name, md.vertices, scene_diag)
    }
    return kept if kept else mesh_map


def _stack_mesh_map_safe(mesh_map: dict[str, Any]) -> np.ndarray:
    chunks = [md.vertices for md in mesh_map.values() if getattr(md, "vertices", None) is not None and md.vertices.size]
    if not chunks:
        return np.zeros((0, 3), dtype=np.float64)
    return np.concatenate(chunks, axis=0)


def _aabb_bounds(vertices: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None:
    if vertices.size == 0:
        return None
    return np.min(vertices, axis=0), np.max(vertices, axis=0)


def _center(bounds: tuple[np.ndarray, np.ndarray] | None) -> np.ndarray:
    if bounds is None:
        return np.zeros(3, dtype=np.float64)
    return 0.5 * (bounds[0] + bounds[1])


def _diag(bounds: tuple[np.ndarray, np.ndarray] | None) -> float:
    if bounds is None:
        return 1.0
    return float(np.linalg.norm(bounds[1] - bounds[0]))


def _first_frame_mesh_map(bbox_mod: Any, payload: dict[str, Any]) -> dict[str, Any]:
    frame = payload["objects_per_frame"][0] if payload.get("objects_per_frame") else {}
    return bbox_mod._to_mesh_map(frame)


def _name_tokens(name: str) -> set[str]:
    tokens = set(re.findall(r"[a-zA-Z]+", name.lower()))
    return {tok for tok in tokens if tok not in OBJECT_NAME_STOPWORDS and len(tok) > 1}


def _best_object_anchor_bounds(
    bbox_mod: Any,
    gt_payload: dict[str, Any],
    pred_payload: dict[str, Any],
) -> tuple[tuple[np.ndarray, np.ndarray] | None, tuple[np.ndarray, np.ndarray] | None, dict[str, Any] | None]:
    gt_map = _first_frame_mesh_map(bbox_mod, gt_payload)
    pred_map = _first_frame_mesh_map(bbox_mod, pred_payload)
    best: tuple[tuple[int, float], str, str, float, tuple[np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]] | None = None
    for gt_name, gt_mesh in gt_map.items():
        gt_bounds = _aabb_bounds(gt_mesh.vertices)
        if gt_bounds is None:
            continue
        gt_tokens = _name_tokens(gt_name)
        for pred_name, pred_mesh in pred_map.items():
            pred_bounds = _aabb_bounds(pred_mesh.vertices)
            if pred_bounds is None:
                continue
            aabb, obb = _bbox_iou_for_meshes(bbox_mod, gt_mesh.vertices, pred_mesh.vertices)
            token_overlap = len(gt_tokens & _name_tokens(pred_name))
            score = (token_overlap, float(aabb))
            if best is None or score > best[0]:
                best = (score, gt_name, pred_name, float(obb), gt_bounds, pred_bounds)
    if best is None:
        return None, None, None
    score, gt_name, pred_name, obb, gt_bounds, pred_bounds = best
    return gt_bounds, pred_bounds, {
        "gt_name": gt_name,
        "pred_name": pred_name,
        "name_token_overlap": score[0],
        "first_frame_aabb_iou_before_alignment": score[1],
        "first_frame_obb_iou_before_alignment": obb,
    }


def _read_depth_values(depth_path: Path | None) -> np.ndarray:
    if depth_path is None or not depth_path.exists():
        return np.zeros((0,), dtype=np.float64)
    ext = depth_path.suffix.lower()
    if ext == ".npy":
        arr = np.load(depth_path)
    elif ext == ".npz":
        data = np.load(depth_path)
        key = "depth" if "depth" in data else data.files[0]
        arr = data[key]
    else:
        arr = cv2.imread(str(depth_path), cv2.IMREAD_UNCHANGED)
        if arr is None:
            return np.zeros((0,), dtype=np.float64)
        if arr.dtype == np.uint16:
            arr = arr.astype(np.float32) / 1000.0
    arr = np.asarray(arr, dtype=np.float64)
    vals = arr[np.isfinite(arr) & (arr > 1e-8)]
    return vals.reshape(-1)


def _depth_median(depth_path: Path | None) -> float | None:
    vals = _read_depth_values(depth_path)
    if vals.size == 0:
        return None
    return float(np.median(vals))


def _as_4x4(matrix_like: Any) -> np.ndarray | None:
    arr = np.asarray(matrix_like, dtype=np.float64)
    if arr.shape == (4, 4):
        return arr
    if arr.shape == (3, 4):
        out = np.eye(4, dtype=np.float64)
        out[:3, :4] = arr
        return out
    if arr.ndim == 3 and arr.shape[-2:] == (4, 4) and arr.shape[0] > 0:
        return arr[0]
    if arr.ndim == 3 and arr.shape[-2:] == (3, 4) and arr.shape[0] > 0:
        out = np.eye(4, dtype=np.float64)
        out[:3, :4] = arr[0]
        return out
    return None


def _matrix_from_json_obj(obj: Any) -> tuple[np.ndarray | None, str | None]:
    if isinstance(obj, list):
        matrix = _as_4x4(obj)
        if matrix is not None:
            return matrix, None
        if obj:
            return _matrix_from_json_obj(obj[0])

    if not isinstance(obj, dict):
        return None, None

    for key in ("world_to_camera", "w2c", "extrinsic", "extrinsics", "T_world_to_camera"):
        if key in obj:
            matrix = _as_4x4(obj[key])
            if matrix is not None:
                return matrix, "world_to_camera"

    for key in ("camera_to_world", "c2w", "pose", "poses", "transform_matrix", "T_camera_to_world"):
        if key in obj:
            matrix = _as_4x4(obj[key])
            if matrix is not None:
                return matrix, "camera_to_world"

    for key in ("frames", "cameras"):
        value = obj.get(key)
        if isinstance(value, list) and value:
            return _matrix_from_json_obj(value[0])

    numeric_values = [v for v in obj.values() if isinstance(v, (list, tuple, dict))]
    for value in numeric_values:
        matrix, convention = _matrix_from_json_obj(value)
        if matrix is not None:
            return matrix, convention

    return None, None


def _load_camera_matrix(camera_path: Path | None) -> tuple[np.ndarray | None, str | None]:
    if camera_path is None or not camera_path.exists():
        return None, None

    ext = camera_path.suffix.lower()
    if ext == ".json":
        data = json.loads(camera_path.read_text(encoding="utf-8"))
        return _matrix_from_json_obj(data)
    if ext == ".npy":
        return _as_4x4(np.load(camera_path)), None
    if ext == ".npz":
        data = np.load(camera_path)
        priority = (
            "world_to_camera",
            "w2c",
            "extrinsics",
            "extrinsic",
            "camera_to_world",
            "c2w",
            "poses",
            "pose",
        )
        for key in priority:
            if key in data:
                matrix = _as_4x4(data[key])
                if matrix is not None:
                    if key in {"world_to_camera", "w2c", "extrinsics", "extrinsic"}:
                        return matrix, "world_to_camera"
                    if key in {"camera_to_world", "c2w", "poses", "pose"}:
                        return matrix, "camera_to_world"
        for key in data.files:
            matrix = _as_4x4(data[key])
            if matrix is not None:
                return matrix, None
    if ext == ".txt":
        arr = np.loadtxt(camera_path)
        return _as_4x4(arr), None
    return None, None


def _orthonormalize_rotation(rot: np.ndarray) -> np.ndarray:
    u, _, vt = np.linalg.svd(rot)
    out = u @ vt
    if np.linalg.det(out) < 0:
        u[:, -1] *= -1.0
        out = u @ vt
    return out


def _camera_world_to_camera(
    camera_path: Path | None,
    *,
    convention: str,
) -> tuple[np.ndarray | None, str | None]:
    matrix, inferred = _load_camera_matrix(camera_path)
    if matrix is None:
        return None, None

    use_convention = inferred if convention == "auto" else convention
    if use_convention is None:
        use_convention = "world_to_camera"

    matrix = np.asarray(matrix, dtype=np.float64)
    if use_convention == "camera_to_world":
        matrix = np.linalg.inv(matrix)
    elif use_convention != "world_to_camera":
        raise ValueError(f"Unsupported camera convention: {use_convention}")

    matrix[:3, :3] = _orthonormalize_rotation(matrix[:3, :3])
    return matrix, use_convention


def _camera_canonical_matrix(
    camera_path: Path | None,
    *,
    convention: str,
    rotation_only: bool,
) -> tuple[np.ndarray | None, str | None]:
    w2c, used_convention = _camera_world_to_camera(camera_path, convention=convention)
    if w2c is None:
        return None, None
    matrix = np.eye(4, dtype=np.float64)
    matrix[:3, :3] = w2c[:3, :3]
    if not rotation_only:
        matrix[:3, 3] = w2c[:3, 3]
    return matrix, used_convention


def _compose_similarity(
    canonical: np.ndarray,
    scale: float,
    *,
    center_after: np.ndarray | None = None,
) -> np.ndarray:
    matrix = canonical.copy()
    matrix[:3, :3] *= float(scale)
    matrix[:3, 3] *= float(scale)
    if center_after is not None:
        matrix[:3, 3] += center_after
    return matrix


def build_alignment_transform(
    gt_payload: dict[str, Any],
    pred_payload: dict[str, Any],
    *,
    gt_depth: Path | None,
    pred_depth: Path | None,
    gt_camera: Path | None = None,
    pred_camera: Path | None = None,
    mode: str,
    bbox_mod: Any,
    camera_convention: str = "auto",
    camera_rotation_only: bool = False,
    ground_policy: str = "exclude",
) -> dict[str, Any]:
    gt_frame = gt_payload["objects_per_frame"][0] if gt_payload["objects_per_frame"] else {}
    pred_frame = pred_payload["objects_per_frame"][0] if pred_payload["objects_per_frame"] else {}
    gt_vertices = _stack_frame_vertices(bbox_mod, gt_frame)
    pred_vertices = _stack_frame_vertices(bbox_mod, pred_frame)
    gt_bounds = _aabb_bounds(gt_vertices)
    pred_bounds = _aabb_bounds(pred_vertices)

    scale = 1.0
    scale_source = "identity"
    gt_matrix = np.eye(4, dtype=np.float64)
    pred_matrix = np.eye(4, dtype=np.float64)
    gt_camera_convention = None
    pred_camera_convention = None
    uses_camera = False
    alignment_anchor: dict[str, Any] | None = None

    if mode == "bbox":
        if ground_policy == "exclude":


            gt_align_bounds = _aabb_bounds(_stack_frame_vertices_no_ground(bbox_mod, gt_frame))
            pred_align_bounds = _aabb_bounds(_stack_frame_vertices_no_ground(bbox_mod, pred_frame))
            if gt_align_bounds is not None:
                gt_bounds = gt_align_bounds
            if pred_align_bounds is not None:
                pred_bounds = pred_align_bounds
            scale_source = "scene_bbox_diag_no_ground"
        else:
            scale_source = "scene_bbox_diag_with_ground"
        scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS)
    elif mode == "object_bbox":
        anchor_gt_bounds, anchor_pred_bounds, alignment_anchor = _best_object_anchor_bounds(
            bbox_mod,
            gt_payload,
            pred_payload,
        )
        if anchor_gt_bounds is not None and anchor_pred_bounds is not None:
            gt_bounds = anchor_gt_bounds
            pred_bounds = anchor_pred_bounds
            scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS)
            scale_source = "best_object_bbox_diag"
        else:
            scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS)
            scale_source = "scene_bbox_diag_fallback_no_object_anchor"
    elif mode == "depth_bbox":
        gt_med = _depth_median(gt_depth)
        pred_med = _depth_median(pred_depth)
        if gt_med is not None and pred_med is not None:
            scale = gt_med / max(pred_med, EPS)
            scale_source = "depth_median_ratio"
        else:
            scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS)
            scale_source = "scene_bbox_diag_fallback"
    elif mode == "identity":
        scale = 1.0
    elif mode == "depth_camera":
        gt_med = _depth_median(gt_depth)
        pred_med = _depth_median(pred_depth)
        if gt_med is not None and pred_med is not None:
            scale = gt_med / max(pred_med, EPS)
            scale_source = "depth_median_ratio"
        else:
            scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS)
            scale_source = "scene_bbox_diag_fallback_no_depth"

        gt_canon, gt_camera_convention = _camera_canonical_matrix(
            gt_camera,
            convention=camera_convention,
            rotation_only=camera_rotation_only,
        )
        pred_canon, pred_camera_convention = _camera_canonical_matrix(
            pred_camera,
            convention=camera_convention,
            rotation_only=camera_rotation_only,
        )
        if gt_canon is None or pred_canon is None:
            raise FileNotFoundError(
                "depth_camera alignment requires readable first-frame camera matrices for both GT and Pred. "
                f"gt_camera={gt_camera} pred_camera={pred_camera}"
            )




        gt_matrix = gt_canon
        pred_matrix = _compose_similarity(pred_canon, scale)
        uses_camera = True
    else:
        raise ValueError(f"Unsupported alignment mode: {mode}")

    if not uses_camera:
        gt_center = _center(gt_bounds)
        pred_center = _center(pred_bounds)
        translation = gt_center - scale * pred_center
        pred_matrix = np.eye(4, dtype=np.float64)
        pred_matrix[:3, :3] *= scale
        pred_matrix[:3, 3] = translation
        if mode == "identity":
            pred_matrix[:3, 3] = 0.0

    return {
        "mode": mode,
        "transform_direction": "gt_to_eval_and_pred_to_eval",
        "matrix": pred_matrix.tolist(),
        "gt_matrix": gt_matrix.tolist(),
        "pred_matrix": pred_matrix.tolist(),
        "scale": float(scale),
        "translation": pred_matrix[:3, 3].astype(float).tolist(),
        "rotation": pred_matrix[:3, :3].astype(float).tolist(),
        "scale_source": scale_source,
        "gt_depth": str(gt_depth) if gt_depth else None,
        "pred_depth": str(pred_depth) if pred_depth else None,
        "gt_camera": str(gt_camera) if gt_camera else None,
        "pred_camera": str(pred_camera) if pred_camera else None,
        "camera_convention": camera_convention,
        "gt_camera_convention_used": gt_camera_convention,
        "pred_camera_convention_used": pred_camera_convention,
        "camera_rotation_only": bool(camera_rotation_only),
        "ground_policy": ground_policy,
        "alignment_anchor": alignment_anchor,
        "note": (
            "This transform is generated before geometry metrics. depth_camera maps "
            "GT and Pred into first-camera canonical coordinates and applies depth "
            "median scale to Pred; bbox/depth_bbox/object_bbox keep pred-to-GT "
            "uniform scale + translation behavior."
        ),
    }


def _transform_vertices(vertices: np.ndarray, matrix: np.ndarray) -> np.ndarray:
    if vertices.size == 0:
        return vertices.astype(np.float64, copy=False)
    rot_scale = matrix[:3, :3]
    trans = matrix[:3, 3]
    return (vertices.astype(np.float64) @ rot_scale.T + trans).astype(np.float64, copy=False)


def _transformed_mesh_map(bbox_mod: Any, raw_frame: dict[str, Any], matrix: np.ndarray) -> dict[str, Any]:
    mesh_map = bbox_mod._to_mesh_map(raw_frame)
    for mesh in mesh_map.values():
        mesh.vertices = _transform_vertices(mesh.vertices, matrix)
    return mesh_map


def _bbox_iou_for_meshes(bbox_mod: Any, gt_vertices: np.ndarray, pred_vertices: np.ndarray) -> tuple[float, float]:
    aabb = bbox_mod._aabb_iou(
        bbox_mod._aabb_from_vertices(gt_vertices),
        bbox_mod._aabb_from_vertices(pred_vertices),
    )
    obb = bbox_mod._obb_iou(
        bbox_mod._obb_from_vertices(gt_vertices),
        bbox_mod._obb_from_vertices(pred_vertices),
    )
    return float(aabb), float(obb)


def _match_objects_by_iou(
    bbox_mod: Any,
    gt_map: dict[str, Any],
    pred_map: dict[str, Any],
) -> dict[str, Any]:
    gt_names = sorted(gt_map.keys())
    pred_names = sorted(pred_map.keys())
    if not gt_names and not pred_names:
        return {
            "aabb_penalized": 1.0,
            "obb_penalized": 1.0,
            "aabb_matched_mean": 1.0,
            "obb_matched_mean": 1.0,
            "matches": [],
            "unmatched_gt": [],
            "unmatched_pred": [],
        }
    if not gt_names or not pred_names:
        return {
            "aabb_penalized": 0.0,
            "obb_penalized": 0.0,
            "aabb_matched_mean": 0.0,
            "obb_matched_mean": 0.0,
            "matches": [],
            "unmatched_gt": gt_names,
            "unmatched_pred": pred_names,
        }

    aabb_matrix = np.zeros((len(gt_names), len(pred_names)), dtype=np.float64)
    obb_matrix = np.zeros_like(aabb_matrix)
    for gi, gt_name in enumerate(gt_names):
        for pi, pred_name in enumerate(pred_names):
            aabb, obb = _bbox_iou_for_meshes(
                bbox_mod,
                gt_map[gt_name].vertices,
                pred_map[pred_name].vertices,
            )
            aabb_matrix[gi, pi] = aabb
            obb_matrix[gi, pi] = obb

    rows, cols = linear_sum_assignment(-aabb_matrix)
    matches: list[dict[str, Any]] = []
    matched_aabb: list[float] = []
    matched_obb: list[float] = []
    used_gt: set[str] = set()
    used_pred: set[str] = set()
    for row, col in zip(rows, cols):
        aabb = float(aabb_matrix[row, col])
        obb = float(obb_matrix[row, col])
        if aabb <= 0.0 and obb <= 0.0:
            continue
        gt_name = gt_names[row]
        pred_name = pred_names[col]
        used_gt.add(gt_name)
        used_pred.add(pred_name)
        matched_aabb.append(aabb)
        matched_obb.append(obb)
        matches.append(
            {
                "gt_name": gt_name,
                "pred_name": pred_name,
                "aabb_iou": aabb,
                "obb_iou": obb,
            }
        )

    denom = max(len(gt_names), len(pred_names), 1)
    return {
        "aabb_penalized": float(np.sum(matched_aabb) / denom),
        "obb_penalized": float(np.sum(matched_obb) / denom),
        "aabb_matched_mean": float(np.mean(matched_aabb)) if matched_aabb else 0.0,
        "obb_matched_mean": float(np.mean(matched_obb)) if matched_obb else 0.0,
        "matches": matches,
        "unmatched_gt": sorted(set(gt_names) - used_gt),
        "unmatched_pred": sorted(set(pred_names) - used_pred),
    }


def ioub_aligned(
    bbox_mod: Any,
    gt_payload: dict[str, Any],
    pred_payload: dict[str, Any],
    transform: dict[str, Any],
    *,
    ground_policy: str = "exclude",
) -> dict[str, Any]:
    gt_frames = gt_payload["objects_per_frame"]
    pred_frames = pred_payload["objects_per_frame"]
    target = min(len(gt_frames), len(pred_frames))
    gt_idx = _aligned_indices(len(gt_frames), target)
    pred_idx = _aligned_indices(len(pred_frames), target)
    gt_matrix = np.asarray(transform.get("gt_matrix", np.eye(4)), dtype=np.float64)
    pred_matrix = np.asarray(transform.get("pred_matrix", transform["matrix"]), dtype=np.float64)

    scene_aabb_frames: list[float] = []
    scene_obb_frames: list[float] = []
    obj_aabb_pen_frames: list[float] = []
    obj_obb_pen_frames: list[float] = []
    frame_details: list[dict[str, Any]] = []

    for gi, pi in zip(gt_idx, pred_idx):
        gt_map = _transformed_mesh_map(bbox_mod, gt_frames[gi], gt_matrix)
        pred_map = _transformed_mesh_map(bbox_mod, pred_frames[pi], pred_matrix)

        if ground_policy == "exclude":


            gt_map = _drop_ground_from_map(gt_map)
            pred_map = _drop_ground_from_map(pred_map)

        gt_scene_vertices = bbox_mod._stack_vertices(gt_map)
        pred_scene_vertices = bbox_mod._stack_vertices(pred_map)
        scene_aabb, scene_obb = _bbox_iou_for_meshes(bbox_mod, gt_scene_vertices, pred_scene_vertices)
        scene_aabb_frames.append(scene_aabb)
        scene_obb_frames.append(scene_obb)

        obj_match = _match_objects_by_iou(bbox_mod, gt_map, pred_map)
        obj_aabb_pen_frames.append(float(obj_match["aabb_penalized"]))
        obj_obb_pen_frames.append(float(obj_match["obb_penalized"]))

        frame_details.append(
            {
                "gt_frame_no": int(gt_payload["frame_indices"][gi]),
                "pred_frame_no": int(pred_payload["frame_indices"][pi]),
                "scene_aabb_iou": scene_aabb,
                "scene_obb_iou": scene_obb,
                "gt_object_count": len(gt_map),
                "pred_object_count": len(pred_map),
                "matched_object_count": len(obj_match["matches"]),
                "object_match_mode": "hungarian_aabb_iou",
                "ground_policy": ground_policy,
                "object_aabb_iou_penalized": obj_match["aabb_penalized"],
                "object_obb_iou_penalized": obj_match["obb_penalized"],
                "matched_object_mean_aabb": obj_match["aabb_matched_mean"],
                "matched_object_mean_obb": obj_match["obb_matched_mean"],
                "unmatched_gt": obj_match["unmatched_gt"],
                "unmatched_pred": obj_match["unmatched_pred"],
                "per_object_matched": obj_match["matches"],
            }
        )

    return {
        "scene_aabb_iou_frames": scene_aabb_frames,
        "scene_obb_iou_frames": scene_obb_frames,
        "object_aabb_iou_penalized_frames": obj_aabb_pen_frames,
        "object_obb_iou_penalized_frames": obj_obb_pen_frames,
        "scene_aabb_iou_mean": float(np.mean(scene_aabb_frames)) if scene_aabb_frames else 0.0,
        "scene_obb_iou_mean": float(np.mean(scene_obb_frames)) if scene_obb_frames else 0.0,
        "object_aabb_iou_penalized_mean": float(np.mean(obj_aabb_pen_frames)) if obj_aabb_pen_frames else 0.0,
        "object_obb_iou_penalized_mean": float(np.mean(obj_obb_pen_frames)) if obj_obb_pen_frames else 0.0,
        "frame_details": frame_details,
    }


def read_image_rgb(path: Path) -> np.ndarray:
    bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
    if bgr is None:
        raise ValueError(f"Unable to decode image: {path}")
    return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)


def _align_image_paths(gt_images: tuple[Path, ...], pred_images: tuple[Path, ...]) -> list[tuple[Path, Path]]:
    if not gt_images or not pred_images:
        return []
    target = min(len(gt_images), len(pred_images))
    gt_idx = _aligned_indices(len(gt_images), target)
    pred_idx = _aligned_indices(len(pred_images), target)
    return [(gt_images[g], pred_images[p]) for g, p in zip(gt_idx, pred_idx)]


def photometric_loss_image(gt_frame: np.ndarray, pred_frame: np.ndarray) -> float:
    if pred_frame.shape[:2] != gt_frame.shape[:2]:
        h, w = gt_frame.shape[:2]
        pred_frame = cv2.resize(pred_frame, (w, h), interpolation=cv2.INTER_AREA)
    gt = gt_frame[..., :3].astype(np.float32) / 255.0
    pred = pred_frame[..., :3].astype(np.float32) / 255.0
    return float(np.mean(np.square(gt - pred)))


def pl_images(gt_images: tuple[Path, ...], pred_images: tuple[Path, ...]) -> dict[str, Any]:
    pairs = _align_image_paths(gt_images, pred_images)
    if not pairs:
        raise FileNotFoundError("PL requires at least one GT image and one prediction image")
    losses = [photometric_loss_image(read_image_rgb(g), read_image_rgb(p)) for g, p in pairs]
    raw = float(np.mean(losses))
    return {
        "metric": "PhotometricLoss_SelectedImages",
        "pl_raw": raw,
        "score_100": float(lower_is_better_to_score(raw, bad_value=1.0)),
        "frame_count": len(pairs),
        "mode": "selected_images",
        "gt_frame_count": len(gt_images),
        "pred_frame_count": len(pred_images),
        "pairs": [{"gt": str(g), "pred": str(p)} for g, p in pairs],
        "frame_losses": losses,
        "direction": "lower_is_better",
    }


def _encode_image_features(
    images: list[Image.Image],
    model: Any,
    processor: Any,
    device: str,
    batch_size: int,
) -> Any:
    import torch

    feats: list[torch.Tensor] = []
    with torch.no_grad():
        for start in range(0, len(images), batch_size):
            chunk = images[start : start + batch_size]
            inputs = processor(images=chunk, return_tensors="pt")
            inputs = {k: v.to(device) for k, v in inputs.items()}
            image_features = model.get_image_features(**inputs)
            image_features = image_features / image_features.norm(dim=-1, keepdim=True)
            feats.append(image_features)
    return torch.cat(feats, dim=0)


def nclip_images(
    gt_images: tuple[Path, ...],
    pred_images: tuple[Path, ...],
    model: Any,
    processor: Any,
    device: str,
    batch_size: int,
) -> dict[str, Any]:
    import torch

    pairs = _align_image_paths(gt_images, pred_images)
    if not pairs:
        raise FileNotFoundError("N-CLIP requires at least one GT image and one prediction image")
    gt_pil = [Image.fromarray(read_image_rgb(g)) for g, _ in pairs]
    pred_pil = [Image.fromarray(read_image_rgb(p)) for _, p in pairs]
    gt_feat = _encode_image_features(gt_pil, model, processor, device, batch_size)
    pred_feat = _encode_image_features(pred_pil, model, processor, device, batch_size)
    sims = torch.nn.functional.cosine_similarity(pred_feat, gt_feat, dim=-1)
    sim_values = sims.detach().cpu().numpy().astype(float).tolist()
    nclip_values = [float(1.0 - x) for x in sim_values]
    raw = float(np.mean(nclip_values))
    return {
        "metric": "VIGA_N_CLIP_SelectedImages",
        "n_clip_raw": raw,
        "clip_similarity_mean": float(np.mean(sim_values)),
        "score_100": float(100.0 * max(0.0, min(1.0, 1.0 - raw))),
        "frame_count": len(pairs),
        "mode": "selected_images_image_image",
        "pairs": [{"gt": str(g), "pred": str(p)} for g, p in pairs],
        "frame_clip_similarity": sim_values,
        "frame_n_clip": nclip_values,
        "formula": "mean_i(1 - CLIPSim(pred_image_i, gt_image_i))",
        "direction": "lower_is_better",
    }


def _missing_visual_metric(
    name: str,
    gt_images: tuple[Path, ...],
    pred_images: tuple[Path, ...],
    *,
    reason: str = "missing selected images",
) -> dict[str, Any]:
    return {
        "metric": name,
        "skipped": True,
        "reason": reason,
        "gt_frame_count": len(gt_images),
        "pred_frame_count": len(pred_images),
        "score_100": 0.0,
    }


def main() -> None:
    args = parse_args()

    project_root = _project_root()
    data_root = _resolve_data_root(project_root, args.data_root)
    out_json = Path(args.out_json).resolve()
    out_json.parent.mkdir(parents=True, exist_ok=True)
    alignment_dir = Path(args.alignment_dir).resolve() if args.alignment_dir else out_json.parent / "alignments"
    alignment_dir.mkdir(parents=True, exist_ok=True)
    scene_meta_dir = Path(args.scene_meta_dir).resolve() if args.scene_meta_dir else out_json.parent / "scene_meta"
    if args.scene_meta_dir and not scene_meta_dir.is_absolute():
        scene_meta_dir = (project_root / scene_meta_dir).resolve()

    gt_key = args.gt_key
    models = [x.strip() for x in args.models.split(",") if x.strip()]
    if not models:
        raise ValueError("models list is empty")

    all_assets = {
        k: load_assets(
            data_root,
            k,
            args.sample_id,
            image_glob=args.image_glob,
            scene_filename=args.scene_filename,
        )
        for k in [gt_key] + models
    }
    if args.auto_scene_meta and args.alignment == "depth_camera":
        all_assets = {
            k: ensure_scene_meta(
                v,
                project_root=project_root,
                blender_bin=args.blender_bin,
                scene_meta_dir=scene_meta_dir,
            )
            for k, v in all_assets.items()
        }

    bbox_mod = import_bbox_helpers(project_root)
    extract_script = project_root / "scripts" / "extract_blend_meshes.py"
    payload_cache: dict[str, dict[str, Any]] = {}

    gt_payload = _load_payload(
        all_assets[gt_key].scene,
        blender_bin=args.blender_bin,
        extract_script=extract_script,
        frame_mode=args.geometry_frame_mode,
        payload_cache=payload_cache,
    )

    ious: dict[str, Any] = {}
    alignments: dict[str, Any] = {}
    for key in models:
        pred_payload = _load_payload(
            all_assets[key].scene,
            blender_bin=args.blender_bin,
            extract_script=extract_script,
            frame_mode=args.geometry_frame_mode,
            payload_cache=payload_cache,
        )
        transform = build_alignment_transform(
            gt_payload,
            pred_payload,
            gt_depth=all_assets[gt_key].depth,
            pred_depth=all_assets[key].depth,
            gt_camera=all_assets[gt_key].camera,
            pred_camera=all_assets[key].camera,
            mode=args.alignment,
            bbox_mod=bbox_mod,
            camera_convention=args.camera_convention,
            camera_rotation_only=args.camera_rotation_only,
            ground_policy=args.ground_policy,
        )
        align_path = alignment_dir / args.sample_id / key / "alignment_transform.json"
        align_path.parent.mkdir(parents=True, exist_ok=True)
        transform_with_paths = {
            **transform,
            "gt_scene": str(all_assets[gt_key].scene),
            "pred_scene": str(all_assets[key].scene),
        }
        align_path.write_text(json.dumps(transform_with_paths, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
        alignments[key] = {**transform_with_paths, "path": str(align_path)}
        ious[key] = ioub_aligned(
            bbox_mod,
            gt_payload,
            pred_payload,
            transform,
            ground_policy=args.ground_policy,
        )

    pl_nclip: dict[str, Any] = {}
    if args.skip_selected_image_metrics:
        device = "skipped"
        for key in models:
            gt_images = all_assets[gt_key].images
            pred_images = all_assets[key].images
            pl_nclip[key] = {
                "media_type": "selected_images",
                "gt_images": [str(x) for x in gt_images],
                "pred_images": [str(x) for x in pred_images],
                "pl": _missing_visual_metric(
                    "PhotometricLoss_SelectedImages",
                    gt_images,
                    pred_images,
                    reason="disabled by --skip_selected_image_metrics",
                ),
                "n_clip": _missing_visual_metric(
                    "VIGA_N_CLIP_SelectedImages",
                    gt_images,
                    pred_images,
                    reason="disabled by --skip_selected_image_metrics",
                ),
            }
    else:
        import torch
        from transformers import CLIPModel, CLIPProcessor

        clip_model = CLIPModel.from_pretrained(args.clip_model_path, local_files_only=True)
        clip_processor = CLIPProcessor.from_pretrained(args.clip_model_path, local_files_only=True)
        device = "cuda" if torch.cuda.is_available() else "cpu"
        clip_model = clip_model.to(device)
        clip_model.eval()

        for key in models:
            gt_images = all_assets[gt_key].images
            pred_images = all_assets[key].images
            if not gt_images or not pred_images:
                if not args.allow_missing_images:
                    raise FileNotFoundError(
                        f"Missing selected images for model={key}: "
                        f"gt_count={len(gt_images)} pred_count={len(pred_images)}"
                    )
                pl = _missing_visual_metric("PhotometricLoss_SelectedImages", gt_images, pred_images)
                n_clip = _missing_visual_metric("VIGA_N_CLIP_SelectedImages", gt_images, pred_images)
            else:
                pl = pl_images(gt_images, pred_images)
                n_clip = nclip_images(
                    gt_images,
                    pred_images,
                    clip_model,
                    clip_processor,
                    device,
                    args.clip_batch_size,
                )
            pl_nclip[key] = {
                "media_type": "selected_images",
                "gt_images": [str(x) for x in gt_images],
                "pred_images": [str(x) for x in pred_images],
                "pl": pl,
                "n_clip": n_clip,
            }

    summary = []
    for key in models:
        summary.append(
            {
                "model": key,
                "scene_aabb_iou_mean": ious[key]["scene_aabb_iou_mean"],
                "scene_obb_iou_mean": ious[key]["scene_obb_iou_mean"],
                "object_aabb_iou_penalized_mean": ious[key]["object_aabb_iou_penalized_mean"],
                "object_obb_iou_penalized_mean": ious[key]["object_obb_iou_penalized_mean"],
                "pl_score_100": pl_nclip[key]["pl"]["score_100"],
                "n_clip_score_100": pl_nclip[key]["n_clip"]["score_100"],
                "pl_raw": pl_nclip[key]["pl"].get("pl_raw"),
                "n_clip_raw": pl_nclip[key]["n_clip"].get("n_clip_raw"),
                "alignment_mode": alignments[key]["mode"],
                "alignment_scale": alignments[key]["scale"],
            }
        )

    output = {
        "sample_id": args.sample_id,
        "paths": {
            k: {
                "base": str(v.base),
                "scene": str(v.scene),
                "images": [str(x) for x in v.images],
                "text": str(v.text) if v.text else None,
                "depth": str(v.depth) if v.depth else None,
                "camera": str(v.camera) if v.camera else None,
                "generated_meta": str(v.generated_meta) if v.generated_meta else None,
            }
            for k, v in all_assets.items()
        },
        "runtime": {
            "blender_bin": args.blender_bin,
            "clip_model_path": args.clip_model_path,
            "clip_device": device,
        },
        "rules": {
            "asset_loader": "auto-detect scene.blend/scene.glb/scene.gltf and selected images",
            "auto_scene_meta": bool(args.auto_scene_meta),
            "scene_meta_dir": str(scene_meta_dir),
            "iou_b_frames": args.geometry_frame_mode,
            "alignment": args.alignment,
            "ground_policy": args.ground_policy,
            "alignment_transform": "saved per model before IoU under alignment_dir",
            "iou_b_object_matching": "Hungarian matching on object AABB IoU; penalty denominator=max(gt_count,pred_count)",
            "selected_image_metrics_skipped": bool(args.skip_selected_image_metrics),
            "pl_definition": "MSE on user-selected image frames only",
            "n_clip_definition": "VIGA-style mean(1 - CLIPSim(pred_selected_image, gt_selected_image))",
        },
        "alignments": alignments,
        "iou_b": ious,
        "pl_nclip": pl_nclip,
        "summary": summary,
        "rankings": {
            "scene_aabb_desc": sorted(summary, key=lambda x: x["scene_aabb_iou_mean"], reverse=True),
            "scene_obb_desc": sorted(summary, key=lambda x: x["scene_obb_iou_mean"], reverse=True),
            "object_aabb_pen_desc": sorted(summary, key=lambda x: x["object_aabb_iou_penalized_mean"], reverse=True),
            "object_obb_pen_desc": sorted(summary, key=lambda x: x["object_obb_iou_penalized_mean"], reverse=True),
            "pl_score_desc": sorted(summary, key=lambda x: x["pl_score_100"], reverse=True),
            "nclip_score_desc": sorted(summary, key=lambda x: x["n_clip_score_100"], reverse=True),
        },
    }

    out_json.write_text(json.dumps(output, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(json.dumps(output, indent=2, ensure_ascii=False))
    print(f"SAVED {out_json}")


if __name__ == "__main__":
    main()