ericchang00 commited on
Commit
7adf21d
·
verified ·
1 Parent(s): d92af20

simplify wrapper: 180->41 lines, direct import, drop redundant cols

Browse files
Files changed (1) hide show
  1. push_trajectories.py +24 -156
push_trajectories.py CHANGED
@@ -1,172 +1,40 @@
1
  #!/usr/bin/env python3
2
  """Push Harbor trial trajectories to an HF dataset repo as a tagged config.
3
 
4
- The workflow:
5
- 1. Run `harbor traces export` against a job dir (ATIF -> parquet rows).
6
- 2. Add person / project / experiment_group / job_name / job_date columns.
7
- 3. Push as a config named `<person>__<job-name>__<YYYYMMDD>` so the HF
8
- dataset viewer surfaces each push as a separate Subset.
9
 
10
- Run via the harbor venv so `harbor` and `datasets` are importable:
11
- ~/Local/harbor-spike/.venv/bin/python push_trajectories.py ...
12
 
13
  Example:
14
- push_trajectories.py \\
15
  --jobs-dir ~/Local/harbor-spike/jobs/screenshot2-claude \\
16
- --person eric \\
17
- --project fullstackbench \\
18
- --experiment-group screenshot-deltas \\
19
- --job-name screenshot2-claude \\
20
- --date 20260509 \\
21
  --repo ApolloTeam/fullstackbench-trajectories
22
  """
23
- from __future__ import annotations
24
-
25
  import argparse
26
- import os
27
- import re
28
- import shutil
29
- import subprocess
30
- import sys
31
- import tempfile
32
- from pathlib import Path
33
-
34
- CONFIG_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")
35
-
36
-
37
- def parse_args() -> argparse.Namespace:
38
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
39
- p.add_argument("--jobs-dir", required=True, type=Path,
40
- help="Harbor job directory containing trial subdirs")
41
- p.add_argument("--person", required=True, help="Contributor slug (e.g. 'eric')")
42
- p.add_argument("--project", required=True, help="Project slug (matches repo name)")
43
- p.add_argument("--experiment-group", required=True,
44
- help="High-level theme tag (e.g. 'screenshot-deltas')")
45
- p.add_argument("--job-name", required=True,
46
- help="Identifier for this push (matches harbor --job-name)")
47
- p.add_argument("--date", required=True,
48
- help="Run date as YYYYMMDD (used in the config_name suffix)")
49
- p.add_argument("--repo", required=True, help="HF dataset repo id (org/name)")
50
- p.add_argument("--harbor-bin", default=None,
51
- help="Path to the harbor CLI. Defaults to `which harbor`; falls back to ~/Local/harbor-spike/.venv/bin/harbor.")
52
- p.add_argument("--dry-run", action="store_true",
53
- help="Export and tag but do not push")
54
- return p.parse_args()
55
-
56
-
57
- def validate_config_name(name: str) -> None:
58
- if not CONFIG_NAME_RE.match(name):
59
- raise SystemExit(
60
- f"config_name {name!r} contains chars outside [A-Za-z0-9._-]; "
61
- "rename your --person / --job-name / --date inputs"
62
- )
63
- if len(name) > 96:
64
- raise SystemExit(f"config_name {name!r} is too long (>96 chars)")
65
-
66
-
67
- def export_with_harbor(harbor_bin: str, jobs_dir: Path, out_dir: Path) -> Path:
68
- """Run `harbor traces export` and return path to the parquet shard."""
69
- # harbor expects to write its own parquet via push_to_hub; we want a local
70
- # artifact, so we invoke the underlying export function via a small Python
71
- # shim rather than --push.
72
- shim = out_dir / "_export_shim.py"
73
- shim.write_text(
74
- "from harbor.utils.traces_utils import export_traces\n"
75
- f"ds = export_traces(root={str(jobs_dir)!r}, recursive=True, episodes='all',\n"
76
- " to_sharegpt=False, push=False, repo_id=None,\n"
77
- " export_subagents=False,\n"
78
- " include_instruction=True, include_verifier_output=True)\n"
79
- f"ds.to_parquet({str(out_dir / 'traces.parquet')!r})\n"
80
- f"print('rows:', ds.num_rows)\n"
81
- )
82
- venv_python = Path(harbor_bin).parent / "python"
83
- res = subprocess.run([str(venv_python), str(shim)], capture_output=True, text=True)
84
- if res.returncode != 0:
85
- print(res.stdout, file=sys.stderr)
86
- print(res.stderr, file=sys.stderr)
87
- raise SystemExit(f"harbor export failed: {res.returncode}")
88
- print(res.stdout.strip())
89
- parquet = out_dir / "traces.parquet"
90
- if not parquet.exists():
91
- raise SystemExit("export produced no parquet")
92
- return parquet
93
-
94
-
95
- def tag_and_push(parquet: Path, args: argparse.Namespace, config_name: str) -> None:
96
- import pyarrow.parquet as pq
97
- from datasets import Dataset
98
-
99
- table = pq.read_table(parquet)
100
- ds = Dataset(table)
101
-
102
- new_cols = {
103
- "person": args.person,
104
- "project": args.project,
105
- "experiment_group": args.experiment_group,
106
- "job_name": args.job_name,
107
- "job_date": args.date,
108
- }
109
- ds = ds.map(lambda _row: new_cols)
110
- print(f"tagged {ds.num_rows} rows; columns now: {ds.column_names}")
111
-
112
- if args.dry_run:
113
- print("--dry-run set; skipping push")
114
- return
115
-
116
- token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
117
- if not token:
118
- token_file = Path.home() / ".cache" / "huggingface" / "token"
119
- if token_file.exists():
120
- token = token_file.read_text().strip()
121
- if not token:
122
- raise SystemExit("No HF token: set HF_TOKEN or run `hf auth login`")
123
-
124
- ds.push_to_hub(
125
- args.repo,
126
- config_name=config_name,
127
- private=True,
128
- token=token,
129
- commit_message=f"push {config_name} ({ds.num_rows} rows)",
130
- )
131
- print(f"pushed {ds.num_rows} rows to {args.repo} :: config={config_name}")
132
-
133
-
134
- def resolve_harbor_bin(explicit: str | None) -> str:
135
- if explicit:
136
- if not Path(explicit).exists():
137
- raise SystemExit(f"--harbor-bin path does not exist: {explicit}")
138
- return explicit
139
- found = shutil.which("harbor")
140
- if found:
141
- return found
142
- fallback = os.path.expanduser("~/Local/harbor-spike/.venv/bin/harbor")
143
- if Path(fallback).exists():
144
- return fallback
145
- raise SystemExit(
146
- "Could not find a `harbor` binary. Either:\n"
147
- " - install harbor and ensure it's on PATH, or\n"
148
- " - pass --harbor-bin /path/to/harbor explicitly.\n"
149
- "See https://github.com/laude-institute/harbor for install instructions."
150
- )
151
 
