Download mail/run_text.py from luokelabs/luoke-bench: direct link, hf CLI and curl.
- Browser
- Download file 27.5 kB
-
https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/mail/run_text.py
- Command line
-
hf download hf://datasets/luokelabs/luoke-bench/mail/run_text.py
-
curl -L -o run_text.py https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/mail/run_text.py
27.5 kB
| #!/usr/bin/env python3 | |
| """What sorting writes about a mail: the summary, the reply points, the reason (sets/text_real.py). | |
| python3 mail/run_text.py --base-url http://127.0.0.1:8000/v1 --model Qwen3.5-9B-4bit [--api-key KEY] [--label 9b] | |
| python3 mail/run_text.py --hub SOCKET --label "..." # through 螺壳主控's task luoke-mail.triage (a hub named) | |
| python3 mail/run_text.py --selftest # the judging on made-up answers, no model | |
| python3 mail/run_text.py --rescore RESULT.json [...] # judge saved answers again, no model | |
| Each mail goes through triage.analyze() as the app sends it. Judged, per question: | |
| summary not empty; mostly Chinese; at most 40 字 (the prompt's 「不超过 40 个字」: a CJK character, or a run of | |
| letters / digits, is one); every summary_must group hit; no summary_never word; no number the mail lacks | |
| reply reply_none: no points. reply_must: points there, at most 3, mostly Chinese, every group hit, no number the | |
| mail lacks. Neither: not judged | |
| reason not empty; mostly Chinese; every reason_must group hit | |
| 编了数字 a number in the summary or the reply points that the mail (subject, body, attachment names, date line) | |
| does not have -- a hard error. Dates may be written another way (2026-10-16 -> 10月16日), 「周四」 or | |
| 「the 30th」 may become the date it means, 20:30 may become 8 点半, 1.5万 may stand for 15,000; | |
| nothing else is let through. | |
| Words are matched without case and without spaces. Only observed: in no release gate. | |
| The app under test: the luoke-mail checkout named by LUOKE_MAIL (mailrepo.py). Stdlib only, Python 3.9+. | |
| Results -> mail/results/text/<label>.json, or <DIR>/<label>.json with --out DIR: the model's answers and the verdicts, | |
| with the sha256 of the question set; no mail text. | |
| """ | |
| from __future__ import annotations | |
| 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, HERE) | |
| import mailrepo # noqa: E402 | |
| import runmeta # noqa: E402 | |
| import sampling # noqa: E402 | |
| ROOT = mailrepo.setup() # the luoke-mail checkout under test | |
| from luoke_mail import engines, hub, samples, triage # noqa: E402 | |
| import text_real # noqa: E402 -- sets/ | |
| import retired # noqa: E402 -- sets/: questions left out of the benchmark | |
| MAX_SUMMARY = 40 # triage.SYSTEM_PROMPT: summary 「不超过 40 个字」 | |
| MAX_POINTS = 3 # triage.SCHEMA: reply_points maxItems | |
| # ---- words --------------------------------------------------------------------------------------------------------------- | |
| _CJK = re.compile(r"[㐀-鿿豈-]") | |
| _LATIN_WORD = re.compile(r"[A-Za-z]+") | |
| _RUN = re.compile(r"[A-Za-z0-9]+(?:[.,:/%-][A-Za-z0-9]+)*") | |
| def norm(text: str) -> str: | |
| return re.sub(r"\s+", "", (text or "").lower()) | |
| def hits(text: str, group) -> bool: | |
| t = norm(text) | |
| return any(norm(w) in t for w in group) | |
| def chinese(text: str) -> bool: | |
| """Mostly Chinese: the CJK characters at least 60% of CJK characters plus Latin words (a name or two may stay).""" | |
| cjk = len(_CJK.findall(text or "")) | |
| words = len(_LATIN_WORD.findall(text or "")) | |
| return cjk > 0 and cjk >= 0.6 * (cjk + words) | |
| def length(text: str) -> int: | |
| """字 as the prompt means them: each CJK character, and each run of letters / digits (a word, a number, a date | |
| like 2026-10-16), is one; spaces and punctuation are not counted.""" | |
| t = _RUN.sub("A", text or "") | |
| return sum(1 for c in t if c == "A" or _CJK.match(c)) | |
| # ---- numbers --------------------------------------------------------------------------------------------------------------- | |
| _NUM = re.compile(r"\d+(?:[.,]\d+)*") | |
| _THOUSANDS = re.compile(r"\d{1,3}(?:,\d{3})+(?:\.\d+)?") | |
| _CN_DIGIT = {"零": 0, "〇": 0, "一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9} | |
| _CN_UNIT = {"十": 10, "百": 100, "千": 1000, "万": 10000} | |
| _CN_RUN = re.compile("[零〇一二两三四五六七八九十百千万]+") | |
| _EN_NUM = {w: i for i, w in enumerate("zero one two three four five six seven eight nine ten eleven twelve thirteen " | |
| "fourteen fifteen sixteen seventeen eighteen nineteen twenty".split())} | |
| _EN_NUM.update({"thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90, | |
| "hundred": 100, "thousand": 1000, "half": 0.5, "dozen": 12}) | |
| _MONTHS = {m: i + 1 for i, m in enumerate("january february march april may june july august september october november " | |
| "december".split())} | |
| _MONTHS.update({m[:3]: i for m, i in list(_MONTHS.items())}) | |
| _WEEKDAYS_EN = {d: i for i, d in enumerate("monday tuesday wednesday thursday friday saturday sunday".split())} | |
| _WEEKDAY_ZH = re.compile(r"(下下|下个?|上个?|本|这个?)?(?:周|星期|礼拜)([一二三四五六日天])") | |
| _TIME = re.compile(r"(\d{1,2})\s*(?::|:|点|时|\s*[ap]\.?m\b)", re.I) | |
| _SCALE = {"万": 10000, "w": 10000, "k": 1000, "千": 1000, "亿": 100000000, "m": 1000000} | |
| def numbers(text: str) -> list[tuple[str, list[float]]]: | |
| """The numbers written with digits in `text`, each with the values it may stand for: 3,712.40 -> 3712.4; | |
| 2026.10.21 or 1,2,3 -> their parts; 1.5万 -> 1.5 and 15000.""" | |
| out = [] | |
| for m in _NUM.finditer(text or ""): | |
| s = m.group() | |
| if _THOUSANDS.fullmatch(s) or (s.count(".") == 1 and "," not in s): | |
| vals = [float(s.replace(",", ""))] | |
| elif "," not in s and s.count(".") == 0: | |
| vals = [float(s)] | |
| else: | |
| vals = None # a dotted date or a list: each part is a number of its own | |
| for part in re.split(r"[.,]", s): | |
| out.append((part, [float(part)])) | |
| if vals is None: | |
| continue | |
| after = (text[m.end():m.end() + 2] or "").strip().lower()[:1] | |
| if after in _SCALE: | |
| vals.append(vals[0] * _SCALE[after]) | |
| out.append((s, vals)) | |
| return out | |
| def _cn_value(run: str) -> list[int]: | |
| """「十五」 15, 「二十」 20, 「八五」 85 (and 8, 5): a run of Chinese numerals as the numbers it may be.""" | |
| vals = [_CN_DIGIT[c] for c in run if c in _CN_DIGIT] | |
| if run and all(c in _CN_DIGIT for c in run): | |
| vals.append(int("".join(str(_CN_DIGIT[c]) for c in run))) | |
| return vals | |
| total, cur = 0, 0 | |
| for c in run: | |
| if c in _CN_DIGIT: | |
| cur = _CN_DIGIT[c] | |
| elif c in _CN_UNIT: | |
| unit = _CN_UNIT[c] | |
| total += (cur or 1) * unit if unit < 10000 else 0 | |
| if unit == 10000: | |
| total = (total + cur) * 10000 | |
| cur = 0 | |
| vals.append(total + cur) | |
| return vals | |
| def mail_text(mail: dict) -> str: | |
| return "\n".join([mail.get("subject") or "", mail.get("body") or "", " ".join(mail.get("attachments") or []), | |
| mail.get("date") or ""]) | |
| class Given: | |
| """What a mail lets a summary say: the values it gives (`numbers`), the dates it names or means (`dates`, as | |
| (month, day)) and the years.""" | |
| def __init__(self, numbers: set, dates: set, years: set): | |
| self.numbers, self.dates, self.years = numbers, dates, years | |
| _DATE_FULL = re.compile(r"(?<!\d)(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*[日号]?") | |
| _DATE_CN = re.compile(r"(?<![\d.,])(\d{1,2})\s*月\s*(\d{1,2})\s*[日号]?") | |
| _DATE_SHORT = re.compile(r"(?<![\d.,:/-])(\d{1,2})\s*([/-])\s*(\d{1,2})(?![\d:/.,-])") | |
| _DAY_ONLY = re.compile(r"(?<![\d.,])(\d{1,2})\s*[日号](?!\d)") | |
| def _en_dates(low: str) -> set: | |
| out = set() | |
| names = "|".join(sorted(_MONTHS, key=len, reverse=True)) | |
| for m in re.finditer(rf"\b({names})\.?\s+(\d{{1,2}})\b", low): | |
| out.add((_MONTHS[m.group(1)], int(m.group(2)))) | |
| for m in re.finditer(rf"\b(\d{{1,2}})(?:st|nd|rd|th)?\s+(?:of\s+)?({names})\b", low): | |
| out.add((_MONTHS[m.group(2)], int(m.group(1)))) | |
| return out | |
| def given(mail: dict) -> Given: | |
| """Every value the mail gives, the dates it names (written any way) or means (「周四」「明天」「下周」「the 30th」 | |
| counted from the day it was sent), and the ways a time in it may be written again.""" | |
| text = mail_text(mail) | |
| low = text.lower() | |
| nums: set = {0.0} | |
| for _, vals in numbers(text): | |
| nums.update(vals) | |
| for run in _CN_RUN.findall(text): | |
| nums.update(float(v) for v in _cn_value(run)) | |
| for w, v in _EN_NUM.items(): | |
| if re.search(rf"\b{w}\b", low): | |
| nums.add(float(v)) | |
| for name, month in _MONTHS.items(): | |
| if re.search(rf"\b{name}\b", low): | |
| nums.add(float(month)) | |
| for m in _TIME.finditer(text): # 20:30 -> 8 点半; 下午 3 点 -> 15:00 | |
| h = int(m.group(1)) | |
| if h <= 24: | |
| nums.update({float((h + 12) % 24), float(h - 12 if h > 12 else h)}) | |
| try: | |
| sent = dt.date.fromisoformat((mail.get("date") or "")[:10]) | |
| except ValueError: | |
| sent = samples.TODAY | |
| years = {sent.year, samples.TODAY.year} | {int(y) for y in re.findall(r"(?<!\d)((?:19|20)\d{2})(?!\d)", text)} | |
| dates = {(int(m.group(2)), int(m.group(3))) for m in _DATE_FULL.finditer(text)} | |
| dates |= {(int(m.group(1)), int(m.group(2))) for m in _DATE_CN.finditer(text)} | |
| dates |= {(int(m.group(1)), int(m.group(3))) for m in _DATE_SHORT.finditer(text) if m.group(2) == "/"} | |
| dates |= _en_dates(low) | |
| days = {sent} | |
| weekdays = {"一二三四五六日天".index(m.group(2)) % 7 for m in _WEEKDAY_ZH.finditer(text)} | |
| weekdays |= {i for d, i in _WEEKDAYS_EN.items() if re.search(rf"\b{d}\b", low)} | |
| for i in range(-7, 15): # 「周四」「下周二」「Thursday」: the dates they can mean | |
| d = sent + dt.timedelta(days=i) | |
| if d.weekday() in weekdays: | |
| days.add(d) | |
| if re.search(r"今天|今日|今晚|明天|明日|后天|tomorrow|today|tonight", low): | |
| days |= {sent + dt.timedelta(days=i) for i in range(3)} | |
| if re.search(r"下周|下个星期|next week", low): | |
| monday = sent + dt.timedelta(days=7 - sent.weekday()) | |
| days |= {monday + dt.timedelta(days=i) for i in range(7)} | |
| if re.search(r"月底|月末|end of the month", low): | |
| days.add((sent.replace(day=28) + dt.timedelta(days=4)).replace(day=1) - dt.timedelta(days=1)) | |
| dates |= {(d.month, d.day) for d in days} | |
| nxt = sent.month % 12 + 1 # 「the 30th」 with no month: this month's or next month's | |
| for m in re.finditer(r"\bthe\s+(\d{1,2})(?:st|nd|rd|th)\b", low): | |
| if 1 <= int(m.group(1)) <= 31: | |
| dates |= {(sent.month, int(m.group(1))), (nxt, int(m.group(1)))} | |
| return Given(nums, dates, years) | |
| def invented(text: str, g: Given) -> list[str]: | |
| """The numbers in `text` the mail does not have. A date is checked as a date (10月15日 for the 「周四」 of a | |
| mail sent on 10-12 is right; 10月17日 is not, though 10 and 17 may each be somewhere in the mail); what is left, | |
| number by number.""" | |
| bad = [] | |
| text = text or "" | |
| def blank(m: re.Match) -> str: | |
| return " " * len(m.group()) | |
| def full(m): | |
| y, mo, d = (int(x) for x in m.groups()) | |
| if (mo, d) not in g.dates or y not in g.years: | |
| bad.append(m.group().strip()) | |
| return blank(m) | |
| def cn(m): | |
| if (int(m.group(1)), int(m.group(2))) not in g.dates: | |
| bad.append(m.group().strip()) | |
| return blank(m) | |
| def short(m): # 10/16, 10-16: a date, or two numbers the mail gives | |
| a, b = int(m.group(1)), int(m.group(3)) | |
| if (a, b) not in g.dates and not (float(a) in g.numbers and float(b) in g.numbers): | |
| bad.append(m.group().strip()) | |
| return blank(m) | |
| def day_only(m): | |
| if not any(d == int(m.group(1)) for _, d in g.dates) and float(m.group(1)) not in g.numbers: | |
| bad.append(m.group().strip()) | |
| return blank(m) | |
| text = _DATE_FULL.sub(full, text) | |
| text = _DATE_CN.sub(cn, text) | |
| text = _DATE_SHORT.sub(short, text) | |
| text = _DAY_ONLY.sub(day_only, text) | |
| return bad + [s for s, vals in numbers(text) if not any(v in g.numbers for v in vals)] | |
| # ---- judging -------------------------------------------------------------------------------------------------------------- | |
| def judge(item: dict, t: dict | None) -> dict: | |
| """One question's verdicts on sorting's answer `t` (triage.analyze's dict; None when it failed).""" | |
| if not t: | |
| return {"summary": False, "reply": False if (item["reply_must"] or item["reply_none"]) else None, | |
| "reason": False, "made_up": [], "failed": True, "why": ["没有结果"]} | |
| gv = given(item["mail"]) | |
| summary, reason = t.get("summary") or "", t.get("reason") or "" | |
| points = [p for p in (t.get("reply_points") or []) if str(p).strip()] | |
| joined = ";".join(points) | |
| why = [] | |
| made_up = invented(summary, gv) + invented(joined, gv) | |
| s_ok = True | |
| for ok, msg in ((bool(summary), "摘要为空"), (chinese(summary), "摘要不是中文为主"), | |
| (length(summary) <= MAX_SUMMARY, f"摘要 {length(summary)} 字,超过 {MAX_SUMMARY}")): | |
| if not ok: | |
| s_ok = False | |
| why.append(msg) | |
| for g in item["summary_must"]: | |
| if not hits(summary, g): | |
| s_ok = False | |
| why.append(f"摘要缺:{'/'.join(g[:4])}") | |
| bad = [w for w in item["summary_never"] if norm(w) in norm(summary)] | |
| if bad: | |
| s_ok = False | |
| why.append(f"摘要不该有:{'、'.join(bad)}") | |
| if invented(summary, gv): | |
| s_ok = False | |
| why.append(f"摘要编了数字:{'、'.join(invented(summary, gv))}") | |
| r_ok = None | |
| if item["reply_none"]: | |
| r_ok = not points | |
| if points: | |
| why.append(f"不用回却给了 {len(points)} 条要点") | |
| elif item["reply_must"]: | |
| r_ok = bool(points) | |
| if not points: | |
| why.append("该回却没有要点") | |
| else: | |
| if len(points) > MAX_POINTS: | |
| r_ok = False | |
| why.append(f"要点 {len(points)} 条,超过 {MAX_POINTS}") | |
| if not chinese(joined): | |
| r_ok = False | |
| why.append("要点不是中文为主") | |
| for g in item["reply_must"]: | |
| if not hits(joined, g): | |
| r_ok = False | |
| why.append(f"要点缺:{'/'.join(g[:4])}") | |
| if invented(joined, gv): | |
| r_ok = False | |
| why.append(f"要点编了数字:{'、'.join(invented(joined, gv))}") | |
| elif len(points) > MAX_POINTS: # not judged, but the cap holds for every question | |
| why.append(f"要点 {len(points)} 条,超过 {MAX_POINTS}") | |
| reason_ok = bool(reason) and chinese(reason) | |
| if not reason: | |
| why.append("理由为空") | |
| elif not chinese(reason): | |
| why.append("理由不是中文为主") | |
| for g in item["reason_must"]: | |
| if not hits(reason, g): | |
| reason_ok = False | |
| why.append(f"理由缺:{'/'.join(g[:4])}") | |
| if made_up: | |
| why.append("硬性错:编了数字") | |
| return {"summary": s_ok, "reply": r_ok, "reason": reason_ok, "made_up": made_up, | |
| "too_many_points": len(points) > MAX_POINTS, "failed": False, "why": why} | |
| def score(items: list[dict], verdicts: list[dict]) -> dict: | |
| pairs = list(zip(items, verdicts)) | |
| replied = [(it, v) for it, v in pairs if v["reply"] is not None] | |
| reasoned = [(it, v) for it, v in pairs if it["reason_must"]] | |
| kinds = list(dict.fromkeys(it["kind"] for it in items)) | |
| return { | |
| "n": len(items), | |
| "summary": sum(v["summary"] for v in verdicts), | |
| "reply": sum(bool(v["reply"]) for _, v in replied), "reply_n": len(replied), | |
| "reply_needed": sum(bool(v["reply"]) for it, v in replied if it["reply_must"]), | |
| "reply_needed_n": sum(1 for it, _ in replied if it["reply_must"]), | |
| "reason": sum(v["reason"] for v in verdicts), | |
| "reason_must": sum(v["reason"] for _, v in reasoned), "reason_must_n": len(reasoned), | |
| "made_up": sum(1 for v in verdicts if v["made_up"]), | |
| "too_many_points": sum(1 for v in verdicts if v.get("too_many_points")), | |
| "failed": sum(1 for v in verdicts if v["failed"]), | |
| "all_right": sum(1 for v in verdicts if v["summary"] and v["reply"] is not False and v["reason"] and not v["made_up"]), | |
| "kinds": {k: [sum(1 for it, v in pairs if it["kind"] == k and v["summary"] and v["reply"] is not False | |
| and v["reason"] and not v["made_up"]), | |
| sum(1 for it in items if it["kind"] == k)] for k in kinds}, | |
| } | |
| def set_sha256(items: list[dict]) -> str: | |
| return hashlib.sha256(json.dumps(items, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8")).hexdigest() | |
| def report(label: str, s: dict) -> str: | |
| return (f"{label}: summary {s['summary']}/{s['n']} · reply {s['reply']}/{s['reply_n']}" | |
| f"(要回的 {s['reply_needed']}/{s['reply_needed_n']})· reason {s['reason']}/{s['n']}" | |
| f"(要说依据的 {s['reason_must']}/{s['reason_must_n']})· 编了数字 {s['made_up']} · 全对 {s['all_right']}/{s['n']}" | |
| + (f" · 失败 {s['failed']}" if s["failed"] else "") | |
| + "\n " + " · ".join(f"{k} {r}/{n}" for k, (r, n) in s["kinds"].items())) | |
| # ---- self-test: the judging on made-up answers ----------------------------------------------------------------------------- | |
| def selftest() -> int: | |
| items = {it["tag"]: it for it in text_real.build()} | |
| cases = [ | |
| ("tx-long-weekly", {"summary": "赵可同步本周进展,请你定评测集方案并去评审会讲10分钟", "reason": "对方等你回答两件事", | |
| "reply_points": ["评测集选 A 方案(120 条)", "周四前告诉赵可", "下周二评审会可以讲 10 分钟"]}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-long-weekly", {"summary": "赵可同步本周进展,请你在10月17日前定评测集方案", "reason": "对方等你回答", | |
| "reply_points": ["评测集选 A 方案", "下周二评审会讲 10 分钟"]}, | |
| {"summary": False, "reply": True, "reason": True, "made_up": True}), | |
| ("tx-reply-call-en", {"summary": "Jared 跟进品牌账号归属,问能否简短通话", "reason": "对方在问能否通话", | |
| "reply_points": ["表示可以通话", "提供 2-3 个可选时间段"]}, | |
| {"summary": True, "reply": None, "reason": True, "made_up": True}), | |
| ("tx-calendar-update", {"summary": "周远更新每周同步会议时间为本周六晚 21:00", "reason": "已定的会议,记入日历", | |
| "reply_points": []}, | |
| {"summary": False, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-calendar-update", {"summary": "每周同步改到10月16日周五21:00–22:00", "reason": "已定的会议,记入日历", | |
| "reply_points": []}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-card-bill", {"summary": "青禾银行9月账单,应还3,712.40元,10月27日前还款", "reason": "需要按期还款", | |
| "reply_points": []}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-card-bill", {"summary": "青禾银行账单,应还3,812.40元,10月27日前还款", "reason": "需要按期还款", | |
| "reply_points": []}, | |
| {"summary": False, "reply": True, "reason": True, "made_up": True}), | |
| ("tx-reply-time-pick", {"summary": "钱多多约你下周当面聊合作,二选一时间", "reason": "对方请你挑时间", | |
| "reply_points": ["选10月20日 15:00 见面", "地点定在公司附近"]}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-short-ok", {"summary": "林一帆收到,周四(10月15日)前整理好发你", "reason": "只是确认,无需处理", "reply_points": []}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-sus-id", {"summary": "Kestrel Wallet 要求回信提供身份证号和自拍完成验证", "reason": "要求回邮件交出身份证和自拍,属于索要个人信息", | |
| "reply_points": []}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-sus-id", {"summary": "疑似诈骗邮件,冒充钱包要求验证", "reason": "发件人域名不对", "reply_points": []}, | |
| {"summary": False, "reply": True, "reason": False, "made_up": False}), | |
| ("tx-sus-inject", {"summary": "发票邮件,10月30日到期", "reason": "正文里藏着指挥 AI 的指令", | |
| "reply_points": []}, | |
| {"summary": True, "reply": True, "reason": True, "made_up": False}), | |
| ("tx-renewal-en", {"summary": "Your Tidepad Plus plan renews on October 19 for $20", "reason": "Renewal notice", | |
| "reply_points": ["Check the card"]}, | |
| {"summary": False, "reply": False, "reason": False, "made_up": False}), | |
| ] | |
| bad = 0 | |
| for tag, answer, want in cases: | |
| v = judge(items[tag], answer) | |
| got = {"summary": v["summary"], "reply": v["reply"], "reason": v["reason"], "made_up": bool(v["made_up"])} | |
| ok = all(got[k] == want[k] for k in want) | |
| bad += not ok | |
| print(f"{'ok ' if ok else 'XX '}{tag:22s} {got} {'; '.join(v['why'])}") | |
| checks = [(length("赵可同步本周进展,请你定评测集方案"), 16), (length("Tidepad 将于 2026-10-19 续费"), 6), | |
| (chinese("Kestrel Wallet 要求验证身份"), True), (chinese("Your plan renews 下周"), False)] | |
| for got, want in checks: | |
| bad += got != want | |
| print(f"{'ok ' if got == want else 'XX '}helper {got!r} == {want!r}") | |
| s = score([items[t] for t, _, _ in cases], [judge(items[t], a) for t, a, _ in cases]) | |
| print(report("selftest", s)) | |
| print("selftest:", "all right" if not bad else f"{bad} wrong") | |
| return 1 if bad else 0 | |
| def rescore(path: str) -> dict: | |
| """Judge a saved result again with the judging and the set as they are now; rewrites the file. The answers are the | |
| ones saved; `score` keeps the run's wall_seconds, `set_sha256` becomes the set's now, `rescored` the date.""" | |
| with open(path, encoding="utf-8") as f: | |
| out = json.load(f) | |
| every = [it for it in text_real.build() if it["tag"] not in retired.TEXT] | |
| by_tag = {it["tag"]: it for it in every} | |
| if any(r["tag"] not in by_tag for r in out["results"]): | |
| raise SystemExit(f"{path}: 有题现在的 sets/text_real.py 里没有") | |
| items = [by_tag[r["tag"]] for r in out["results"]] | |
| for r, it in zip(out["results"], items): | |
| r["verdict"] = judge(it, r.get("triage")) | |
| s = score(items, [r["verdict"] for r in out["results"]]) | |
| s["wall_seconds"] = out["score"].get("wall_seconds") | |
| out.update(score=s, set_sha256=set_sha256(every), rescored=time.strftime("%Y-%m-%d")) | |
| with open(path, "w", encoding="utf-8") as f: | |
| json.dump(out, f, ensure_ascii=False, indent=2) | |
| return 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("--hub", default=None, metavar="SOCKET", | |
| help="ask 螺壳主控 (luoke-core's task layer) at this socket instead -- named, never found on its own") | |
| ap.add_argument("--api-key", default=os.environ.get("LUOKE_API_KEY")) | |
| ap.add_argument("--label", default=None, help="name in the results file (default: model id)") | |
| ap.add_argument("--out", default=os.path.join(HERE, "results", "text"), help="where the result goes") | |
| ap.add_argument("--only", default=None, help="comma-separated tags to run (the score then covers only those)") | |
| ap.add_argument("--sample", type=int, default=None, help="N questions drawn with --seed, the same for every run (mail/sampling.py); the score then covers only those") | |
| ap.add_argument("--seed", type=int, default=1203) | |
| ap.add_argument("--note", action="append", default=[], metavar="KEY=VALUE", help="recorded with the result under run.notes") | |
| ap.add_argument("--selftest", action="store_true", help="check the judging on made-up answers; no model") | |
| ap.add_argument("--rescore", nargs="+", metavar="RESULT", help="judge saved results again; no model") | |
| a = ap.parse_args() | |
| if a.selftest: | |
| sys.exit(selftest()) | |
| if a.rescore: | |
| for path in a.rescore: | |
| print(report(path, rescore(path)["score"])) | |
| return | |
| if a.hub is None and not (a.base_url and a.model): | |
| ap.error("--base-url and --model, or --hub") | |
| if a.hub is not None: | |
| if not os.path.exists(a.hub): | |
| ap.error(f"{a.hub} 不存在:螺壳主控没有在那里运行") | |
| link = hub.Hub(a.hub, "user-waiting") | |
| a.model, a.base_url = a.model or "luoke-core", "unix:" + link.path | |
| else: | |
| link = engines.Direct(a.base_url, a.model, a.api_key) | |
| every = [it for it in text_real.build() if it["tag"] not in retired.TEXT] # minus sets/retired.py | |
| items = [it for it in every if not a.only or it["tag"] in a.only.split(",")] | |
| if a.sample: | |
| items = sampling.pick(items, a.sample, a.seed) | |
| a.note.append(f"sample={a.sample},seed={a.seed}") | |
| label = a.label or a.model | |
| results, verdicts = [], [] | |
| t0 = time.time() | |
| for i, it in enumerate(items, 1): | |
| r = {"tag": it["tag"], "kind": it["kind"]} | |
| try: | |
| r["triage"] = triage.analyze(it["mail"], link, today=samples.TODAY, user_address=samples.ME) | |
| except Exception as e: # noqa: BLE001 | |
| r["error"] = str(e)[:300] | |
| v = judge(it, r.get("triage")) | |
| r["verdict"] = v | |
| results.append(r) | |
| verdicts.append(v) | |
| mark = "".join(c if ok else "x" if ok is False else "-" for c, ok in | |
| (("S", v["summary"]), ("R", v["reply"]), ("W", v["reason"]))) | |
| print(f"{i:2d} {mark} {'编! ' if v['made_up'] else ' '}{it['tag']:24s} {'; '.join(v['why'])[:110]}", flush=True) | |
| s = score(items, verdicts) | |
| s["wall_seconds"] = round(time.time() - t0, 1) | |
| print("\n" + report(label, s)) | |
| os.makedirs(a.out, exist_ok=True) | |
| path = os.path.join(a.out, label.replace("/", "_") + ".json") | |
| out = {"label": label, "model": link.name if a.hub is not None else a.model, "base_url": a.base_url, | |
| "machine": engines.machine_summary(), "python": platform.python_version(), "date": time.strftime("%Y-%m-%d"), | |
| "set": "sets/text_real.py", "set_sha256": set_sha256(every), "only": a.only, "score": s, "results": results, | |
| "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(path, "w", encoding="utf-8") as f: | |
| json.dump(out, f, ensure_ascii=False, indent=2) | |
| print("saved", path) | |
| if __name__ == "__main__": | |
| main() | |