File size: 3,259 Bytes
1ac3948
240bbb0
1ac3948
240bbb0
 
 
 
1ac3948
240bbb0
 
 
 
 
f1acc97
240bbb0
1ac3948
 
7adf21d
1ac3948
240bbb0
1ac3948
 
 
240bbb0
 
f1acc97
 
 
 
 
117d2d7
 
240bbb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ac3948
7adf21d
f1acc97
7adf21d
 
 
 
f1acc97
 
 
 
240bbb0
 
 
 
 
 
 
 
 
 
 
 
f1acc97
 
240bbb0
 
 
 
 
 
 
 
 
f1acc97
 
 
240bbb0
 
f1acc97
 
240bbb0
1ac3948
 
 
 
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
#!/usr/bin/env python3
"""Push a Harbor job directory into the merged tasks+trajectories repo.

Lands at:
    trajectories/<task-id>/<contributor>_<model>_<date>/
        config.json   result.json   job.log
        trial-0/      trial-1/      ...

`<task-id>` is harbor's task_name with any provider prefix stripped
(`loki/screenshot2-add-expense-sparse` -> `screenshot2-add-expense-sparse`).
`<model>` and `<date>` are pulled from each trial's `result.json`. Trial dirs
are renamed from harbor's random `<task>__<trial-id>` to sequential `trial-N`
(sorted by `started_at`).

Re-pushing the same `<contributor>_<model>_<date>` overwrites.

Example:
  python push_trajectories.py \\
      --jobs-dir ~/Local/harbor-spike/jobs/screenshot2-claude \\
      --person eric \\
      --repo ApolloTeam/fullstackbench-trajectories
"""
import argparse
import json
import re
import shutil
import tempfile
from pathlib import Path

from huggingface_hub import HfApi


def _slug(name: str) -> str:
    return re.sub(r"[^a-zA-Z0-9._-]+", "-", name).strip("-")


def _trial_meta(trial_dir: Path) -> dict | None:
    """Pull task_id, model, started_at from a harbor trial's result.json."""
    rj = trial_dir / "result.json"
    if not rj.exists() or not (trial_dir / "agent").exists():
        return None
    r = json.loads(rj.read_text())
    return {
        "dir": trial_dir,
        "started_at": r.get("started_at") or "",
        "model": ((r.get("agent_info") or {}).get("model_info") or {}).get("name"),
        "task_id": (r.get("task_name") or "").split("/")[-1],
    }


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--jobs-dir", required=True, help="Harbor job dir to upload")
    ap.add_argument("--person", required=True, help="Contributor slug, e.g. 'eric'")
    ap.add_argument("--repo", required=True, help="HF dataset repo id (org/name)")
    args = ap.parse_args()

    src = Path(args.jobs_dir).expanduser().resolve()
    if not src.is_dir():
        raise SystemExit(f"--jobs-dir not a directory: {src}")

    trials = sorted(
        (m for m in (_trial_meta(p) for p in src.iterdir() if p.is_dir()) if m),
        key=lambda m: m["started_at"],
    )
    if not trials:
        raise SystemExit(f"no harbor trial dirs found under {src}")

    t0 = trials[0]
    if not (t0["model"] and t0["task_id"] and t0["started_at"]):
        raise SystemExit(f"missing metadata in {t0['dir']}: {t0}")
    run = f"{args.person}_{_slug(t0['model'])}_{t0['started_at'][:10]}"
    remote = f"trajectories/{t0['task_id']}/{run}"

    with tempfile.TemporaryDirectory() as tmp:
        staging = Path(tmp) / run
        staging.mkdir()
        for name in ("config.json", "result.json", "job.log"):
            if (src / name).exists():
                shutil.copy(src / name, staging / name)
        for i, tm in enumerate(trials):
            shutil.copytree(tm["dir"], staging / f"trial-{i}")

        HfApi().upload_folder(
            repo_id=args.repo,
            repo_type="dataset",
            folder_path=str(staging),
            path_in_repo=remote,
            commit_message=f"push {remote}",
        )

    print(f"pushed {src} -> {args.repo} :: {remote}/ ({len(trials)} trials)")


if __name__ == "__main__":
    main()