152
 
153
  def main() -> None:
154
- args = parse_args()
155
- config_name = f"{args.person}__{args.job_name}__{args.date}"
156
- validate_config_name(config_name)
157
- print(f"config_name = {config_name}")
158
-
159
- if not args.jobs_dir.exists():
160
- raise SystemExit(f"jobs-dir does not exist: {args.jobs_dir}")
161
-
162
- harbor_bin = resolve_harbor_bin(args.harbor_bin)
163
- print(f"using harbor: {harbor_bin}")
164
-
165
- with tempfile.TemporaryDirectory(prefix="push_traj_") as tmp:
166
- out_dir = Path(tmp)
167
- parquet = export_with_harbor(harbor_bin, args.jobs_dir, out_dir)
168
- args.harbor_bin = harbor_bin # for downstream
169
- tag_and_push(parquet, args, config_name)
170
 
171
 
172
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
  """Push Harbor trial trajectories to an HF dataset repo as a tagged config.
3
 
4
+ Adds two provenance columns (`person`, `job_name`) and pushes under
5
+ `config_name=<person>__<job_name>`. Re-pushing the same name overwrites that
6
+ config; pick a fresh name (e.g. `screenshot2-claude-v2`) if you want both kept.
 
 
7
 
8
+ Requires `harbor` (the python package), `datasets`, and `huggingface_hub` to be
9
+ importable in the active interpreter.
10
 
11
  Example:
12
+ python push_trajectories.py \\
13
  --jobs-dir ~/Local/harbor-spike/jobs/screenshot2-claude \\
14
+ --person eric --job-name screenshot2-claude \\
 
 
 
 
15
  --repo ApolloTeam/fullstackbench-trajectories
16
  """
 
 
17
  import argparse
18
+ from harbor.utils.traces_utils import export_traces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
 
21
  def main() -> None:
22
+ ap = argparse.ArgumentParser()
23
+ ap.add_argument("--jobs-dir", required=True, help="Harbor job dir to export")
24
+ ap.add_argument("--person", required=True, help="Contributor slug, e.g. 'eric'")
25
+ ap.add_argument("--job-name", required=True, help="Identifier for this push; matches harbor --job-name")
26
+ ap.add_argument("--repo", required=True, help="HF dataset repo id (org/name)")
27
+ ap.add_argument("--private", action="store_true", help="Push as private (default: inherit from existing repo)")
28
+ args = ap.parse_args()
29
+
30
+ config = f"{args.person}__{args.job_name}"
31
+ ds = export_traces(root=args.jobs_dir, include_instruction=True,
32
+ include_verifier_output=True, export_subagents=False)
33
+ ds = ds.map(lambda _: {"person": args.person, "job_name": args.job_name})
34
+ ds.push_to_hub(args.repo, config_name=config,
35
+ commit_message=f"push {config} ({ds.num_rows} rows)",
36
+ **({"private": True} if args.private else {}))
37
+ print(f"pushed {ds.num_rows} rows -> {args.repo} :: config={config}")
38
 
39
 
40
  if __name__ == "__main__":