#!/usr/bin/env python3 """Build a v2 of a *-w-hardnegs dataset that keeps the v1 positive/negative pairing byte-for-byte and only rewrites `text` / `hard_negative_texts` using the eval-aligned raw query generator of the corresponding domain. """ from __future__ import annotations import argparse import hashlib import importlib.util import json import sys from collections import Counter from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq FLUID_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_fluid") SOLID_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_solid") OPTICS_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_optics") DYNAMICS_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_dynamics") def _load_module(path: Path, name: str): spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def make_text_fn(domain: str): if domain == "optics": sys.path.insert(0, str(OPTICS_ROOT / "src")) from physics_bench_optics import dataset as ds def fn(case): return ds._parsed_query_text(case, ds._case_tokens(case)) return fn, ds.QUERY_VERSION if domain == "fluid": exp = _load_module(FLUID_ROOT / "scripts" / "export_hf_fluid_test_format.py", "fluid_export") return exp._eval_parsed_query_text, exp.EVAL_QUERY_VERSION if domain == "solid": sys.path.insert(0, str(SOLID_ROOT / "src")) from physics_bench_solid import release_pipeline as rp return rp._eval_parsed_query_text, rp.EVAL_QUERY_VERSION if domain == "dynamics": sys.path.insert(0, str(DYNAMICS_ROOT / "src")) from physics_bench_dynamics import parsed_query as pqm return pqm.generate_template_text, pqm.PARSED_QUERY_VERSION raise ValueError(domain) def disambiguate(domain: str, texts: dict, cases: dict) -> dict: if domain == "dynamics": sys.path.insert(0, str(DYNAMICS_ROOT / "src")) from physics_bench_dynamics import parsed_query as pqm return pqm.disambiguate_texts(texts, cases) if domain == "optics": sys.path.insert(0, str(OPTICS_ROOT / "src")) from physics_bench_optics import dataset as ds case_vals = {cid: ds._case_tokens(cases[cid]) for cid in texts} return ds.disambiguate_parsed_texts(texts, case_vals) return texts def case_id_from_path(path: str) -> str: return path.split("/")[-1].rsplit(".", 1)[0] def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--domain", required=True, choices=["optics", "fluid", "solid", "dynamics"]) ap.add_argument("--v1-metadata", required=True, help="metadata.parquet downloaded from the v1 repo") ap.add_argument("--train-cases", required=True, help="train cases.jsonl / release_cases.jsonl") ap.add_argument("--out-dir", required=True) ap.add_argument("--benchmark-cases", default=None, help="optional benchmark cases file; asserts train params differ (solid safety check)") args = ap.parse_args() text_fn, version = make_text_fn(args.domain) cases: dict[str, dict] = {} with open(args.train_cases) as fh: for line in fh: c = json.loads(line) cases[str(c["case_id"])] = c if args.benchmark_cases: bench: dict[str, dict] = {} with open(args.benchmark_cases) as fh: for line in fh: c = json.loads(line) bench[str(c["case_id"])] = c shared = sorted(set(cases) & set(bench)) identical = [c for c in shared if cases[c].get("params") == bench[c].get("params")] print(f"[safety] case_id shared with benchmark: {len(shared)}; identical params: {len(identical)}") if identical: raise ValueError(f"train metadata appears to be the benchmark set, e.g. {identical[:3]}") table = pq.read_table(args.v1_metadata) rows = table.to_pylist() referenced: list[str] = [] for r in rows: referenced.append(case_id_from_path(r["video"])) referenced.extend(case_id_from_path(v) for v in r["hard_negative_videos"]) missing = sorted({c for c in referenced if c not in cases}) if missing: raise ValueError(f"{len(missing)} referenced case_ids missing from train metadata, e.g. {missing[:3]}") texts: dict[str, str] = {cid: text_fn(cases[cid]) for cid in sorted(set(referenced))} texts = disambiguate(args.domain, texts, cases) new_text = [texts[case_id_from_path(r["video"])] for r in rows] new_negs = [[texts[case_id_from_path(v)] for v in r["hard_negative_videos"]] for r in rows] dupes = {k: v for k, v in Counter(new_text).items() if v > 1} if dupes: raise ValueError(f"positive texts not unique: {len(dupes)} collisions") names = table.schema.names out_table = table.set_column(names.index("text"), table.schema.field(names.index("text")), pa.array(new_text, type=pa.string())) out_table = out_table.set_column(names.index("hard_negative_texts"), out_table.schema.field(names.index("hard_negative_texts")), pa.array(new_negs, type=out_table.schema.field(names.index("hard_negative_texts")).type)) # pairing must be untouched assert out_table.column("video").to_pylist() == table.column("video").to_pylist() assert out_table.column("hard_negative_videos").to_pylist() == table.column("hard_negative_videos").to_pylist() pair_repr = json.dumps( [[r["video"], r["hard_negative_videos"]] for r in rows], separators=(",", ":"), sort_keys=False ) pairing_sha = hashlib.sha256(pair_repr.encode()).hexdigest() out = Path(args.out_dir) out.mkdir(parents=True, exist_ok=True) pq.write_table(out_table, out / "metadata.parquet", compression="snappy", write_page_index=True) summary = { "domain": args.domain, "text_version": version, "text_style": "eval-aligned raw structured query", "rows": len(rows), "distinct_cases": len(texts), "negatives_per_case": len(rows[0]["hard_negative_videos"]), "pairing_identical_to_v1": True, "pairing_sha256": pairing_sha, "unique_positive_texts": len(set(new_text)), "v1_metadata": args.v1_metadata, "train_cases": args.train_cases, } (out / "v2_manifest.json").write_text(json.dumps(summary, indent=2)) sample = {"positive": new_text[0], "negatives": new_negs[0][:2], "video": rows[0]["video"], "negative_videos": rows[0]["hard_negative_videos"][:2]} (out / "sample.json").write_text(json.dumps(sample, indent=2)) print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()