File size: 5,684 Bytes
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python3
"""Checks the Chinese webqa set against its pages.  python3 -I screen/webqa/check.py

- every row has id, page, q, answers, type, design; ids unique and wq001.. in order
- type is one of read / find / compare / count / infer / none; `today`, if a row has it, is YYYY-MM-DD
- the page exists, says how to shoot it (phone / desktop), and every link on it is on a `.example` domain
- answers are a non-empty list of short strings, no duplicates
- the answer is on the page (HTML with tags stripped, all whitespace removed on both sides):
    read, find      at least one accepted answer must be found on the page
    compare         same, unless the answer is a number (a difference worked out from two numbers)
    count, infer    not checked: the answer is worked out (a count, a sum, a date, yes / no)
    none            the answers must be exactly ["页面上没有"]
- pages don't name real platforms or brands from the blocklist below
"""
import collections
import html
import json
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
SET = os.path.join(HERE, "sets", "webqa_zh.jsonl")
TYPES = ["read", "find", "compare", "count", "infer", "none"]
FIELDS = ["id", "page", "q", "answers", "type", "design"]
BLOCK = ["微信", "支付宝", "淘宝", "天猫", "京东", "美团", "饿了么", "拼多多", "12306", "滴滴", "钉钉", "飞书", "小红书",
         "抖音", "B站", "哔哩", "携程", "大众点评", "顺丰", "MacBook", "云栖", "龙井", "iPhone", "Apple", "华为", "小米", "Windows"]
NUM = re.compile(r"^[¥¥]?\d+(\.\d+)?\s*(元|分|积分|GB|个|家|场|天|册|本|份|人|类|种)?$")


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 main():
    errs, rows = [], [json.loads(l) for l in open(SET, encoding="utf-8") if l.strip()]
    texts = {}
    seen = set()
    for i, r in enumerate(rows, 1):
        rid = r.get("id", "?")
        for f in FIELDS:
            if f not in r:
                errs.append("%s: missing %s" % (rid, f))
        if rid in seen:
            errs.append("%s: duplicate id" % rid)
        seen.add(rid)
        if rid != "wq%03d" % i:
            errs.append("%s: expected id wq%03d" % (rid, i))
        if r.get("type") not in TYPES:
            errs.append("%s: bad type %r" % (rid, r.get("type")))
        if "today" in r and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(r["today"])):
            errs.append("%s: bad today %r" % (rid, r["today"]))
        if not str(r.get("design", "")).strip() or not str(r.get("q", "")).strip():
            errs.append("%s: empty q or design" % rid)
        ans = r.get("answers")
        if not isinstance(ans, list) or not ans or not all(isinstance(a, str) and a.strip() for a in ans):
            errs.append("%s: answers must be a non-empty list of strings" % rid)
            continue
        if len(set(ans)) != len(ans):
            errs.append("%s: duplicate answers" % rid)
        if len(ans[0]) > 15:
            errs.append("%s: main answer longer than 15 chars: %s" % (rid, ans[0]))
        path = os.path.join(HERE, "pages", "%s.html" % r.get("page"))
        if not os.path.exists(path):
            errs.append("%s: no page %s" % (rid, path))
            continue
        if r["page"] not in texts:
            texts[r["page"]] = page_text(open(path, encoding="utf-8").read())
        text = texts[r["page"]]
        t = r["type"]
        found = any(re.sub(r"\s+", "", a) in text for a in ans)
        if t in ("read", "find") and not found:
            errs.append("%s: no accepted answer found on %s: %s" % (rid, r["page"], ans))
        if t == "compare" and not found and not NUM.match(ans[0]):
            errs.append("%s: compare answer not on page and not a number: %s" % (rid, ans))
        if t == "none" and ans != ["页面上没有"]:
            errs.append("%s: none answers must be exactly ['页面上没有']" % rid)

    pages = sorted(f[:-5] for f in os.listdir(os.path.join(HERE, "pages"))   # en*.html belong to own_en (gen_en.py)
                   if f.endswith(".html") and not f.startswith("en"))
    shots = collections.Counter()
    for p in pages:
        raw = open(os.path.join(HERE, "pages", p + ".html"), encoding="utf-8").read()
        m = re.search(r'<meta\s+name="shot"\s+content="([^"]+)"', raw)
        if not m:
            errs.append("%s.html: no shot meta" % p)
        else:
            shots[m.group(1)] += 1
        for host in re.findall(r"\b((?:[a-z0-9-]+\.)+[a-z]{2,})(?=[/\"'<\s]|$)", page_text(raw) + " " + raw):
            if not host.endswith(".example") and not re.fullmatch(r"[\d.]+", host) and host.split(".")[-1] in ("com", "cn", "net", "org", "io", "app"):
                errs.append("%s.html: non-.example domain %s" % (p, host))
        for w in BLOCK:
            if w in raw:
                errs.append("%s.html: real name %s" % (p, w))
        if p not in {r["page"] for r in rows}:
            errs.append("%s.html: page has no questions" % p)

    by_type = collections.Counter(r["type"] for r in rows)
    by_page = collections.Counter(r["page"] for r in rows)
    print("%d questions on %d pages (%s)" % (len(rows), len(pages), ", ".join("%s %d" % kv for kv in sorted(shots.items()))))
    print("by type: " + ", ".join("%s %d" % (t, by_type[t]) for t in TYPES))
    print("questions per page: %d–%d" % (min(by_page.values()), max(by_page.values())))
    for e in errs:
        print("ERROR", e)
    print("OK" if not errs else "%d errors" % len(errs))
    sys.exit(1 if errs else 0)


if __name__ == "__main__":
    main()