#!/usr/bin/env python3 """Write a collection out in the layout the world model is trained from. Run against a collection root -- the directory holding ``//`` -- and it walks every trajectory it finds. Nothing is read from a VM, so this is safe to re-run and safe to run while collection continues elsewhere. """ from __future__ import annotations import argparse import json import sys from pathlib import Path def walked_to_the_end(trajectory: Path) -> bool: """Whether every recorded step of this trajectory was reproduced. Read from the run summary rather than recomputed, because the summary is what the collector concluded at the time and the pairs file cannot distinguish "the recording had four steps and we walked four" from "the recording had nine and we walked four". """ for summary in sorted(trajectory.glob("runs/*.json")): try: record = json.loads(summary.read_text(encoding="utf-8")) except (OSError, ValueError): continue walked = record.get("validated_transition_count") total = record.get("spine_action_count") if isinstance(walked, int) and isinstance(total, int) and total > 0: if record.get("priming_action_count", 0) > 0: alignment = record.get("initial_alignment") if alignment is None: try: state = json.loads( (trajectory / "states" / "state_000" / "state.json") .read_text(encoding="utf-8") ) alignment = state.get("priming") except (OSError, ValueError): alignment = None if not isinstance(alignment, dict) or alignment.get("passed") is not True: return False return walked == total return False def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source", type=Path, required=True) parser.add_argument("--destination", type=Path, required=True) parser.add_argument("--repository", type=Path, default=Path(__file__).parent.parent) parser.add_argument( "--manifest", type=Path, action="append", default=[], help=( "a manifest, for the task instruction each prompt needs. " "Repeatable: a collection may draw on several archives." ), ) parser.add_argument( "--collection-mode", default="", help="fills `collection_mode` for rows collected before the field existed", ) parser.add_argument( "--anchor-agent", default="", help=( "what reached the states: `recording` for a replayed archive, or " "the model that walked them, e.g. `OpenCUA-7B`" ), ) parser.add_argument( "--only-listed", type=Path, default=None, help=( "a file of `/` lines; deliver only those. A " "collection root accumulates -- Mode B keeps walking into the same " "root for days -- so re-exporting all of it would republish " "trajectories already shipped. This delivers the increment." ), ) parser.add_argument( "--full-spine-only", action="store_true", help=( "deliver only trajectories walked end to end. A partial walk " "stops where the desktop and the recording part company, and its " "prompts carry a task instruction the trajectory never went on to " "satisfy -- so the steps are true about the desktop and misleading " "about the task. The collection keeps them either way; this " "decides what leaves it." ), ) parser.add_argument( "--keep-duplicates", action="store_true", help="Export every transition, including ones the dataset already " "carries. Deduplication is on by default because a published " "set that repeats itself overstates what was collected; this " "exists for inspecting what would have been removed.") args = parser.parse_args() repository = args.repository.resolve() if str(repository) not in sys.path: sys.path.insert(0, str(repository)) from guiwm_collector.dataset.export import ( export_trajectory, scan_for_duplicates) from guiwm_collector.dataset.dedup import Ledger instructions: dict[str, str] = {} # One manifest means one archive, so its name can fill in for records # collected before the provenance field existed. Several means the # collection is mixed and the export must not guess. archive_name = "" if len(args.manifest) == 1 and args.manifest[0].is_file(): archive_name = str( (json.loads(args.manifest[0].read_text(encoding="utf-8")).get( "source_archive") or {}).get("name") or "" ) for source in args.manifest: if not source.is_file(): continue manifest = json.loads(source.read_text(encoding="utf-8")) for task in manifest.get("tasks", []): path = task.get("task_config_path") if not path or not Path(path).is_file(): continue config = json.loads(Path(path).read_text(encoding="utf-8")) instructions[str(task["task_id"])] = str(config.get("instruction") or "") wanted: set[str] | None = None if args.only_listed: wanted = {line.strip() for line in args.only_listed.read_text(encoding="utf-8").splitlines() if line.strip()} # Which trajectories are in scope has to be settled before anything is # written, because deduplication is a property of the set: the same # transition in two tasks is a duplicate only if both tasks are exported. partial = 0 selected: list[Path] = [] for pairs in sorted(args.source.glob("*/*/pairs.jsonl")): trajectory = pairs.parent if wanted is not None and ( f"{trajectory.parent.name}/{trajectory.name}" not in wanted): continue if args.full_spine_only and not walked_to_the_end(trajectory): partial += 1 continue selected.append(trajectory) ledger = None if not args.keep_duplicates: print(f"scanning {len(selected)} trajectories for duplicates...", flush=True) ledger = scan_for_duplicates(selected, Ledger()) counts = ledger.counts() print(" " + " ยท ".join(f"{k} {v}" for k, v in counts.items()), flush=True) total_steps = total_skipped = trajectories = 0 total_deduplicated = 0 for trajectory in selected: task_id = trajectory.name summary = export_trajectory( source=trajectory, destination=args.destination / trajectory.parent.name / task_id, instruction=instructions.get(task_id, ""), source_archive=archive_name, collection_mode=args.collection_mode, anchor_agent=args.anchor_agent, ledger=ledger, ) trajectories += 1 total_steps += summary.steps total_skipped += summary.skipped total_deduplicated += summary.deduplicated print(f"{trajectory.parent.name}/{task_id}: {summary.steps} steps " f"({summary.skipped} skipped, {summary.deduplicated} duplicate)", flush=True) print(f"\n{trajectories} trajectories, {total_steps} steps, " f"{total_skipped} skipped, {total_deduplicated} deduplicated" + (f", {partial} partial trajectories withheld" if partial else "") + f" -> {args.destination}") return 0 if __name__ == "__main__": raise SystemExit(main())