File size: 5,180 Bytes
e39a6b5
 
 
 
 
 
 
 
 
7f02d8a
 
 
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f02d8a
 
 
 
 
 
 
 
 
 
 
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f02d8a
 
 
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
113
114
115
116
117
118
"""Builds the public part of the screen benchmark (webqa's English web pages), reproducibly.

    python3 -I screen/fetch.py download --raw <folder>     # the source files at pinned revisions (~0.3 GB)
    python3 -I screen/fetch.py build --raw <that folder>   # picks the questions: sets/ here, images in <cache>/screen/img

Needs huggingface_hub and pyarrow (a virtual environment of your own). The downloaded files are data, never run.
Every random choice comes from SEED. Images keep their published bytes. The release (screen-data-v1) is made by
pack.py together with our own rendered pages.

- VisualWebBench (Apache-2.0): webqa 30 (one per website), element_ocr 20, heading_ocr 10 drawn; 2 heading_ocr left
  out and 3 keys changed to what the screenshot shows (VWB_FIX, VWB_DROP). The screenshots of element_ocr already
  have the red box drawn on them; the prompts are VisualWebBench's own (run_screen.py).

"""
from __future__ import annotations

import argparse
import json
import os
import random

HERE = os.path.dirname(os.path.abspath(__file__))
SEED = 20261124
CACHE = os.path.abspath(os.path.expanduser(os.environ.get("LUOKE_BENCH_CACHE") or "~/.cache/luoke-bench"))
IMG = os.path.join(CACHE, "screen", "img")

HF = {
    "visualwebbench/VisualWebBench": ("9dace8acebf210929bd47256d7ded44439377946", [
        "README.md", "webqa/test-00000-of-00001.parquet", "element_ocr/test-00000-of-00001.parquet",
        "heading_ocr/test-00000-of-00001.parquet"]),
}
VWB = {"webqa": 30, "element_ocr": 20, "heading_ocr": 10}


def rp(raw, repo, path):
    return os.path.join(raw, repo.replace("/", "__"), path)


def download(raw):
    from huggingface_hub import hf_hub_download
    for repo, (rev, files) in HF.items():
        for f in files:
            if not os.path.exists(rp(raw, repo, f)):
                hf_hub_download(repo, f, repo_type="dataset", revision=rev, local_dir=os.path.join(raw, repo.replace("/", "__")))
    print("downloaded")


def write_set(path, rows):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as fh:
        for r in rows:
            fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"{len(rows):4d}  {os.path.relpath(path, HERE)}")


# VisualWebBench keys changed after checking them against the screenshots, and questions left out (still drawn, so the
# others stay the same)
VWB_FIX = {
    "webqa_178": {"answers": ["US States", "50-State Surveys"]},   # 「各州的法律」:两个栏目都说得通
    "element_ocr_163": {"answers": ["LA’s star-studded dining scene means the celebratory meal options are…"]},   # 框里只露出两行,到「are…」截断
    "element_ocr_225": {"answers": ["Valvoline Instant Oil Change has over 1,500 locations offering stay-in-your-car vehicle maintenance services from certified technicians. Our no-appointment necessary oil changes only take about 15 minutes and include an 18-point"]},   # 最后的「safety check!」被 cookie 横幅挡住
}
VWB_DROP = {"heading_ocr_14": "logo、弹窗、「free shipping」横幅都可能算主标题",
            "heading_ocr_20": "答案是 h1,顶部横幅和标语的字更大"}


def build_vwb(raw, rng):
    import pyarrow.parquet as pq
    os.makedirs(IMG, exist_ok=True)
    rows_out = []
    for task, n in VWB.items():
        rows = pq.read_table(rp(raw, "visualwebbench/VisualWebBench", f"{task}/test-00000-of-00001.parquet")).to_pylist()
        rng.shuffle(rows)
        seen, picks = set(), []
        for r in rows:
            if r["website"] in seen:
                continue
            seen.add(r["website"])
            picks.append(r)
            if len(picks) == n:
                break
        for r in sorted(picks, key=lambda r: int(r["id"].rsplit("_", 1)[1])):
            qid = f"vwb_{r['id']}"
            data = r["image"]["bytes"]
            fname = qid + (".png" if data[:4] == b"\x89PNG" else ".jpg")
            with open(os.path.join(IMG, fname), "wb") as fh:
                fh.write(data)
            ans = r["answer"]
            answers = [str(x) for x in ans] if isinstance(ans, (list, tuple)) else [str(ans)]
            row = {"id": qid, "image": fname, "task": task, "answers": answers, "website": r["website"],
                   "source": {"set": "VisualWebBench", "id": r["id"]}}
            if task == "webqa":
                row["q"] = r["question"]
            if r.get("bbox") is not None:
                row["bbox"] = r["bbox"]
            row.update(VWB_FIX.get(r["id"], {}))
            if r["id"] not in VWB_DROP:
                rows_out.append(row)
    write_set(os.path.join(HERE, "webqa", "sets", "vwb.jsonl"), rows_out)




def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("download").add_argument("--raw", required=True)
    sub.add_parser("build").add_argument("--raw", required=True)
    a = ap.parse_args()
    if a.cmd == "download":
        download(a.raw)
    else:
        build_vwb(a.raw, random.Random(f"{SEED}-vwb"))


if __name__ == "__main__":
    main()