Download build/build_db.py from HuggingFaceSwarms/pybot-explorer: direct link, hf CLI and curl.
- Browser
- Download file 9.25 kB
-
https://huggingface.co/spaces/HuggingFaceSwarms/pybot-explorer/resolve/main/build/build_db.py
- Command line
-
hf download hf://spaces/HuggingFaceSwarms/pybot-explorer/build/build_db.py
-
curl -L -o build_db.py https://huggingface.co/spaces/HuggingFaceSwarms/pybot-explorer/resolve/main/build/build_db.py
9.25 kB
| """Build data/explorer.sqlite from the scrubbed release tables and the board export. | |
| Usage: build_db.py TABLES_DIR BOARD_DIR TRACE_MANIFEST OUT_SQLITE | |
| TABLES_DIR has prs/reviews/commits.jsonl; BOARD_DIR is the board export (data/manifest.json, | |
| data/messages/*.json.gz); TRACE_MANIFEST is traces/_manifest.jsonl. | |
| """ | |
| import glob, gzip, json, os, re, sqlite3, sys | |
| from datetime import datetime, timezone | |
| CUTOFF = "2026-11-13T10:17:13.000Z" # commit 24cbc04 | |
| AUTHOR_LEAD_S, REVIEW_PAD_S = 600, 900 | |
| # Links to the run's PR pages become plain "#N" (the UI links those to the explorer); workspace paths are masked. | |
| PR_LINK = re.compile(r"(?:https?://)?huggingface\.co/datasets/HuggingFaceSwarms/[\w.-]+/discussions/(\d+)(?:/files)?") | |
| WS_PATH = re.compile(r"/data/workspaces/[^\s`'\"()<>\[\]]*") | |
| CLEANED = {} | |
| def clean(s, column): | |
| if not s: | |
| return s | |
| out, n1 = PR_LINK.subn(r"#\1", s) | |
| out, n2 = WS_PATH.subn("[WORKSPACE-PATH]", out) | |
| if n1 or n2: | |
| CLEANED[column] = [a + b for a, b in zip(CLEANED.get(column, [0, 0]), [n1, n2])] | |
| return out | |
| PR_REF = re.compile(r"(?:#|\bPR\s*#?\s*|\bpr:|refs/pr/)(\d{1,6})\b", re.I) | |
| def iso(x): | |
| """Normalise ISO strings and epoch seconds to YYYY-MM-DDTHH:MM:SS.mmmZ (sorts as text).""" | |
| if x is None: | |
| return None | |
| dt = datetime.fromtimestamp(x, timezone.utc) if isinstance(x, (int, float)) else \ | |
| datetime.fromisoformat(x.replace("Z", "+00:00")) | |
| return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z" | |
| def epoch(s): | |
| return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp() | |
| def rows(path): | |
| with open(path) as f: | |
| return [json.loads(line) for line in f] | |
| def main(tables, board, trace_manifest, out): | |
| if os.path.exists(out): | |
| os.remove(out) | |
| db = sqlite3.connect(out) | |
| db.executescript(""" | |
| CREATE TABLE commits(idx INT, sha TEXT PRIMARY KEY, parent TEXT, ts TEXT, author TEXT, title TEXT, pr INT, | |
| approvers TEXT, lp_win_rate REAL, standard_error REAL, score_revision TEXT); | |
| CREATE TABLE prs(pr INT PRIMARY KEY, author TEXT, title TEXT, description TEXT, branch TEXT, base_sha TEXT, | |
| opened_ts TEXT, state TEXT, merged_ts TEXT, merged_sha TEXT, head_sha_final TEXT, | |
| close_reason TEXT, n_updates INT, approvers TEXT, first_event_ts TEXT, last_event_ts TEXT); | |
| CREATE TABLE reviews(pr INT, reviewer TEXT, ts TEXT, head_sha TEXT, verdict TEXT, comment TEXT); | |
| CREATE TABLE channels(id INT PRIMARY KEY, name TEXT, description TEXT); | |
| CREATE TABLE messages(id INT PRIMARY KEY, channel TEXT, author TEXT, ts TEXT, thread_id INT, reply_to INT, body TEXT); | |
| CREATE VIRTUAL TABLE messages_fts USING fts5(body, content='messages', content_rowid='id'); | |
| CREATE TABLE agents(name TEXT PRIMARY KEY, lane TEXT, trace_records INT, trace_bytes INT, trace_last TEXT, | |
| posts INT, prs_opened INT, prs_merged INT, reviews INT); | |
| CREATE TABLE pr_traces(pr INT, agent TEXT, role TEXT, from_ts TEXT, to_ts TEXT); | |
| CREATE TABLE pr_messages(pr INT, message_id INT, reason TEXT, PRIMARY KEY(pr, message_id)) WITHOUT ROWID; | |
| """) | |
| commits = rows(f"{tables}/commits.jsonl") | |
| db.executemany("INSERT INTO commits VALUES (?,?,?,?,?,?,?,?,?,?,?)", [ | |
| (i, c["sha"], (c["parent_shas"] or [None])[0], iso(c["ts"]), c["author"], clean(c["title"], "commits.title"), c["pr"], | |
| json.dumps(c["approvers"]) if c["approvers"] else None, | |
| *((c["score"]["lp_win_rate"], c["score"]["standard_error"], c["score"]["revision"]) if c["score"] else (None,) * 3)) | |
| for i, c in enumerate(commits)]) | |
| prs = rows(f"{tables}/prs.jsonl") | |
| db.executemany("INSERT INTO prs VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [ | |
| (p["pr"], p["author"], clean(p["title"], "prs.title"), clean(p["description"], "prs.description"), p["branch"], | |
| p["base_sha"], iso(p["opened_ts"]), p["state_at_cutoff"], iso(p["merged_ts"]), p["merged_sha"], | |
| p["head_sha_final"], clean(p["close_reason"], "prs.close_reason"), | |
| p["n_updates"], json.dumps(p["approvers"]) if p["approvers"] else None, | |
| iso(p["first_event_ts"]), iso(p["last_event_ts"])) for p in prs]) | |
| reviews = rows(f"{tables}/reviews.jsonl") | |
| db.executemany("INSERT INTO reviews VALUES (?,?,?,?,?,?)", [ | |
| (r["pr"], r["reviewer"], iso(r["ts"]), r["head_sha"], r["verdict"], clean(r["comment"], "reviews.comment")) | |
| for r in reviews]) | |
| # Board export: chunk rows are [id, seq, sender, created_at, body, reply_to, thread_id, edited_at, mentions]. | |
| manifest = json.load(open(f"{board}/data/manifest.json")) | |
| people = {p["id"]: p["external_id"] for p in manifest["people"]} | |
| chans = {c["id"]: c["name"] for c in manifest["channels"]} | |
| db.executemany("INSERT INTO channels VALUES (?,?,?)", | |
| [(c["id"], c["name"], c["description"]) for c in manifest["channels"]]) | |
| cutoff = manifest["last_at"] | |
| msgs = [] | |
| for path in glob.glob(f"{board}/data/messages/*.json.gz"): | |
| cid = int(os.path.basename(path).split("-")[0]) | |
| for r in json.load(gzip.open(path)): | |
| body = r[4] | |
| if r[7] and r[7] > cutoff: # same rule as the board reader: show the text as of the cutoff | |
| prev = [v for v in manifest["revisions"].get(str(r[0]), []) if v[2] <= cutoff < v[3]] | |
| body = prev[0][1] if prev else body | |
| msgs.append((r[0], chans[cid], people.get(r[2], f"principal-{r[2]}"), iso(r[3]), r[6] or None, r[5] or None, | |
| clean(body, "messages.body"))) | |
| msgs.sort() | |
| db.executemany("INSERT INTO messages VALUES (?,?,?,?,?,?,?)", msgs) | |
| db.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')") | |
| # Agents: the board's experiment agents (1,000), with their lane and trace size when a trace was released. | |
| traced = {m["agent"]: m for m in map(json.loads, open(trace_manifest))} | |
| roster = sorted({p["external_id"] for p in manifest["people"] if p.get("experiment_agent")} | set(traced)) | |
| db.executemany("INSERT INTO agents(name, lane, trace_records, trace_bytes, trace_last) VALUES (?,?,?,?,?)", | |
| [(a, *((traced[a]["lane"], traced[a]["kept"], traced[a]["bytes_out"], traced[a]["last_record"]) | |
| if a in traced else (None,) * 4)) for a in roster]) | |
| # Trace windows: author [opened - 10 min, merged | closed | cutoff]; each review ts +/- 15 min. | |
| pr_end, windows = {}, [] | |
| for p in prs: | |
| end = p["merged_ts"] or (p["last_event_ts"] if p["state_at_cutoff"] == "closed" else CUTOFF) | |
| start = epoch(p["opened_ts"]) - AUTHOR_LEAD_S | |
| pr_end[p["pr"]] = (p["author"], iso(start), iso(end)) | |
| windows.append((p["pr"], p["author"], "author", iso(start), iso(end))) | |
| for r in reviews: | |
| t = epoch(r["ts"]) | |
| windows.append((r["pr"], r["reviewer"], "reviewer", iso(t - REVIEW_PAD_S), iso(t + REVIEW_PAD_S))) | |
| db.executemany("INSERT INTO pr_traces VALUES (?,?,?,?,?)", windows) | |
| # Messages: those naming the PR number, plus the author's posts inside the author window. | |
| # A mention counts only from the PR's opening until a day after it ended: "#1" in a later post is rarely PR 1. | |
| opened = {p["pr"]: iso(p["opened_ts"]) for p in prs} | |
| late = {pr: iso(epoch(end) + 86400) for pr, (_, _, end) in pr_end.items()} | |
| links = set() | |
| for mid, _, _, ts, _, _, body in msgs: | |
| for n in {int(x) for x in PR_REF.findall(body or "")}: | |
| if n in pr_end and opened[n] <= ts <= late[n]: | |
| links.add((n, mid, "mention")) | |
| db.executemany("INSERT OR IGNORE INTO pr_messages VALUES (?,?,?)", sorted(links)) | |
| db.execute("CREATE INDEX messages_author_ts ON messages(author, ts)") | |
| for pr, (author, start, end) in pr_end.items(): | |
| db.execute("""INSERT OR IGNORE INTO pr_messages SELECT ?, id, 'author_window' FROM messages | |
| WHERE author = ? AND ts BETWEEN ? AND ?""", (pr, author, start, end)) | |
| db.executescript(""" | |
| UPDATE agents SET | |
| posts = (SELECT count(*) FROM messages WHERE author = name), | |
| prs_opened = (SELECT count(*) FROM prs WHERE author = name), | |
| prs_merged = (SELECT count(*) FROM prs WHERE author = name AND state = 'merged'), | |
| reviews = (SELECT count(*) FROM reviews WHERE reviewer = name); | |
| CREATE INDEX commits_pr ON commits(pr); CREATE INDEX commits_author ON commits(author); | |
| CREATE INDEX commits_idx ON commits(idx); CREATE INDEX prs_author ON prs(author); | |
| CREATE INDEX reviews_pr ON reviews(pr); CREATE INDEX reviews_reviewer ON reviews(reviewer); | |
| CREATE INDEX messages_thread ON messages(thread_id); CREATE INDEX pr_traces_pr ON pr_traces(pr); | |
| """) | |
| db.commit() | |
| for t in ["commits", "prs", "reviews", "messages", "agents", "pr_traces", "pr_messages"]: | |
| print(t, db.execute(f"SELECT count(*) FROM {t}").fetchone()[0]) | |
| print(db.execute("SELECT reason, count(*) FROM pr_messages GROUP BY 1").fetchall()) | |
| print("rewritten [PR links, workspace paths] by column:", CLEANED) | |
| db.execute("VACUUM") | |
| db.close() | |
| print("bytes", os.path.getsize(out)) | |
| if __name__ == "__main__": | |
| main(*sys.argv[1:]) | |