Spaces:
Running
Running
Download grader.worker.js from sh1k4ku/python-playground: direct link, hf CLI and curl.
- Browser
- Download file 8.15 kB
-
https://huggingface.co/spaces/sh1k4ku/python-playground/resolve/main/grader.worker.js
- Command line
-
hf download hf://spaces/sh1k4ku/python-playground/grader.worker.js
-
curl -L -o grader.worker.js https://huggingface.co/spaces/sh1k4ku/python-playground/resolve/main/grader.worker.js
8.15 kB
| // =========================================================================== | |
| // Grader Web Worker — runs its OWN Pyodide, holds the hidden answer key. | |
| // | |
| // The oracle / bug definitions / reasons live in THIS worker's Python | |
| // interpreter, in a separate thread with separate memory. The student's code | |
| // runs in the main-thread Pyodide and cannot reach into here: gc.get_objects(), | |
| // closure reflection and print(globals()) only see the student's own interpreter. | |
| // | |
| // The worker receives {problem, source, tests(JSON)} and returns a JSON report. | |
| // Student code never executes here — only their TESTS *data* crosses the boundary. | |
| // =========================================================================== | |
| const PYODIDE_INDEX = "https://cdn.jsdelivr.net/pyodide/v0.26.2/full/"; | |
| importScripts(PYODIDE_INDEX + "pyodide.js"); | |
| const PROBLEMS = { | |
| Q1: { data: "q1.dat", public: "allocate" }, | |
| Q2: { data: "q2.dat", public: "approve" }, | |
| }; | |
| // ----- Decryption (must match build_blackbox.py / PASSPHRASE) ----- | |
| const PASSPHRASE = "t2-unsw-bbt-v1-rotate-me"; | |
| let __keyBytes = null; | |
| async function _sha256(bytes) { | |
| return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); | |
| } | |
| async function decryptDat(b64) { | |
| if (!__keyBytes) __keyBytes = await _sha256(new TextEncoder().encode(PASSPHRASE)); | |
| const cipher = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)); | |
| const out = new Uint8Array(cipher.length); | |
| const blk = new Uint8Array(__keyBytes.length + 8); | |
| blk.set(__keyBytes, 0); | |
| const dv = new DataView(blk.buffer); | |
| let counter = -1, ks = null; | |
| for (let off = 0; off < cipher.length; off++) { | |
| const c = Math.floor(off / 32); | |
| if (c !== counter) { counter = c; dv.setBigUint64(__keyBytes.length, BigInt(c), false); ks = await _sha256(blk); } | |
| out[off] = cipher[off] ^ ks[off % 32]; | |
| } | |
| return new TextDecoder("utf-8").decode(out); | |
| } | |
| // ----- The grading harness (closure-isolated; identical to the verified one) ----- | |
| const HARNESS_FACTORY = ` | |
| def __bb_make(): | |
| import sys, types, linecache, ast, json, inspect | |
| _og = inspect.getsource | |
| def _guard(obj, *a, **k): | |
| if getattr(obj, "__module__", None) in (None, "blackbox", "blackbox_impl"): | |
| raise OSError("source code is not available") | |
| return _og(obj, *a, **k) | |
| inspect.getsource = _guard | |
| inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available")) | |
| state = {} | |
| def install(public_name, source): | |
| ns = {} | |
| exec(compile(source, "blackbox_impl", "exec"), ns) | |
| combined = ns["blackbox"] | |
| ref = ns["reference"] | |
| bugs = ns["BUGS"] | |
| reasons = ns.get("REASONS", {}) | |
| for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"): | |
| ns.pop(k, None) | |
| linecache.cache.clear() | |
| def _public(*a, **k): | |
| return combined(*a, **k) | |
| _public.__name__ = public_name | |
| sys.modules.pop("blackbox", None) | |
| pub = types.ModuleType("blackbox") | |
| setattr(pub, public_name, _public) | |
| sys.modules["blackbox"] = pub | |
| state.clear() | |
| state.update(fn=combined, ref=ref, bugs=bugs, reasons=reasons) | |
| def _s(v): | |
| return v if isinstance(v, str) else repr(v) | |
| def run(source, tests): | |
| fn = state["fn"]; ref = state["ref"]; BUGS = state["bugs"]; REASONS = state["reasons"] | |
| order = list(BUGS) | |
| linenos = {} | |
| try: | |
| tree = ast.parse(source) | |
| for node in ast.walk(tree): | |
| if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets): | |
| if isinstance(node.value, (ast.List, ast.Tuple)): | |
| for i, el in enumerate(node.value.elts): | |
| linenos[i] = el.lineno | |
| except Exception: | |
| pass | |
| if not isinstance(tests, (list, tuple)): | |
| return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."}) | |
| caught = {} | |
| rows = [] | |
| for i, case in enumerate(tests): | |
| line = linenos.get(i) | |
| try: | |
| args, expected = case | |
| args = tuple(args) | |
| except Exception: | |
| rows.append({"line": line, "status": "malformed", "raw": repr(case)}) | |
| continue | |
| try: | |
| actual = fn(*args) | |
| except Exception as e: | |
| rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)}) | |
| continue | |
| spec = ref(*args) | |
| bug = None | |
| for name in BUGS: | |
| try: | |
| if BUGS[name][0](*args) != spec: | |
| bug = name; break | |
| except Exception: | |
| pass | |
| argstr = repr(args) | |
| valid_expected = (expected == spec) | |
| if actual != expected: | |
| if not valid_expected: | |
| rows.append({"line": line, "status": "invalid", "argstr": argstr, | |
| "expected": _s(expected), "actual": _s(actual)}) | |
| elif bug is None: | |
| # Real discrepancy, but it can't be attributed to ONE of the 5 | |
| # bugs (e.g. several boundaries broken at once). Don't count it. | |
| rows.append({"line": line, "status": "combo", "argstr": argstr, | |
| "actual": _s(actual), "expected": _s(expected)}) | |
| else: | |
| num = order.index(bug) + 1 | |
| first = bug not in caught | |
| if first: | |
| caught[bug] = line | |
| rows.append({"line": line, "status": "bug" if first else "dup", | |
| "bug": bug, "num": num, "total": len(BUGS), | |
| "reason": REASONS.get(bug, "output differs from the spec"), | |
| "argstr": argstr, "actual": _s(actual), "expected": _s(expected)}) | |
| else: | |
| if not valid_expected: | |
| rows.append({"line": line, "status": "invalid", "argstr": argstr, | |
| "expected": _s(expected), "actual": _s(actual)}) | |
| else: | |
| rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": _s(actual)}) | |
| return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()), | |
| "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(tests)}) | |
| class _H: | |
| pass | |
| h = _H() | |
| h.install = install | |
| h.run = run | |
| return h | |
| __bb_make() | |
| `; | |
| let pyodide, harness, bbInstall, bbRun, installed = null; | |
| async function init() { | |
| pyodide = await loadPyodide({ indexURL: PYODIDE_INDEX }); | |
| harness = pyodide.runPython(HARNESS_FACTORY); | |
| pyodide.runPython("del __bb_make"); | |
| bbInstall = harness.install; | |
| bbRun = harness.run; | |
| postMessage({ type: "ready" }); | |
| } | |
| const ready = init().catch((e) => postMessage({ type: "fatal", error: String(e) })); | |
| async function ensureProblem(key) { | |
| if (installed === key) return; | |
| const b64 = (await (await fetch(PROBLEMS[key].data, { cache: "no-store" })).text()).trim(); | |
| const src = await decryptDat(b64); | |
| if (!src.includes("def blackbox") || !src.includes("def reference")) { | |
| throw new Error("Could not decrypt " + PROBLEMS[key].data); | |
| } | |
| bbInstall(PROBLEMS[key].public, src); | |
| installed = key; | |
| } | |
| onmessage = async (e) => { | |
| const { id, problem, source, tests } = e.data; | |
| try { | |
| await ready; | |
| await ensureProblem(problem); | |
| pyodide.globals.set("__tests_json", tests); | |
| const testsPy = pyodide.runPython("import json\njson.loads(__tests_json)"); | |
| const report = bbRun(source, testsPy); | |
| if (testsPy && typeof testsPy.destroy === "function") testsPy.destroy(); | |
| pyodide.runPython("del __tests_json"); | |
| postMessage({ id, ok: true, report }); | |
| } catch (err) { | |
| postMessage({ id, ok: false, error: String((err && err.message) || err) }); | |
| } | |
| }; | |