mogs 0.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mogs/__init__.py +17 -0
- mogs/_assertrewrite.py +44 -0
- mogs/_env.py +26 -0
- mogs/_run.py +111 -0
- mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
- mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
- mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
- mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
- mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
- mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
- mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
- mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
- mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
- mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
- mogs/assignment.py +172 -0
- mogs/build.py +605 -0
- mogs/check.py +410 -0
- mogs/cli.py +272 -0
- mogs/config.py +619 -0
- mogs/environment.py +118 -0
- mogs/export.py +556 -0
- mogs/grader/__init__.py +1 -0
- mogs/grader/_process.py +383 -0
- mogs/grader/_user.py +7 -0
- mogs/grader/bundle.py +320 -0
- mogs/grader/child.py +317 -0
- mogs/grader/datafiles.py +54 -0
- mogs/grader/main.py +132 -0
- mogs/grader/protocol.py +175 -0
- mogs/grader/results.py +337 -0
- mogs/grader/sandbox.py +462 -0
- mogs/grader/templates/__init__.py +38 -0
- mogs/grader/templates/run_autograder +3 -0
- mogs/grader/templates/setup.sh +28 -0
- mogs/loader.py +260 -0
- mogs/pdf.py +676 -0
- mogs/regrade.py +223 -0
- mogs/requirements.py +232 -0
- mogs/runner.py +281 -0
- mogs/scaffold.py +155 -0
- mogs/selfcheck.py +173 -0
- mogs/source.py +1438 -0
- mogs/transform.py +769 -0
- mogs-0.7.0.dist-info/METADATA +17 -0
- mogs-0.7.0.dist-info/RECORD +49 -0
- mogs-0.7.0.dist-info/WHEEL +4 -0
- mogs-0.7.0.dist-info/entry_points.txt +3 -0
mogs/check.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"""The panel a student sees at the end of each question: `grade()`."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import html
|
|
5
|
+
import inspect
|
|
6
|
+
import sys
|
|
7
|
+
import textwrap
|
|
8
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from types import CodeType, FunctionType
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from mogs._env import grading
|
|
14
|
+
from mogs.config import default_title, read_config
|
|
15
|
+
from mogs.runner import Outcome, run_test, run_test_source, shorten
|
|
16
|
+
from mogs.source import module_tests
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
import marimo as mo
|
|
20
|
+
|
|
21
|
+
# Translucent accents and inherited text colors read in both light and dark themes.
|
|
22
|
+
PASS = "rgba(34, 160, 80, 0.9)"
|
|
23
|
+
FAIL = "rgba(220, 60, 60, 0.9)"
|
|
24
|
+
WARN = "rgba(210, 140, 20, 0.9)"
|
|
25
|
+
SHADE = "rgba(127, 127, 127, 0.12)"
|
|
26
|
+
|
|
27
|
+
PANEL_STYLE = (
|
|
28
|
+
"border: 1px solid rgba(127, 127, 127, 0.35); border-left: 4px solid {accent}; "
|
|
29
|
+
"border-radius: 6px; padding: 0.9em 1.2em; line-height: 1.55; color: inherit; "
|
|
30
|
+
"background: {shade};"
|
|
31
|
+
)
|
|
32
|
+
TITLE_STYLE = "font-weight: 600; margin-bottom: 0.4em;"
|
|
33
|
+
LIST_STYLE = "list-style: none; margin: 0; padding: 0;"
|
|
34
|
+
ITEM_STYLE = "margin: 0.15em 0;"
|
|
35
|
+
MARK_STYLE = "color: {accent}; font-weight: 700;"
|
|
36
|
+
MESSAGE_STYLE = (
|
|
37
|
+
"margin: 0.3em 0 0.5em; margin-left: 1.5em; padding: 0.5em 0.7em; border-radius: 4px; "
|
|
38
|
+
f"background: {SHADE}; color: inherit; white-space: pre-wrap; font-size: 0.85em;"
|
|
39
|
+
)
|
|
40
|
+
NOTE_STYLE = "margin-top: 0.4em; opacity: 0.75;"
|
|
41
|
+
NO_NOTEBOOK = (
|
|
42
|
+
"Cannot find this notebook's file, so its public tests cannot run. Save the notebook, then "
|
|
43
|
+
"open it with `marimo edit <your notebook>.py`."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def grade(
|
|
48
|
+
qid: str,
|
|
49
|
+
*,
|
|
50
|
+
points: float | None = None,
|
|
51
|
+
title: str | None = None,
|
|
52
|
+
tests: Sequence[Callable[[], object]] | None = None,
|
|
53
|
+
test_file: str | None = None,
|
|
54
|
+
uses: Sequence[object] = (),
|
|
55
|
+
hidden: int = 0,
|
|
56
|
+
manual: bool = False,
|
|
57
|
+
) -> "mo.Html":
|
|
58
|
+
"""End a question: declare its points, and show how the answer does as a panel.
|
|
59
|
+
|
|
60
|
+
The build reads `points` and `title` from the source notebook without running it, so they
|
|
61
|
+
must be literals there. The other arguments are for the student copy, which the build
|
|
62
|
+
writes.
|
|
63
|
+
|
|
64
|
+
For an auto-graded question, the panel runs its public tests. In the source notebook,
|
|
65
|
+
`grade("q1", points=4)` finds every `test_q1_*` callable among the caller's globals,
|
|
66
|
+
hidden tests included. The student copy keeps its public tests in a file next to the
|
|
67
|
+
notebook and passes its path as `test_file`. That file runs as a module in a copy of the
|
|
68
|
+
caller's globals, with assertion rewriting. The student copy also passes the names the
|
|
69
|
+
tests use as `uses`, so marimo runs the cell again when one of them changes.
|
|
70
|
+
|
|
71
|
+
Each test is compiled again from its source with pytest's assertion rewriting, so failed
|
|
72
|
+
asserts show their values. The recompiled test runs against its own snapshot of its
|
|
73
|
+
globals, copied when `grade` runs, so the kernel's globals stay untouched. A test without
|
|
74
|
+
source, one whose source does not match its code (as with marimo's mangled `_private`
|
|
75
|
+
names), or one that does not compile again runs as it is.
|
|
76
|
+
|
|
77
|
+
A question without tests is written: the panel shows its points and that it is graded by
|
|
78
|
+
hand. The student copy says so with `manual=True`; in the source notebook, a question
|
|
79
|
+
without tests in the caller's globals is looked up in the saved notebook.
|
|
80
|
+
|
|
81
|
+
While grading (`MOGS_GRADING=1`), it runs nothing and returns an empty panel, so a whole
|
|
82
|
+
notebook run on the grader does not run the public tests a second time.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
qid: Question id, e.g. `"q1"`.
|
|
86
|
+
points: Points for the question, shown in the title.
|
|
87
|
+
title: Question title; `None` gives `Question N` for `qN`, else `qid`.
|
|
88
|
+
tests: The tests to run; `None` finds them in the caller's globals, unless `test_file`
|
|
89
|
+
is given.
|
|
90
|
+
test_file: Path of a file with the tests, relative to the notebook's folder.
|
|
91
|
+
uses: The names the tests use. Only marimo reads them, to know when to run the cell.
|
|
92
|
+
hidden: Number of hidden tests, shown as a note.
|
|
93
|
+
manual: The question is graded by hand.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
The panel, as marimo HTML.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
ValueError: If both `tests` and `test_file` are given.
|
|
100
|
+
ConfigError: If the question has no tests in the source notebook and the saved
|
|
101
|
+
notebook's config is invalid.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
import marimo as mo
|
|
105
|
+
|
|
106
|
+
if tests is not None and test_file is not None:
|
|
107
|
+
raise ValueError("grade() takes `tests` or `test_file`, not both.")
|
|
108
|
+
|
|
109
|
+
if grading():
|
|
110
|
+
return mo.Html("")
|
|
111
|
+
|
|
112
|
+
namespace = sys._getframe(1).f_globals
|
|
113
|
+
|
|
114
|
+
if manual:
|
|
115
|
+
return mo.Html(written_panel(qid, points, title))
|
|
116
|
+
|
|
117
|
+
problem = None
|
|
118
|
+
|
|
119
|
+
if test_file is not None:
|
|
120
|
+
outcomes, problem = file_outcomes(test_file, namespace)
|
|
121
|
+
else:
|
|
122
|
+
found = discover(qid, namespace) if tests is None else tests
|
|
123
|
+
|
|
124
|
+
if not found and tests is None and _written_in_source(qid, namespace):
|
|
125
|
+
return mo.Html(written_panel(qid, points, title, source=True))
|
|
126
|
+
|
|
127
|
+
outcomes = [run_test(name_of(test), with_rewritten_asserts(test)) for test in found]
|
|
128
|
+
|
|
129
|
+
# Tests found in the source notebook include the hidden ones.
|
|
130
|
+
public = tests is not None or test_file is not None
|
|
131
|
+
|
|
132
|
+
return mo.Html(panel(qid, outcomes, points, hidden, title, problem, public=public))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def written_panel(
|
|
136
|
+
qid: str, points: float | None, title: str | None, *, source: bool = False
|
|
137
|
+
) -> str:
|
|
138
|
+
"""HTML for a written question: its title and points, and where the answer goes.
|
|
139
|
+
|
|
140
|
+
In the `source` notebook, which has no export button, it says where the student's answer goes.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
title = question_title(qid) if title is None else title
|
|
144
|
+
|
|
145
|
+
if points:
|
|
146
|
+
title += f" — {format_points(points)}"
|
|
147
|
+
note = "Written answer, graded by hand."
|
|
148
|
+
else:
|
|
149
|
+
note = "Written answer, not graded."
|
|
150
|
+
|
|
151
|
+
if source:
|
|
152
|
+
note += " Students write it in the cell above, and it goes into the PDF they export."
|
|
153
|
+
else:
|
|
154
|
+
note += " Write it in the cell above. It goes into the PDF when you export."
|
|
155
|
+
|
|
156
|
+
return (
|
|
157
|
+
f'<div style="{PANEL_STYLE.format(accent=SHADE, shade=SHADE)}">'
|
|
158
|
+
f'<div style="{TITLE_STYLE}">{html.escape(title)}</div>'
|
|
159
|
+
f'<div style="{NOTE_STYLE}">{html.escape(note)}</div></div>'
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _written_in_source(qid: str, namespace: Mapping[str, object]) -> bool:
|
|
164
|
+
"""Whether the saved notebook makes `qid` a written question; `False` when unreadable.
|
|
165
|
+
|
|
166
|
+
Raises:
|
|
167
|
+
ConfigError: If the saved notebook's config is invalid.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
path = locate(namespace)
|
|
171
|
+
if path is None:
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
src = path.read_text(encoding="utf-8")
|
|
176
|
+
except (OSError, UnicodeDecodeError):
|
|
177
|
+
return False
|
|
178
|
+
|
|
179
|
+
question = read_config(src, path).questions.get(qid)
|
|
180
|
+
|
|
181
|
+
return question is not None and question.manual
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def file_outcomes(
|
|
185
|
+
test_file: str, namespace: Mapping[str, object]
|
|
186
|
+
) -> tuple[list[Outcome], str | None]:
|
|
187
|
+
"""Run the tests in `test_file`, next to the notebook, in a copy of `namespace`.
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
The outcomes, and why there are none when the file cannot be found or parsed.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
notebook = locate(namespace)
|
|
194
|
+
if notebook is None:
|
|
195
|
+
return [], NO_NOTEBOOK
|
|
196
|
+
|
|
197
|
+
path = notebook.parent / test_file
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
source = path.read_text(encoding="utf-8")
|
|
201
|
+
except FileNotFoundError:
|
|
202
|
+
return [], (
|
|
203
|
+
f"Cannot find {test_file} next to {notebook.name}. Keep the `tests` folder of the "
|
|
204
|
+
"assignment next to the notebook."
|
|
205
|
+
)
|
|
206
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
207
|
+
return [], f"Cannot read {test_file}: {exc}"
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
names = module_tests(source)
|
|
211
|
+
except SyntaxError as exc:
|
|
212
|
+
return [], f"{test_file} is not valid Python (line {exc.lineno})."
|
|
213
|
+
|
|
214
|
+
return run_test_source(source, test_file, names, dict(namespace)), None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def locate(namespace: Mapping[str, object]) -> Path | None:
|
|
218
|
+
"""The notebook file: `__file__` in `namespace`, else marimo's running notebook, else `None`.
|
|
219
|
+
|
|
220
|
+
The second lookup uses marimo's private runtime context and gives `None` when that fails.
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
match namespace.get("__file__"):
|
|
224
|
+
case str() as file if file:
|
|
225
|
+
return Path(file).resolve()
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
from marimo._runtime.context import get_context
|
|
229
|
+
|
|
230
|
+
filename = get_context().filename
|
|
231
|
+
except Exception:
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
return Path(filename).resolve() if filename else None
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def discover(qid: str, namespace: dict[str, object]) -> list[Callable[[], object]]:
|
|
238
|
+
"""Callables named `test_<qid>_*` in `namespace`, in definition order."""
|
|
239
|
+
|
|
240
|
+
prefix = f"test_{qid}_"
|
|
241
|
+
|
|
242
|
+
return [
|
|
243
|
+
value
|
|
244
|
+
for name, value in list(namespace.items())
|
|
245
|
+
if name.startswith(prefix) and callable(value)
|
|
246
|
+
]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def name_of(test: object) -> str:
|
|
250
|
+
"""A function's name, or the `repr` of anything else, cut to `MAX_SOURCE_WIDTH` characters."""
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
match test:
|
|
254
|
+
case FunctionType():
|
|
255
|
+
name = str.__str__(test.__name__)
|
|
256
|
+
case _:
|
|
257
|
+
name = str.__str__(repr(test))
|
|
258
|
+
except BaseException:
|
|
259
|
+
return "<test>"
|
|
260
|
+
|
|
261
|
+
return shorten(name)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def with_rewritten_asserts(test: Callable[[], object]) -> Callable[[], object]:
|
|
265
|
+
"""The test compiled again with assertion rewriting, or the test itself when that fails."""
|
|
266
|
+
|
|
267
|
+
# Closures would lose their cells when compiled again at module level.
|
|
268
|
+
match test:
|
|
269
|
+
case FunctionType() if not test.__code__.co_freevars:
|
|
270
|
+
pass
|
|
271
|
+
case _:
|
|
272
|
+
return test
|
|
273
|
+
|
|
274
|
+
from mogs._assertrewrite import compile_tests
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
source = textwrap.dedent(inspect.getsource(test))
|
|
278
|
+
tree = ast.parse(source)
|
|
279
|
+
except Exception:
|
|
280
|
+
return test
|
|
281
|
+
|
|
282
|
+
# Run nothing but a plain definition: a lambda's source is its whole line, and
|
|
283
|
+
# decorators, defaults and annotations are arbitrary code that already ran once.
|
|
284
|
+
match tree.body:
|
|
285
|
+
case [
|
|
286
|
+
ast.FunctionDef(
|
|
287
|
+
name=name,
|
|
288
|
+
args=ast.arguments(posonlyargs=[], args=[], vararg=None, kwonlyargs=[], kwarg=None),
|
|
289
|
+
decorator_list=[],
|
|
290
|
+
returns=None,
|
|
291
|
+
)
|
|
292
|
+
] if name == test.__name__:
|
|
293
|
+
pass
|
|
294
|
+
case _:
|
|
295
|
+
return test
|
|
296
|
+
|
|
297
|
+
# marimo compiles a cell's `_private` names mangled, but its registered source keeps them
|
|
298
|
+
# plain, so the recompiled test would look up names the kernel does not have. Recompile only
|
|
299
|
+
# when the source asks for no global or attribute the running code lacks.
|
|
300
|
+
try:
|
|
301
|
+
plain = compile(source, "<check>", "exec", dont_inherit=True)
|
|
302
|
+
except Exception:
|
|
303
|
+
return test
|
|
304
|
+
|
|
305
|
+
match [const for const in plain.co_consts if isinstance(const, CodeType)]:
|
|
306
|
+
case [CodeType() as recompiled] if names_used(recompiled) <= names_used(test.__code__):
|
|
307
|
+
pass
|
|
308
|
+
case _:
|
|
309
|
+
return test
|
|
310
|
+
|
|
311
|
+
try:
|
|
312
|
+
code = compile_tests(source, test.__code__.co_filename)
|
|
313
|
+
|
|
314
|
+
# A copy, so the kernel's own globals keep the original function.
|
|
315
|
+
namespace = dict(test.__globals__)
|
|
316
|
+
exec(code, namespace)
|
|
317
|
+
except Exception:
|
|
318
|
+
return test
|
|
319
|
+
|
|
320
|
+
match namespace.get(test.__name__):
|
|
321
|
+
case FunctionType() as rewritten:
|
|
322
|
+
return rewritten
|
|
323
|
+
case _:
|
|
324
|
+
return test
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def names_used(code: CodeType) -> set[str]:
|
|
328
|
+
"""Global and attribute names in `code` and the code nested in it."""
|
|
329
|
+
|
|
330
|
+
names = set(code.co_names)
|
|
331
|
+
|
|
332
|
+
for const in code.co_consts:
|
|
333
|
+
match const:
|
|
334
|
+
case CodeType():
|
|
335
|
+
names |= names_used(const)
|
|
336
|
+
|
|
337
|
+
return names
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def panel(
|
|
341
|
+
qid: str,
|
|
342
|
+
outcomes: list[Outcome],
|
|
343
|
+
points: float | None,
|
|
344
|
+
hidden: int,
|
|
345
|
+
title: str | None = None,
|
|
346
|
+
problem: str | None = None,
|
|
347
|
+
*,
|
|
348
|
+
public: bool = True,
|
|
349
|
+
) -> str:
|
|
350
|
+
"""HTML for the panel, headed by `title`, or by `question_title(qid)` when it is `None`.
|
|
351
|
+
|
|
352
|
+
`problem` says why there are no outcomes; it defaults to "No tests found". `public` says the
|
|
353
|
+
outcomes are of public tests only, and the title calls them so.
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
title = question_title(qid) if title is None else title
|
|
357
|
+
|
|
358
|
+
if points is not None:
|
|
359
|
+
title += f" — {format_points(points)}"
|
|
360
|
+
|
|
361
|
+
if not outcomes:
|
|
362
|
+
accent = WARN
|
|
363
|
+
warning = html.escape(problem or f"No tests found for {qid}")
|
|
364
|
+
body = f'<div style="{MARK_STYLE.format(accent=accent)}">{warning}</div>'
|
|
365
|
+
else:
|
|
366
|
+
passed = sum(outcome.passed for outcome in outcomes)
|
|
367
|
+
accent = PASS if passed == len(outcomes) else FAIL
|
|
368
|
+
kind = "public tests" if public else "tests"
|
|
369
|
+
title += f" · {passed}/{len(outcomes)} {kind} passed"
|
|
370
|
+
items = "".join(outcome_item(outcome) for outcome in outcomes)
|
|
371
|
+
body = f'<ul style="{LIST_STYLE}">{items}</ul>'
|
|
372
|
+
|
|
373
|
+
if hidden > 0:
|
|
374
|
+
noun = "test" if hidden == 1 else "tests"
|
|
375
|
+
body += f'<div style="{NOTE_STYLE}">+ {hidden} hidden {noun} run on Gradescope</div>'
|
|
376
|
+
|
|
377
|
+
return (
|
|
378
|
+
f'<div style="{PANEL_STYLE.format(accent=accent, shade=SHADE)}">'
|
|
379
|
+
f'<div style="{TITLE_STYLE}">{html.escape(title)}</div>'
|
|
380
|
+
f"{body}</div>"
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def outcome_item(outcome: Outcome) -> str:
|
|
385
|
+
"""One list item: a mark, the test name and, for a failure, its message."""
|
|
386
|
+
|
|
387
|
+
name = html.escape(outcome.name)
|
|
388
|
+
|
|
389
|
+
if outcome.passed:
|
|
390
|
+
mark = f'<span style="{MARK_STYLE.format(accent=PASS)}">✓</span>'
|
|
391
|
+
return f'<li style="{ITEM_STYLE}">{mark} {name}</li>'
|
|
392
|
+
|
|
393
|
+
mark = f'<span style="{MARK_STYLE.format(accent=FAIL)}">✗</span>'
|
|
394
|
+
message = f'<pre style="{MESSAGE_STYLE}">{html.escape(outcome.message)}</pre>'
|
|
395
|
+
|
|
396
|
+
return f'<li style="{ITEM_STYLE}">{mark} {name}{message}</li>'
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def question_title(qid: str) -> str:
|
|
400
|
+
"""The title a question gets when the config gives none; see `config.default_title`."""
|
|
401
|
+
|
|
402
|
+
return default_title(qid)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def format_points(points: float) -> str:
|
|
406
|
+
"""`25 pts`, `2.5 pts` or `1 pt`."""
|
|
407
|
+
|
|
408
|
+
shown = f"{points:g}"
|
|
409
|
+
|
|
410
|
+
return f"{shown} pt" if points == 1 else f"{shown} pts"
|
mogs/cli.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""The `mogs` command."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import shlex
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from copy import replace
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from mogs import __version__
|
|
11
|
+
from mogs.build import BuildError, BuildResult, build, failure_report, source_notebook
|
|
12
|
+
from mogs.check import format_points
|
|
13
|
+
from mogs.config import ConfigError
|
|
14
|
+
from mogs.regrade import GradeResult, grade_submission
|
|
15
|
+
from mogs.requirements import RequirementsError
|
|
16
|
+
from mogs.scaffold import InitError, init
|
|
17
|
+
from mogs.source import NO_TEXT, SourceError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main(argv: list[str] | None = None) -> int:
|
|
21
|
+
"""Run the command line.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
argv: Arguments; `sys.argv[1:]` when `None`.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
Exit code: 0 on success, 1 when the command fails.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
args = _parser().parse_args(argv)
|
|
31
|
+
|
|
32
|
+
match args.command:
|
|
33
|
+
case "init":
|
|
34
|
+
return _init(args.dir)
|
|
35
|
+
case "edit":
|
|
36
|
+
return _edit(args.path)
|
|
37
|
+
case "build":
|
|
38
|
+
return _build(args.dir)
|
|
39
|
+
case "grade":
|
|
40
|
+
return _grade(args.dir, args.submission)
|
|
41
|
+
case _:
|
|
42
|
+
raise AssertionError(f"unhandled command {args.command!r}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _init(folder: Path) -> int:
|
|
46
|
+
try:
|
|
47
|
+
path = init(folder)
|
|
48
|
+
except (InitError, ConfigError, OSError) as error:
|
|
49
|
+
print(f"Init failed.\n{error}", file=sys.stderr)
|
|
50
|
+
return 1
|
|
51
|
+
|
|
52
|
+
print(f"Created {path}")
|
|
53
|
+
print(f"Edit it : mogs edit {shlex.quote(str(folder))}")
|
|
54
|
+
print(f"Build it : mogs build {shlex.quote(str(folder))}")
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _edit(path: Path) -> int:
|
|
59
|
+
"""Open the source notebook at `path`, a file or its folder, with `marimo edit --sandbox`.
|
|
60
|
+
|
|
61
|
+
marimo runs on this package's Python, which has pytest. The editor server compiles the
|
|
62
|
+
test cells there, and without pytest it logs a warning for each of them.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
notebook = source_notebook(path)
|
|
67
|
+
marimo = subprocess.Popen(
|
|
68
|
+
[sys.executable, "-m", "marimo", "edit", "--sandbox", str(notebook)]
|
|
69
|
+
)
|
|
70
|
+
except (BuildError, OSError) as error:
|
|
71
|
+
print(f"Edit failed.\n{error}", file=sys.stderr)
|
|
72
|
+
return 1
|
|
73
|
+
|
|
74
|
+
# Ctrl+C reaches marimo too, and marimo asks whether to quit. Wait until it exits.
|
|
75
|
+
while True:
|
|
76
|
+
try:
|
|
77
|
+
return marimo.wait()
|
|
78
|
+
except KeyboardInterrupt:
|
|
79
|
+
continue
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _build(folder: Path) -> int:
|
|
83
|
+
try:
|
|
84
|
+
result = build(folder)
|
|
85
|
+
except (BuildError, ConfigError, SourceError, RequirementsError, OSError) as error:
|
|
86
|
+
print(f"Build failed.\n{error}", file=sys.stderr)
|
|
87
|
+
return 1
|
|
88
|
+
|
|
89
|
+
print(report(result))
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _grade(folder: Path, submission: Path) -> int:
|
|
94
|
+
try:
|
|
95
|
+
result = grade_submission(folder, submission)
|
|
96
|
+
except (BuildError, ConfigError, SourceError, RequirementsError, OSError) as error:
|
|
97
|
+
print(f"Grading failed.\n{error}", file=sys.stderr)
|
|
98
|
+
return 1
|
|
99
|
+
|
|
100
|
+
print(grade_report(result))
|
|
101
|
+
|
|
102
|
+
if result.load_error is not None:
|
|
103
|
+
print(
|
|
104
|
+
f"Grading failed.\n{result.submission} failed to load: {result.load_error}",
|
|
105
|
+
file=sys.stderr,
|
|
106
|
+
)
|
|
107
|
+
return 1
|
|
108
|
+
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def grade_report(result: GradeResult) -> str:
|
|
113
|
+
"""Per-question scores and the failing tests, hidden ones marked, as text."""
|
|
114
|
+
|
|
115
|
+
lines = [f"Graded: {result.submission}", ""]
|
|
116
|
+
rows = [("Question", "Score")]
|
|
117
|
+
titles = {q.id: q.title for q in result.bundle.config.questions.values()}
|
|
118
|
+
|
|
119
|
+
for row in result.results["tests"]:
|
|
120
|
+
if "number" in row:
|
|
121
|
+
rows.append((titles[row["number"]], _fraction(row["score"], row["max_score"])))
|
|
122
|
+
|
|
123
|
+
rows.append(("Total", _fraction(*result.score)))
|
|
124
|
+
width = max(len(row[0]) for row in rows)
|
|
125
|
+
lines += [f"{name:<{width}} {score:>9}" for name, score in rows]
|
|
126
|
+
|
|
127
|
+
hidden = {name for cell in result.bundle.cells if cell.hidden for name in cell.tests}
|
|
128
|
+
failed = [
|
|
129
|
+
replace(outcome, name=f"{outcome.name} (hidden)") if outcome.name in hidden else outcome
|
|
130
|
+
for outcome in result.outcomes.values()
|
|
131
|
+
if not outcome.passed
|
|
132
|
+
]
|
|
133
|
+
|
|
134
|
+
if failed:
|
|
135
|
+
lines += ["", "Failing tests:", *failure_report(failed, count_load_failures=False)]
|
|
136
|
+
|
|
137
|
+
return "\n".join(lines)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def report(result: BuildResult) -> str:
|
|
141
|
+
"""The files to upload and distribute, then the self-check scores and the warnings.
|
|
142
|
+
|
|
143
|
+
Each written question is listed with the first line of each of its prompt cells, so the
|
|
144
|
+
instructor can check which text goes into the PDF.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
lines = [
|
|
148
|
+
"All done!",
|
|
149
|
+
f"Upload to Gradescope : {_shown(result.zip)}",
|
|
150
|
+
f"Distribute to students: {_shown(result.student)}",
|
|
151
|
+
"",
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
rows = [("Question", "Public", "Hidden", "Solution", "Blank")]
|
|
155
|
+
manual = []
|
|
156
|
+
|
|
157
|
+
for score in result.scores:
|
|
158
|
+
if score.solution is None or score.blank is None:
|
|
159
|
+
how = (
|
|
160
|
+
f"{format_points(score.points)}, graded by hand"
|
|
161
|
+
if score.points
|
|
162
|
+
else "collected in the PDF, not graded"
|
|
163
|
+
)
|
|
164
|
+
manual.append(f"- {score.id} {score.title}: {how}")
|
|
165
|
+
manual += [f" {line}" for line in score.prompts or (NO_TEXT,)]
|
|
166
|
+
continue
|
|
167
|
+
|
|
168
|
+
rows.append(
|
|
169
|
+
(
|
|
170
|
+
score.title,
|
|
171
|
+
str(score.public),
|
|
172
|
+
str(score.hidden),
|
|
173
|
+
_fraction(score.solution, score.points),
|
|
174
|
+
_fraction(score.blank, score.points),
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
rows.append(("Total", "", "", _fraction(*result.solution), _fraction(*result.blank)))
|
|
179
|
+
width = max(len(row[0]) for row in rows)
|
|
180
|
+
lines += [
|
|
181
|
+
f"{name:<{width}} {public:>6} {hidden:>6} {solution:>9} {blank:>9}"
|
|
182
|
+
for name, public, hidden, solution, blank in rows
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
if manual:
|
|
186
|
+
lines += ["", "Not in the autograder total:"]
|
|
187
|
+
lines += manual
|
|
188
|
+
|
|
189
|
+
if result.warnings:
|
|
190
|
+
lines += ["", "Warnings:"]
|
|
191
|
+
lines += [f"- {warning}" for warning in result.warnings]
|
|
192
|
+
|
|
193
|
+
return "\n".join(lines)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _shown(path: Path) -> Path:
|
|
197
|
+
"""`path` relative to the working directory when it is inside it, else as it is."""
|
|
198
|
+
|
|
199
|
+
cwd = Path.cwd()
|
|
200
|
+
|
|
201
|
+
return path.relative_to(cwd) if path.is_relative_to(cwd) else path
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _fraction(score: float, points: float) -> str:
|
|
205
|
+
return f"{score:g}/{points:g}"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _parser() -> argparse.ArgumentParser:
|
|
209
|
+
parser = argparse.ArgumentParser(
|
|
210
|
+
prog="mogs",
|
|
211
|
+
description="Build Gradescope autograders from marimo notebooks.",
|
|
212
|
+
)
|
|
213
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
214
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
215
|
+
|
|
216
|
+
init_parser = commands.add_parser(
|
|
217
|
+
"init",
|
|
218
|
+
help="start a new assignment",
|
|
219
|
+
description=(
|
|
220
|
+
"Create DIR with one notebook, DIR/<name of DIR>.py, holding the assignment cell, "
|
|
221
|
+
"a guide and two example questions."
|
|
222
|
+
),
|
|
223
|
+
)
|
|
224
|
+
init_parser.add_argument("dir", type=Path, metavar="DIR", help="new assignment folder")
|
|
225
|
+
|
|
226
|
+
edit_parser = commands.add_parser(
|
|
227
|
+
"edit",
|
|
228
|
+
help="open the source notebook in marimo's editor",
|
|
229
|
+
description=(
|
|
230
|
+
"Run `marimo edit --sandbox` on the source notebook PATH, or the one in the "
|
|
231
|
+
"assignment folder PATH, with the marimo installed next to mogs."
|
|
232
|
+
),
|
|
233
|
+
)
|
|
234
|
+
edit_parser.add_argument(
|
|
235
|
+
"path",
|
|
236
|
+
type=Path,
|
|
237
|
+
metavar="PATH",
|
|
238
|
+
help="source notebook, or the assignment folder with it",
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
build_parser = commands.add_parser(
|
|
242
|
+
"build",
|
|
243
|
+
help="build the student notebook and the autograder zip",
|
|
244
|
+
description=(
|
|
245
|
+
"Build DIR/dist/student/ and DIR/dist/autograder/ (the autograder zip and the "
|
|
246
|
+
"solved student notebook) from the notebook in DIR, then grade the solved and the "
|
|
247
|
+
"blank student copy."
|
|
248
|
+
),
|
|
249
|
+
)
|
|
250
|
+
build_parser.add_argument(
|
|
251
|
+
"dir", type=Path, metavar="DIR", help="assignment folder with the source notebook"
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
grade_parser = commands.add_parser(
|
|
255
|
+
"grade",
|
|
256
|
+
help="grade one submission locally",
|
|
257
|
+
description=(
|
|
258
|
+
"Grade SUBMISSION against the source notebook in DIR with the real grader, as "
|
|
259
|
+
"Gradescope would, and list every failing test, hidden ones included."
|
|
260
|
+
),
|
|
261
|
+
)
|
|
262
|
+
grade_parser.add_argument(
|
|
263
|
+
"dir", type=Path, metavar="DIR", help="assignment folder with the source notebook"
|
|
264
|
+
)
|
|
265
|
+
grade_parser.add_argument(
|
|
266
|
+
"submission",
|
|
267
|
+
type=Path,
|
|
268
|
+
metavar="SUBMISSION",
|
|
269
|
+
help="student notebook (.py), the zip a student exported, or a folder with one",
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
return parser
|