Files
coding-bench/images/cb-web/webcheck.py
wlkns-dev f44ba7681c
All checks were successful
release / deb (push) Successful in 4m2s
release / arch (push) Successful in 5m37s
d-11 mit Nutzertext (Canvas, Zeichenabfang und künstliche Uhr), Image-Label cb.hash mit Veraltet-Prüfung, lokaler Webserver und Im Browser öffnen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:15:12 +01:00

195 lines
8.4 KiB
Python

"""Gemeinsame Hilfen für die Prüfung der Demo-Aufgaben (Gruppe D).
Eine Prüfung öffnet die Seite des Modells (`/work/index.html`) im Browser, arbeitet eine Checkliste ab
und schreibt zuletzt eine JSON-Zeile `{"score": 0.0 bis 1.0, "notes": "..."}`. Ein Screenshot und ein
Bericht landen in `/checks/out/` und werden von coding-bench eingesammelt.
Die Seite hat kein Netz. Jeder Versuch, ins Netz zu gehen, wird abgebrochen und gezählt.
"""
import json
import os
import sys
import time
from playwright.sync_api import sync_playwright
OUT = "/checks/out"
PAGE = "/work/index.html"
ALLOWED_SCHEMES = ("file:", "data:", "blob:", "about:")
# Fängt Zeichenaufrufe auf Canvas ab (Kreise, Texte), damit man Positionen aus dem Bild nicht raten muss.
# `window.__cb.div` > 1 lässt nur jedes n-te Animationsbild an die Seite durch (geringere Bildrate).
CANVAS_HOOK = r"""
(() => {
const S = (window.__cb = { frame: 0, arcs: [], rings: [], texts: [], div: 1, k: 0 });
const P = CanvasRenderingContext2D.prototype;
const ids = new WeakMap();
// Index unter den Canvas-Elementen der Seite. Canvas ohne Platz im Dokument (Zwischenpuffer) ergibt -1.
const cidx = (c) => [...document.querySelectorAll('canvas')].indexOf(c);
const T = (ctx, x, y) => { const m = ctx.getTransform(); return [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f]; };
const K = (ctx) => { const m = ctx.getTransform(); return Math.sqrt(Math.abs(m.a * m.d - m.b * m.c)); };
let pending = [];
const keep = () => { S.arcs = S.arcs.filter((a) => a.f >= S.frame - 2); };
const nextFrame = () => { S.frame++; keep(); };
const rec = (ctx, x, y, r, full) => {
const [X, Y] = T(ctx, x, y);
const e = { f: S.frame, x: X, y: Y, r: r * K(ctx), c: cidx(ctx.canvas), cw: ctx.canvas.width, ch: ctx.canvas.height, full };
S.arcs.push(e); pending.push(e);
};
const bp = P.beginPath; P.beginPath = function () { pending = []; return bp.apply(this, arguments); };
const oarc = P.arc;
P.arc = function (x, y, r, a0, a1) {
try { rec(this, x, y, r, Math.abs((a1 || 0) - (a0 || 0)) >= 2 * Math.PI - 0.02); } catch (e) {}
return oarc.apply(this, arguments);
};
const oell = P.ellipse;
P.ellipse = function (x, y, rx, ry, rot, a0, a1) {
try { rec(this, x, y, (rx + ry) / 2, Math.abs((a1 || 0) - (a0 || 0)) >= 2 * Math.PI - 0.02); } catch (e) {}
return oell.apply(this, arguments);
};
const ofill = P.fill;
P.fill = function () { try { for (const e of pending) { e.filled = true; e.fillStyle = String(this.fillStyle); } } catch (e) {} return ofill.apply(this, arguments); };
const ostroke = P.stroke;
P.stroke = function () {
try {
for (const e of pending) {
e.stroked = true;
if (e.full && e.r > 15) {
const key = Math.round(e.x) + "," + Math.round(e.y) + "," + Math.round(e.r * 2) / 2;
if (!S.rings.some((q) => q.key === key)) S.rings.push({ key, x: e.x, y: e.y, r: e.r, c: e.c });
}
}
} catch (e) {}
return ostroke.apply(this, arguments);
};
for (const name of ["fillText", "strokeText"]) {
const o = P[name];
P[name] = function (text) { try { S.texts.push(String(text)); if (S.texts.length > 400) S.texts.shift(); } catch (e) {} return o.apply(this, arguments); };
}
const full = (ctx, w, h) => w >= ctx.canvas.width * 0.9 && h >= ctx.canvas.height * 0.9;
const ocr = P.clearRect; P.clearRect = function (x, y, w, h) { try { if (full(this, w, h)) nextFrame(); } catch (e) {} return ocr.apply(this, arguments); };
const ofr = P.fillRect; P.fillRect = function (x, y, w, h) { try { if (full(this, w, h)) nextFrame(); } catch (e) {} return ofr.apply(this, arguments); };
const raf = window.requestAnimationFrame.bind(window);
window.requestAnimationFrame = (cb) => {
const wrapped = (t) => {
if (S.div > 1 && (S.k++ % S.div) !== 0) { raf(wrapped); return; }
nextFrame();
cb(t);
};
return raf(wrapped);
};
})();
"""
class Checklist:
"""Sammelt Prüfpunkte mit Gewicht. Der Score ist der Anteil der bestandenen Gewichte."""
def __init__(self):
self.items = []
def add(self, name, ok, note="", weight=1):
self.items.append({"name": name, "ok": bool(ok), "note": note, "weight": weight})
mark = "ok " if ok else "FEHL"
print(f"[{mark}] {name}" + (f" ({note})" if note and not ok else ""), file=sys.stderr)
def guard(self, name, fn, weight=1):
"""Führt eine Prüfung aus. Eine Ausnahme zählt als nicht bestanden, nicht als Absturz."""
try:
result = fn()
if isinstance(result, tuple):
self.add(name, result[0], result[1] if len(result) > 1 else "", weight)
else:
self.add(name, result, "", weight)
except Exception as e: # noqa: BLE001 - jede Störung der Seite ist ein Prüfergebnis
self.add(name, False, f"{type(e).__name__}: {str(e)[:120]}", weight)
def finish(self):
total = sum(i["weight"] for i in self.items) or 1
got = sum(i["weight"] for i in self.items if i["ok"])
failed = [i["name"] for i in self.items if not i["ok"]]
passed = sum(1 for i in self.items if i["ok"])
notes = f"{passed} von {len(self.items)} Punkten"
if failed:
notes += ". Fehlt: " + "; ".join(failed[:6]) + (" …" if len(failed) > 6 else "")
os.makedirs(OUT, exist_ok=True)
with open(os.path.join(OUT, "report.json"), "w") as f:
json.dump({"items": self.items, "score": got / total}, f, ensure_ascii=False, indent=1)
print(json.dumps({"score": round(got / total, 4), "notes": notes}, ensure_ascii=False))
class Session:
"""Chromium mit der Seite des Modells. Netzwerk- und Konsolenfehler werden mitgeschrieben."""
def __init__(self, path=PAGE, width=1280, height=800, clock=False):
self.path = path
self.use_clock = clock
self.size = {"width": width, "height": height}
self.errors = []
self.blocked = []
def __enter__(self):
self._pw = sync_playwright().start()
self.browser = self._pw.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
self.context = self.browser.new_context(viewport=self.size)
# Kurze Zeitlimits: Fehlt ein Element, soll die Prüfung zügig mit „nicht bestanden“ weitergehen
# (Standard wären 30 Sekunden je Zugriff, dann liefe die ganze Prüfung ins Zeitlimit).
self.context.set_default_timeout(2500)
self.context.set_default_navigation_timeout(15000)
self.context.route("**/*", self._route)
self.page = self.context.new_page()
if self.use_clock:
# Zuerst die Uhr, dann der Hook: Er umhüllt die Animationsschleife der Uhr.
self.page.clock.install(time=0)
self.page.add_init_script(CANVAS_HOOK)
self.page.on("pageerror", lambda e: self.errors.append(f"pageerror: {e}"))
self.page.on(
"console", lambda m: self.errors.append(f"console: {m.text}") if m.type == "error" else None
)
return self
def __exit__(self, *exc):
try:
self.browser.close()
finally:
self._pw.stop()
def _route(self, route):
url = route.request.url
if url.startswith(ALLOWED_SCHEMES):
route.continue_()
else:
self.blocked.append(url)
route.abort()
def open(self):
"""Öffnet die Seite. Gibt False zurück, wenn die Datei fehlt."""
if not os.path.isfile(self.path):
return False
self.page.goto("file://" + self.path, wait_until="load", timeout=15000)
return True
def screenshot(self, name="screenshot.png"):
os.makedirs(OUT, exist_ok=True)
try:
self.page.screenshot(path=os.path.join(OUT, name), full_page=False)
except Exception as e: # noqa: BLE001
print(f"Screenshot nicht möglich: {e}", file=sys.stderr)
def center(self, selector):
"""Mittelpunkt (x, y) des ersten Elements oder None."""
box = self.page.locator(selector).first.bounding_box()
if not box:
return None
return (box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
def tick(self, ms):
"""Lässt `ms` Millisekunden der Seitenzeit vergehen (nur mit clock=True), in Schritten von 16 ms."""
self.page.clock.run_for(int(ms))
def wait(self, seconds):
self.page.wait_for_timeout(int(seconds * 1000))
def distance(a, b):
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5