papers / build_tasks.py
abidlabs's picture
abidlabs HF Staff
Claude Fable 5.2
Add 764 papers from the updated claim atlas
a78ce54 verified
Raw History Blame Contribute Delete
12.3 kB
"""Build the task papers the page shows, in data/, from the claim atlas and the claim extractions.
Usage (from the project root or this folder):
python3 space/build_tasks.py
Inputs, all outside the Space repo:
../atlas/data/ the reviewed claim catalog (AdithyaSK/paper2env-claim-atlas): one "central"
claim per paper gives the claim text, the task and the code link
../claims/<id>.json the claim extraction for the same paper: title, figure caption, metric
../claims/img/ the cropped table or figure (already published in the dataset as site/img/<id>.png)
../manifest.csv authors
../atlas/crops.json for atlas papers with no claim extraction: which claim to show and the table or
../atlas/crops/ figure cropped for it from the PDF (crop_figures.py); crops_bad.json lists crops
that failed review and are left out. These images are copied to img/<id>.webp here
../neurips2026_accepted.csv authors for papers not in the manifest, matched by title
../atlas/pwc_tags.json tasks from Papers with Code (fetch_pwc_tags.py)
../atlas/pwc_areas.json which of the six Papers with Code areas each task belongs to
../atlas/areas_manual*.json area and tags for papers Papers with Code has no tasks for
Outputs:
index.html the list of papers (area -> IDs, hand-written ones included) is written into the
page between the INDEX:START and INDEX:END marks, so the page needs no list request.
In each area's string, IDs after the "|" have their image in this Space (img/<id>.webp)
and the ones before it in the dataset (site/img/<id>.png)
img/<id>.webp images for the papers cropped by crop_figures.py
data/index.json [[id, area], ...], the same list as a file (the page doesn't read it)
data/p/<id>.json one small file per paper, fetched when that paper is shown
data/search.json [[id, text], ...] fetched when someone types in the search box
data/skipped.json papers left out, with the reason
Papers in tasks.json (written by hand) are left out here; the page shows those first.
"""
import csv
import glob
import json
import os
import re
import shutil
import struct
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
ATLAS = os.path.join(ROOT, "atlas")
CLAIMS = os.path.join(ROOT, "claims")
OUT = os.path.join(HERE, "data")
AREAS = ["General", "Vision", "Video", "Language", "Audio", "Other"]
GENERIC_TASK = "Reproduce this comparison under the paper's stated conditions"
def load(path, default=None):
return json.load(open(path)) if os.path.exists(path) else default
def png_size(path):
with open(path, "rb") as f:
return struct.unpack(">II", f.read(24)[16:24])
def plain(text):
"""Markdown emphasis and code marks out, whitespace squeezed."""
return " ".join(re.sub(r"[*`]", "", text or "").split())
def locator(text):
"""('Table', '3') from 'Table 3 (Appendix F.2), page 22; ...', or None."""
m = re.match(r"\s*(?:Supplementary\s+)?(Table|Figure|Fig\.?)\s*([A-Z]?\.?\d+)", text or "", re.I)
return (m.group(1)[0].upper(), m.group(2)) if m else None
def webp(src, dst):
"""Lossless WebP copy of a crop, a third of the PNG's size. Returns (width, height)."""
from PIL import Image
im = Image.open(src)
if not os.path.exists(dst) or os.path.getmtime(dst) < os.path.getmtime(src):
im.convert("RGB").save(dst, "WEBP", lossless=True, method=6)
return im.size
def code_links(d):
return [f"{a['url']} (pinned at commit {a['commit']})" if a.get("commit") else a["url"] for a in d.get("assets") or [] if a.get("url")]
def area_and_tags(aid, pwc, slug_area, manual):
tasks = pwc.get(aid) or []
if tasks:
votes = {}
for slug, _ in tasks:
a = slug_area.get(slug.lower())
if a:
votes[a] = votes.get(a, 0) + 1
# a paper tagged with any vision/video/language/audio/other task goes there before General
specific = {a: n for a, n in votes.items() if a != "General"}
pool = specific or votes
area = max(pool, key=lambda a: (pool[a], -AREAS.index(a))) if pool else None
if area:
return area, [name for _, name in tasks][:3]
if aid in manual:
area, tags = manual[aid]
return (area if area in AREAS else "General"), list(tags)[:3]
return "General", [name for _, name in tasks][:3]
def main():
index = load(os.path.join(ATLAS, "data", "index.json"))
if not index:
sys.exit(f"No atlas catalog in {ATLAS}/data; nothing written.")
details = {}
for f in sorted(glob.glob(os.path.join(ATLAS, "data", "details-*.json"))):
details.update(json.load(open(f)))
manifest = {r["arxiv_id"]: r for r in csv.DictReader(open(os.path.join(ROOT, "manifest.csv"), newline=""))}
pwc = load(os.path.join(ATLAS, "pwc_tags.json"), {})
slug_area = {s.lower(): a for a, slugs in load(os.path.join(ATLAS, "pwc_areas.json"), {}).items() for s in slugs.split()}
manual = {}
for f in sorted(glob.glob(os.path.join(ATLAS, "areas_manual*.json"))):
manual.update(json.load(open(f)))
hand = load(os.path.join(HERE, "tasks.json"), [])
by_hand = {p["id"] for p in hand}
papers, skipped = [], {}
for row in index:
if row["series"] != "central" or row["paper"] in by_hand:
continue
aid, d = row["paper"], details[row["id"]]
claim = load(os.path.join(CLAIMS, aid + ".json"))
if not claim:
skipped[aid] = "no claim extraction"
continue
mc = claim["main_claim"]
img = os.path.join(CLAIMS, mc["image"])
if not os.path.exists(img):
skipped[aid] = "no figure image"
continue
# the atlas review sometimes moved the claim to a different table or figure than the one we cropped
if locator(d["paper"]["anchor"]) != locator(mc["source"]):
skipped[aid] = f"reviewed claim cites '{d['paper']['anchor']}' but the cropped image is '{mc['source']}'"
continue
w, h = png_size(img)
task = plain(d["task"]["objective"].split("**Metric:**")[0])
if not task:
task = GENERIC_TASK + " and compare your numbers with the paper's."
area, tags = area_and_tags(aid, pwc, slug_area, manual)
code = code_links(d)
facts = [
["Metric", plain(d.get("metric") or mc.get("metric", ""))],
["Compared against", plain(mc.get("comparison", ""))],
["The claim is falsified if", plain(mc.get("falsification_criterion", ""))],
["Author code", "; ".join(code) if code else "No official code was found, so implement the method from the paper."],
["Compute the authors report", plain((d.get("compute") or {}).get("reported") or "")],
]
papers.append({
"id": aid,
"arxiv": "https://arxiv.org/abs/" + d["paper"]["version"],
"title": " ".join(claim["title"].split()),
"authors": manifest.get(aid, {}).get("authors", "").replace("; ", ", "),
"area": area,
"tags": tags,
"claim": plain(row["statement"]),
"source": mc["source"].split(";")[0].strip(),
"caption": mc["caption"],
"image": f"img/{aid}.png",
"image_w": w,
"image_h": h,
"task": task,
"details": [f for f in facts if f[1]],
"code": bool(code),
"review": row["status"],
})
# Atlas papers that have no claim extraction: the claim and image come from crop_figures.py.
crops = load(os.path.join(ATLAS, "crops.json"), {})
bad = set(load(os.path.join(ATLAS, "crops_bad.json"), []))
norm = lambda t: re.sub(r"[^a-z0-9]", "", t.lower())
accepted = {norm(r["title"]): r["authors"] for r in csv.DictReader(open(os.path.join(ROOT, "neurips2026_accepted.csv"), newline=""))}
rows = {r["id"]: r for r in index}
have = by_hand | {p["id"] for p in papers} | set(skipped)
in_space = set()
os.makedirs(os.path.join(HERE, "img"), exist_ok=True)
for aid, c in sorted(crops.items()):
if aid in have or aid in bad or c["claim"] not in rows:
continue
row, d = rows[c["claim"]], details[c["claim"]]
w, h = webp(os.path.join(ATLAS, "crops", aid + ".png"), os.path.join(HERE, "img", aid + ".webp"))
area, tags = area_and_tags(aid, pwc, slug_area, manual)
code = code_links(d)
task = plain(d["task"]["objective"]) or GENERIC_TASK + " and compare your numbers with the paper's."
facts = [
["Metric", plain(d.get("metric") or "")],
["The paper reports", plain(d.get("reported") or "")],
["Counts as reproduced if", plain(d["task"].get("acceptance_rule") or "")],
["Author code", "; ".join(code) if code else "No official code was found, so implement the method from the paper."],
["Compute the authors report", plain((d.get("compute") or {}).get("reported") or "")],
]
authors = manifest.get(aid, {}).get("authors") or accepted.get(norm(row["paperTitle"]), "")
papers.append({
"id": aid,
"arxiv": "https://arxiv.org/abs/" + d["paper"]["version"],
"title": " ".join(row["paperTitle"].split()),
"authors": authors.replace("; ", ", "),
"area": area,
"tags": tags,
"claim": plain(row["statement"]),
"source": c["source"],
"caption": c["caption"],
"image": f"img/{aid}.webp",
"image_w": w,
"image_h": h,
"task": task,
"details": [f for f in facts if f[1]],
"code": bool(code),
})
in_space.add(aid)
# images of crops that are no longer shown
for f in glob.glob(os.path.join(HERE, "img", "*.webp")):
if os.path.basename(f)[:-5] not in in_space:
os.remove(f)
if not papers:
sys.exit("No papers built; nothing written.")
compact = dict(ensure_ascii=False, separators=(",", ":"))
pdir = os.path.join(OUT, "p")
shutil.rmtree(pdir, ignore_errors=True)
os.makedirs(pdir)
for p in papers:
with open(os.path.join(pdir, p["id"] + ".json"), "w") as out:
json.dump(p, out, **compact)
with open(os.path.join(OUT, "index.json"), "w") as out:
json.dump([[p["id"], p["area"]] for p in papers], out, **compact)
listed = {a: " ".join(sorted(p["id"] for p in [*hand, *papers] if p["area"] == a and p["id"] not in in_space))
+ "|" + " ".join(sorted(p["id"] for p in papers if p["area"] == a and p["id"] in in_space)) for a in AREAS}
page_path = os.path.join(HERE, "index.html")
page = open(page_path).read()
inline = f"/*INDEX:START*/const INDEX = {json.dumps(listed, **compact)}, BY_HAND = {json.dumps(sorted(by_hand), **compact)};/*INDEX:END*/"
page, n = re.subn(r"/\*INDEX:START\*/.*?/\*INDEX:END\*/", lambda m: inline, page, flags=re.S)
if n != 1:
sys.exit("index.html has no INDEX:START ... INDEX:END marks; the page's paper list was not updated.")
with open(page_path, "w") as out:
out.write(page)
with open(os.path.join(OUT, "search.json"), "w") as out:
json.dump([[p["id"], " ".join([p["title"], p["authors"], p["claim"], p["task"], p["area"], *p["tags"]]).lower()] for p in papers], out, **compact)
with open(os.path.join(OUT, "skipped.json"), "w") as out:
json.dump(skipped, out, ensure_ascii=False, indent=1, sort_keys=True)
counts = {a: sum(p["area"] == a for p in papers) for a in AREAS}
tagged = sum(bool(pwc.get(p["id"])) for p in papers)
by_manual = sum(not pwc.get(p["id"]) and p["id"] in manual for p in papers)
print(f"wrote {len(papers)} papers to data/ ({len(in_space)} of them with their image in img/; areas {counts}); skipped {len(skipped)}")
print(f"tags: {tagged} from Papers with Code, {by_manual} from areas_manual*.json, {len(papers) - tagged - by_manual} with no tags (area General)")
if __name__ == "__main__":
main()