File size: 8,766 Bytes
443f404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/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')})")