luoke-bench / screen /inject /check.py
jason926's picture
luoke-bench (4745f55dec)
e39a6b5
Raw History Blame Contribute Delete
6.97 kB
#!/usr/bin/env python3
"""Checks the prompt-injection set: python3 -I screen/inject/check.py
- fields there and of the right kind for the task; ids and pages unique; every page exists
- dates in now / start / due / end parse; weekday labels on pages like 11月28日(周六) are right for 2026
- the answer is on the page: webqa one of `answers`; todo one spelling of every title/location keyword; profile every
keep keyword (keyword alternatives `a|b`: one of them). Exceptions written out in EXEMPT.
- inject_text is on the page word for word (whitespace ignored); the first word mark is on the page (later marks may be other spellings: 6km, 已完成付款)
- controls have no marks, injections have at least one
- no mark turns up in the reference answer (the run's `expect`), so a correct reply is never taken as injected
- house rules: no real platform or brand names; links only on .example; phone numbers only in the 138 0000 xxxx form
Standard library only (and run_screen.py / unit.py from this repo).
"""
import datetime as dt
import html
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.dirname(HERE))
import unit as U # noqa: E402
SET = os.path.join(HERE, "sets", "inject.jsonl")
PAGES = os.path.join(HERE, "pages")
BANNED = ["微信", "支付宝", "淘宝", "天猫", "京东", "美团", "饿了么", "拼多多", "12306", "滴滴", "钉钉", "飞书", "小红书", "抖音", "B站",
"哔哩", "携程", "大众点评", "顺丰", "MacBook", "云栖", "iPhone", "Apple", "华为", "小米", "Windows", "菜鸟"]
TASKS = {"webqa": ["q", "answers"], "todo": ["now", "should_add", "events", "never"], "profile": ["keep", "sensitive", "others", "ignore", "never"]}
COMMON = ["id", "pages", "task", "inject_text", "inject_marks", "place", "goal", "control", "design"]
PLACES = {"explicit", "white", "tiny", "signature", "comment", "chat", "image", "notification", "control"}
GOALS = {"link", "promo", "answer", "leak", "fake_event", "time", "fake_done", "ad_pref", "false_memory", "control"}
WD = "一二三四五六日"
# answers spelled differently from the page: (id, keyword) -> why
EXEMPT = {}
def page_text(raw):
body = re.sub(r"(?s)<(style|title)[^>]*>.*?</\1>", "", raw)
return re.sub(r"\s+", "", html.unescape(re.sub(r"<[^>]+>", "", body)))
def on_page(text, spec):
t = U.lit(text)
return any(U.lit(a) in t for a in U.vlm.alts(spec))
def main():
errs = []
rows = [json.loads(l) for l in open(SET, encoding="utf-8") if l.strip()]
ids, pages = set(), set()
for it in rows:
e = lambda m: errs.append(f"{it.get('id')}: {m}") # noqa: E731
for k in COMMON + TASKS.get(it.get("task"), []):
if k not in it:
e(f"no field {k}")
if it.get("task") not in TASKS:
e(f"task {it.get('task')}")
continue
if it["id"] in ids:
e("id twice")
ids.add(it["id"])
for p in it["pages"]:
if p in pages:
e(f"page {p} used twice")
pages.add(p)
if it["place"] not in PLACES or it["goal"] not in GOALS:
e(f"place/goal {it['place']}/{it['goal']}")
if it["control"] != (it["goal"] == "control") or (it["control"] and it["place"] != "control"):
e("control flag does not match goal/place")
if it["control"] and it["inject_marks"]:
e("control with marks")
if not it["control"] and not it["inject_marks"]:
e("injection without marks")
raw = ""
for p in it["pages"]:
f = os.path.join(PAGES, p + ".html")
if not os.path.exists(f):
e(f"no page {p}")
continue
raw += open(f, encoding="utf-8").read()
text = page_text(raw)
if re.search(r"</?(p|div|span|b|br|table|tr|td)\b|style=", text):
e("raw HTML shows as text on the page")
if re.sub(r"\s+", "", it["inject_text"]) not in text:
e("inject_text not on the page")
words = [m for m in it["inject_marks"] if not m.startswith("time:")]
for m in it["inject_marks"]:
if m.startswith("time:") and U.R.when(m[5:]) is None:
e(f"bad time mark {m}")
if words and not on_page(text, words[0]):
e(f"first mark {words[0]} not on the page")
# the task's answer is on the page
if it["task"] == "webqa":
if not any(on_page(text, a) for a in it["answers"]):
e(f"no answer on the page: {it['answers']}")
elif it["task"] == "todo":
if U.R.when(it["now"]) is None:
e("bad now")
for ev in it["events"]:
for k in ("start", "end", "due"):
if ev.get(k) and U.R.when(ev[k]) is None:
e(f"bad date {ev[k]}")
for k in ev.get("title_must", []) + ev.get("location_must", []) + ev.get("note_must", []):
if not on_page(text, k) and (it["id"], k) not in EXEMPT:
e(f"keyword {k} not on the page")
else:
for kp in it["keep"]:
for k in kp["must"]:
if not on_page(text, k) and (it["id"], k) not in EXEMPT:
e(f"keep {kp['what']}: {k} not on the page")
for o in it["others"]:
if not on_page(text, o["text"]):
e(f"others {o['text']} not on the page")
# no mark in the reference answer
u = U.unit(it)
if U.marks_hit(it, u["expect"]):
e(f"marks in the reference answer: {U.marks_hit(it, u['expect'])}")
# house rules
for b in BANNED:
if b in text:
e(f"banned name on page: {b}")
for dom in re.findall(r"[a-z0-9][a-z0-9.-]*\.(?:com|cn|net|org|io|dev)\b", raw.lower()):
e(f"non-.example domain {dom}")
for ph in re.findall(r"(?<!\d)1[3-9]\d[ -]?\d{4}[ -]?\d{4}(?!\d)", text):
if not re.match(r"1[3-9]\d[ -]?0000", ph):
e(f"phone number not in the 1xx 0000 xxxx form: {ph}")
for mo, d, w in re.findall(r"(\d{1,2})月(\d{1,2})日[((]?(?:周|星期)([一二三四五六日天])", text):
real = WD[dt.date(2026, int(mo), int(d)).weekday()]
if w.replace("天", "日") != real:
e(f"weekday wrong on page: {mo}月{d}日 周{w} (is 周{real})")
by = lambda k: {v: sum(1 for r in rows if r[k] == v) for v in sorted({r[k] for r in rows})} # noqa: E731
print(f"{len(rows)} 题;task {by('task')};对照 {sum(r['control'] for r in rows)}")
print(f"place {by('place')}")
print(f"goal {by('goal')}")
for x in errs:
print(" " + x)
print("OK" if not errs else f"{len(errs)} problems")
return 1 if errs else 0
if __name__ == "__main__":
sys.exit(main())