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
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
#!/usr/bin/env python3


from __future__ import annotations

import argparse
import csv
import hashlib
import json
import os
import subprocess
import sys
import threading
import queue
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[1]


def collect_samples(
    data_root: Path,
    models: list[str],
    only: set[str] | None,
    default_mode: str,
    *,
    mode_by_sample: dict[str, str] | None = None,
    allow_missing_models: bool = False,
) -> list[tuple[str, str]]:
    gt_root = data_root / "gt"
    if not gt_root.is_dir():
        raise FileNotFoundError(f"ground-truth directory missing: {gt_root}")

    out: list[tuple[str, str]] = []
    missing_gt = sorted(only - {d.name for d in gt_root.iterdir() if d.is_dir()}) if only else []
    if missing_gt:
        preview = ", ".join(missing_gt[:10])
        raise FileNotFoundError(f"track manifest references missing GT samples: {preview}")

    missing_models: list[str] = []
    for d in sorted(gt_root.iterdir()):
        if not d.is_dir():
            continue
        sid = d.name
        if only is not None and sid not in only:
            continue
        if not _has_scene(d):
            raise FileNotFoundError(f"GT geometry missing for sample {sid}: {d}")

        missing = [model for model in models if not _has_scene(data_root / model / sid)]
        if missing and not allow_missing_models:
            missing_models.append(f"{sid}: {','.join(missing)}")
            continue

        mode = (mode_by_sample or {}).get(sid, default_mode)
        out.append((sid, mode))

    if missing_models:
        preview = "; ".join(missing_models[:10])
        suffix = "" if len(missing_models) <= 10 else f"; ... and {len(missing_models) - 10} more"
        raise FileNotFoundError(f"requested model geometry is incomplete: {preview}{suffix}")
    return out


def load_track_manifest_sample_ids(manifest_path: Path) -> set[str]:
    if not manifest_path.is_file():
        raise FileNotFoundError(f"track manifest missing: {manifest_path}")

    def rows_from_payload(payload):
        if isinstance(payload, list):
            return payload
        if isinstance(payload, dict):
            samples = payload.get("samples")
            if isinstance(samples, list):
                return samples
            return [payload]
        raise ValueError(f"Unsupported manifest payload: {manifest_path}")

    rows = []
    if manifest_path.suffix.lower() == ".jsonl":
        for line_no, line in enumerate(manifest_path.read_text(encoding="utf-8").splitlines(), start=1):
            raw = line.strip()
            if not raw:
                continue
            obj = json.loads(raw)
            if not isinstance(obj, dict):
                raise ValueError(f"Expected JSON object at {manifest_path}:{line_no}")
            rows.append(obj)
    else:
        rows = rows_from_payload(json.loads(manifest_path.read_text(encoding="utf-8")))

    sample_ids: set[str] = set()
    for idx, row in enumerate(rows, start=1):
        if not isinstance(row, dict):
            raise ValueError(f"Expected JSON object at {manifest_path}:{idx}")
        sid = row.get("sample_id") or row.get("id")
        if not sid:
            raise ValueError(f"Missing sample_id/id at {manifest_path}:{idx}")
        sample_ids.add(str(sid))
    return sample_ids


def load_track_manifest_modes(manifest_path: Path, default_mode: str) -> dict[str, str]:
    modes: dict[str, str] = {}
    lines = manifest_path.read_text(encoding="utf-8").splitlines()
    if manifest_path.suffix.lower() == ".jsonl":
        rows = [json.loads(line) for line in lines if line.strip()]
    else:
        payload = json.loads("\n".join(lines))
        rows = payload.get("samples", [payload]) if isinstance(payload, dict) else payload

    for row in rows:
        sid = row.get("sample_id") or row.get("id")
        if not sid:
            continue
        mode = row.get("geometry_frame_mode")
        if not mode and row.get("frame") is not None:
            mode = f"exact:{int(row['frame'])}"
        modes[str(sid)] = str(mode or default_mode)
    return modes


SCENE_EXTS = (".glb", ".blend", ".gltf")


def _has_scene(model_dir: Path) -> bool:
    if not model_dir.is_dir():
        return False
    for ext in SCENE_EXTS:
        if (model_dir / f"scene{ext}").exists():
            return True

    return any(model_dir.glob(f"*{ext}") for ext in SCENE_EXTS if list(model_dir.glob(f"*{ext}")))


def _scene_path(model_dir: Path) -> Path | None:
    for ext in SCENE_EXTS:
        candidate = model_dir / f"scene{ext}"
        if candidate.is_file():
            return candidate.resolve()
    for ext in SCENE_EXTS:
        matches = sorted(model_dir.glob(f"*{ext}")) if model_dir.is_dir() else []
        if matches:
            return matches[0].resolve()
    return None


