HelioAI's picture
LFM3-1.7B inference modules: experimental release
67ebcef verified
Raw History Blame Contribute Delete
5.15 kB
"""Collects the visual benchmark into a data bundle for the comparison page: for every task the screenshots, objective
checks and source code of each condition (model runs and my references).
usage: build_vis_page.py --out artifact_vis --src "Исходная модель=vis_base" "Система=vis_rep" --ref vis_claude \
--template artifact_vis/template.html --lede "..." --note "..."
Writes <out>/img/<key>_<task>_<sample>.webp, <out>/data.json and, with --template, <out>/index.html (data inline).
"""
import argparse
import json
import os
import sys
from PIL import Image
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from render import extract # noqa: E402
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--src", nargs="+", required=True, help="label=tag of model runs (results/<tag>/vis.jsonl, visual.json)")
ap.add_argument("--ref", default="vis_claude")
ap.add_argument("--ref-dir", default="data/visual/claude")
ap.add_argument("--tasks", default="data/visual/tasks.jsonl")
ap.add_argument("--w", type=int, default=560)
ap.add_argument("--template", default=None, help="page template with a /*DATA*/ placeholder -> <out>/index.html")
ap.add_argument("--lede", default="")
ap.add_argument("--note", default="")
a = ap.parse_args()
tasks = [json.loads(l) for l in open(a.tasks, encoding="utf-8")]
os.makedirs(os.path.join(a.out, "img"), exist_ok=True)
def webp(png, key):
if not os.path.exists(png):
return None
im = Image.open(png).convert("RGB")
im = im.resize((a.w, a.w * im.height // im.width), Image.LANCZOS)
name = f"img/{key}.webp"
im.save(os.path.join(a.out, name), "WEBP", quality=82, method=6)
return name
def checks(rep, task):
if rep is None:
return {"clean": False, "issues": ["no answer"]}
issues = []
if rep.get("parse_error") == "no code":
issues.append("no code block")
elif rep.get("parse_error"):
issues.append("invalid SVG")
issues += [e[:120] for e in rep.get("errors", [])[:2] if e != "no code block"]
if rep.get("failed"):
issues.append("resource failed to load")
if rep.get("blank") and rep.get("parse_error") != "no code":
issues.append("blank page")
if task["animated"] and not rep.get("animated"):
issues.append("does not move")
if rep.get("overflow"):
issues.append("wider than the window")
return {"clean": bool(rep.get("clean")), "issues": issues}
conds = []
for spec in a.src:
label, tag = spec.split("=", 1)
reps = {(r["id"], r["sample"]): r for r in json.load(open(f"results/{tag}/visual.json", encoding="utf-8"))}
recs = {}
for fn in os.listdir(f"results/{tag}"):
if fn.endswith(".jsonl") and "graded" not in fn:
for l in open(f"results/{tag}/{fn}", encoding="utf-8"):
r = json.loads(l)
recs[(r["id"], r.get("sample", 0))] = r
conds.append((label, tag, reps, recs))
data = {"conditions": [c[0] for c in conds] + ["Claude"], "tasks": []}
for t in tasks:
tid, short = t["id"], t["id"].split("/")[1]
prompt = t["prompt"].split("Answer with")[0].strip()
row = {"id": short, "cat": t["cat"], "kind": t["kind"], "animated": t["animated"], "prompt": prompt, "cells": []}
for label, tag, reps, recs in conds:
samples = []
for s in (0, 1):
rec = recs.get((tid, s))
if rec is None:
continue
fin = rec["completion"].split("</think>", 1)[1] if "</think>" in rec["completion"] else None
code = extract(fin, t["kind"])
rep = reps.get((tid, s))
samples.append({"img": webp(f"results/{tag}/png/{short}_{s}.png", f"{tag}_{short}_{s}"), "code": code or "",
"tokens": rec.get("n_tokens"), **checks(rep, t)})
row["cells"].append(samples)
ref = None
for ext in ("svg", "html"):
p = os.path.join(a.ref_dir, f"{short}.{ext}")
if os.path.exists(p):
reps = {r["id"]: r for r in json.load(open(f"results/{a.ref}/visual.json", encoding="utf-8"))}
ref = [{"img": webp(f"results/{a.ref}/png/{short}_0.png", f"ref_{short}_0"),
"code": open(p, encoding="utf-8").read(), "tokens": None, **checks(reps.get(tid), t)}]
row["cells"].append(ref or [])
data["tasks"].append(row)
data["meta"] = {"lede": a.lede, "note": a.note}
json.dump(data, open(os.path.join(a.out, "data.json"), "w", encoding="utf-8"), ensure_ascii=False)
if a.template:
page = open(a.template, encoding="utf-8").read()
blob = json.dumps(data, ensure_ascii=False).replace("</", "<\\/")
open(os.path.join(a.out, "index.html"), "w", encoding="utf-8").write(page.replace("/*DATA*/", blob))
n_img = len(os.listdir(os.path.join(a.out, "img")))
size = sum(os.path.getsize(os.path.join(a.out, "img", f)) for f in os.listdir(os.path.join(a.out, "img")))
print(f"{len(data['tasks'])} tasks, {len(data['conditions'])} conditions, {n_img} images ({size / 1e6:.1f} MB), "
f"data.json {os.path.getsize(os.path.join(a.out, 'data.json')) / 1e3:.0f} kB")