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/environment.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""The Python environment the build grades in.
|
|
2
|
+
|
|
3
|
+
It holds what Gradescope installs: the pinned requirements and mogs. The
|
|
4
|
+
mogs in it is the one that runs the build, so a build from a source checkout grades
|
|
5
|
+
with that checkout.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import importlib.metadata
|
|
9
|
+
import json
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from urllib.parse import urlparse
|
|
14
|
+
from urllib.request import url2pathname
|
|
15
|
+
|
|
16
|
+
from mogs import __version__
|
|
17
|
+
from mogs._env import clean_env
|
|
18
|
+
from mogs.config import TOOL, normalized_name
|
|
19
|
+
from mogs.requirements import RequirementsError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def grading_python(requirements: str, folder: Path, python_version: str) -> Path:
|
|
23
|
+
"""Create a virtual environment in `folder` and install the grading requirements.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
requirements: Text of Gradescope's `requirements.txt`. Its mogs line is
|
|
27
|
+
replaced by the running mogs.
|
|
28
|
+
folder: Where to create the environment; must not exist.
|
|
29
|
+
python_version: Python version for the environment, as on Gradescope.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
The environment's interpreter.
|
|
33
|
+
|
|
34
|
+
Raises:
|
|
35
|
+
RequirementsError: If `uv` is missing, or the environment cannot be created or the
|
|
36
|
+
requirements cannot be installed.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
uv = shutil.which("uv")
|
|
40
|
+
if uv is None:
|
|
41
|
+
raise RequirementsError("`uv` is not on PATH; it is needed to install the requirements.")
|
|
42
|
+
|
|
43
|
+
_uv([uv, "venv", "--quiet", "--python", python_version, str(folder)], "create")
|
|
44
|
+
|
|
45
|
+
python = folder / "bin" / "python"
|
|
46
|
+
lines = [line for line in requirements.splitlines() if normalized_name(line) != TOOL]
|
|
47
|
+
listed = folder / "requirements.txt"
|
|
48
|
+
listed.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
|
|
49
|
+
|
|
50
|
+
# Gradescope installs with pip, which takes each package's best version from any index.
|
|
51
|
+
command = [uv, "pip", "install", "--quiet", "--python", str(python), "-r", str(listed)]
|
|
52
|
+
command += ["--index-strategy", "unsafe-best-match"]
|
|
53
|
+
_uv(command + tool_install_args(_direct_url()), "install the requirements in")
|
|
54
|
+
|
|
55
|
+
return python
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def tool_install_args(direct_url: str | None) -> list[str]:
|
|
59
|
+
"""`uv pip install` arguments that install the running mogs.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
direct_url: Its `direct_url.json` (PEP 610), present when it was installed from a
|
|
63
|
+
folder, an archive or a repository; `None` when it came from an index.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
RequirementsError: If `direct_url` describes none of these.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
match None if direct_url is None else json.loads(direct_url):
|
|
70
|
+
case None:
|
|
71
|
+
return [f"{TOOL}=={__version__}"]
|
|
72
|
+
case {"url": str(url), "dir_info": {"editable": True}} as info:
|
|
73
|
+
return ["--editable", _local_path(url, info)]
|
|
74
|
+
case {"url": str(url), "dir_info": dict()} as info:
|
|
75
|
+
return [_local_path(url, info)]
|
|
76
|
+
case {"url": str(url), "archive_info": dict()} as info:
|
|
77
|
+
return [f"{TOOL} @ {url}{_fragment(info)}"]
|
|
78
|
+
case {"url": str(url), "vcs_info": {"vcs": str(vcs), "commit_id": str(commit)}} as info:
|
|
79
|
+
return [f"{TOOL} @ {vcs}+{url}@{commit}{_fragment(info)}"]
|
|
80
|
+
case other:
|
|
81
|
+
raise RequirementsError(
|
|
82
|
+
f"Cannot tell where {TOOL} was installed from; its direct_url.json is {other!r}."
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _local_path(url: str, info: dict[str, object]) -> str:
|
|
87
|
+
"""The folder a `file://` URL names, with PEP 610's `subdirectory` appended."""
|
|
88
|
+
|
|
89
|
+
path = Path(url2pathname(urlparse(url).path))
|
|
90
|
+
|
|
91
|
+
match info.get("subdirectory"):
|
|
92
|
+
case str(subdirectory):
|
|
93
|
+
path = path / subdirectory
|
|
94
|
+
|
|
95
|
+
return str(path)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _fragment(info: dict[str, object]) -> str:
|
|
99
|
+
"""The `#subdirectory=...` URL fragment for PEP 610's `subdirectory`, if any."""
|
|
100
|
+
|
|
101
|
+
match info.get("subdirectory"):
|
|
102
|
+
case str(subdirectory):
|
|
103
|
+
return f"#subdirectory={subdirectory}"
|
|
104
|
+
case _:
|
|
105
|
+
return ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _direct_url() -> str | None:
|
|
109
|
+
return importlib.metadata.distribution(TOOL).read_text("direct_url.json")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _uv(command: list[str], action: str) -> None:
|
|
113
|
+
result = subprocess.run(command, capture_output=True, text=True, check=False, env=clean_env())
|
|
114
|
+
|
|
115
|
+
if result.returncode != 0:
|
|
116
|
+
raise RequirementsError(
|
|
117
|
+
f"`uv` could not {action} the build's grading environment:\n{result.stderr.strip()}"
|
|
118
|
+
)
|
mogs/export.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
"""The export button: check the saved notebook and package it for Gradescope.
|
|
2
|
+
|
|
3
|
+
The build appends two cells to the student notebook:
|
|
4
|
+
|
|
5
|
+
export_button = mogs.export_button()
|
|
6
|
+
export_button
|
|
7
|
+
|
|
8
|
+
mogs.export(export_button, name="hw", manual=["q3"],
|
|
9
|
+
titles={"q1": "Question 1", "q2": "Question 2", "q3": "Question 3"},
|
|
10
|
+
placeholders={"answer_q3": "*Write your answer here.*"})
|
|
11
|
+
|
|
12
|
+
On a click, `export` works from the notebook file on disk, not the kernel's state. It reads
|
|
13
|
+
the file once, runs the public tests on the file in a subprocess, makes a PDF of the written
|
|
14
|
+
answers from the snapshot (or a Markdown file when the PDF fails), and offers a zip of both
|
|
15
|
+
as a download. A save during the export gets a warning. Nothing is written next to the
|
|
16
|
+
notebook.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import html
|
|
21
|
+
import io
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
import tempfile
|
|
26
|
+
import zipfile
|
|
27
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from datetime import datetime
|
|
30
|
+
from enum import StrEnum
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import TYPE_CHECKING
|
|
33
|
+
|
|
34
|
+
from mogs._env import grading
|
|
35
|
+
from mogs._run import run_capped
|
|
36
|
+
from mogs.check import (
|
|
37
|
+
FAIL,
|
|
38
|
+
LIST_STYLE,
|
|
39
|
+
MARK_STYLE,
|
|
40
|
+
NOTE_STYLE,
|
|
41
|
+
PANEL_STYLE,
|
|
42
|
+
PASS,
|
|
43
|
+
SHADE,
|
|
44
|
+
WARN,
|
|
45
|
+
locate,
|
|
46
|
+
)
|
|
47
|
+
from mogs.config import default_title
|
|
48
|
+
from mogs.pdf import NO_ANSWER, PdfUnavailable, cell_markdown, quiet, render_manual_pdf
|
|
49
|
+
from mogs.runner import exception_summary, shorten
|
|
50
|
+
from mogs.source import Notebook, SourceError, answer_text, parse_notebook, unanswered
|
|
51
|
+
|
|
52
|
+
if TYPE_CHECKING:
|
|
53
|
+
import marimo as mo
|
|
54
|
+
|
|
55
|
+
SELFCHECK_TIMEOUT = 300.0
|
|
56
|
+
BUTTON_LABEL = "Export submission"
|
|
57
|
+
NOTE = "rgba(127, 127, 127, 0.6)"
|
|
58
|
+
CHANGED = "The notebook changed during the export; export again."
|
|
59
|
+
NOT_FOUND = (
|
|
60
|
+
"Cannot find this notebook's file, so it cannot be exported. Save the notebook, then open "
|
|
61
|
+
"it with `marimo edit <your notebook>.py`."
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# Room between the panel's groups: the checks, and the download below a rule.
|
|
65
|
+
LINE_STYLE = "margin: 0 0 0.75em;"
|
|
66
|
+
SUBLIST_STYLE = "list-style: none; margin: 0.4em 0 0 1.6em; padding: 0;"
|
|
67
|
+
SUBITEM_STYLE = "margin: 0.25em 0;"
|
|
68
|
+
DOWNLOAD_STYLE = (
|
|
69
|
+
"margin-top: 1em; padding-top: 1em; border-top: 1px solid rgba(127, 127, 127, 0.3);"
|
|
70
|
+
)
|
|
71
|
+
BUTTON_STYLE = "margin: 0.75em 0;"
|
|
72
|
+
|
|
73
|
+
type Status = Callable[[str], None]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Mark(StrEnum):
|
|
77
|
+
"""The symbol in front of a panel line."""
|
|
78
|
+
|
|
79
|
+
OK = "✓"
|
|
80
|
+
WARN = "⚠"
|
|
81
|
+
FAIL = "✗"
|
|
82
|
+
DOWNLOAD = "⬇"
|
|
83
|
+
NOTE = "→"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
ACCENTS = {
|
|
87
|
+
Mark.OK: PASS,
|
|
88
|
+
Mark.WARN: WARN,
|
|
89
|
+
Mark.FAIL: FAIL,
|
|
90
|
+
Mark.DOWNLOAD: PASS,
|
|
91
|
+
Mark.NOTE: NOTE,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True, slots=True)
|
|
96
|
+
class Line:
|
|
97
|
+
"""One line of the export panel.
|
|
98
|
+
|
|
99
|
+
Attributes:
|
|
100
|
+
mark: Symbol in front.
|
|
101
|
+
text: Plain text; escaped when rendered.
|
|
102
|
+
items: Lines shown indented below this one.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
mark: Mark
|
|
106
|
+
text: str
|
|
107
|
+
items: tuple["Line", ...] = ()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True, slots=True)
|
|
111
|
+
class Package:
|
|
112
|
+
"""An exported submission.
|
|
113
|
+
|
|
114
|
+
Attributes:
|
|
115
|
+
lines: What the checks found, in order.
|
|
116
|
+
filename: Name of the zip.
|
|
117
|
+
data: The zip.
|
|
118
|
+
note: Which file was exported and when it was saved.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
lines: tuple[Line, ...]
|
|
122
|
+
filename: str
|
|
123
|
+
data: bytes
|
|
124
|
+
note: str
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass(frozen=True, slots=True)
|
|
128
|
+
class Download:
|
|
129
|
+
"""The download part of the export panel.
|
|
130
|
+
|
|
131
|
+
Attributes:
|
|
132
|
+
button: The download button's HTML, trusted.
|
|
133
|
+
filename: Name of the zip.
|
|
134
|
+
note: Small print under the button.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
button: str
|
|
138
|
+
filename: str
|
|
139
|
+
note: str
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def export_button() -> "mo.ui.run_button":
|
|
143
|
+
"""The button that starts an export."""
|
|
144
|
+
|
|
145
|
+
import marimo as mo
|
|
146
|
+
|
|
147
|
+
return mo.ui.run_button(label=BUTTON_LABEL)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def export(
|
|
151
|
+
button: "mo.ui.run_button",
|
|
152
|
+
*,
|
|
153
|
+
name: str,
|
|
154
|
+
manual: Sequence[str],
|
|
155
|
+
titles: Mapping[str, str],
|
|
156
|
+
placeholders: Mapping[str, str] | None = None,
|
|
157
|
+
) -> "mo.Html":
|
|
158
|
+
"""Export the notebook when `button` was clicked; otherwise say which file it would export.
|
|
159
|
+
|
|
160
|
+
The notebook file is the caller's `__file__`, or else the file of marimo's running
|
|
161
|
+
notebook. When neither is known, the panel says so. An unexpected error shows as a failed
|
|
162
|
+
panel; `KeyboardInterrupt` stops the export. While grading (`MOGS_GRADING=1`) it does
|
|
163
|
+
nothing and returns an empty panel.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
button: The button from `export_button()`.
|
|
167
|
+
name: Base name of the files in the zip, e.g. `hw` for `hw_submission.zip`.
|
|
168
|
+
manual: Ids of the questions graded by hand.
|
|
169
|
+
titles: Title per question: a heading in the PDF, a label in the test summary.
|
|
170
|
+
placeholders: The text each answer cell starts with, by cell name, such as
|
|
171
|
+
`answer_q3` or `answer_q3_2`. An answer still equal to it (ignoring whitespace)
|
|
172
|
+
gets a warning. A key that is a question id stands for `answer_<qid>`.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
The export panel, with the download when the export ran.
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
import marimo as mo
|
|
179
|
+
|
|
180
|
+
if grading():
|
|
181
|
+
return mo.Html("")
|
|
182
|
+
|
|
183
|
+
namespace = sys._getframe(1).f_globals
|
|
184
|
+
|
|
185
|
+
return export_panel(button.value, namespace, name, manual, titles, placeholders or {})
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def export_panel(
|
|
189
|
+
clicked: bool,
|
|
190
|
+
namespace: Mapping[str, object],
|
|
191
|
+
name: str,
|
|
192
|
+
manual: Sequence[str],
|
|
193
|
+
titles: Mapping[str, str],
|
|
194
|
+
placeholders: Mapping[str, str],
|
|
195
|
+
) -> "mo.Html":
|
|
196
|
+
"""`export`, with the button's state and the caller's globals passed in."""
|
|
197
|
+
|
|
198
|
+
import marimo as mo
|
|
199
|
+
|
|
200
|
+
notebook = locate(namespace)
|
|
201
|
+
|
|
202
|
+
if notebook is None:
|
|
203
|
+
return mo.Html(panel((Line(Mark.FAIL, NOT_FOUND),)))
|
|
204
|
+
|
|
205
|
+
if not clicked:
|
|
206
|
+
note = f"Click “{BUTTON_LABEL}” to check and package {notebook}. Save your changes first."
|
|
207
|
+
return mo.Html(panel((Line(Mark.NOTE, note),)))
|
|
208
|
+
|
|
209
|
+
if not notebook.is_file():
|
|
210
|
+
message = f"{notebook} does not exist. Save the notebook, then export again."
|
|
211
|
+
return mo.Html(panel((Line(Mark.FAIL, message),)))
|
|
212
|
+
|
|
213
|
+
try:
|
|
214
|
+
with mo.status.spinner(title="Exporting your submission…") as spinner:
|
|
215
|
+
result = package(
|
|
216
|
+
notebook,
|
|
217
|
+
name=name,
|
|
218
|
+
manual=manual,
|
|
219
|
+
titles=titles,
|
|
220
|
+
placeholders=placeholders,
|
|
221
|
+
status=lambda message: spinner.update(title=message),
|
|
222
|
+
)
|
|
223
|
+
except Exception as exc:
|
|
224
|
+
return mo.Html(panel((Line(Mark.FAIL, f"Export failed: {exception_summary(exc)}"),)))
|
|
225
|
+
|
|
226
|
+
download = mo.download(
|
|
227
|
+
data=result.data, filename=result.filename, mimetype="application/zip", label="Download"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
return mo.Html(panel(result.lines, Download(download.text, result.filename, result.note)))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def package(
|
|
234
|
+
notebook: Path,
|
|
235
|
+
*,
|
|
236
|
+
name: str,
|
|
237
|
+
manual: Sequence[str],
|
|
238
|
+
titles: Mapping[str, str],
|
|
239
|
+
placeholders: Mapping[str, str] | None = None,
|
|
240
|
+
status: Status | None = None,
|
|
241
|
+
) -> Package:
|
|
242
|
+
"""Check the notebook file, make the answers file, and zip both.
|
|
243
|
+
|
|
244
|
+
The file is read once; the PDF is made from a copy of that snapshot in a temporary folder
|
|
245
|
+
and the zip holds the snapshot. The public tests run on the real file, as the grader runs
|
|
246
|
+
them next to the data files. If the file's bytes differ from the snapshot after the
|
|
247
|
+
tests and the PDF, a warning asks to export again. A `KeyboardInterrupt` stops the
|
|
248
|
+
export: it propagates and no zip is made.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
notebook: The notebook file.
|
|
252
|
+
name: Base name of the files in the zip.
|
|
253
|
+
manual: Ids of the questions graded by hand.
|
|
254
|
+
titles: Title per question.
|
|
255
|
+
placeholders: The text each answer cell starts with, by cell name; a question id
|
|
256
|
+
stands for `answer_<qid>`.
|
|
257
|
+
status: Called with a short message before slow steps.
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
The panel lines and the zip.
|
|
261
|
+
|
|
262
|
+
Raises:
|
|
263
|
+
OSError: If the notebook cannot be read.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
report = status or quiet
|
|
267
|
+
starts = {
|
|
268
|
+
(f"answer_{key}" if key in manual else key): text
|
|
269
|
+
for key, text in (placeholders or {}).items()
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
with notebook.open("rb") as file:
|
|
273
|
+
modified = os.fstat(file.fileno()).st_mtime
|
|
274
|
+
data = file.read()
|
|
275
|
+
|
|
276
|
+
saved = datetime.fromtimestamp(modified).strftime("%Y-%m-%d %H:%M:%S")
|
|
277
|
+
lines = []
|
|
278
|
+
entries = {notebook.name: data}
|
|
279
|
+
|
|
280
|
+
with tempfile.TemporaryDirectory(prefix="mogs-export-", ignore_cleanup_errors=True) as folder:
|
|
281
|
+
snapshot = Path(folder) / notebook.name
|
|
282
|
+
snapshot.write_bytes(data)
|
|
283
|
+
|
|
284
|
+
report("Running the public tests…")
|
|
285
|
+
lines += test_lines(notebook, notebook.parent, titles)
|
|
286
|
+
|
|
287
|
+
if manual:
|
|
288
|
+
nb = _parse(data)
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
out = Path(folder) / f"{name}.pdf"
|
|
292
|
+
render_manual_pdf(snapshot, manual, titles, out, placeholders=starts, status=report)
|
|
293
|
+
entries[out.name] = out.read_bytes()
|
|
294
|
+
lines.append(Line(Mark.OK, f"Written answers → {name}.pdf"))
|
|
295
|
+
except PdfUnavailable as exc:
|
|
296
|
+
answers = answers_markdown(nb, name, manual, titles, starts)
|
|
297
|
+
entries[f"{name}_answers.md"] = answers.encode()
|
|
298
|
+
lines.append(
|
|
299
|
+
Line(Mark.WARN, f"PDF not created: {exc}; answers included as Markdown")
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
lines += unanswered_lines(nb, manual, titles, starts)
|
|
303
|
+
|
|
304
|
+
if _digest_of(notebook) != hashlib.sha256(data).hexdigest():
|
|
305
|
+
lines.append(Line(Mark.WARN, CHANGED))
|
|
306
|
+
|
|
307
|
+
filename = f"{name}_submission.zip"
|
|
308
|
+
note = f"Exported {notebook.name} as saved at {saved}."
|
|
309
|
+
|
|
310
|
+
return Package(tuple(lines), filename, build_zip(entries), note)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def test_lines(
|
|
314
|
+
notebook: Path, folder: Path, titles: Mapping[str, str] | None = None
|
|
315
|
+
) -> tuple[Line, ...]:
|
|
316
|
+
"""Run the public tests of a notebook file in a subprocess and summarize them.
|
|
317
|
+
|
|
318
|
+
The first line gives the total, with one line per question below it. The check under each
|
|
319
|
+
question names the failing tests. A warning follows for each name the tests use that the
|
|
320
|
+
notebook could not provide, such as a name lost to a failed notebook run, with why.
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
notebook: The notebook file.
|
|
324
|
+
folder: Working directory for the tests: the folder of the student's notebook.
|
|
325
|
+
titles: Title per question; a question without one gets `default_title`.
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
result = run_capped(
|
|
329
|
+
[sys.executable, "-m", "mogs.selfcheck", str(notebook), str(folder)],
|
|
330
|
+
cwd=folder,
|
|
331
|
+
timeout=SELFCHECK_TIMEOUT,
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
if result is None:
|
|
335
|
+
return (
|
|
336
|
+
Line(Mark.WARN, f"Public tests: the check timed out after {SELFCHECK_TIMEOUT:g} s"),
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
summary = _summary(result.stdout) if result.returncode == 0 else None
|
|
340
|
+
|
|
341
|
+
if summary is None:
|
|
342
|
+
errors = [line.strip() for line in result.stderr.splitlines() if line.strip()]
|
|
343
|
+
reason = shorten(errors[-1]) if errors else f"exit status {result.returncode}"
|
|
344
|
+
return (Line(Mark.WARN, f"Public tests could not run: {reason}"),)
|
|
345
|
+
|
|
346
|
+
questions, missing = summary
|
|
347
|
+
passed = sum(passed for passed, _, _ in questions.values())
|
|
348
|
+
total = sum(total for _, total, _ in questions.values())
|
|
349
|
+
items = tuple(
|
|
350
|
+
Line(
|
|
351
|
+
Mark.OK if done == count else Mark.FAIL,
|
|
352
|
+
f"{(titles or {}).get(qid) or default_title(qid)}: {done}/{count} passed",
|
|
353
|
+
)
|
|
354
|
+
for qid, (done, count, _) in questions.items()
|
|
355
|
+
)
|
|
356
|
+
mark = Mark.OK if passed == total else Mark.WARN
|
|
357
|
+
|
|
358
|
+
return (
|
|
359
|
+
Line(mark, f"Public tests: {passed}/{total} passed", items),
|
|
360
|
+
*unavailable_lines(missing),
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def unavailable_lines(missing: Mapping[str, str]) -> tuple[Line, ...]:
|
|
365
|
+
"""One warning per reason, naming the names it made unavailable, in name order."""
|
|
366
|
+
|
|
367
|
+
names_by_reason: dict[str, list[str]] = {}
|
|
368
|
+
|
|
369
|
+
for name in sorted(missing):
|
|
370
|
+
names_by_reason.setdefault(missing[name], []).append(name)
|
|
371
|
+
|
|
372
|
+
lines = []
|
|
373
|
+
|
|
374
|
+
for reason, names in names_by_reason.items():
|
|
375
|
+
quoted = [f"`{name}`" for name in names]
|
|
376
|
+
listed = quoted[0] if len(quoted) == 1 else f"{', '.join(quoted[:-1])} and {quoted[-1]}"
|
|
377
|
+
verb, pronoun = ("is", "it") if len(names) == 1 else ("are", "them")
|
|
378
|
+
text = f"{listed} {verb} unavailable: {reason}."
|
|
379
|
+
lines.append(Line(Mark.WARN, f"{text} Tests that use {pronoun} fail, on Gradescope too."))
|
|
380
|
+
|
|
381
|
+
return tuple(lines)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def unanswered_lines(
|
|
385
|
+
nb: Notebook | None,
|
|
386
|
+
manual: Sequence[str],
|
|
387
|
+
titles: Mapping[str, str],
|
|
388
|
+
placeholders: Mapping[str, str],
|
|
389
|
+
) -> list[Line]:
|
|
390
|
+
"""A warning per written question, or part of one, that is blank or still its start text.
|
|
391
|
+
|
|
392
|
+
A question with all its parts unanswered gets one line; otherwise each part does. Parts
|
|
393
|
+
are numbered from 1 in file order.
|
|
394
|
+
|
|
395
|
+
Args:
|
|
396
|
+
nb: The notebook; `None` when it does not parse, which warns about every question.
|
|
397
|
+
manual: Ids of the questions graded by hand.
|
|
398
|
+
titles: Title per question; a question without one gets `default_title`.
|
|
399
|
+
placeholders: The text each answer cell starts with, by cell name.
|
|
400
|
+
"""
|
|
401
|
+
|
|
402
|
+
lines = []
|
|
403
|
+
|
|
404
|
+
for qid in manual:
|
|
405
|
+
title = titles.get(qid) or default_title(qid)
|
|
406
|
+
cells = () if nb is None else nb.answer_cells(qid)
|
|
407
|
+
parts = [
|
|
408
|
+
index
|
|
409
|
+
for index, cell in enumerate(cells, start=1)
|
|
410
|
+
if nb is not None and unanswered(answer_text(nb, cell), placeholders.get(cell.name))
|
|
411
|
+
]
|
|
412
|
+
|
|
413
|
+
if len(parts) == len(cells):
|
|
414
|
+
lines.append(Line(Mark.WARN, f"{title} has no answer yet"))
|
|
415
|
+
continue
|
|
416
|
+
|
|
417
|
+
lines += [Line(Mark.WARN, f"{title}, part {index} has no answer yet") for index in parts]
|
|
418
|
+
|
|
419
|
+
return lines
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def answers_markdown(
|
|
423
|
+
nb: Notebook | None,
|
|
424
|
+
name: str,
|
|
425
|
+
manual: Sequence[str],
|
|
426
|
+
titles: Mapping[str, str],
|
|
427
|
+
placeholders: Mapping[str, str] | None = None,
|
|
428
|
+
) -> str:
|
|
429
|
+
"""The written answers as Markdown, for when the PDF cannot be made.
|
|
430
|
+
|
|
431
|
+
An answer cell that is blank or still its text in `placeholders` shows as "No answer."
|
|
432
|
+
"""
|
|
433
|
+
|
|
434
|
+
parts = [f"# Written answers: {name}"]
|
|
435
|
+
|
|
436
|
+
for qid in manual:
|
|
437
|
+
parts.append(f"## {titles.get(qid, qid)}")
|
|
438
|
+
|
|
439
|
+
if nb is None:
|
|
440
|
+
parts.append("*The notebook does not parse, so no answer could be read.*")
|
|
441
|
+
continue
|
|
442
|
+
|
|
443
|
+
cells = nb.answer_cells(qid)
|
|
444
|
+
if not cells:
|
|
445
|
+
parts.append(f"*No answer cell `answer_{qid}` found.*")
|
|
446
|
+
|
|
447
|
+
parts += [
|
|
448
|
+
f"*{NO_ANSWER}*"
|
|
449
|
+
if unanswered(answer_text(nb, cell), (placeholders or {}).get(cell.name))
|
|
450
|
+
else cell_markdown(nb, cell)
|
|
451
|
+
for cell in cells
|
|
452
|
+
]
|
|
453
|
+
|
|
454
|
+
return "\n\n".join(parts) + "\n"
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def build_zip(entries: Mapping[str, bytes]) -> bytes:
|
|
458
|
+
"""A zip of `entries`, built in memory."""
|
|
459
|
+
|
|
460
|
+
buffer = io.BytesIO()
|
|
461
|
+
|
|
462
|
+
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
|
463
|
+
for name, data in entries.items():
|
|
464
|
+
archive.writestr(name, data)
|
|
465
|
+
|
|
466
|
+
return buffer.getvalue()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def panel(lines: Sequence[Line], download: Download | None = None) -> str:
|
|
470
|
+
"""HTML for the export panel: the lines, then the download set apart below a rule.
|
|
471
|
+
|
|
472
|
+
The accent is the worst mark among the lines; indented lines do not count.
|
|
473
|
+
"""
|
|
474
|
+
|
|
475
|
+
marks = {line.mark for line in lines}
|
|
476
|
+
accent = FAIL if Mark.FAIL in marks else WARN if Mark.WARN in marks else PASS
|
|
477
|
+
|
|
478
|
+
if marks <= {Mark.NOTE}:
|
|
479
|
+
accent = NOTE
|
|
480
|
+
|
|
481
|
+
items = "".join(_line(line, LINE_STYLE) for line in lines)
|
|
482
|
+
after = ""
|
|
483
|
+
|
|
484
|
+
if download is not None:
|
|
485
|
+
label = f"{download.filename} — upload this to Gradescope"
|
|
486
|
+
after = (
|
|
487
|
+
f'<div style="{DOWNLOAD_STYLE}">'
|
|
488
|
+
f'<ul style="{LIST_STYLE}">{_line(Line(Mark.DOWNLOAD, label), "margin: 0;")}</ul>'
|
|
489
|
+
f'<div style="{BUTTON_STYLE}">{download.button}</div>'
|
|
490
|
+
f'<div style="{NOTE_STYLE}">{html.escape(download.note)} Export again after further '
|
|
491
|
+
"changes.</div></div>"
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
return (
|
|
495
|
+
f'<div style="{PANEL_STYLE.format(accent=accent, shade=SHADE)}">'
|
|
496
|
+
f'<ul style="{LIST_STYLE}">{items}</ul>{after}</div>'
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _line(line: Line, style: str) -> str:
|
|
501
|
+
"""One list item: the mark, the text, and the indented lines below it."""
|
|
502
|
+
|
|
503
|
+
mark = f'<span style="{MARK_STYLE.format(accent=ACCENTS[line.mark])}">{line.mark}</span>'
|
|
504
|
+
below = "".join(_line(item, SUBITEM_STYLE) for item in line.items)
|
|
505
|
+
sublist = f'<ul style="{SUBLIST_STYLE}">{below}</ul>' if below else ""
|
|
506
|
+
|
|
507
|
+
return f'<li style="{style}">{mark} {html.escape(line.text)}{sublist}</li>'
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
type Summary = tuple[dict[str, tuple[int, int, list[str]]], dict[str, str]]
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _summary(stdout: str) -> Summary | None:
|
|
514
|
+
"""The selfcheck summary: the last stdout line that is a valid one, else `None`.
|
|
515
|
+
|
|
516
|
+
Returns:
|
|
517
|
+
`(passed, total, failed names)` per question, and the reason per unavailable name.
|
|
518
|
+
"""
|
|
519
|
+
|
|
520
|
+
for line in reversed(stdout.splitlines()):
|
|
521
|
+
try:
|
|
522
|
+
data = json.loads(line)
|
|
523
|
+
except ValueError:
|
|
524
|
+
continue
|
|
525
|
+
|
|
526
|
+
match data:
|
|
527
|
+
case {"questions": dict() as entries, "unavailable": dict() as missing}:
|
|
528
|
+
questions = {}
|
|
529
|
+
|
|
530
|
+
for qid, entry in entries.items():
|
|
531
|
+
match entry:
|
|
532
|
+
case {"passed": int() as passed, "total": int() as total, "failed": list()}:
|
|
533
|
+
names = [str(name) for name in entry["failed"]]
|
|
534
|
+
questions[str(qid)] = (passed, total, names)
|
|
535
|
+
case _:
|
|
536
|
+
return None
|
|
537
|
+
|
|
538
|
+
return questions, {str(name): str(reason) for name, reason in missing.items()}
|
|
539
|
+
|
|
540
|
+
return None
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _parse(data: bytes) -> Notebook | None:
|
|
544
|
+
try:
|
|
545
|
+
return parse_notebook(data.decode("utf-8"))
|
|
546
|
+
except (UnicodeDecodeError, SourceError):
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _digest_of(path: Path) -> str | None:
|
|
551
|
+
"""SHA-256 of the file's bytes, or `None` when it cannot be read."""
|
|
552
|
+
|
|
553
|
+
try:
|
|
554
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
555
|
+
except OSError:
|
|
556
|
+
return None
|
mogs/grader/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Gradescope grader: the test bundle, the child process that runs it, and their protocol."""
|