Download OVOW/benchmark/scripts/build_track_manifests.py from AIGeeksGroup/PhysicalWM: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/benchmark/scripts/build_track_manifests.py
- Command line
-
hf download hf://datasets/AIGeeksGroup/PhysicalWM/OVOW/benchmark/scripts/build_track_manifests.py
-
curl -L -o build_track_manifests.py https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/benchmark/scripts/build_track_manifests.py
10.4 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| from collections import OrderedDict | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| PROJECT_ROOT = Path(__file__).resolve().parents[1] | |
| FRAME_SUFFIX_RE = re.compile(r"^(?P<case>.+)_f(?P<frame>\d+)$") | |
| def _display_path(path: Path) -> str: | |
| try: | |
| return os.path.relpath(path.resolve(), PROJECT_ROOT) | |
| except Exception: | |
| return str(path) | |
| def _load_records(path: Path) -> list[dict[str, Any]]: | |
| if not path.exists(): | |
| raise FileNotFoundError(f"Missing input manifest: {path}") | |
| if path.suffix.lower() == ".jsonl": | |
| records: list[dict[str, Any]] = [] | |
| for line_no, line in enumerate(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 {path}:{line_no}") | |
| records.append(obj) | |
| return records | |
| payload = json.loads(path.read_text(encoding="utf-8")) | |
| if isinstance(payload, list): | |
| if not all(isinstance(item, dict) for item in payload): | |
| raise ValueError(f"Expected a list of JSON objects in {path}") | |
| return list(payload) | |
| if isinstance(payload, dict): | |
| samples = payload.get("samples") | |
| if isinstance(samples, list) and all(isinstance(item, dict) for item in samples): | |
| return list(samples) | |
| return [payload] | |
| raise ValueError(f"Unsupported JSON payload in {path}") | |
| def _sample_id(row: dict[str, Any]) -> str: | |
| sample_id = row.get("sample_id") or row.get("id") | |
| if not sample_id: | |
| raise ValueError("Missing sample_id/id") | |
| return str(sample_id) | |
| def _case_and_frame(row: dict[str, Any]) -> tuple[str, int | None]: | |
| if row.get("case_id"): | |
| case_id = str(row["case_id"]) | |
| else: | |
| sample_id = _sample_id(row) | |
| match = FRAME_SUFFIX_RE.match(sample_id) | |
| case_id = match.group("case") if match else sample_id | |
| frame_value = row.get("frame") | |
| if isinstance(frame_value, (int, np.integer)): | |
| return case_id, int(frame_value) | |
| if isinstance(frame_value, str) and frame_value.strip().isdigit(): | |
| return case_id, int(frame_value.strip()) | |
| sample_id = _sample_id(row) | |
| match = FRAME_SUFFIX_RE.match(sample_id) | |
| if match: | |
| return case_id, int(match.group("frame")) | |
| return case_id, None | |
| def _sort_key(row: dict[str, Any]) -> tuple[int, int, str]: | |
| _, frame = _case_and_frame(row) | |
| sample_id = _sample_id(row) | |
| if frame is None: | |
| return (1, 10**9, sample_id) | |
| return (0, frame, sample_id) | |
| def _even_indices(total: int, count: int) -> list[int]: | |
| if total <= 0 or count <= 0: | |
| return [] | |
| if count >= total: | |
| return list(range(total)) | |
| return np.linspace(0, total - 1, num=count, dtype=int).tolist() | |
| def _augment_row( | |
| row: dict[str, Any], | |
| *, | |
| benchmark_track: str, | |
| case_id: str, | |
| selected_frames: list[int], | |
| selected_sample_ids: list[str], | |
| source_sample_ids: list[str], | |
| source_frames: list[int | None], | |
| track_rank: int, | |
| source_manifest: str, | |
| ) -> dict[str, Any]: | |
| out = dict(row) | |
| out["case_id"] = case_id | |
| out["benchmark_track"] = benchmark_track | |
| out["track_rank"] = track_rank | |
| out["selected_frames"] = selected_frames | |
| out["selected_sample_ids"] = selected_sample_ids | |
| out["source_sample_ids"] = source_sample_ids | |
| out["source_frames"] = source_frames | |
| out["source_sample_count"] = len(source_sample_ids) | |
| out["source_manifest"] = source_manifest | |
| if "frame" not in out or out["frame"] is None: | |
| _, frame = _case_and_frame(row) | |
| if frame is not None: | |
| out["frame"] = frame | |
| return out | |
| def build_track_manifests( | |
| input_paths: list[Path], | |
| out_dir: Path, | |
| *, | |
| dynamic_frame_count: int = 7, | |
| include_single_frame_dynamic: bool = True, | |
| ) -> dict[str, Any]: | |
| if dynamic_frame_count <= 0: | |
| raise ValueError("dynamic_frame_count must be > 0") | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| rows_by_case: "OrderedDict[str, list[tuple[dict[str, Any], Path]]]" = OrderedDict() | |
| seen_sample_ids: set[str] = set() | |
| source_files: list[str] = [] | |
| for path in input_paths: | |
| source_files.append(_display_path(path)) | |
| for row in _load_records(path): | |
| sample_id = _sample_id(row) | |
| if sample_id in seen_sample_ids: | |
| continue | |
| seen_sample_ids.add(sample_id) | |
| case_id, _ = _case_and_frame(row) | |
| rows_by_case.setdefault(case_id, []).append((row, path)) | |
| static_rows: list[dict[str, Any]] = [] | |
| dynamic_rows: list[dict[str, Any]] = [] | |
| case_index: list[dict[str, Any]] = [] | |
| for case_id, rows_and_sources in rows_by_case.items(): | |
| rows_sorted = sorted(rows_and_sources, key=lambda item: _sort_key(item[0])) | |
| rows = [row for row, _ in rows_sorted] | |
| source_manifest = _display_path(rows_sorted[0][1]) if rows_sorted else "" | |
| source_sample_ids = [_sample_id(row) for row in rows] | |
| source_frames = [_case_and_frame(row)[1] for row in rows] | |
| static_source = next((row for row in rows if _case_and_frame(row)[1] == 1), None) | |
| if static_source is None: | |
| static_source = rows[0] | |
| static_frames = [_case_and_frame(static_source)[1]] | |
| if static_frames[0] is None: | |
| static_frames = [] | |
| static_row = _augment_row( | |
| static_source, | |
| benchmark_track="static", | |
| case_id=case_id, | |
| selected_frames=static_frames, | |
| selected_sample_ids=[_sample_id(static_source)], | |
| source_sample_ids=source_sample_ids, | |
| source_frames=source_frames, | |
| track_rank=0, | |
| source_manifest=source_manifest, | |
| ) | |
| static_rows.append(static_row) | |
| dynamic_selected_rows: list[tuple[dict[str, Any], int]] = [] | |
| if len(rows) == 1 and not include_single_frame_dynamic: | |
| dynamic_selected_rows = [] | |
| else: | |
| selected_indices = _even_indices(len(rows), dynamic_frame_count) | |
| dynamic_selected_rows = [(rows[idx], rank) for rank, idx in enumerate(selected_indices)] | |
| dynamic_selected_frames = [] | |
| dynamic_selected_ids = [] | |
| for row, _ in dynamic_selected_rows: | |
| _, frame = _case_and_frame(row) | |
| if frame is not None: | |
| dynamic_selected_frames.append(frame) | |
| dynamic_selected_ids.append(_sample_id(row)) | |
| for row, rank in dynamic_selected_rows: | |
| dynamic_rows.append( | |
| _augment_row( | |
| row, | |
| benchmark_track="dynamic", | |
| case_id=case_id, | |
| selected_frames=dynamic_selected_frames, | |
| selected_sample_ids=dynamic_selected_ids, | |
| source_sample_ids=source_sample_ids, | |
| source_frames=source_frames, | |
| track_rank=rank, | |
| source_manifest=source_manifest, | |
| ) | |
| ) | |
| case_index.append( | |
| { | |
| "case_id": case_id, | |
| "source_sample_ids": source_sample_ids, | |
| "source_frames": source_frames, | |
| "source_sample_count": len(source_sample_ids), | |
| "static_sample_id": _sample_id(static_source), | |
| "static_frame": static_frames[0] if static_frames else None, | |
| "dynamic_sample_ids": dynamic_selected_ids, | |
| "dynamic_frames": dynamic_selected_frames, | |
| "dynamic_sample_count": len(dynamic_selected_ids), | |
| } | |
| ) | |
| static_path = out_dir / "static.jsonl" | |
| dynamic_path = out_dir / "dynamic.jsonl" | |
| case_index_path = out_dir / "case_index.json" | |
| summary_path = out_dir / "track_summary.json" | |
| with static_path.open("w", encoding="utf-8") as f: | |
| for row in static_rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| with dynamic_path.open("w", encoding="utf-8") as f: | |
| for row in dynamic_rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| case_index_path.write_text(json.dumps(case_index, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") | |
| summary = { | |
| "source_files": source_files, | |
| "case_count": len(rows_by_case), | |
| "static_row_count": len(static_rows), | |
| "dynamic_row_count": len(dynamic_rows), | |
| "dynamic_frame_count": dynamic_frame_count, | |
| "include_single_frame_dynamic": include_single_frame_dynamic, | |
| "static_manifest": _display_path(static_path), | |
| "dynamic_manifest": _display_path(dynamic_path), | |
| "case_index": _display_path(case_index_path), | |
| } | |
| summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") | |
| return { | |
| "summary": summary, | |
| "case_index": case_index, | |
| "static_rows": static_rows, | |
| "dynamic_rows": dynamic_rows, | |
| } | |
| def build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(description="Split manifests into static and dynamic tracks") | |
| parser.add_argument( | |
| "--inputs", | |
| nargs="+", | |
| required=True, | |
| help="Input JSON or JSONL manifests", | |
| ) | |
| parser.add_argument("--out_dir", required=True, help="Output directory for track manifests") | |
| parser.add_argument("--dynamic_frame_count", type=int, default=7, help="Frames to keep per dynamic case") | |
| parser.add_argument( | |
| "--include_single_frame_dynamic", | |
| action=argparse.BooleanOptionalAction, | |
| default=True, | |
| help="Keep singleton cases in the dynamic track", | |
| ) | |
| return parser | |
| def main() -> None: | |
| args = build_parser().parse_args() | |
| input_paths = [Path(p) for p in args.inputs] | |
| out_dir = Path(args.out_dir) | |
| result = build_track_manifests( | |
| input_paths, | |
| out_dir, | |
| dynamic_frame_count=args.dynamic_frame_count, | |
| include_single_frame_dynamic=args.include_single_frame_dynamic, | |
| ) | |
| print(json.dumps(result["summary"], indent=2, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |