luoke-bench / mail /run_tasks.py
jason926's picture
Sync: scoring fixes and corrected keys from the 12-05 review
7f02d8a verified
Raw History Blame Contribute Delete
20.2 kB
#!/usr/bin/env python3
"""Run the mail sets here that aren't sorting (sets/task_sets_real.py) through the app's own code, and score them.
python3 mail/run_tasks.py --base-url http://127.0.0.1:8000/v1 --model gemma-4-26b [--api-key KEY] [--task draft,...]
python3 mail/run_tasks.py --hub SOCKET --label "..." # through 螺壳主控 (a hub named, never found on its own)
python3 mail/run_tasks.py --rescore RESULT.json [...] # judge saved draft results again, no model
Tasks here (the default): draft (回复邮件·写回信), digest-read and digest-pick (订阅管理·精选), cleanup-real and senders-real (more
收件箱清理 and 订阅管理·退订建议). A hard failure: a contact detail the mail didn't give in a draft; an advert or what the user isn't
interested in shown or picked; something to keep suggested for the trash; a bank or a person suggested for unsubscribing.
luoke-mail's release sets (cleanup, senders, learn-sent, learn-orgs, thread, in its bench/task_sets.py) can be named
with --task too, for comparison; they are scored the same way.
The app under test: the luoke-mail checkout named by LUOKE_MAIL (default ../luoke-mail next to this repository).
Results -> mail/results/tasks/<task>/<label>.json, with the set's sha256 and the prompt's (prompt_sha256: all of
the task's files in luoke_mail/prompts/, top-level ADR 0019); `--out DIR` writes <DIR>/<task>/<label>.json instead.
Stdlib only, Python 3.9.
"""
from __future__ import annotations
import argparse
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, HERE)
import mailrepo # noqa: E402
import runmeta # noqa: E402
ROOT = mailrepo.setup() # the luoke-mail checkout under test
from luoke_mail import __version__, digest, editor, engines, hub, learn, prompts, threads, triage # noqa: E402
import task_sets as S # noqa: E402 -- luoke-mail's bench/: the release sets and their constants
import task_sets_real as R # noqa: E402 -- sets/
import retired # noqa: E402 -- sets/: questions left out of the benchmark
TASKS = ("cleanup", "senders", "learn-sent", "learn-orgs", "thread")
# the sets here (sets/task_sets_real.py): only observed, no part of a release's evaluation
OBSERVED = ("draft", "digest-read", "digest-pick", "cleanup-real", "senders-real")
# the release sets rewritten from real mails (sets/tasks_rewrite.py, sets/tasks_rewrite_thread.py): only observed
REWRITTEN = ("cleanup-rw", "senders-rw", "learn-orgs-rw", "learn-sent-rw", "thread-rw")
# more 邮件内容分析 questions (sets/learn_more.py): only observed
MORE = ("learn-orgs-more", "learn-sent-more")
# hard questions from the user's own mailbox (sets/tasks_local.py) and from public mail rewritten (sets/tasks_public.py)
LOCAL = ("cleanup-local", "senders-local", "learn-orgs-local", "digest-read-local", "digest-pick-local")
PUBLIC = ("draft-public", "thread-public", "learn-sent-public")
def _rw(name: str):
"""The rewritten sets, imported only when asked for."""
import importlib
return importlib.import_module(name)
UNSUB = triage.UNSUB_SENDER_KINDS # what the app suggests unsubscribing from
def set_hash(data) -> str:
return hashlib.sha256(json.dumps(data, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")).hexdigest()
# ---- the runs: (items with results, score) -----------------------------------------------------------------
def run_cleanup(link, sets=None) -> tuple[list, dict]:
out = []
for scope, items in (sets or S.CLEANUP).items():
rows = [dict(r, message_id=f"<{scope}{i}@task.example>", _i=i) for i, (r, _, _) in enumerate(items)
if not triage.held(r)] # as in the app: starred or kept by a label, never asked about
sizes = {}
for r in rows:
sizes[r["from_addr"]] = sizes.get(r["from_addr"], 0) + 1
rows.sort(key=lambda r: (-sizes[r["from_addr"]], r["from_addr"], r["date"])) # as 清理 batches them
got, i = {}, 0
while i < len(rows):
kinds, count = triage.classify_old(rows[i:], link, S.TODAY, scope)
for n, k in kinds.items():
got[rows[i + n - 1]["_i"]] = k
i += count
for idx, (r, ok, hard) in enumerate(items):
k = "held" if triage.held(r) else got.get(idx)
out.append({"scope": scope, "subject": r["subject"], "from": r["from_addr"], "expect": list(ok), "hard": hard,
"kind": k, "ok": k in ok or (k == "held" and not set(ok) <= set(S.TRASH)),
"hard_failure": hard and k in S.TRASH})
trash = [o for o in out if set(o["expect"]) <= set(S.TRASH)]
return out, {"n": len(out), "ok": sum(o["ok"] for o in out), "hard_n": sum(o["hard"] for o in out),
"hard_failures": sum(o["hard_failure"] for o in out), "unanswered": sum(o["kind"] is None for o in out),
"trash_found": sum(o["kind"] in S.TRASH for o in trash), "trash_n": len(trash)}
def run_senders(link, items=None) -> tuple[list, dict]:
items = items or S.SENDERS
got, i = {}, 0
senders = [s for s, _, _ in items]
while i < len(senders):
kinds, count = triage.classify_senders(senders[i:], link)
for n, k in kinds.items():
got[i + n - 1] = k
i += count
out = [{"sender": s["from_addr"], "expect": list(ok), "hard": hard, "kind": got.get(idx), "ok": got.get(idx) in ok,
"hard_failure": hard and got.get(idx) in UNSUB} for idx, (s, ok, hard) in enumerate(items)]
unsub = [o for o in out if not o["hard"]]
return out, {"n": len(out), "ok": sum(o["ok"] for o in out), "hard_n": sum(o["hard"] for o in out),
"hard_failures": sum(o["hard_failure"] for o in out), "unanswered": sum(o["kind"] is None for o in out),
"unsub_found": sum(o["kind"] in UNSUB for o in unsub), "unsub_n": len(unsub)}
def _has(text: str, words) -> bool:
low = text.lower()
return any(w.lower() in low for w in words)
def run_learn(link, kind: str, cases=None) -> tuple[list, dict]:
out, found, wanted, bad = [], 0, 0, 0
for b, case in enumerate(cases if cases is not None else S.LEARN_SENT if kind == "learn-sent" else S.LEARN_ORGS):
if kind == "learn-sent":
facts, _ = learn.from_sent(case["mails"], S.ME, link)
else:
facts, _ = learn.from_received(case["senders"], link)
facts = facts or [] # no usable answer scores as nothing found, as before
hits = []
for e in case["expect"]:
if kind == "learn-sent":
topics, words = e
hit = any(f["topic"].split(":")[0] in topics and _has(f["text"], words) for f in facts)
else:
pos, topics, words = e
hit = any(pos in f["n"] and f["topic"].split(":")[0] in topics and _has(f["text"], words) for f in facts)
hits.append(hit)
never = [f["text"] for f in facts if _has(f["text"], case["never"])]
found, wanted, bad = found + sum(hits), wanted + len(hits), bad + len(never)
out.append({"batch": b + 1, "facts": [{"topic": f["topic"], "text": f["text"], "n": f["n"]} for f in facts],
"expect_found": hits, "hard_failures": never})
return out, {"n": wanted, "ok": found, "hard_failures": bad, "facts": sum(len(o["facts"]) for o in out)}
def run_thread(link, cases=None) -> tuple[list, dict]:
out = []
for msgs, ok, hard in (cases if cases is not None else S.THREAD):
got = threads.judge(msgs, link)
state = got["state"]
why = None
if hard and "done" in ok and "you" not in ok and state == "you":
why = "done_as_you"
elif hard and "you" in ok and state != "you":
why = "missed_you"
out.append({"subject": msgs[-1]["subject"], "last_me": msgs[-1]["me"], "expect": list(ok), "hard": hard,
"state": state, "what": got["what"], "ok": state in ok, "hard_failure": bool(why), "why": why})
return out, {"n": len(out), "ok": sum(o["ok"] for o in out), "hard_n": sum(o["hard"] for o in out),
"hard_failures": sum(o["hard_failure"] for o in out),
"done_as_you": sum(o["why"] == "done_as_you" for o in out),
"missed_you": sum(o["why"] == "missed_you" for o in out)}
def _lang_ok(text: str, lang: str) -> bool:
cjk = sum("\u4e00" <= c <= "\u9fff" for c in text)
kana = sum("\u3040" <= c <= "\u30ff" for c in text)
return kana > 0 if lang == "ja" else cjk > 0 if lang == "zh" else cjk + kana == 0
def _unbracketed(text: str) -> str:
"""The draft without its 【…】: what is left there for the user to fill in is not said in the user's name."""
return re.sub(r"【[^】]*】", "", text)
def judge_draft(c: dict, body: str) -> dict:
"""One draft's verdict. `never` words and the language are looked for outside 【…】."""
said = _unbracketed(body)
bad = [w for w in c["never"] if w.lower() in said.lower()] + triage.draft_strangers(c["mail"], body, c.get("me", R.ME))
misses = [str(w) for w in c["must"] if not _has(body, w)]
if not _lang_ok(said, c["lang"]):
misses.append("language")
if c["signature"] and c["signature"] not in body[-len(c["signature"]) - 12:]:
misses.append("signature")
if c["blank"] and "【" not in body:
misses.append("no 【】")
return {"subject": c["mail"]["subject"], "body": body, "misses": misses, "hard_failures": bad, "ok": bool(body) and not misses and not bad}
def draft_score(out: list) -> dict:
return {"n": len(out), "ok": sum(o["ok"] for o in out), "hard_failures": sum(bool(o["hard_failures"]) for o in out),
"unanswered": sum(not o["body"] for o in out)}
def run_draft(link, cases=None) -> tuple[list, dict]:
out = []
for c in (cases if cases is not None else R.DRAFT):
try:
body = triage.draft_reply(c["mail"], c["points"], link, c.get("about", R.ABOUT), c["signature"], c.get("today", R.TODAY))
except engines.EngineError:
body = ""
out.append(judge_draft(c, body))
return out, draft_score(out)
# the parts whose result keeps the whole answer, so they can be judged again without the model
RESCORABLE = {"draft": lambda: R.DRAFT, "draft-public": lambda: _rw("tasks_public").DRAFT}
def rescore(path: str) -> dict:
"""Judge a saved result of a RESCORABLE part again with the judging and the set as they are now; rewrites the file.
The drafts are the ones saved; `set_sha256` becomes the set's now, `rescored` the date."""
with open(path, encoding="utf-8") as f:
rec = json.load(f)
task = rec["task"].split(".", 1)[1]
if task not in RESCORABLE:
raise SystemExit(f"{path}: {task} 的结果不能重判(只能 {', '.join(RESCORABLE)})")
cases = RESCORABLE[task]()
if [c["mail"]["subject"] for c in cases] != [it["subject"] for it in rec["items"]]:
raise SystemExit(f"{path}: 题和现在的 {task} 对不上")
items = [judge_draft(c, it["body"]) for c, it in zip(cases, rec["items"])]
score = draft_score(items)
score.update(seconds=rec["score"].get("seconds"), passes=score["hard_failures"] == 0)
rec.update(items=items, score=score, set_sha256=set_hash(cases), rescored=time.strftime("%Y-%m-%d"))
with open(path, "w", encoding="utf-8") as f:
json.dump(rec, f, ensure_ascii=False, indent=1)
return rec
def run_digest_read(link, cases=None) -> tuple[list, dict]:
out = []
for c in (cases if cases is not None else R.READ):
mail = digest.read(c["raw"])
pieces = digest.extract(mail, c["taste"], [], [], c.get("today", R.TODAY), link) or []
shown = [p for p in pieces if p["score"] >= digest.PICK]
misses = [str(w) for w in c["want"] if not any(_has(p["title"] + p["summary"], w) for p in shown)]
bad = [p["title"] for p in shown if _has(p["title"] + p["summary"], c["low"])]
if c["link"]:
word, host = c["link"]
piece = next((p for p in pieces if word in p["title"]), None)
if not piece or piece.get("host") != host:
misses.append("link")
out.append({"subject": mail["subject"], "pieces": [{k: p[k] for k in ("title", "score", "host")} for p in pieces],
"misses": misses, "hard_failures": bad, "ok": not misses and not bad})
return out, {"n": len(out), "ok": sum(o["ok"] for o in out), "hard_failures": sum(bool(o["hard_failures"]) for o in out),
"unanswered": sum(not o["pieces"] for o in out)}
def run_digest_pick(link, cases=None) -> tuple[list, dict]:
out = []
for c in (cases if cases is not None else R.PICK):
chosen = [it["title"] for it, _ in editor.choose(c["cands"], c["k"], c["taste"], c.get("liked", []), c["disliked"], link)]
bad = [t for t in chosen if _has(t, c["never"])]
hit = not c["any_of"] or any(_has(t, c["any_of"]) for t in chosen)
missed = [str(w) for w in c.get("must", []) if not any(_has(t, w) for t in chosen)] # each group: some pick has it
out.append({"picked": chosen, "hard_failures": bad, "misses": missed, "ok": hit and not bad and not missed})
return out, {"n": len(out), "ok": sum(o["ok"] for o in out), "hard_failures": sum(bool(o["hard_failures"]) for o in out)}
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--base-url")
ap.add_argument("--model")
ap.add_argument("--api-key", default=os.environ.get("LUOKE_API_KEY"))
ap.add_argument("--hub", default=None, metavar="SOCKET")
ap.add_argument("--label", default=None)
ap.add_argument("--task", default=",".join(OBSERVED))
ap.add_argument("--out", default=os.path.join(HERE, "results", "tasks"), help="where results go")
ap.add_argument("--note", action="append", default=[], metavar="KEY=VALUE", help="recorded with the result under run.notes")
ap.add_argument("--rescore", nargs="+", metavar="RESULT", help="judge saved results again (draft, draft-public), no model")
a = ap.parse_args()
if a.rescore:
for path in a.rescore:
s = rescore(path)["score"]
print(f"{path}: {s['ok']}/{s['n']} · hard failures {s['hard_failures']}")
return
if a.hub:
if not os.path.exists(a.hub):
ap.error(f"{a.hub} 不存在:螺壳主控没有在那里运行")
link = hub.Hub(a.hub, "user-waiting")
elif a.base_url and a.model:
link = engines.Direct(a.base_url, a.model, a.api_key)
else:
ap.error("--base-url and --model, or --hub SOCKET")
label = a.label or a.model or "luoke-core"
sets = {"cleanup": S.CLEANUP, "senders": S.SENDERS, "learn-sent": S.LEARN_SENT, "learn-orgs": S.LEARN_ORGS,
"thread": S.THREAD, "cleanup-real": retired.tasks("cleanup-real", R.CLEANUP), "senders-real": retired.tasks("senders-real", R.SENDERS),
"draft": R.DRAFT, "digest-read": [c["want"] for c in R.READ], "digest-pick": R.PICK,
"cleanup-rw": lambda: retired.tasks("cleanup-rw", _rw("tasks_rewrite").CLEANUP),
"senders-rw": lambda: retired.tasks("senders-rw", _rw("tasks_rewrite").SENDERS),
"learn-orgs-rw": lambda: _rw("tasks_rewrite").LEARN_ORGS,
"learn-sent-rw": lambda: _rw("tasks_rewrite_thread").LEARN_SENT, "thread-rw": lambda: retired.tasks("thread-rw", _rw("tasks_rewrite_thread").THREAD),
"learn-orgs-more": lambda: _rw("learn_more").LEARN_ORGS, "learn-sent-more": lambda: _rw("learn_more").LEARN_SENT,
"cleanup-local": lambda: _rw("tasks_local").CLEANUP, "senders-local": lambda: _rw("tasks_local").SENDERS,
"learn-orgs-local": lambda: _rw("tasks_local").LEARN_ORGS,
"digest-read-local": lambda: [c["want"] for c in _rw("tasks_local").READ], "digest-pick-local": lambda: _rw("tasks_local").PICK,
"draft-public": lambda: _rw("tasks_public").DRAFT, "thread-public": lambda: _rw("tasks_public").THREAD,
"learn-sent-public": lambda: _rw("tasks_public").LEARN_SENT}
runs = {"cleanup": run_cleanup, "senders": run_senders, "learn-sent": lambda l: run_learn(l, "learn-sent"),
"learn-orgs": lambda l: run_learn(l, "learn-orgs"), "thread": run_thread, "draft": run_draft,
"digest-read": run_digest_read, "digest-pick": run_digest_pick,
"cleanup-real": lambda l: run_cleanup(l, retired.tasks("cleanup-real", R.CLEANUP)),
"senders-real": lambda l: run_senders(l, retired.tasks("senders-real", R.SENDERS)),
"cleanup-rw": lambda l: run_cleanup(l, retired.tasks("cleanup-rw", _rw("tasks_rewrite").CLEANUP)),
"senders-rw": lambda l: run_senders(l, retired.tasks("senders-rw", _rw("tasks_rewrite").SENDERS)),
"learn-orgs-rw": lambda l: run_learn(l, "learn-orgs", _rw("tasks_rewrite").LEARN_ORGS),
"learn-sent-rw": lambda l: run_learn(l, "learn-sent", _rw("tasks_rewrite_thread").LEARN_SENT),
"thread-rw": lambda l: run_thread(l, retired.tasks("thread-rw", _rw("tasks_rewrite_thread").THREAD)),
"learn-orgs-more": lambda l: run_learn(l, "learn-orgs", _rw("learn_more").LEARN_ORGS),
"learn-sent-more": lambda l: run_learn(l, "learn-sent", _rw("learn_more").LEARN_SENT),
"cleanup-local": lambda l: run_cleanup(l, _rw("tasks_local").CLEANUP),
"senders-local": lambda l: run_senders(l, _rw("tasks_local").SENDERS),
"learn-orgs-local": lambda l: run_learn(l, "learn-orgs", _rw("tasks_local").LEARN_ORGS),
"digest-read-local": lambda l: run_digest_read(l, _rw("tasks_local").READ),
"digest-pick-local": lambda l: run_digest_pick(l, _rw("tasks_local").PICK),
"draft-public": lambda l: run_draft(l, _rw("tasks_public").DRAFT),
"thread-public": lambda l: run_thread(l, _rw("tasks_public").THREAD),
"learn-sent-public": lambda l: run_learn(l, "learn-sent", _rw("tasks_public").LEARN_SENT)}
for task in [t.strip() for t in a.task.split(",") if t.strip()]:
t0 = time.time()
items, score = runs[task](link)
score.update(seconds=round(time.time() - t0, 1), passes=score["hard_failures"] == 0)
print(f"{task:11s} {score['ok']}/{score['n']} · hard failures {score['hard_failures']} · "
f"{'PASS' if score['passes'] else 'FAIL'} · {score['seconds']}s "
+ " ".join(f"{k}={v}" for k, v in score.items() if k not in ("ok", "n", "hard_failures", "passes", "seconds")), flush=True)
for it in items:
if it.get("hard_failure") or (isinstance(it.get("hard_failures"), list) and it["hard_failures"]):
print(" hard:", json.dumps(it, ensure_ascii=False)[:240], flush=True)
base = task.removesuffix("-real").removesuffix("-rw").removesuffix("-more").removesuffix("-local").removesuffix("-public")
out_dir = os.path.join(a.out, task)
os.makedirs(out_dir, exist_ok=True)
rec = {"task": f"luoke-mail.{task}", "accessory": f"luoke-mail/{__version__}", "label": label,
"model": link.name if a.hub else a.model, "base_url": "unix:" + a.hub if a.hub else a.base_url,
"machine": engines.machine_summary(), "python": platform.python_version(), "date": time.strftime("%Y-%m-%d"),
"set_sha256": set_hash(sets[task]() if callable(sets[task]) else sets[task]), "prompt_sha256": prompts.sha256(base),
"prompt_files": prompts.files(base), "score": score, "items": items,
"run": runmeta.collect(app_root=ROOT, bench_root=os.path.dirname(HERE), base_url=a.base_url, api_key=a.api_key, notes=a.note)}
with open(os.path.join(out_dir, label.replace("/", "_") + ".json"), "w", encoding="utf-8") as f:
json.dump(rec, f, ensure_ascii=False, indent=1)
if __name__ == "__main__":
main()