| """chronopercept v3: ~10x scale-up (target ~1M new scenes) + `solvable_from_year` column. |
| |
| Differences vs chrono_v2_gen.py: |
| - taxonomy comes from Fable subagents (v3/tax_l0_new.json + v3/tax_l1_*.json), merged here |
| with global L1 dedup; no API taxonomy stage. |
| - entities: 6 calls/pair x 30 with per-pair avoid-lists (v1+v2+agent examples), 2 of the 6 |
| calls decade-steered (1955-1990 / 1990-2025) to flatten the year distribution. |
| - NEW verify stage (entity gate): real+verifiable? evidence anchor? solvable_from_year>=1931? |
| - scenes: rotating per-request fewshot from v1 (v2 used 2 fixed examples for all requests). |
| - qc: adds year_ok + per-scene corrected solvable_from_year. |
| - NEW backfill stage: judges solvable_from_year for all existing published merged rows. |
| - batches sharded (SHARD=20000 requests) with per-shard resume. |
| |
| Stages (each resumable; state under --workdir): |
| taxonomy -> entities -> verify -> scenes -> qc -> backfill -> assemble -> publish |
| |
| Model: claude-sonnet-5 Message Batches (no temperature — rejected by model). |
| Key: repo .env with override=True (the workbench shell exports a restricted key). |
| """ |
| import argparse, hashlib, json, re, time |
| from pathlib import Path |
|
|
| import pandas as pd |
|
|
| MODEL = "claude-sonnet-5" |
| V1_PARQUET = "/workspace-vast/jbauer/chronopercept/chronopercept_v1.parquet" |
| V2_ENTITIES = "/workspace-vast/jbauer/chronopercept/v2/entities.jsonl" |
| MERGED_DIR = Path("/workspace-vast/jbauer/chronopercept/merged") |
| SHARD = 20000 |
| SOLVABLE_DEF = ("solvable_from_year = the smallest calendar year Y such that a well-informed " |
| "reader in year Y could already know the fact(s) needed to perceive the second " |
| "meaning (the year the gap-knowledge became publicly available/true). By corpus " |
| "premise it must be >= 1931; if the knowledge existed by 1930 the item is invalid.") |
|
|
| ENT_PROMPT = """We build a corpus of short scenes in plain pre-1931 English whose implication requires post-1931 knowledge. Task type: {l0_name} — {l0_def} |
| Domain: {l1} |
| |
| List {n} entities/instances in this domain fitting the task type: each must be mentionable in a pre-1931-plausible sentence (name existed or is period-plausible as a name), while a well-informed MODERN reader attaches decisive post-1931 knowledge to it. Every entity must be REAL and its post-1931 significance verifiable — do not invent. Prefer entities NOT already famous before 1931.{decade_hint} |
| |
| Do NOT propose any of these already-mined entities (or trivial variants of them): |
| {avoid} |
| |
| Batch seed {seed} — choose entities a different assistant answering this prompt would be unlikely to duplicate; favor the less-obvious. |
| |
| Reply with ONLY JSON: {{"entities": [{{"name": "<as it would appear in text>", "gloss": "<1 sentence of the modern knowledge>", "year": <smallest year a well-informed reader could know this; must be >= 1931>}}]}}""" |
|
|
| VERIFY_PROMPT = """For each candidate entity below (mined for a corpus of pre-1931 scenes whose implication requires post-1931 knowledge), judge: |
| - real: the entity/instance actually exists(ed) as described and the stated modern knowledge is factually accurate (not invented, not garbled). |
| - evidence: one terse line naming the concrete post-1931 event/fact (with year) that carries the modern meaning. |
| - solvable_from_year: {solvable_def} |
| - valid: real AND 1931 <= solvable_from_year <= 2026 AND the modern knowledge genuinely postdates 1930 (a founding date or pre-1931 fame does NOT count as the gap). |
| |
| CANDIDATES: |
| {cands} |
| |
| Reply with ONLY JSON: {{"verdicts": [{{"i": <index>, "real": bool, "evidence": "...", "solvable_from_year": <int>, "valid": bool}}]}}""" |
|
|
| SCENE_PROMPT = """We build "chronopercept" scenes: 1-2 sentences of plain pre-1931 English in which an entity appears innocently, such that a reader in 1930 finds the text unremarkable while a well-informed modern reader perceives a decisive second meaning. |
| |
| Entity: {name} |
| Modern knowledge (the gap): {gloss} (knowable from ~{year}: {evidence}) |
| Task type: {l0_name} — {l0_def} |
| Domain: {l1} |
| |
| Two examples of the format from the existing corpus: |
| {fewshot} |
| |
| Write {n} scenes for this entity. Rules per scene: |
| - 1-2 sentences, ~15-40 words, plain pre-1931 English prose (letters, notices, diary entries, news briefs, shop talk); the entity name appears VERBATIM; no post-1930 facts, vocabulary, or tone in the TEXT itself. |
| - Vary the register, speaker, and implication across the {n} scenes. |
| - gold_percept: one sentence beginning "An informed modern reader would know that ..." stating the specific post-1931 knowledge and how it colors the scene. |
| - gold_secret: the same insight re-expressed strictly within a 1930 knowledge horizon — preserve the content shape (entity domain/category, emotional coloring, era-relation, implied consequence), FORBID post-1930 proper nouns/dates/concepts, refer to the entity only via the scene's words or 1930-expressible description, style plain English c. 1930, 1-2 sentences. |
| - secret_atoms: 2-4 terse 1930-expressible content claims. |
| - implication_class: one of dramatic-irony | poignancy | benign-surface | foreboding | hindsight-hazard | hope-or-triumph | moral-weight | valence-reversal. |
| - intended_valence: positive | negative | neutral. |
| |
| Reply with ONLY JSON: {{"scenes": [{{"scene": "...", "gold_percept": "...", "gold_secret": "...", "secret_atoms": ["..."], "implication_class": "...", "intended_valence": "..."}}]}}""" |
|
|
| QC_PROMPT = """Judge each scene below for a corpus where the TEXT must be plausible to a reader in 1930 while the PERCEPT requires post-1931 knowledge. Definition: {solvable_def} |
| |
| Per scene answer: |
| - text_ok: the scene text alone reads as unremarkable pre-1931 English (no anachronistic vocabulary, facts, or tone). |
| - gap_ok: gold_percept states knowledge a 1930 reader could NOT possess (post-1931), and it genuinely recolors the scene. |
| - secret_ok: gold_secret contains NO post-1930 proper nouns, dates, or concepts, and preserves the percept's content shape. |
| - year_ok: the stated solvable_from_year is correct within ~3 years for THIS scene's percept (not earlier knowable, not requiring later knowledge). |
| - year: the corrected solvable_from_year for this scene (equal to the stated one if year_ok). |
| |
| SCENES: |
| {scenes} |
| |
| Reply with ONLY JSON: {{"verdicts": [{{"i": <index>, "text_ok": bool, "gap_ok": bool, "secret_ok": bool, "year_ok": bool, "year": <int>}}]}}""" |
|
|
| BACKFILL_PROMPT = """For each item below (a short scene in pre-1931 English plus the modern-reader percept it is built to carry), determine: {solvable_def} |
| |
| Some items carry a prior estimate; correct it if wrong. If the percept was already knowable by 1930, return the true year anyway (it will be flagged). |
| |
| ITEMS: |
| {items} |
| |
| Reply with ONLY JSON: {{"verdicts": [{{"i": <index>, "year": <int>, "basis": "<terse: the fact+year that makes it knowable>"}}]}}""" |
|
|
|
|
| def get_client(): |
| from dotenv import load_dotenv |
| load_dotenv("/workspace-vast/jbauer/activation_oracles_dev/.env", override=True) |
| import anthropic |
| return anthropic.Anthropic() |
|
|
|
|
| def jparse(txt): |
| s0, s1 = txt.index("{"), txt.rindex("}") + 1 |
| return json.loads(txt[s0:s1]) |
|
|
|
|
| def msg_text(message): |
| return "".join(b.text for b in message.content if b.type == "text") |
|
|
|
|
| def norm_name(s): |
| return re.sub(r"[^a-z0-9]", "", str(s).lower()).rstrip("s") |
|
|
|
|
| def run_sharded(client, reqs, wd, name, parse_result): |
| """Submit reqs in shards of SHARD, poll all, stream parsed rows to per-shard files. Resumable.""" |
| shards = [reqs[i:i + SHARD] for i in range(0, len(reqs), SHARD)] |
| idfile = wd / f"batch_{name}.txt" |
| ids = idfile.read_text().split() if idfile.exists() else [] |
| while len(ids) < len(shards): |
| k = len(ids) |
| for attempt in range(30): |
| try: |
| b = client.messages.batches.create(requests=shards[k]) |
| break |
| except Exception as e: |
| print(f"[v3/{name}] shard {k} submit failed ({type(e).__name__}: {e}); retry in 120s") |
| time.sleep(120) |
| else: |
| raise RuntimeError(f"shard {k} submission failed after retries") |
| ids.append(b.id); idfile.write_text("\n".join(ids)) |
| print(f"[v3/{name}] shard {k}/{len(shards)}: {len(shards[k])} reqs -> {b.id}") |
| n_skip = 0 |
| for k, bid in enumerate(ids): |
| out = wd / f"{name}_shard{k}.jsonl" |
| if out.exists(): print(f"[v3/{name}] shard {k} already fetched"); continue |
| while True: |
| b = client.messages.batches.retrieve(bid) |
| print(f"[v3/{name}] shard {k} {bid}: {b.processing_status} | {b.request_counts}", flush=True) |
| if b.processing_status == "ended": break |
| time.sleep(120) |
| rows = [] |
| for res in client.messages.batches.results(bid): |
| if res.result.type != "succeeded": n_skip += 1; continue |
| try: rows.extend(parse_result(res.custom_id, msg_text(res.result.message))) |
| except Exception: n_skip += 1 |
| tmp = out.with_suffix(".tmp"); tmp.write_text("".join(json.dumps(r) + "\n" for r in rows)) |
| tmp.rename(out) |
| print(f"[v3/{name}] shard {k}: {len(rows)} rows") |
| allrows = [json.loads(l) for k in range(len(ids)) for l in open(wd / f"{name}_shard{k}.jsonl")] |
| print(f"[v3/{name}] TOTAL {len(allrows)} rows | skipped/failed results so far: {n_skip}") |
| return allrows |
|
|
|
|
| def load_merged(): |
| return pd.concat([pd.read_parquet(MERGED_DIR / f"{s}.parquet").assign(split=s) |
| for s in ("train", "heldout_entity", "test")], ignore_index=True) |
|
|
|
|
| def row_key(source, entity, scene_idx): |
| return f"{source}|{entity}|{scene_idx}" |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("stage", choices=["taxonomy", "entities", "verify", "scenes", "qc", |
| "backfill", "assemble", "publish"]) |
| ap.add_argument("--workdir", default="/workspace-vast/jbauer/chronopercept/v3") |
| ap.add_argument("--ent-calls-per-pair", type=int, default=6) |
| ap.add_argument("--ent-per-call", type=int, default=30) |
| ap.add_argument("--scenes-per-entity", type=int, default=8) |
| ap.add_argument("--l1-cap", type=int, default=60) |
| args = ap.parse_args() |
| wd = Path(args.workdir); wd.mkdir(parents=True, exist_ok=True) |
|
|
| if args.stage == "taxonomy": |
| v2tax = json.loads(Path("/workspace-vast/jbauer/chronopercept/v2/taxonomy.json").read_text()) |
| l0s = {x["name"]: {"name": x["name"], "definition": x["definition"], "l1": list(x["l1"]), |
| "l1_new": []} for x in v2tax["l0"]} |
| for x in json.loads((wd / "tax_l0_new.json").read_text())["l0_types"]: |
| l0s[x["name"]] = {"name": x["name"], "definition": x["definition"], "l1": [], "l1_new": []} |
| seen = {norm_name(l1) for x in l0s.values() for l1 in x["l1"]} |
| examples = {} |
| for f in sorted(wd.glob("tax_l1_*.json")): |
| d = json.loads(f.read_text()) |
| assert d["l0"] in l0s, f"unknown l0 {d['l0']} in {f.name}" |
| n_dup = 0 |
| for dom in d["domains"]: |
| key = norm_name(dom["name"]) |
| if key in seen: n_dup += 1; continue |
| seen.add(key) |
| l0s[d["l0"]]["l1_new"].append(dom["name"]) |
| examples[(d["l0"], dom["name"])] = dom.get("examples", []) |
| print(f"[v3/taxonomy] {d['l0']}: +{len([k for k in l0s[d['l0']]['l1_new']])} new " |
| f"(dropped {n_dup} dups)") |
| tax = {"l0": []} |
| for x in l0s.values(): |
| l1 = x["l1"] + x["l1_new"][: max(0, args.l1_cap - len(x["l1"]))] |
| tax["l0"].append({"name": x["name"], "definition": x["definition"], "l1": l1, |
| "l1_existing": x["l1"]}) |
| (wd / "taxonomy_v3.json").write_text(json.dumps(tax, indent=1)) |
| (wd / "tax_examples.json").write_text(json.dumps( |
| [{"l0": k[0], "l1": k[1], "examples": v} for k, v in examples.items()])) |
| n_pairs = sum(len(x["l1"]) for x in tax["l0"]) |
| print(f"[v3/taxonomy] {len(tax['l0'])} L0, {n_pairs} (L0,L1) pairs " |
| f"({sum(len(x['l1_existing']) for x in tax['l0'])} existing)") |
|
|
| elif args.stage == "entities": |
| client = get_client() |
| tax = json.loads((wd / "taxonomy_v3.json").read_text()) |
| v1 = pd.read_parquet(V1_PARQUET) |
| old = [{"name": r.L2_entity, "L0": r.L0, "L1": r.L1} for r in v1.itertuples()] + \ |
| [json.loads(l) for l in open(V2_ENTITIES)] |
| by_pair = {} |
| for e in old: by_pair.setdefault((e["L0"], e["L1"]), set()).add(e["name"]) |
| agent_ex = json.loads((wd / "tax_examples.json").read_text()) |
| for d in agent_ex: |
| for e in d["examples"]: by_pair.setdefault((d["l0"], d["l1"]), set()).add(e["name"]) |
| pairs = [(l0, l1) for l0 in tax["l0"] for l1 in l0["l1"]] |
| (wd / "pairs.json").write_text(json.dumps([[l0["name"], l1] for l0, l1 in pairs])) |
| hints = {4: " Strongly prefer entities whose modern meaning arises between 1955 and 1990.", |
| 5: " Strongly prefer entities whose modern meaning arises between 1990 and 2025."} |
| reqs = [] |
| for pi, (l0, l1) in enumerate(pairs): |
| avoid = sorted(by_pair.get((l0["name"], l1), set()))[:80] |
| avoid_s = "; ".join(avoid) if avoid else "(none yet)" |
| for s in range(args.ent_calls_per_pair): |
| reqs.append({"custom_id": f"ent-{pi}-{s}", |
| "params": {"model": MODEL, "max_tokens": 12000, |
| "output_config": {"effort": "low"}, |
| "messages": [{"role": "user", "content": ENT_PROMPT.format( |
| l0_name=l0["name"], l0_def=l0["definition"], l1=l1, |
| n=args.ent_per_call, seed=s, avoid=avoid_s, |
| decade_hint=hints.get(s, ""))}]}}) |
| pair_of = {f"ent-{pi}-{s}": pairs[pi] for pi in range(len(pairs)) |
| for s in range(args.ent_calls_per_pair)} |
| def parse(cid, txt): |
| l0, l1 = pair_of[cid] |
| return [{"name": str(e["name"]).strip(), "gloss": str(e["gloss"]), |
| "year": int(e.get("year", 0)), "L0": l0["name"], "L1": l1} |
| for e in jparse(txt)["entities"]] |
| rows = run_sharded(client, reqs, wd, "entities", parse) |
| for d in agent_ex: |
| for e in d["examples"]: |
| rows.append({"name": str(e["name"]).strip(), "gloss": str(e.get("gloss", "")), |
| "year": int(e.get("year", 0)), "L0": d["l0"], "L1": d["l1"]}) |
| seen = {norm_name(e["name"]) for e in ([json.loads(l) for l in open(V2_ENTITIES)] + |
| [{"name": n} for n in pd.read_parquet(V1_PARQUET).L2_entity.unique()])} |
| out, n_dup = [], 0 |
| for e in rows: |
| key = norm_name(e["name"]) |
| if key in seen or len(key) < 2: n_dup += 1; continue |
| seen.add(key); out.append(e) |
| (wd / "entities_mined.jsonl").write_text("".join(json.dumps(x) + "\n" for x in out)) |
| print(f"[v3/entities] {len(out)} net-new unique entities ({n_dup} dropped as dup/short)") |
|
|
| elif args.stage == "verify": |
| client = get_client() |
| ents = [json.loads(l) for l in open(wd / "entities_mined.jsonl")] |
| reqs = [] |
| for c0 in range(0, len(ents), 10): |
| chunk = ents[c0: c0 + 10] |
| cands = "\n".join(f'{i}. name: "{e["name"]}" | claimed modern knowledge: {e["gloss"]} ' |
| f'(claimed year {e["year"]}) | task type: {e["L0"]} | domain: {e["L1"]}' |
| for i, e in enumerate(chunk)) |
| reqs.append({"custom_id": f"vf-{c0}", |
| "params": {"model": MODEL, "max_tokens": 8000, |
| "output_config": {"effort": "low"}, |
| "messages": [{"role": "user", "content": VERIFY_PROMPT.format( |
| solvable_def=SOLVABLE_DEF, cands=cands)}]}}) |
| def parse(cid, txt): |
| c0 = int(cid.split("-")[1]) |
| out = [] |
| for v in jparse(txt)["verdicts"]: |
| e = ents[c0 + int(v["i"])] |
| out.append({**e, "real": bool(v["real"]), "evidence": str(v["evidence"]), |
| "solvable_from_year": int(v["solvable_from_year"]), |
| "valid": bool(v["valid"])}) |
| return out |
| rows = run_sharded(client, reqs, wd, "verify", parse) |
| kept = [r for r in rows if r["real"] and r["valid"] |
| and 1931 <= r["solvable_from_year"] <= 2026] |
| (wd / "entities_verified.jsonl").write_text("".join(json.dumps(x) + "\n" for x in kept)) |
| print(f"[v3/verify] kept {len(kept)}/{len(rows)} ({100 * len(kept) / max(1, len(rows)):.0f}%)") |
|
|
| elif args.stage == "scenes": |
| client = get_client() |
| tax = {x["name"]: x for x in json.loads((wd / "taxonomy_v3.json").read_text())["l0"]} |
| ents = [json.loads(l) for l in open(wd / "entities_verified.jsonl")] |
| v1 = pd.read_parquet(V1_PARQUET) |
| fs_pool = v1[v1.gold_percept.str.len() > 10] |
| reqs = [] |
| for i, e in enumerate(ents): |
| fs_rows = fs_pool.sample(2, random_state=i).to_dict("records") |
| fewshot = "\n".join(f'- scene: "{r["scene"]}"\n gold_percept: "{r["gold_percept"]}"' |
| for r in fs_rows) |
| l0 = tax[e["L0"]] |
| reqs.append({"custom_id": f"sc-{i}", |
| "params": {"model": MODEL, "max_tokens": 12000, |
| "output_config": {"effort": "medium"}, |
| "messages": [{"role": "user", "content": SCENE_PROMPT.format( |
| name=e["name"], gloss=e["gloss"], |
| year=e["solvable_from_year"], evidence=e["evidence"], |
| l0_name=l0["name"], l0_def=l0["definition"], l1=e["L1"], |
| fewshot=fewshot, n=args.scenes_per_entity)}]}}) |
| def parse(cid, txt): |
| e = ents[int(cid.split("-")[1])] |
| return [{"L0": e["L0"], "L1": e["L1"], "L2_entity": e["name"], "gloss": e["gloss"], |
| "year": e["solvable_from_year"], "solvable_from_year": e["solvable_from_year"], |
| "evidence": e["evidence"], "scene_idx": j, "scene": str(s["scene"]), |
| "gold_percept": str(s["gold_percept"]), "gold_secret": str(s["gold_secret"]), |
| "secret_atoms": [str(a) for a in s["secret_atoms"]], |
| "implication_class": str(s.get("implication_class", "")), |
| "intended_valence": str(s.get("intended_valence", ""))} |
| for j, s in enumerate(jparse(txt)["scenes"])] |
| rows = run_sharded(client, reqs, wd, "scenes", parse) |
| (wd / "scenes_raw.jsonl").write_text("".join(json.dumps(x) + "\n" for x in rows)) |
| print(f"[v3/scenes] {len(rows)} scenes from {len(ents)} entities") |
|
|
| elif args.stage == "qc": |
| client = get_client() |
| rows = [json.loads(l) for l in open(wd / "scenes_raw.jsonl")] |
| reqs = [] |
| for c0 in range(0, len(rows), 8): |
| chunk = rows[c0: c0 + 8] |
| scenes = "\n".join( |
| f'{i}. scene: "{r["scene"]}"\n gold_percept: "{r["gold_percept"]}"\n' |
| f' gold_secret: "{r["gold_secret"]}"\n stated solvable_from_year: {r["solvable_from_year"]}' |
| for i, r in enumerate(chunk)) |
| reqs.append({"custom_id": f"qc-{c0}", |
| "params": {"model": MODEL, "max_tokens": 6000, |
| "output_config": {"effort": "low"}, |
| "messages": [{"role": "user", "content": QC_PROMPT.format( |
| solvable_def=SOLVABLE_DEF, scenes=scenes)}]}}) |
| def parse(cid, txt): |
| c0 = int(cid.split("-")[1]) |
| return [{"row": c0 + int(v["i"]), "keep": bool(v["text_ok"]) and bool(v["gap_ok"]) |
| and bool(v["secret_ok"]) and 1931 <= int(v["year"]) <= 2026, |
| "year": int(v["year"])} for v in jparse(txt)["verdicts"]] |
| verdicts = run_sharded(client, reqs, wd, "qc", parse) |
| vmap = {v["row"]: v for v in verdicts} |
| kept = [] |
| for i, r in enumerate(rows): |
| v = vmap.get(i) |
| if v is None or not v["keep"]: continue |
| r["solvable_from_year"] = v["year"] |
| kept.append(r) |
| (wd / "scenes_kept.jsonl").write_text("".join(json.dumps(x) + "\n" for x in kept)) |
| print(f"[v3/qc] kept {len(kept)}/{len(rows)} ({100 * len(kept) / max(1, len(rows)):.0f}%)") |
|
|
| elif args.stage == "backfill": |
| client = get_client() |
| m = load_merged() |
| m["rk"] = [row_key(*t) for t in zip(m.source, m.L2_entity, m.scene_idx)] |
| assert m.rk.nunique() == len(m), "row_key collision in merged corpus" |
| recs = m.to_dict("records") |
| reqs = [] |
| for c0 in range(0, len(recs), 8): |
| chunk = recs[c0: c0 + 8] |
| items = "\n".join( |
| f'{i}. scene: "{r["scene"]}"\n percept: "{r["gold_percept"]}"' + |
| (f'\n prior estimate: {int(r["year"])}' if pd.notna(r.get("year")) else "") |
| for i, r in enumerate(chunk)) |
| reqs.append({"custom_id": f"bf-{c0}", |
| "params": {"model": MODEL, "max_tokens": 6000, |
| "output_config": {"effort": "low"}, |
| "messages": [{"role": "user", "content": BACKFILL_PROMPT.format( |
| solvable_def=SOLVABLE_DEF, items=items)}]}}) |
| def parse(cid, txt): |
| c0 = int(cid.split("-")[1]) |
| return [{"rk": recs[c0 + int(v["i"])]["rk"], "year": int(v["year"]), |
| "basis": str(v.get("basis", ""))} for v in jparse(txt)["verdicts"]] |
| rows = run_sharded(client, reqs, wd, "backfill", parse) |
| (wd / "backfill.jsonl").write_text("".join(json.dumps(x) + "\n" for x in rows)) |
| pre = sum(1 for r in rows if r["year"] <= 1930) |
| print(f"[v3/backfill] {len(rows)}/{len(recs)} rows judged; {pre} pre-1931 " |
| f"({100 * pre / max(1, len(rows)):.1f}%) will be flagged") |
|
|
| elif args.stage == "assemble": |
| rows = [json.loads(l) for l in open(wd / "scenes_kept.jsonl")] |
| m = load_merged() |
| split_map = dict(zip(m.L2_entity.str.lower().str.strip(), m.split)) |
| def split_of(entity): |
| k = entity.lower().strip() |
| if k in split_map: return split_map[k] |
| h = int(hashlib.sha1(k.encode()).hexdigest(), 16) % 100 |
| return "train" if h < 85 else "heldout_entity" if h < 95 else "test" |
| for r in rows: r["split"] = split_of(r["L2_entity"]) |
| df = pd.DataFrame(rows) |
| (wd / "data").mkdir(exist_ok=True) |
| for s in ("train", "heldout_entity", "test"): |
| d = df[df.split == s].reset_index(drop=True) |
| d.to_parquet(wd / "data" / f"{s}.parquet") |
| print(f"[v3/assemble] {s}: {len(d)} scenes, {d.L2_entity.nunique()} entities, " |
| f"{d.L1.nunique()} L1, {d.L0.nunique()} L0") |
|
|
| else: |
| from huggingface_hub import HfApi |
| import os |
| from dotenv import load_dotenv |
| load_dotenv("/workspace-vast/jbauer/activation_oracles_dev/.env", override=True) |
| api = HfApi(token=os.environ["HF_TOKEN"]) |
| v3 = pd.concat([pd.read_parquet(wd / "data" / f"{s}.parquet").assign(split=s) |
| for s in ("train", "heldout_entity", "test")], ignore_index=True) |
| v3["source"] = "v3"; v3["twin_certified"] = False; v3["solvable_pre1931"] = False |
| REPO3 = "cds-jb/chronopercept-v3" |
| api.create_repo(REPO3, repo_type="dataset", private=False, exist_ok=True) |
| for s in ("train", "heldout_entity", "test"): |
| api.upload_file(path_or_fileobj=str(wd / "data" / f"{s}.parquet"), |
| path_in_repo=f"data/{s}.parquet", repo_id=REPO3, repo_type="dataset", |
| commit_message=f"v3 {s} split") |
| api.upload_file(path_or_fileobj=__file__, path_in_repo="code/chrono_v3_gen.py", |
| repo_id=REPO3, repo_type="dataset", commit_message="generation pipeline") |
| |
| m = load_merged() |
| bf = {r["rk"]: r for r in (json.loads(l) for l in open(wd / "backfill.jsonl"))} |
| m["rk"] = [row_key(*t) for t in zip(m.source, m.L2_entity, m.scene_idx)] |
| m["solvable_from_year"] = m.rk.map(lambda k: bf[k]["year"] if k in bf else pd.NA) |
| n_miss = int(m.solvable_from_year.isna().sum()) |
| assert n_miss < 0.005 * len(m), f"backfill coverage too low: {n_miss} missing" |
| m["solvable_from_year"] = m.solvable_from_year.fillna( |
| m.year if "year" in m.columns else 1950).fillna(1950).astype(int) |
| m["solvable_pre1931"] = m.solvable_from_year <= 1930 |
| m = m.drop(columns=["rk"]) |
| allrows = pd.concat([m, v3], ignore_index=True) |
| ent_splits = allrows.groupby(allrows.L2_entity.str.lower().str.strip()).split.nunique() |
| assert (ent_splits == 1).all(), "entity spans splits after merge" |
| outdir = wd / "merged_data"; outdir.mkdir(exist_ok=True) |
| REPO = "cds-jb/chronopercept" |
| for s in ("train", "heldout_entity", "test"): |
| d = allrows[allrows.split == s].reset_index(drop=True) |
| d.to_parquet(outdir / f"{s}.parquet") |
| api.upload_file(path_or_fileobj=str(outdir / f"{s}.parquet"), |
| path_in_repo=f"data/{s}.parquet", repo_id=REPO, repo_type="dataset", |
| commit_message=f"merged v1+v2+v3 {s} split (+solvable_from_year)") |
| print(f"[v3/publish] merged {s}: {len(d)} rows") |
| api.upload_file(path_or_fileobj=__file__, path_in_repo="code/chrono_v3_gen.py", |
| repo_id=REPO, repo_type="dataset", commit_message="v3 pipeline") |
| print(f"[v3/publish] v3 rows {len(v3)}, merged total {len(allrows)}, " |
| f"entities {allrows.L2_entity.nunique()}") |
| print(f"[v3/publish] https://huggingface.co/datasets/{REPO3} and .../{REPO} " |
| f"(update README cards separately with final stats)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|