def _run_config(sid: str, mode: str, models: list[str], args) -> dict:
    data_root = Path(args.data_root).resolve()
    scene_keys = ["gt", *models]
    scenes = {}
    for key in scene_keys:
        scene = _scene_path(data_root / key / sid)
        if scene is None:
            continue
        stat = scene.stat()
        scenes[key] = {
            "path": str(scene),
            "size": stat.st_size,
            "mtime_ns": stat.st_mtime_ns,
        }
    payload = {
        "schema_version": 1,
        "sample_id": sid,
        "models": models,
        "geometry_frame_mode": mode,
        "alignment": args.alignment,
        "ground_policy": args.ground_policy,
        "blender_bin": args.blender_bin,
        "clip_model_path": args.clip_model_path,
        "clip_batch_size": args.clip_batch_size,
        "resolution_x": args.resolution_x,
        "resolution_y": args.resolution_y,
        "render_samples": args.render_samples,
        "render_engine": args.render_engine,
        "scenes": scenes,
    }
    encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
    payload["fingerprint"] = hashlib.sha256(encoded).hexdigest()
    return payload


def run_one(sid: str, mode: str, gpu: str, args) -> tuple[str, bool, str]:
    out_dir = Path(args.out_root) / sid
    final = out_dir / "reports" / "final_report.json"
    config_path = out_dir / "run_config.json"
    data_root = Path(args.data_root).resolve()
    requested = [m.strip() for m in args.models.split(",") if m.strip()]
    present = [m for m in requested if _has_scene(data_root / m / sid)]
    missing = [m for m in requested if m not in present]
    if missing and not args.allow_partial:
        return sid, False, f"missing model geometry: {','.join(missing)}"
    if not present:
        return sid, False, "no model geometry"

    config = _run_config(sid, mode, present, args)
    if final.exists() and config_path.exists() and not args.force:
        try:
            previous = json.loads(config_path.read_text(encoding="utf-8"))
            if previous.get("fingerprint") == config["fingerprint"]:
                return sid, True, "cached (matching configuration)"
        except Exception:
            pass

    models_arg = ",".join(present)
    env = dict(os.environ)
    env["CUDA_VISIBLE_DEVICES"] = gpu



    tpw = str(args.threads_per_worker)
    for var in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS",
                "NUMEXPR_NUM_THREADS", "VECLIB_MAXIMUM_THREADS", "BLENDER_NUM_THREADS"):
        env[var] = tpw
    cmd = [
        sys.executable, "scripts/run_blend_glb_eval_pipeline.py",
        "--sample_id", sid,
        "--models", models_arg,
        "--gt_key", "gt",
        "--data_root", str(data_root),
        "--blender_bin", args.blender_bin,
        "--clip_model_path", args.clip_model_path,
        "--clip_batch_size", str(args.clip_batch_size),
        "--alignment", args.alignment,
        "--ground_policy", args.ground_policy,
        "--geometry_frame_mode", mode,
        "--resolution_x", str(args.resolution_x),
        "--resolution_y", str(args.resolution_y),
        "--samples", str(args.render_samples),
        "--render_engine", args.render_engine,
        "--out_dir", str(out_dir),
    ]
    logf = out_dir / "pipeline.log"
    out_dir.mkdir(parents=True, exist_ok=True)
    with open(logf, "w") as fh:
        proc = subprocess.run(cmd, cwd=REPO_ROOT, env=env, stdout=fh,
                              stderr=subprocess.STDOUT, text=True)
    if proc.returncode == 0 and final.exists():
        config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
        return sid, True, "ok"
    return sid, False, f"rc={proc.returncode} (see {logf})"


def worker(wq: queue.Queue, gpu: str, args, results: list, lock: threading.Lock):
    while True:
        try:
            sid, mode = wq.get_nowait()
        except queue.Empty:
            return
        sid_, ok, msg = run_one(sid, mode, gpu, args)
        if not ok and args.retries > 0:
            sid_, ok, msg = run_one(sid, mode, gpu, args)
        with lock:
            results.append((sid_, ok, msg))
            n = len(results)
        print(f"[gpu{gpu}] ({n}) {sid_}: {'OK' if ok else 'FAIL'} {msg}", flush=True)
        wq.task_done()


