File size: 6,467 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | """Fetches the pictures and clips of the vision or screen benchmark into the local cache, or packs them.
python3 -I vision/get_data.py vision # download vision-data-v1, check, unpack into <cache>/vision/
python3 -I vision/get_data.py screen # screen-data-v1 -> <cache>/screen/
python3 -I vision/get_data.py vision --from <folder> # a .tar you already have, instead of downloading
python3 -I vision/get_data.py vision --pack <folder> # make the .tar from the cache and write <app>/data.sha256
The archives are attachments of the luoke-bench GitHub release of the same name (luokelabs/luoke-bench; `gh` must be
logged in with access). An archive is checked against <app>/data.sha256 before it is opened, and unpacked only if every
entry is a plain file at <app>/img/<name> or <app>/video/<name>. Then every file the question sets name is looked for.
The archive is deterministic (sorted, no owners, time 0), so packing the same files gives the same sha256.
How the files are made: <app>/fetch.py (public sets) and screen/render.py (our own pages, from the HTML in git).
Where: $LUOKE_BENCH_CACHE, else ~/.cache/luoke-bench. Standard library only (Python 3.9+).
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
BENCH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REPO = os.environ.get("LUOKE_BENCH_REPO", "luokelabs/luoke-bench")
CACHE = os.path.abspath(os.path.expanduser(os.environ.get("LUOKE_BENCH_CACHE") or "~/.cache/luoke-bench"))
APPS = {"vision": ("vision-data-v1", ("photo", "ocr", "video", "translate", "board", "album", "compare", "describe")),
"screen": ("screen-data-v1", ("webqa", "todo", "profile", "digest", "errhelp", "inject", "multi", "variants",
"history"))}
NAME = re.compile(r"^[A-Za-z0-9_.-]+$")
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def needed(app):
"""Every picture and clip the question sets name: {(subdir, file name)}."""
want = set()
for part in APPS[app][1]:
d = os.path.join(BENCH, app, part, "sets")
for f in sorted(os.listdir(d)) if os.path.isdir(d) else []:
if not f.endswith(".jsonl"):
continue
for line in open(os.path.join(d, f), encoding="utf-8"):
if not line.strip():
continue
r = json.loads(line)
shown = r.get("image") or r.get("page") # a row with both shows `image` (page is its source)
if shown:
want.add(("img", shown if "." in shown else shown + ".png"))
for p in r.get("pages", []) + r.get("images", []) + [a["image"] for a in r.get("album", [])]:
want.add(("img", p if "." in p else p + ".png"))
if r.get("video"):
want.add(("video", r["video"]))
users = os.path.join(d, "users.json") # screen/history: every user's screenshots
if os.path.exists(users):
for u in json.load(open(users, encoding="utf-8")).values():
want |= {("img", s["image"]) for s in u["shots"]}
return want
def pack(app, dest):
tag = APPS[app][0]
root = os.path.join(CACHE, app)
files = sorted(needed(app))
missing = [f"{d}/{n}" for d, n in files if not os.path.exists(os.path.join(root, d, n))]
if missing:
sys.exit(f"{len(missing)} files missing from {root}, e.g. {missing[:5]}")
os.makedirs(dest, exist_ok=True)
path = os.path.join(dest, tag + ".tar")
with tarfile.open(path, "w", format=tarfile.PAX_FORMAT) as tar:
for d, n in files:
src = os.path.join(root, d, n)
info = tarfile.TarInfo(f"{app}/{d}/{n}")
info.size = os.path.getsize(src)
info.mtime, info.mode = 0, 0o644
with open(src, "rb") as fh:
tar.addfile(info, fh)
digest = sha256_file(path)
with open(os.path.join(BENCH, app, "data.sha256"), "w") as fh:
fh.write(f"{digest} {tag}.tar\n")
print(f"{len(files)} files -> {path} ({os.path.getsize(path) / 1e6:.0f} MB), sha256 {digest[:12]}…")
def fetch(app, src):
tag = APPS[app][0]
name = tag + ".tar"
digests = dict(reversed(line.split()) for line in open(os.path.join(BENCH, app, "data.sha256"), encoding="utf-8")
if line.strip())
root = os.path.join(CACHE, app)
with tempfile.TemporaryDirectory(prefix=f"luoke-{app}-") as tmp:
if src:
path = os.path.join(src, name)
else:
subprocess.run(["gh", "release", "download", tag, "--repo", REPO, "--pattern", name, "--dir", tmp], check=True)
path = os.path.join(tmp, name)
if sha256_file(path) != digests.get(name):
sys.exit(f"{name}: sha256 does not match {app}/data.sha256")
with tarfile.open(path) as tar:
members = tar.getmembers()
for m in members:
bits = m.name.split("/")
if not m.isfile() or len(bits) != 3 or bits[0] != app or bits[1] not in ("img", "video") \
or not NAME.match(bits[2]):
sys.exit(f"{name}: refusing to unpack, unexpected entry {m.name!r}")
for m in members:
_, d, n = m.name.split("/")
os.makedirs(os.path.join(root, d), exist_ok=True)
with tar.extractfile(m) as s, open(os.path.join(root, d, n), "wb") as t:
shutil.copyfileobj(s, t)
missing = [f"{d}/{n}" for d, n in sorted(needed(app)) if not os.path.exists(os.path.join(root, d, n))]
if missing:
sys.exit(f"unpacked {len(members)} files, but {len(missing)} the sets name are missing: {missing[:5]}")
print(f"{name}: {len(members)} files -> {root}")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("app", choices=sorted(APPS))
ap.add_argument("--from", dest="src", metavar="DIR")
ap.add_argument("--pack", metavar="DIR")
a = ap.parse_args()
if a.pack:
pack(a.app, a.pack)
else:
fetch(a.app, a.src)
if __name__ == "__main__":
main()
|