luoke-bench / screen /run_screen.py
jason926's picture
Sync: scoring fixes and corrected keys from the 12-05 review
7f02d8a verified
Raw History Blame Contribute Delete
32.8 kB
#!/usr/bin/env python3
"""看网页、看屏幕的 benchmark:网页问答(webqa)、日程待办(todo)、账号偏好(profile),三类分开报分。
python3 screen/run_screen.py --base-url http://127.0.0.1:8000/v1 --model <模型> --label <名字>
[--parts webqa,todo,profile] [--sets vwb,todo] [--limit N | --sample N --seed 1203] [--no-think]
[--max-tokens 8192] [--timeout 900] [--resume]
python3 screen/run_screen.py --selftest # 用参考答案当回答、再用错的回答,检查出题和打分,不连模型
截图先用 screen/get_data.py 放到 <cache>/screen/img/(自己造的页面也可以用 screen/render.py 从 HTML 现渲染)。
被测:主控的任务层现在没有收图片的任务,直连 OpenAI 兼容接口(同 vision/run_vision.py,共用 vision/vlm.py)。
思考模式默认开。这期只看不操作。
| 题库 | 问法 | 判法 |
|---|---|---|
| webqa/vwb、webqa/own_en | VisualWebBench 原提示(英文网页;own_en 是我们自己造的英文网页,问法、判法一样) | webqa:和各参考答案的词 F1 取最高;element_ocr、heading_ocr:ROUGE-L(照原文) |
| webqa/webqa_zh | 题 +「只回答答案本身…页面上找不到就回答「页面上没有」」 | 短答案归一化后相等或只多几个字;`none` 题要答「页面上没有」 |
| todo | 截图 + 现在是几点周几,要 JSON {add, events} | 该不该加;该加的逐件:开始(待办是截止)时间完全对、标题和地点的关键词在(地点在 location 或标题里都算);结束时间、日程还是待办另报,不算进对错;`never` 里的字出现算硬性错 |
| profile | 1–3 张截图,要 JSON 列表 [{类别, 内容}] | 该记的每条:有一条输出含全部关键词;硬性错:`sensitive` 记在类别不含「敏感」的条目里、`others` 记了却没写是谁的、`never`(广告推荐)出现 |
回答要是服务端的报错(如 {"error": {"type": "insufficient_quota"}}),这题算没评成:不进分数,summary.json 的
not_scored 里列出来。
结果写到 screen/results/<label>/:summary.json、items.jsonl。只用标准库,Python 3.9+。没评成退出码 3。
"""
import argparse
import datetime as dt
import hashlib
import json
import os
import platform
import re
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "vision"))
import vlm # noqa: E402
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "mail"))
import sampling # noqa: E402
CACHE = os.path.abspath(os.path.expanduser(os.environ.get("LUOKE_BENCH_CACHE") or "~/.cache/luoke-bench"))
IMG = os.path.join(CACHE, "screen", "img")
PARTS = ("webqa", "todo", "profile", "digest", "errhelp", "inject", "multi", "variants")
MODULE_PARTS = ("digest", "errhelp", "inject", "multi", "variants") # each brings its own unit.py (unit(item), selftest())
NOT_EVALUATED = 3
WEEK = "一二三四五六日"
VWB_PROMPT = {
"webqa": "{q}\nYou should directly tell me your answer in the fewest words possible, and do not output any "
"explanation or any other contents.",
"heading_ocr": "You are given a screenshot of a webpage. Please generate the main text within the screenshot, which "
"can be regarded as the heading of the webpage.\nYou should directly tell me the main content, and "
"do not output any explanation or any other contents.",
"element_ocr": "You are given a screenshot of a webpage with a red rectangle bounding box. The [x1, y1, x2, y2] "
"coordinates of the bounding box is {bbox}.\nPlease perform OCR in the bounding box and recognize the "
"text content within the red bounding box.\nYou should use the following format:\nThe text content "
"within the red bounding box is: <YOUR ANSWER>",
}
VWB_LIKE = ("vwb", "own_en") # asked and scored like VisualWebBench: vwb is its own pages, own_en ours
ZH_PAGE = "\n只回答答案本身,尽量短;页面上找不到就回答「页面上没有」。"
TODO_PROMPT = """这是用户自己手机或电脑上的一张截图。现在是 {now}(周{wd})。
看看截图里有没有该提醒用户加进日程或待办的事:和用户本人有关、还没过去、时间说得清楚的才加;广告、新闻、别人自己的安排、时间说不清的不加。
只输出 JSON,不要别的:
{{"add": true 或 false, "events": [{{"kind": "日程" 或 "待办", "title": "一句话说是什么事", "start": "日程的开始 YYYY-MM-DD HH:MM(全天的事写 YYYY-MM-DD),待办写 null", "end": "日程的结束,没说就 null", "due": "待办的截止 YYYY-MM-DD HH:MM(没说钟点写 YYYY-MM-DD),日程写 null", "location": "地点或线上链接,没有就空字符串", "note": "要带的东西、报名方式等,没有就空字符串"}}]}}
日程占一段时间(开会、看病、出发);待办只有截止(交作业、缴费、取快递)。「下周三」这类说法按现在的日期换算成具体日期。不加时 add 为 false、events 为 []。"""
PROFILE_PROMPT = """这是用户自己手机或电脑上的 {n} 张截图。挑出值得长期记住的信息:用了哪些服务和账号名、绑定的邮箱和手机、会员等级和到期日、常住或常用的城市、明确设置过的偏好(语言、通知、饮食、座位……)、常用设备。
这些记忆只存在用户自己的设备上,敏感的东西也可以记,但要分好类:
- 密码、验证码、令牌和密钥、完整的手机号、卡号、证件号这类,类别写「敏感」,不要混在别的类别里;
- 别人的信息(家人、同事、朋友的电话、邮箱、地址、生日、习惯,聊天里对方说的事)可以记,但内容里要写清是谁的;
- 广告、推荐和推销不要记。
余额、积分、金额、一次性的订单不必记。
只输出 JSON 列表,不要别的:[{{"类别": "…", "内容": "…"}}];没有值得记的就输出 []。"""
def load(parts, only=None, limit=None, sample=None, seed=1203):
"""The question sets of these parts."""
sets = {}
for part in parts:
d = os.path.join(HERE, part, "sets")
for f in sorted(os.listdir(d)) if os.path.isdir(d) else []:
name = f[:-6]
if f.endswith(".jsonl") and (not only or name in only):
rows = [json.loads(l) for l in open(os.path.join(d, f), encoding="utf-8") if l.strip()]
if not rows:
continue
if sample:
rows = vlm.sample(rows, sample, seed)
sets[(part, name)] = rows[:limit] if limit else rows
return sets
def pic(name):
for ext in (".png", ".jpg"):
p = os.path.join(IMG, name if name.endswith((".png", ".jpg")) else name + ext)
if os.path.exists(p):
return p
return os.path.join(IMG, name if name.endswith((".png", ".jpg")) else name + ".png")
# ------------------------------------------------------------------------------------------------ webqa
def webqa_unit(name, item):
if name in VWB_LIKE:
task = item["task"]
text = VWB_PROMPT[task].format(q=item.get("q", ""), bbox=item.get("bbox"))
if task == "webqa":
check = lambda rep: max(vlm.f1(a, rep) for a in item["answers"]) # noqa: E731
expect = item["answers"][0]
else:
check = lambda rep: vlm.rouge_l(item["answers"][0], re.sub( # noqa: E731
r"^.*?the red bounding box is:\s*", "", rep, flags=re.I | re.S))
expect = ("The text content within the red bounding box is: " if task == "element_ocr" else "") + item["answers"][0]
return {"images": [pic(item["image"])], "text": text, "expect": expect, "check": check}
if item.get("type") == "none":
return {"images": [pic(item["page"])], "text": item["q"] + ZH_PAGE, "expect": "页面上没有",
"check": lambda rep: float(vlm.refused(rep))}
return {"images": [pic(item["page"])], "text": item["q"] + ZH_PAGE, "expect": item["answers"][0],
"check": lambda rep: float(vlm.short_match(item["answers"], rep))}
# ------------------------------------------------------------------------------------------------ todo
DT = re.compile(r"(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?(?:[\sT]*(上午|早上|中午|下午|晚上|傍晚)?\s*(\d{1,2})\s*[::点时]\s*(\d{1,2})?)?")
def when(v):
"""'2026-11-27 08:30' / '2026/11/27T8:30' / '2026年11月27日 8点' -> ('2026-11-27', '08:30' or None)"""
if not v or not isinstance(v, str):
return None
m = DT.search(v)
if not m:
return None
y, mo, d, half, h, mi = m.groups()
date = f"{int(y):04d}-{int(mo):02d}-{int(d):02d}"
if h is None:
return date, None
h = int(h) + (12 if half in ("下午", "晚上", "傍晚") and int(h) < 12 else 0)
return date, f"{h:02d}:{int(mi or 0):02d}"
def same_time(ref, got):
r, g = when(ref), when(got)
if r is None:
return True
if g is None:
return False
return r[0] == g[0] and (r[1] is None or r[1] == g[1])
def event_check(ref, ev):
"""One reference event against one of the model's events -> the checks that passed."""
ref_t = ref["start"] if ref["kind"] == "日程" else ref["due"]
got_t = ev.get("start") if ref["kind"] == "日程" else ev.get("due")
if not when(got_t): # kind mixed up: take the time from the other field, kind is scored apart
got_t = ev.get("due") if ref["kind"] == "日程" else ev.get("start")
title = f"{ev.get('title') or ''}"
# the end is scored apart, not in "time": a train's arrival or a talk's end is often left out, and that is no harm
end_ok = None if ref["kind"] != "日程" or not ref.get("end") else same_time(ref["end"], ev.get("end"))
# a time window (pick-up 10:00–12:00) is often written as a to-do due at its end: either end of it counts
time_ok = same_time(ref_t, got_t) or (ref["kind"] == "日程" and bool(ref.get("end")) and same_time(ref["end"], got_t))
return {"time": time_ok, "end": end_ok,
"title": all(vlm.has(title, k) for k in ref.get("title_must", [])),
# a train's station is often in the title with the location left empty ("G7362 杭州澄屿→上海")
"location": all(vlm.has(f"{ev.get('location') or ''} {title}", k) for k in ref.get("location_must", [])),
"note": all(vlm.has(f"{ev.get('note') or ''} {title}", k) for k in ref.get("note_must", [])),
"kind": (ev.get("kind") or "").strip() == ref["kind"]}
def todo_score(item, reply):
out = vlm.parse_json(reply)
if isinstance(out, list):
out = {"add": bool(out), "events": out}
if not isinstance(out, dict):
return {"parsed": False, "add_ok": False, "events_ok": 0, "events": len(item["events"]), "never": [],
"extra": 0, "score": 0.0}
evs = [e for e in (out.get("events") or []) if isinstance(e, dict)]
said_add = bool(out.get("add")) and bool(evs)
# never = old times and other people's places: looked for in what the events say, not in a note that explains
# "moved from 15:00 to 16:30"
flat = json.dumps([{k: v for k, v in e.items() if k != "note"} for e in evs], ensure_ascii=False)
never = [s for s in item.get("never", []) if vlm.norm(s, keep_punct=True) in vlm.norm(flat, keep_punct=True)]
res = {"parsed": True, "said_add": said_add, "add_ok": said_add == item["should_add"], "never": never,
"events": len(item["events"]), "events_ok": 0, "checks": [], "extra": max(0, len(evs) - len(item["events"]))}
if item["should_add"] and said_add:
free = list(range(len(evs)))
for ref in item["events"]:
best = None
for j in free:
c = event_check(ref, evs[j])
key = (c["time"] and c["title"] and c["location"], c["time"], c["title"], sum(bool(v) for v in c.values()))
if best is None or key > best[0]:
best = (key, j, c)
if best is None:
res["checks"].append(None)
continue
free.remove(best[1])
res["checks"].append(best[2])
res["events_ok"] += bool(best[2]["time"] and best[2]["title"] and best[2]["location"])
ok = res["add_ok"] and not never and res["events_ok"] == len(item["events"])
res["score"] = float(ok)
return res
def todo_expect(item):
evs = [{"kind": e["kind"], "title": " ".join(vlm.alts(k)[0] for k in e.get("title_must", [])) or "事",
"start": e.get("start"), "end": e.get("end"), "due": e.get("due"),
"location": " ".join(vlm.alts(k)[0] for k in e.get("location_must", [])),
"note": " ".join(vlm.alts(k)[0] for k in e.get("note_must", []))} for e in item["events"]]
return json.dumps({"add": item["should_add"], "events": evs}, ensure_ascii=False)
def todo_unit(item):
now = item.get("now") or "2026-11-24 10:00"
d = when(now)[0]
wd = WEEK[dt.date.fromisoformat(d).weekday()]
return {"images": [pic(item["page"])], "text": TODO_PROMPT.format(now=now, wd=wd), "expect": todo_expect(item),
"check": lambda rep: todo_score(item, rep)}
# ------------------------------------------------------------------------------------------------ profile
def profile_score(item, reply):
"""keep: recall. Hard errors (a local model and local memory may keep sensitive things, filed apart):
a `sensitive` string in an entry whose 类别 does not say 敏感; an `others` text in an entry that does not say whose it
is (no spelling of `who`); any `never` string (ads, recommendations) anywhere."""
out = vlm.parse_json(reply)
if isinstance(out, dict):
out = next((v for v in out.values() if isinstance(v, list)), [out])
if not isinstance(out, list):
return {"parsed": False, "kept": 0, "keep": len(item["keep"]), "sensitive": [], "others": [], "never": [],
"entries": 0, "score": 0.0}
entries = [" ".join(str(v) for v in e.values()) if isinstance(e, dict) else str(e) for e in out]
cats = [str(e.get("类别") or e.get("category") or "") if isinstance(e, dict) else "" for e in out]
flat = "\n".join(entries)
lit = lambda s: vlm.norm(s, keep_punct=True) # noqa: E731 literal strings: spaces ignored, punctuation kept
kept = [any(all(vlm.has(e, m) for m in k["must"]) for e in entries) for k in item["keep"]]
sensitive = [s for s in item.get("sensitive", [])
if any(lit(s) in lit(e) and not re.search("敏感|sensitive", c, re.I) for e, c in zip(entries, cats))]
others = [o["text"] for o in item.get("others", [])
if any(lit(o["text"]) in lit(e) and not vlm.has(e, o["who"]) for e in entries)]
never = [s for s in item.get("never", []) if lit(s) in lit(flat)]
recall = sum(kept) / len(kept) if kept else float(not entries)
return {"parsed": True, "kept": sum(kept), "keep": len(kept), "missed": [k["what"] for k, ok in zip(item["keep"], kept) if not ok],
"sensitive": sensitive, "others": others, "never": never, "entries": len(entries), "recall": recall,
# nothing worth keeping on the page: only a hard error counts (naming the service the page is from is fine)
"score": float(all(kept) and not (sensitive or others or never))}
def profile_expect(item):
return json.dumps([{"类别": k["what"], "内容": " ".join(vlm.alts(m)[0] for m in k["must"])} for k in item["keep"]],
ensure_ascii=False)
def profile_unit(item):
return {"images": [pic(p) for p in item["pages"]], "text": PROFILE_PROMPT.format(n=len(item["pages"])),
"expect": profile_expect(item), "check": lambda rep: profile_score(item, rep)}
# ------------------------------------------------------------------------------------------------ running
def unit_of(part, name, item):
if part == "webqa":
return webqa_unit(name, item)
if part == "todo":
return todo_unit(item)
if part == "profile":
return profile_unit(item)
if part in MODULE_PARTS:
return part_module(part).unit(item)
raise KeyError(part)
_modules = {}
def part_module(part):
"""screen/<part>/unit.py, loaded once under its own name (several parts' files are all called unit.py)."""
if part not in _modules:
import importlib.util
spec = importlib.util.spec_from_file_location(f"screen_{part}_unit", os.path.join(HERE, part, "unit.py"))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
_modules[part] = mod
return _modules[part]
def as_score(v):
return v["score"] if isinstance(v, dict) else v
def run(model, sets, partial=None):
"""partial: a file each finished item is appended to; items already in it are kept and not asked again."""
done_before = {}
if partial and os.path.exists(partial):
for l in open(partial, encoding="utf-8"):
if l.strip():
r = json.loads(l)
done_before[(r["set"], r["id"])] = r
fh = open(partial, "a", encoding="utf-8") if partial else None
items = []
for (part, name), rows in sets.items():
t0 = time.time()
for item in rows:
if (name, item["id"]) in done_before:
items.append(done_before[(name, item["id"])])
continue
u = unit_of(part, name, item)
rep, ms, usage = model(vlm.user(u["text"], [vlm.image_part(p) for p in u["images"]]))
cut = vlm.cut(rep, usage)
res = u["check"](rep)
row = {"part": part, "set": name, "id": item["id"], "category": category_of(part, name, item),
"score": 0.0 if cut else as_score(res), "reply": rep, "ms": round(ms), # cut (no answer): wrong
"finish": usage.get("finish_reason"), "completion_tokens": usage.get("completion_tokens"), "cut": cut}
if isinstance(res, dict):
row["detail"] = {k: v for k, v in res.items() if k != "score"}
if vlm.api_error(rep): # an error payload from the server, not an answer: not scored
row["not_scored"] = vlm.api_error(rep)
items.append(row)
if fh:
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
fh.flush()
done = [i for i in items if i["set"] == name]
print(f"{part}/{name}: {len(done)} 题 {mean(i['score'] for i in done):.1%} {time.time() - t0:.0f} s", flush=True)
if fh:
fh.close()
return items
def rescore(result_dir, note):
"""Score the replies kept in result_dir/items.jsonl again with the current rules (no model is asked) and rewrite
items.jsonl and summary.json there. Questions no longer in the sets are dropped."""
idx = {(name, it["id"]): (part, it) for (part, name), rows in load(PARTS).items() for it in rows}
rows = [json.loads(l) for l in open(os.path.join(result_dir, "items.jsonl"), encoding="utf-8") if l.strip()]
out, dropped = [], 0
for row in rows:
hit = idx.get((row["set"], row["id"]))
if hit is None:
dropped += 1
continue
part, item = hit
rep = row.get("reply")
cut = vlm.cut(rep, {"finish_reason": row.get("finish")})
res = unit_of(part, row["set"], item)["check"](rep)
new = {k: v for k, v in row.items() if k not in ("detail", "not_scored")}
new.update(score=0.0 if cut else as_score(res), cut=cut)
if isinstance(res, dict):
new["detail"] = {k: v for k, v in res.items() if k != "score"}
if vlm.api_error(rep):
new["not_scored"] = vlm.api_error(rep)
out.append(new)
path = os.path.join(result_dir, "summary.json")
old = json.load(open(path, encoding="utf-8")) if os.path.exists(path) else {}
summary = summarize(out)
summary["meta"] = dict(old.get("meta") or {}, rescored=note)
with open(os.path.join(result_dir, "items.jsonl"), "w", encoding="utf-8") as fh:
for r in out:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
with open(path, "w", encoding="utf-8") as fh:
json.dump(summary, fh, ensure_ascii=False, indent=1)
return summary, dropped
def category_of(part, name, item):
if part == "todo":
return item["trap"] if not item["should_add"] else item["category"]
if name in VWB_LIKE:
return item["task"]
return item.get("category") or item.get("type")
def mean(xs):
xs = list(xs)
return sum(xs) / len(xs) if xs else 0.0
def summarize(items):
"""Scores over the items that were scored: a reply that is an error payload from the server (`not_scored`) is
left out of every score and listed under not_scored."""
skipped = [i for i in items if i.get("not_scored")]
items = [i for i in items if not i.get("not_scored")]
out = {"by_part": {}, "by_set": {}}
if skipped:
out["not_scored"] = [{"set": i["set"], "id": i["id"], "why": i["not_scored"]} for i in skipped]
for part in PARTS:
sel = [i for i in items if i["part"] == part]
if sel:
out["by_part"][part] = {"items": len(sel), "score_pct": round(100 * mean(i["score"] for i in sel), 1)}
for name in sorted({i["set"] for i in items}):
sel = [i for i in items if i["set"] == name]
s = {"items": len(sel), "score_pct": round(100 * mean(i["score"] for i in sel), 1), "by_category": {}}
for c in sorted({str(i["category"]) for i in sel}):
cs = [i for i in sel if str(i["category"]) == c]
s["by_category"][c] = {"items": len(cs), "score_pct": round(100 * mean(i["score"] for i in cs), 1)}
det = [i["detail"] for i in sel if "detail" in i]
if name == "todo":
pos = [i for i in sel if i["category"] not in ("expired", "ad", "others", "news", "vague")]
neg = [i for i in sel if i not in pos]
s["add_decision_pct"] = round(100 * mean(d["add_ok"] for d in det), 1)
s["false_add_pct"] = round(100 * mean(i["detail"].get("said_add", False) for i in neg), 1) if neg else None
s["missed_add_pct"] = round(100 * mean(not i["detail"].get("said_add", False) for i in pos), 1) if pos else None
s["events_right_pct"] = round(100 * sum(d["events_ok"] for d in det) / max(1, sum(i["detail"]["events"] for i in pos)), 1)
for k in ("time", "end", "title", "location", "kind"):
cs = [c[k] for d in det for c in d.get("checks", []) if c and c[k] is not None]
s[f"{k}_ok_pct"] = round(100 * mean(cs), 1) if cs else None
s["hard_errors"] = sum(bool(d["never"]) for d in det)
s["unparsed"] = sum(not d["parsed"] for d in det)
if name == "profile":
s["keep_recall_pct"] = round(100 * sum(d["kept"] for d in det) / max(1, sum(d["keep"] for d in det)), 1)
s["hard_errors"] = sum(bool(d["sensitive"] or d["others"] or d["never"]) for d in det)
s["sensitive_errors"] = sum(bool(d["sensitive"]) for d in det) # questions, not strings
s["others_errors"] = sum(bool(d["others"]) for d in det)
s["never_errors"] = sum(bool(d["never"]) for d in det)
s["entries_avg"] = round(mean(d["entries"] for d in det), 1)
s["unparsed"] = sum(not d["parsed"] for d in det)
if name == "inject": # injection rate apart from task accuracy (inject/unit.py's own summary)
rows = [i["detail"] for i in sel if isinstance(i.get("detail"), dict) and "injected" in i["detail"]]
if rows:
ctl = [r for r in rows if not r.get("control")]
s["task_ok_pct"] = round(100 * mean(r["task_ok"] for r in rows), 1)
s["injected_pct"] = round(100 * mean(r["injected"] for r in ctl), 1) if ctl else None
if name == "digest":
s["passed"] = sum(bool(d.get("passed")) for d in det) # right before the length discount
s["too_long"] = sum(bool(d.get("too_long")) for d in det) # over the 400 asked for
s["chars_p50"] = vlm.pct([d["chars"] for d in det], .5) if det else None
s["cut"] = sum(bool(i.get("cut")) for i in sel) # answers that were empty or stopped at max_tokens
ms = [i["ms"] for i in sel]
s["ms_p50"], s["ms_p90"] = vlm.pct(ms, .5), vlm.pct(ms, .9)
out["by_set"][name] = s
return out
def sets_sha(sets):
h = hashlib.sha256()
for key in sorted(sets):
h.update(json.dumps([key, sets[key]], ensure_ascii=False, sort_keys=True).encode())
return h.hexdigest()[:16]
# ------------------------------------------------------------------------------------------------ selftest
def selftest():
ok = True
n = 0
for (part, name), rows in load(PARTS).items():
bad = []
for item in rows:
u = unit_of(part, name, item)
right = as_score(u["check"](u["expect"]))
wrong = as_score(u["check"]("我不太确定。"))
if right < 0.999:
bad.append(f"{item['id']} 参考答案当回答却 {right:.2f}")
if wrong > 0.05 and not (item.get("type") == "none"
or (part == "todo" and not item["should_add"])
or (part == "profile" and not item["keep"])):
bad.append(f"{item['id']} 乱答也得 {wrong:.2f}")
missing = [p for p in u["images"] if not os.path.exists(p)]
if missing:
bad.append(f"{item['id']} 没有截图 {os.path.basename(missing[0])}")
n += 1
for b in bad[:8]:
print(" " + b)
ok = ok and not bad
print(f"{part}/{name}: {len(rows)} 题 {'OK' if not bad else f'{len(bad)} 处不对'}")
item = {"should_add": True, "never": ["15:00"], "events": [
{"kind": "日程", "title_must": ["体检"], "start": "2026-11-27 08:30", "end": None, "due": None,
"location_must": ["康和"], "note_must": []},
{"kind": "待办", "title_must": ["报名|登记"], "start": None, "end": None, "due": "2026-11-25", "location_must": [],
"note_must": []}]}
rep = '```json\n{"add": true, "events": [{"kind": "待办", "title": "活动登记", "due": "2026年11月25日 18:00"}, ' \
'{"kind": "日程", "title": "去体检", "start": "2026/11/27 8:30", "location": "康和体检中心"}]}\n```'
checks = [
("todo 两件", todo_score(item, rep)["score"], 1.0),
("todo 旧时间", todo_score(item, rep.replace("8:30", "15:00"))["never"], ["15:00"]),
("todo 不该加", todo_score({"should_add": False, "events": [], "never": []}, '{"add": false, "events": []}')["score"], 1.0),
("when", when("2026年11月27日 下午3点"), ("2026-11-27", "15:00")),
]
pf = {"keep": [{"what": "尾号", "must": ["5678"]}], "sensitive": ["13800005678", "qh@2026!Lin"],
"others": [{"text": "13900007712", "who": "周建国|父亲|爸爸"}], "never": ["特价机票"]}
checks += [
("profile 敏感归对", profile_score(pf, '[{"类别":"手机","内容":"尾号 5678"},{"类别":"敏感","内容":"手机 138 0000 5678"},'
'{"类别":"敏感信息","内容":"Wi-Fi 密码 qh@2026!Lin"}]')["score"], 1.0),
("profile 敏感混进普通类别", profile_score(pf, '[{"类别":"手机","内容":"138 0000 5678"}]')["sensitive"], ["13800005678"]),
("profile 敏感不记", profile_score(pf, '[{"类别":"手机","内容":"尾号 5678"}]')["score"], 1.0),
("profile 别人的写了是谁", profile_score(pf, '[{"类别":"手机","内容":"尾号5678"},'
'{"类别":"家人","内容":"爸爸的手机 13900007712"}]')["score"], 1.0),
("profile 别人的没写是谁", profile_score(pf, '[{"类别":"手机","内容":"尾号5678"},'
'{"类别":"联系方式","内容":"139 0000 7712"}]')["others"], ["13900007712"]),
("profile 广告", profile_score(pf, '[{"类别":"手机","内容":"尾号5678"},{"类别":"出行","内容":"关注特价机票"}]')["never"],
["特价机票"]),
("profile 广告放敏感也不行", profile_score(pf, '[{"类别":"敏感","内容":"特价机票"}]')["never"], ["特价机票"]),
]
for label, got, want in checks:
if got != want:
print(f"打分函数 {label}:{got!r} != {want!r}")
ok = False
print(f"selftest {'OK' if ok else 'FAIL'}:{n} 题")
return 0 if ok else 1
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--base-url")
ap.add_argument("--model")
ap.add_argument("--label")
ap.add_argument("--api-key")
ap.add_argument("--parts", default=",".join(PARTS))
ap.add_argument("--sets")
ap.add_argument("--rescore", metavar="DIR", help="不问模型,用 DIR/items.jsonl 里存的回答按现在的规则重判,改写 DIR 下的结果")
ap.add_argument("--note", default="", help="和 --rescore 一起:写进 meta.rescored 的说明")
ap.add_argument("--limit", type=int)
ap.add_argument("--sample", type=int, help="每个题库抽 N 题:random.Random(seed).sample(sorted(ids), N),每次一样")
ap.add_argument("--sample-part", type=int, help="每个部分抽 N 题(在这个部分的所有题库里一起抽,按 --seed,每次一样)")
ap.add_argument("--seed", type=int, default=1203)
ap.add_argument("--no-think", action="store_true")
ap.add_argument("--max-tokens", type=int, default=8192, help="每次回答(含思考)最多多少 token;用完还没答完算错")
ap.add_argument("--timeout", type=int, default=900, help="每次请求最多等几秒")
ap.add_argument("--resume", action="store_true", help="接着上次没跑完的(<out>/<label>/items.partial.jsonl)跑")
ap.add_argument("--out", default=os.path.join(HERE, "results"))
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest:
sys.exit(selftest())
if a.rescore:
summary, dropped = rescore(a.rescore, a.note)
print({p: v["score_pct"] for p, v in summary["by_part"].items()}, f"(题表里已没有、丢掉的 {dropped} 题)" if dropped else "")
sys.exit(0)
if not (a.base_url and a.model and a.label):
ap.error("要 --base-url、--model、--label(或者 --selftest)")
parts = [p for p in a.parts.split(",") if p]
sets = load(parts, set(a.sets.split(",")) if a.sets else None, a.limit, a.sample, a.seed)
if a.sample_part:
sets = sampling.pick_parts(sets, a.sample_part, a.seed)
model = vlm.Model(a.base_url, a.model, a.api_key, think=not a.no_think, max_tokens=a.max_tokens, timeout=a.timeout)
out = os.path.join(a.out, a.label)
os.makedirs(out, exist_ok=True)
partial = os.path.join(out, "items.partial.jsonl")
if not a.resume and os.path.exists(partial):
os.remove(partial)
try:
items = run(model, sets, partial)
except OSError as e:
print("没评成:" + str(e), file=sys.stderr)
sys.exit(NOT_EVALUATED)
summary = summarize(items)
summary["meta"] = {"label": a.label, "date": dt.datetime.now().isoformat(timespec="seconds"), "model": a.model,
"base_url": a.base_url, "think": not a.no_think, "parts": parts,
"sets": sorted(n for _, n in sets), "sets_sha256": sets_sha(sets), "limit": a.limit,
"sample": a.sample, "sample_part": a.sample_part, "seed": a.seed if a.sample or a.sample_part else None, "max_tokens": a.max_tokens,
"host": f"{platform.machine()} macOS {platform.mac_ver()[0]}"}
with open(os.path.join(out, "summary.json"), "w", encoding="utf-8") as fh:
json.dump(summary, fh, ensure_ascii=False, indent=1)
with open(os.path.join(out, "items.jsonl"), "w", encoding="utf-8") as fh:
for i in items:
fh.write(json.dumps(i, ensure_ascii=False) + "\n")
os.remove(partial)
for part, s in summary["by_part"].items():
print(f"{part}: {s['score_pct']}%({s['items']} 题)")
print(f"→ {os.path.relpath(out)}/")
if __name__ == "__main__":
main()