def aggregate(
    out_root: Path,
    samples: list[tuple[str, str]],
    models: list[str],
    *,
    allow_partial: bool = False,
) -> dict:
    rows = []
    missing_reports: list[str] = []
    for sid, _ in samples:
        fr = out_root / sid / "reports" / "final_report.json"
        if not fr.exists():
            missing_reports.append(sid)
            continue
        d = json.loads(fr.read_text())
        for s in d.get("summary", []):
            rows.append({
                "sample_id": sid,
                "model": s.get("model"),
                "scene_aabb_iou": s.get("scene_aabb_iou_mean"),
                "scene_obb_iou": s.get("scene_obb_iou_mean"),
                "object_aabb_iou": s.get("object_aabb_iou_penalized_mean"),
                "object_obb_iou": s.get("object_obb_iou_penalized_mean"),
                "pl_score": s.get("rendered_pl_score_100"),
                "n_clip_score": s.get("rendered_n_clip_score_100"),
                "pl_raw": s.get("rendered_pl_raw"),
                "n_clip_raw": s.get("rendered_n_clip_raw"),
            })

    found_pairs = {(row["sample_id"], row["model"]) for row in rows}
    expected_pairs = {(sid, model) for sid, _ in samples for model in models}
    missing_pairs = sorted(expected_pairs - found_pairs)
    if not allow_partial and (missing_reports or missing_pairs):
        details = []
        if missing_reports:
            details.append(f"missing reports={len(missing_reports)}")
        if missing_pairs:
            details.append(f"missing sample/model rows={len(missing_pairs)}")
        raise RuntimeError("incomplete evaluation; " + ", ".join(details))
    csv_path = out_root / "results_per_sample.csv"
    fields = ["sample_id", "model", "scene_aabb_iou", "scene_obb_iou",
              "object_aabb_iou", "object_obb_iou", "pl_score", "n_clip_score",
              "pl_raw", "n_clip_raw"]
    with open(csv_path, "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=fields)
        w.writeheader()
        w.writerows(rows)


    means = {}
    for m in models:
        mr = [r for r in rows if r["model"] == m]
        if not mr:
            continue
        def avg(k):
            vals = [r[k] for r in mr if isinstance(r[k], (int, float))]
            return sum(vals) / len(vals) if vals else None
        pl_raw = avg("pl_raw")
        n_clip_raw = avg("n_clip_raw")
        means[m] = {
            "n": len(mr),
            "expected_n": len(samples),
            "coverage": len(mr) / len(samples) if samples else 0.0,
            "scene_aabb_iou": avg("scene_aabb_iou"),
            "scene_obb_iou": avg("scene_obb_iou"),
            "object_aabb_iou": avg("object_aabb_iou"),
            "object_obb_iou": avg("object_obb_iou"),
            "pl": 100.0 * pl_raw if pl_raw is not None else None,
            "n_clip": 10.0 * n_clip_raw if n_clip_raw is not None else None,
            "pl_raw": pl_raw,
            "n_clip_raw": n_clip_raw,
            "pl_score": avg("pl_score"),
            "n_clip_score": avg("n_clip_score"),
        }
    payload = {
        "schema_version": 1,
        "complete": not missing_reports and not missing_pairs,
        "sample_count": len(samples),
        "models": models,
        "metric_definitions": {
            "pl": "100 * mean normalized RGB MSE; lower is better",
            "n_clip": "10 * mean(1 - CLIPSim); lower is better",
            "scene_aabb_iou": "scene union AABB IoU; higher is better",
            "scene_obb_iou": "scene union OBB IoU; higher is better",
            "object_aabb_iou": "Hungarian-matched object AABB IoU with count penalty; higher is better",
            "object_obb_iou": "Hungarian-matched object OBB IoU with count penalty; higher is better",
        },
        "missing_reports": missing_reports,
        "missing_pairs": [{"sample_id": sid, "model": model} for sid, model in missing_pairs],
        "results": means,
    }
    (out_root / "results_summary.json").write_text(json.dumps(payload, indent=2) + "\n")

    print(f"\n=== aggregated {len(rows)} model-rows over {len({r['sample_id'] for r in rows})} samples ===")
    print("%-10s %4s | %-9s %-9s %-9s %-9s | %-8s %-8s" % (
        "model", "n", "scn_aabb", "scn_obb", "obj_aabb", "obj_obb", "PL", "NCLIP"))
    print("-" * 80)
    for m, v in means.items():
        print("%-10s %4d | %-9.3f %-9.3f %-9.3f %-9.3f | %-8.2f %-8.2f" % (
            m, v["n"], v["scene_aabb_iou"] or 0, v["scene_obb_iou"] or 0,
            v["object_aabb_iou"] or 0, v["object_obb_iou"] or 0,
            v["pl"] or 0, v["n_clip"] or 0))
    print(f"\nCSV: {csv_path}\nJSON: {out_root/'results_summary.json'}")
    return payload


def main():
    pre = argparse.ArgumentParser(add_help=False)
    pre.add_argument("--protocol", default=None, help="JSON file providing evaluator defaults")
    pre_args, _ = pre.parse_known_args()
    protocol_defaults = {}
    if pre_args.protocol:
        protocol_path = Path(pre_args.protocol).resolve()
        protocol_defaults = json.loads(protocol_path.read_text(encoding="utf-8"))
        if not isinstance(protocol_defaults, dict):
            raise ValueError(f"protocol must be a JSON object: {protocol_path}")

    ap = argparse.ArgumentParser(parents=[pre])
    ap.add_argument(
        "--data_root",
        required=True,
        help="Dataset root containing gt/ and one directory per submitted model.",
    )
    ap.add_argument("--models", required=True)
    ap.add_argument("--gpus", default="2,3,5,7")
    ap.add_argument("--workers_per_gpu", type=int, default=2)
    ap.add_argument("--threads_per_worker", type=int, default=10,
                    help="cap CPU threads per worker (geometry stage is CPU-bound)")
    ap.add_argument("--blender_bin", default="blender")
    ap.add_argument("--clip_model_path", default="openai/clip-vit-base-patch32")
    ap.add_argument("--clip_batch_size", type=int, default=32)
    ap.add_argument("--alignment", default="bbox")
    ap.add_argument(
        "--ground_policy",
        choices=["exclude", "include"],
        default="exclude",
        help="Whether bbox alignment and geometry IoU exclude detected ground planes.",
    )
    ap.add_argument("--out_root", required=True)
    ap.add_argument("--only_samples", default=None)
    ap.add_argument(
        "--track_manifest",
        default=None,
        help="Optional static/dynamic track manifest; sample ids are used as an evaluation filter.",
    )
    ap.add_argument("--default_frame_mode", default="first_only")
    ap.add_argument("--resolution_x", type=int, default=768)
    ap.add_argument("--resolution_y", type=int, default=432)
    ap.add_argument("--render_samples", type=int, default=32)
    ap.add_argument(
        "--render_engine",
        choices=["BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "CYCLES"],
        default="BLENDER_EEVEE",
    )
    ap.add_argument("--limit", type=int, default=0, help="cap number of samples (debug)")
    ap.add_argument("--retries", type=int, default=1)
    ap.add_argument("--force", action="store_true", help="re-run even if final_report exists")
    ap.add_argument("--aggregate_only", action="store_true")
    ap.add_argument(
        "--allow_partial",
        action="store_true",
        help="Allow missing models or failed samples. Off by default for comparable benchmark results.",
    )
    known_destinations = {action.dest for action in ap._actions}
    unknown_defaults = sorted(set(protocol_defaults) - known_destinations)
    if unknown_defaults:
        raise ValueError(f"unknown protocol keys: {', '.join(unknown_defaults)}")
    ap.set_defaults(**protocol_defaults)
    args = ap.parse_args()

    data_root = Path(args.data_root).resolve()
    models = [m.strip() for m in args.models.split(",") if m.strip()]
    only = set(s.strip() for s in args.only_samples.split(",") if s.strip()) if args.only_samples else None
    if args.track_manifest:
        manifest_path = Path(args.track_manifest).resolve()
        manifest_ids = load_track_manifest_sample_ids(manifest_path)
        mode_by_sample = load_track_manifest_modes(manifest_path, args.default_frame_mode)
        only = manifest_ids if only is None else only & manifest_ids
        print(f"track_manifest={args.track_manifest} sample_ids={len(manifest_ids)} active_filter={len(only)}")
    else:
        mode_by_sample = {}
    out_root = Path(args.out_root)
    out_root.mkdir(parents=True, exist_ok=True)

    samples = collect_samples(
        data_root,
        models,
        only,
        args.default_frame_mode,
        mode_by_sample=mode_by_sample,
        allow_missing_models=args.allow_partial,
    )
    if args.limit:
        samples = samples[:args.limit]
    if not samples:
        raise SystemExit("no evaluation samples found")
    print(f"collected {len(samples)} samples; gpus={args.gpus} x {args.workers_per_gpu} workers")

    if not args.aggregate_only:
        wq: queue.Queue = queue.Queue()
        for item in samples:
            wq.put(item)
        gpus = [g.strip() for g in args.gpus.split(",") if g.strip()]
        results: list = []
        lock = threading.Lock()
        threads = []
        for gpu in gpus:
            for _ in range(args.workers_per_gpu):
                t = threading.Thread(target=worker, args=(wq, gpu, args, results, lock))
                t.start()
                threads.append(t)
        for t in threads:
            t.join()
        ok = sum(1 for _, o, _ in results if o)
        print(f"\n=== eval done: {ok}/{len(results)} ok ===")
        if ok != len(results) and not args.allow_partial:
            failed = [f"{sid}: {msg}" for sid, success, msg in results if not success]
            raise SystemExit("evaluation failed:\n  " + "\n  ".join(failed))

    aggregate(out_root, samples, models, allow_partial=args.allow_partial)


if __name__ == "__main__":
    main()