#!/usr/bin/env python3 """Auto-grade UNSW give submissions for Assignment 1 (black-box testing). For every student id in the xlsx: 1. extract submission.tar -> nested zip/tar -> find Q1/Q2 test files 2. pull out the TESTS list (tolerant: lowercase 'Tests', .txt files, q1.py, inline comments, and missing-comma syntax errors via per-line recovery) 3. grade against our reference + 5-bug black box (same logic as the playground: a case counts only if its expected matches the spec; combined/multi-boundary discrepancies that don't isolate ONE of the 5 bugs are NOT counted) 4. write Q1/Q2 scores (0.5 per bug, /2.5 each) back into the xlsx. Student code is NEVER executed -- TESTS is parsed with ast.literal_eval only. Usage: python3 grade_submissions.py """ import importlib.util, ast, re, glob, os, json, tarfile, zipfile, tempfile, shutil, collections import openpyxl HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = "/Users/shangzhi/Downloads/26ass1" XLSX = "/Users/shangzhi/Downloads/26ass1.xlsx" def load(n, p): s = importlib.util.spec_from_file_location(n, p); m = importlib.util.module_from_spec(s); s.loader.exec_module(m); return m Q1 = load("q1", os.path.join(HERE, "_solution/q1.py")) Q2 = load("q2", os.path.join(HERE, "_solution/q2.py")) # ---------- archive extraction ---------- def _safe_tar(p, d): try: with tarfile.open(p) as t: t.extractall(d, filter='data') except Exception: pass def _safe_zip(p, d): try: with zipfile.ZipFile(p) as z: z.extractall(d) except Exception: pass def explode(zdir, dest): # final submission first sub = os.path.join(zdir, "submission.tar") if os.path.exists(sub): _safe_tar(sub, dest) if not os.listdir(dest): for f in glob.glob(os.path.join(zdir, "*.tar")): _safe_tar(f, dest) # already-extracted dirs (e.g. a manually opened ass1/) for sub in os.listdir(zdir): sp = os.path.join(zdir, sub) if os.path.isdir(sp): shutil.copytree(sp, os.path.join(dest, "_" + sub), dirs_exist_ok=True) # nested zip/tar, a couple levels deep for _ in range(3): for f in glob.glob(os.path.join(dest, "**", "*.zip"), recursive=True): if "__MACOSX" not in f: _safe_zip(f, os.path.dirname(f)) for f in glob.glob(os.path.join(dest, "**", "*.tar"), recursive=True): _safe_tar(f, os.path.dirname(f)) # ---------- TESTS extraction (tolerant) ---------- def _balanced(src, start, op, cl): depth = 0; q = None for j in range(start, len(src)): c = src[j] if q: if c == q and src[j-1] != '\\': q = None continue if c in '"\'': q = c; continue if c == op: depth += 1 elif c == cl: depth -= 1 if depth == 0: return j return None def _perline(block): cases = [] for raw in block.splitlines(): s = raw.strip() if not s or s.startswith('#') or '(' not in s: continue i = s.index('('); end = _balanced(s, i, '(', ')') if end is None: continue try: v = ast.literal_eval(s[i:end+1]) if isinstance(v, tuple) and len(v) == 2: cases.append(v) except Exception: continue return cases def extract_tests(src): m = re.search(r'^[ \t]*tests?\s*=\s*\[', src, re.M | re.I) # tolerant: TESTS/Tests/tests/TEST if not m: return None, "no_TESTS" start = src.index('[', m.start()) end = _balanced(src, start, '[', ']') if end is not None: try: v = ast.literal_eval(src[start:end+1]) if isinstance(v, (list, tuple)): return list(v), "ok" except Exception: pass block = src[start+1:end] if end else src[start+1:] cases = _perline(block) if cases: return cases, "recovered" # e.g. missing-comma syntax error return None, "parse_fail" # ---------- which question does a TESTS list belong to? (by content) ---------- def detect_q(cases): si = ii = 0 for case in cases: try: args, exp = case except Exception: continue if not (isinstance(args, (tuple, list)) and len(args) >= 1): continue a0 = args[0] if isinstance(a0, str): si += 1 # role -> Q2 elif isinstance(a0, (int, float)) and not isinstance(a0, bool): ii += 1 # students -> Q1 if ii > si: return 1 if si > ii: return 2 return None # ---------- discover Q1/Q2 test cases: filename first, then by content ---------- def discover(dest): files = [] # (path, cases, status, detected_q) for p in glob.glob(os.path.join(dest, "**", "*"), recursive=True): if not os.path.isfile(p): continue b = os.path.basename(p) if b.startswith("._") or "__MACOSX" in p: continue if not b.lower().endswith((".py", ".txt")): continue try: src = open(p, encoding='utf-8', errors='replace').read() except Exception: continue cases, st = extract_tests(src) if cases: files.append((p, cases, st, detect_q(cases))) res = {1: (None, "missing"), 2: (None, "missing")} used = set() # 1) filename-based (a file named q1* / q2*, prefer "test" + .py) for qn in (1, 2): named = [f for f in files if f"q{qn}" in os.path.basename(f[0]).lower()] named.sort(key=lambda t: (0 if "test" in os.path.basename(t[0]).lower() else 1, 0 if t[0].lower().endswith(".py") else 1, len(t[0]))) if named: res[qn] = (named[0][1], named[0][2]); used.add(named[0][0]) # 2) content-based fallback for whatever is still missing for qn in (1, 2): if res[qn][0] is None: for (p, c, st, dq) in files: if p not in used and dq == qn: res[qn] = (c, st + "/by-content"); used.add(p); break return res # ---------- grade (same rules as the playground) ---------- def grade(mod, cases): caught = set() for case in cases: try: args, exp = case; args = tuple(args) except Exception: continue try: ref = mod.reference(*args); bb = mod.blackbox(*args) except Exception: continue if exp != ref: continue # expected must match spec if bb != exp: for nm, (fn, _) in mod.BUGS.items(): try: if fn(*args) != ref: caught.add(nm); break except Exception: pass return len(caught) # ---------- run over all students ---------- wb = openpyxl.load_workbook(XLSX) ws = wb.active ids = [(r, ws.cell(r, 1).value) for r in range(2, ws.max_row + 1) if ws.cell(r, 1).value is not None] rows = [] base = tempfile.mkdtemp() for row, sid in ids: z = str(int(sid)); zdir = os.path.join(ROOT, z) dest = os.path.join(base, z); os.makedirs(dest, exist_ok=True) n1 = n2 = None; s1 = s2 = "missing" if os.path.isdir(zdir): explode(zdir, dest) found = discover(dest) c1, s1 = found[1]; c2, s2 = found[2] if c1 is not None: n1 = grade(Q1, c1) if c2 is not None: n2 = grade(Q2, c2) rows.append((row, z, n1, s1, n2, s2)) shutil.rmtree(base, ignore_errors=True) # ---------- write back to xlsx (after backup; keep the FIRST/original backup) ---------- _bak = XLSX.replace(".xlsx", "_backup.xlsx") if not os.path.exists(_bak): shutil.copyfile(XLSX, _bak) ws.cell(1, 2, "Q1 (/2.5)"); ws.cell(1, 3, "Q2 (/2.5)"); ws.cell(1, 4, "Total (/5)"); ws.cell(1, 5, "notes") flagged = [] for row, z, n1, s1, n2, s2 in rows: q1s = (n1 * 0.5) if isinstance(n1, int) else None q2s = (n2 * 0.5) if isinstance(n2, int) else None ws.cell(row, 2, q1s if q1s is not None else 0) ws.cell(row, 3, q2s if q2s is not None else 0) ws.cell(row, 4, (q1s or 0) + (q2s or 0)) note = [] if n1 is None: note.append("Q1:" + s1) elif s1 == "recovered": note.append("Q1:recovered(syntax fixed)") if n2 is None: note.append("Q2:" + s2) elif s2 == "recovered": note.append("Q2:recovered(syntax fixed)") if note: ws.cell(row, 5, "; ".join(note)); flagged.append((z, "; ".join(note))) wb.save(XLSX) # ---------- report ---------- ok = sum(1 for r in rows if isinstance(r[2], int) and isinstance(r[4], int)) print(f"graded {len(rows)} students; both questions auto-scored for {ok}") d1 = collections.Counter(r[2] for r in rows if isinstance(r[2], int)) d2 = collections.Counter(r[4] for r in rows if isinstance(r[4], int)) print("Q1 bug-count distribution:", dict(sorted(d1.items()))) print("Q2 bug-count distribution:", dict(sorted(d2.items()))) print(f"\nflagged for manual review ({len(flagged)}):") for z, note in flagged: print(f" {z}: {note}") print(f"\nwrote scores to {XLSX} (backup: {XLSX.replace('.xlsx','_backup.xlsx')})")