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.
Files changed (49) hide show
  1. mogs/__init__.py +17 -0
  2. mogs/_assertrewrite.py +44 -0
  3. mogs/_env.py +26 -0
  4. mogs/_run.py +111 -0
  5. mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
  6. mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
  7. mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
  8. mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
  9. mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
  10. mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
  11. mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
  12. mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
  13. mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
  14. mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
  15. mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
  16. mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
  17. mogs/assignment.py +172 -0
  18. mogs/build.py +605 -0
  19. mogs/check.py +410 -0
  20. mogs/cli.py +272 -0
  21. mogs/config.py +619 -0
  22. mogs/environment.py +118 -0
  23. mogs/export.py +556 -0
  24. mogs/grader/__init__.py +1 -0
  25. mogs/grader/_process.py +383 -0
  26. mogs/grader/_user.py +7 -0
  27. mogs/grader/bundle.py +320 -0
  28. mogs/grader/child.py +317 -0
  29. mogs/grader/datafiles.py +54 -0
  30. mogs/grader/main.py +132 -0
  31. mogs/grader/protocol.py +175 -0
  32. mogs/grader/results.py +337 -0
  33. mogs/grader/sandbox.py +462 -0
  34. mogs/grader/templates/__init__.py +38 -0
  35. mogs/grader/templates/run_autograder +3 -0
  36. mogs/grader/templates/setup.sh +28 -0
  37. mogs/loader.py +260 -0
  38. mogs/pdf.py +676 -0
  39. mogs/regrade.py +223 -0
  40. mogs/requirements.py +232 -0
  41. mogs/runner.py +281 -0
  42. mogs/scaffold.py +155 -0
  43. mogs/selfcheck.py +173 -0
  44. mogs/source.py +1438 -0
  45. mogs/transform.py +769 -0
  46. mogs-0.7.0.dist-info/METADATA +17 -0
  47. mogs-0.7.0.dist-info/RECORD +49 -0
  48. mogs-0.7.0.dist-info/WHEEL +4 -0
  49. mogs-0.7.0.dist-info/entry_points.txt +3 -0
mogs/build.py ADDED
@@ -0,0 +1,605 @@
1
+ """Build the student notebook and the Gradescope autograder zip, then self-check them.
2
+
3
+ The build writes, next to the source notebook, the layout Otter uses:
4
+
5
+ - `dist/student/<name>.zip`, for students: one `<name>/` folder with the student notebook, its
6
+ public tests in `tests/` and the data files;
7
+ - `dist/autograder/<name>-autograder-<timestamp>.zip` with `setup.sh`, `run_autograder`,
8
+ `bundle.json`, `requirements.txt` and the data files, for Gradescope;
9
+ - `dist/autograder/<notebook>.py`, the solved copy: the student notebook with the solutions
10
+ kept, to upload to Gradescope as a test submission. The public tests, the data files and
11
+ `requirements.txt` sit next to it.
12
+
13
+ Before it writes anything, it grades the solved copy and the student copy with the real
14
+ grader, in a fresh environment with Gradescope's requirements. The solved copy must get full
15
+ marks. The student copy should get none; tests that pass
16
+ on it come back as warnings.
17
+ """
18
+
19
+ import ast
20
+ import re
21
+ import shutil
22
+ import stat
23
+ import subprocess
24
+ import sys
25
+ import tempfile
26
+ import zipfile
27
+ from collections.abc import Iterable, Mapping
28
+ from dataclasses import dataclass
29
+ from datetime import datetime
30
+ from pathlib import Path, PurePosixPath
31
+ from typing import TYPE_CHECKING
32
+
33
+ from mogs import __version__
34
+ from mogs._env import clean_env
35
+ from mogs.config import (
36
+ ASSIGNMENT,
37
+ TOOL,
38
+ Api,
39
+ AssignmentConfig,
40
+ ConfigError,
41
+ api_calls,
42
+ read_config,
43
+ )
44
+ from mogs.environment import grading_python
45
+ from mogs.grader.bundle import GradingBundle, bundle_from_notebook
46
+ from mogs.grader.datafiles import data_files as shared_data_files
47
+ from mogs.grader.results import Results, build_results
48
+ from mogs.grader.templates import run_autograder_script, setup_script
49
+ from mogs.requirements import gradescope_requirements
50
+ from mogs.runner import FailureReason, Outcome
51
+ from mogs.source import (
52
+ Notebook,
53
+ parse_notebook,
54
+ prompt_previews,
55
+ question_id,
56
+ source_warnings,
57
+ validate,
58
+ )
59
+ from mogs.transform import (
60
+ TESTS_FOLDER,
61
+ pinned_requirement,
62
+ public_test_files,
63
+ student_notebook,
64
+ )
65
+
66
+ if TYPE_CHECKING:
67
+ from mogs.grader.sandbox import Graded
68
+
69
+ DIST = "dist"
70
+ # What an `assignment(...)` call looks like in a file that is not valid Python.
71
+ ASSIGNMENT_RE = re.compile(r"\bassignment\s*\(")
72
+ SCRIPTS = ("setup.sh", "run_autograder")
73
+ ZIP_FILES = (*SCRIPTS, "bundle.json", "requirements.txt")
74
+ ZIP_DATE = (1980, 1, 1, 0, 0, 0)
75
+ PORTING_URL = "https://mogs.kristia.de/porting"
76
+ # Otter Assign's own markers. Its solution and `# HIDDEN` markers are left out: mogs uses them
77
+ # too.
78
+ OTTER_RE = re.compile(
79
+ r"(?<![\w#])# (?:ASSIGNMENT CONFIG|(?:BEGIN|END) (?:QUESTION|TESTS|PROMPT|TEST CONFIG))\b"
80
+ )
81
+ # Otter's timestamp in the zip name, e.g. 2026_09_30T12_30_41_890583.
82
+ STAMP = "%Y_%m_%dT%H_%M_%S_%f"
83
+
84
+
85
+ class BuildError(Exception):
86
+ """The assignment cannot be built: no single notebook, invalid source, or a failed check."""
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class QuestionScore:
91
+ """Self-check scores of one question.
92
+
93
+ Attributes:
94
+ id: Question id.
95
+ title: Question title.
96
+ points: Maximum score.
97
+ solution: Score of the solved copy; `None` for a question graded by hand.
98
+ blank: Score of the student copy; `None` for a question graded by hand.
99
+ public: Number of public tests.
100
+ hidden: Number of hidden tests.
101
+ prompts: First line of each prompt cell of a written question, as
102
+ `prompt_previews` gives it.
103
+ """
104
+
105
+ id: str
106
+ title: str
107
+ points: float
108
+ solution: float | None
109
+ blank: float | None
110
+ public: int = 0
111
+ hidden: int = 0
112
+ prompts: tuple[str, ...] = ()
113
+
114
+
115
+ @dataclass(frozen=True, slots=True)
116
+ class BuildResult:
117
+ """What a build wrote and how the self-check went.
118
+
119
+ Attributes:
120
+ student: The zip for students: the student notebook, its public tests and the data.
121
+ zip: The Gradescope autograder zip.
122
+ solved: The solved copy of the student notebook.
123
+ solution: Score and maximum of the solved copy.
124
+ blank: Score and maximum of the student copy.
125
+ warnings: Things the instructor should look at.
126
+ scores: Per-question scores, in notebook order.
127
+ """
128
+
129
+ student: Path
130
+ zip: Path
131
+ solved: Path
132
+ solution: tuple[float, float]
133
+ blank: tuple[float, float]
134
+ warnings: list[str]
135
+ scores: tuple[QuestionScore, ...] = ()
136
+
137
+
138
+ @dataclass(frozen=True, slots=True)
139
+ class Assignment:
140
+ """A source notebook, read and validated.
141
+
142
+ Attributes:
143
+ path: The source notebook.
144
+ src: Its text.
145
+ cfg: Its config.
146
+ nb: Its parsed cells.
147
+ """
148
+
149
+ path: Path
150
+ src: str
151
+ cfg: AssignmentConfig
152
+ nb: Notebook
153
+
154
+
155
+ def require_posix() -> None:
156
+ """Refuse to grade on a platform the sandbox does not support.
157
+
158
+ Raises:
159
+ BuildError: If the platform is not Linux or macOS.
160
+ """
161
+
162
+ if sys.platform not in ("linux", "darwin"):
163
+ raise BuildError("Grading needs Linux or macOS (WSL on Windows).")
164
+
165
+
166
+ def read_assignment(assignment_dir: Path) -> Assignment:
167
+ """Find, read and validate the source notebook in `assignment_dir`.
168
+
169
+ Raises:
170
+ BuildError: If there is no single source notebook, or it is invalid.
171
+ ConfigError: If its config is invalid.
172
+ SourceError: If it cannot be parsed.
173
+ """
174
+
175
+ path = find_notebook(assignment_dir)
176
+ src = path.read_text(encoding="utf-8")
177
+ cfg = read_config(src, path)
178
+ nb = parse_notebook(src)
179
+
180
+ errors = validate(nb, cfg)
181
+ if errors:
182
+ listed = "\n".join("- " + error.replace("\n", "\n ") for error in errors)
183
+ raise BuildError(f"{path} has {len(errors)} problem(s):\n{listed}")
184
+
185
+ return Assignment(path, src, cfg, nb)
186
+
187
+
188
+ def find_notebook(assignment_dir: Path) -> Path:
189
+ """The one `*.py` file in `assignment_dir` that calls `assignment(...)`.
190
+
191
+ Raises:
192
+ BuildError: If `assignment_dir` is missing or not a folder, or it holds no such file
193
+ or several.
194
+ """
195
+
196
+ if not assignment_dir.exists():
197
+ raise BuildError(f"{assignment_dir} does not exist.")
198
+
199
+ if not assignment_dir.is_dir():
200
+ raise BuildError(f"{assignment_dir} is not a folder.")
201
+
202
+ candidates = [
203
+ path
204
+ for path in sorted(assignment_dir.glob("*.py"))
205
+ if path.is_file() and _is_notebook(path.read_text(encoding="utf-8", errors="replace"))
206
+ ]
207
+
208
+ match candidates:
209
+ case [path]:
210
+ return path
211
+ case []:
212
+ otter = _otter_hint(
213
+ [*sorted(assignment_dir.glob("*.py")), *sorted(assignment_dir.glob("*.ipynb"))]
214
+ )
215
+ raise BuildError(
216
+ f"No notebook in {assignment_dir} calls `mogs.assignment(...)`. "
217
+ + (
218
+ otter
219
+ or "Add a cell with that call, or start a new assignment with `mogs init`."
220
+ )
221
+ )
222
+ case _:
223
+ names = "\n".join(f" {path.name}" for path in candidates)
224
+ raise BuildError(
225
+ f"Several notebooks in {assignment_dir} call `mogs.assignment(...)`; keep "
226
+ f"exactly one:\n{names}"
227
+ )
228
+
229
+
230
+ def source_notebook(path: Path) -> Path:
231
+ """The source notebook at `path`, a notebook file or the assignment folder holding it.
232
+
233
+ Raises:
234
+ BuildError: If `path` is missing, is a file that does not call `assignment(...)`, or is
235
+ a folder that `find_notebook` rejects.
236
+ """
237
+
238
+ if not path.is_file():
239
+ return find_notebook(path)
240
+
241
+ if not _is_notebook(path.read_text(encoding="utf-8", errors="replace")):
242
+ raise BuildError(
243
+ f"{path} does not call `mogs.assignment(...)`. "
244
+ + (_otter_hint([path]) or "Pass the source notebook or the assignment folder.")
245
+ )
246
+
247
+ return path
248
+
249
+
250
+ def _otter_hint(paths: Iterable[Path]) -> str | None:
251
+ """Where the first of `paths` with an Otter Assign marker has it, and where to read on.
252
+
253
+ Returns:
254
+ The hint, or `None` when no file has such a marker.
255
+ """
256
+
257
+ for path in paths:
258
+ if not path.is_file():
259
+ continue
260
+
261
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
262
+ for number, line in enumerate(lines, start=1):
263
+ found = OTTER_RE.search(line)
264
+ if found:
265
+ return (
266
+ f"{path}:{number} has `{found.group()}`, which is otter-assign syntax. "
267
+ f"Port the notebook to mogs by hand: {PORTING_URL}"
268
+ )
269
+
270
+ return None
271
+
272
+
273
+ def _is_notebook(text: str) -> bool:
274
+ """A source notebook: it calls `assignment(...)`, under any name its imports give it.
275
+
276
+ A file that is not valid Python counts when it looks like it calls `assignment`, so that
277
+ reading it reports the syntax error.
278
+ """
279
+
280
+ try:
281
+ tree = ast.parse(text)
282
+ except SyntaxError:
283
+ return bool(ASSIGNMENT_RE.search(text))
284
+
285
+ return bool(api_calls(tree, tree, Api.ASSIGNMENT))
286
+
287
+
288
+ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildResult:
289
+ """Build and self-check the assignment in `assignment_dir`.
290
+
291
+ The output is written in full to a temporary folder first. Only when every step succeeds
292
+ does it replace `dist/student/` and `dist/autograder/`, so only the newest zip is kept. A
293
+ failed build removes them.
294
+
295
+ Args:
296
+ assignment_dir: Folder with the source notebook and its data files.
297
+ tool_requirement: mogs requirement for Gradescope's `requirements.txt`.
298
+ Defaults to this exact version. Student notebooks always pin this version.
299
+
300
+ Returns:
301
+ The artifact paths, self-check scores and warnings.
302
+
303
+ Raises:
304
+ BuildError: If the platform is not Linux or macOS, the notebook is missing or invalid,
305
+ `marimo check` fails on the student or solved copy, or the solved copy does not get
306
+ full marks.
307
+ ConfigError: If the config, a data file or a header edit is invalid.
308
+ SourceError: If the notebook cannot be parsed or transformed.
309
+ RequirementsError: If the dependencies cannot be pinned or installed.
310
+ """
311
+
312
+ try:
313
+ return _build(assignment_dir, tool_requirement)
314
+ except Exception:
315
+ for part in ("student", "autograder"):
316
+ shutil.rmtree(assignment_dir / DIST / part, ignore_errors=True)
317
+
318
+ raise
319
+
320
+
321
+ def _build(assignment_dir: Path, tool_requirement: str | None) -> BuildResult:
322
+ """`build` without the cleanup of a failed build."""
323
+
324
+ require_posix()
325
+ assignment = read_assignment(assignment_dir)
326
+ src, cfg, nb = assignment.src, assignment.cfg, assignment.nb
327
+
328
+ data = data_files(assignment_dir, cfg)
329
+ student = student_notebook(src, nb, cfg, pinned_requirement(cfg))
330
+ solved = student_notebook(src, nb, cfg, pinned_requirement(cfg), solutions=True)
331
+ bundle = bundle_from_notebook(nb, cfg)
332
+ tests = public_test_files(nb)
333
+ requirement = tool_requirement or f"{TOOL}=={__version__}"
334
+ requirements, warnings = gradescope_requirements(src, cfg, requirement)
335
+ warnings = source_warnings(nb) + warnings
336
+ entries = {
337
+ "setup.sh": setup_script(cfg).encode(),
338
+ "run_autograder": run_autograder_script().encode(),
339
+ "bundle.json": bundle.to_json().encode(),
340
+ "requirements.txt": requirements.encode(),
341
+ }
342
+ entries |= {str(rel): source.read_bytes() for rel, source in data.items()}
343
+
344
+ dist = assignment_dir / DIST
345
+ zip_name = f"{cfg.name}-autograder-{datetime.now().strftime(STAMP)}.zip"
346
+
347
+ with tempfile.TemporaryDirectory(prefix="mogs-build-") as folder:
348
+ stage = Path(folder)
349
+
350
+ # Self-check, in an environment with what Gradescope installs.
351
+ python = str(grading_python(requirements, stage / "env", cfg.python))
352
+ check = stage / "check"
353
+ check.mkdir()
354
+ student_path = check / "student" / cfg.notebook
355
+ solved_path = check / "solved" / cfg.notebook
356
+ for notebook, text in ((student_path, student), (solved_path, solved)):
357
+ notebook.parent.mkdir()
358
+ notebook.write_text(text, encoding="utf-8")
359
+
360
+ warnings += marimo_check(student_path, "student notebook", python)
361
+ warnings += marimo_check(solved_path, "solved notebook", python)
362
+
363
+ # The solved copy, not the source: it is what the instructor's test upload sends.
364
+ solution = _self_grade(bundle, solved_path, check / "solution", assignment_dir, python)
365
+ failed = [outcome for outcome in solution.outcomes.values() if not outcome.passed]
366
+ if failed:
367
+ raise BuildError(
368
+ f"The solved copy of {cfg.notebook} does not get full marks. Failing tests:\n"
369
+ + "\n".join(failure_report(failed))
370
+ )
371
+
372
+ blank = _self_grade(bundle, student_path, check / "blank", assignment_dir, python)
373
+ warnings += free_points_warnings(blank.outcomes, cfg)
374
+
375
+ # Output, written in full before it replaces the old one.
376
+ out = stage / DIST
377
+ (out / "student").mkdir(parents=True)
378
+ files = {str(rel): source.read_bytes() for rel, source in data.items()}
379
+ files |= {str(rel): text.encode() for rel, text in tests.items()}
380
+ student_files = {cfg.notebook: student.encode(), **files}
381
+ write_zip(
382
+ out / "student" / f"{cfg.name}.zip",
383
+ {f"{cfg.name}/{rel}": content for rel, content in student_files.items()},
384
+ )
385
+
386
+ autograder = out / "autograder"
387
+ for rel, content in {cfg.notebook: solved.encode(), **files}.items():
388
+ (autograder / rel).parent.mkdir(parents=True, exist_ok=True)
389
+ (autograder / rel).write_bytes(content)
390
+
391
+ (autograder / "requirements.txt").write_text(requirements, encoding="utf-8")
392
+ write_zip(autograder / zip_name, entries)
393
+
394
+ for part in ("student", "autograder"):
395
+ if (dist / part).exists():
396
+ shutil.rmtree(dist / part)
397
+ dist.mkdir(exist_ok=True)
398
+ shutil.move(out / part, dist / part)
399
+
400
+ return BuildResult(
401
+ student=dist / "student" / f"{cfg.name}.zip",
402
+ zip=dist / "autograder" / zip_name,
403
+ solved=dist / "autograder" / cfg.notebook,
404
+ solution=total(solution.results),
405
+ blank=total(blank.results),
406
+ warnings=warnings,
407
+ scores=_scores(cfg, nb, solution.results, blank.results),
408
+ )
409
+
410
+
411
+ def data_files(assignment_dir: Path, cfg: AssignmentConfig) -> dict[PurePosixPath, Path]:
412
+ """The data files to ship, by path relative to the notebook, with folders expanded.
413
+
414
+ Uses the sandbox's own checks and junk filter (`grader.datafiles`).
415
+
416
+ Raises:
417
+ ConfigError: If an entry of `files` is missing, is not inside the notebook's folder, or
418
+ would replace the notebook, its public tests folder, a file of the autograder zip
419
+ or the grader's copy of the submission.
420
+ """
421
+
422
+ # Case-insensitive, as the file systems of macOS and Windows are.
423
+ reserved = {name.casefold() for name in (*ZIP_FILES, cfg.notebook, TESTS_FOLDER)}
424
+
425
+ for name in cfg.files:
426
+ first = PurePosixPath(name).parts[:1]
427
+ if first and first[0].casefold() in reserved:
428
+ raise ConfigError(
429
+ f"{ASSIGNMENT} `files` entry {name!r} would replace `{first[0]}` in the build "
430
+ "output."
431
+ )
432
+
433
+ try:
434
+ return shared_data_files(assignment_dir, cfg.files)
435
+ except ValueError as error:
436
+ raise ConfigError(f"{ASSIGNMENT} `files`: {error}.") from error
437
+
438
+
439
+ def write_zip(path: Path, entries: Mapping[str, bytes]) -> None:
440
+ """Write a reproducible zip: sorted entries, fixed timestamps, executable scripts."""
441
+
442
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive:
443
+ for name in sorted(entries):
444
+ info = zipfile.ZipInfo(name, date_time=ZIP_DATE)
445
+ info.compress_type = zipfile.ZIP_DEFLATED
446
+ info.create_system = 3 # Unix, so tools read the mode bits below.
447
+ mode = 0o755 if name in SCRIPTS else 0o644
448
+ info.external_attr = (stat.S_IFREG | mode) << 16
449
+ archive.writestr(info, entries[name])
450
+
451
+
452
+ # Self-check
453
+
454
+
455
+ @dataclass(frozen=True, slots=True)
456
+ class _Graded:
457
+ outcomes: dict[str, Outcome]
458
+ results: Results
459
+
460
+
461
+ def _self_grade(
462
+ bundle: GradingBundle, notebook: Path, workdir: Path, assignment_dir: Path, python: str
463
+ ) -> _Graded:
464
+ """Grade `notebook` on `python` the way Gradescope would, as the current user."""
465
+
466
+ outcomes = grade_locally(bundle, notebook, workdir, assignment_dir, python).outcomes
467
+ return _Graded(outcomes, build_results(bundle, outcomes, []))
468
+
469
+
470
+ def grade_locally(
471
+ bundle: GradingBundle, notebook: Path, workdir: Path, assignment_dir: Path, python: str
472
+ ) -> "Graded":
473
+ """Grade `notebook` on `python` with the real grader, as the current user.
474
+
475
+ Args:
476
+ bundle: The grading bundle.
477
+ notebook: The notebook to grade.
478
+ workdir: Folder for the grader's phase folders; must not exist.
479
+ assignment_dir: Folder the data files are relative to.
480
+ python: Interpreter with the grading requirements.
481
+
482
+ Returns:
483
+ One outcome per test of the bundle, and why the notebook did not load, if it did not.
484
+ """
485
+
486
+ # Imported here: the sandbox needs POSIX, and the CLI must start on any platform.
487
+ from mogs.grader.sandbox import grade
488
+
489
+ workdir.mkdir()
490
+
491
+ return grade(
492
+ bundle,
493
+ notebook,
494
+ workdir,
495
+ user=None,
496
+ files_root=assignment_dir,
497
+ files=bundle.config.files,
498
+ python=python,
499
+ )
500
+
501
+
502
+ def failure_report(failed: Iterable[Outcome], *, count_load_failures: bool = True) -> list[str]:
503
+ """One line per distinct failure message, naming the tests that share it.
504
+
505
+ Args:
506
+ failed: The failed outcomes.
507
+ count_load_failures: Count the tests that failed to load and name their questions
508
+ instead of the tests, since a failing setup cell fails every test.
509
+ """
510
+
511
+ by_message: dict[tuple[str, bool], list[str]] = {}
512
+ for outcome in failed:
513
+ counted = count_load_failures and outcome.reason is FailureReason.LOAD_FAILED
514
+ by_message.setdefault((outcome.message.strip(), counted), []).append(outcome.name)
515
+
516
+ return [
517
+ f"- {_failed_tests(names, load_failed)}: " + message.replace("\n", "\n ")
518
+ for (message, load_failed), names in by_message.items()
519
+ ]
520
+
521
+
522
+ def _failed_tests(names: list[str], load_failed: bool) -> str:
523
+ if not load_failed:
524
+ return ", ".join(names)
525
+
526
+ questions = ", ".join(dict.fromkeys(question_id(name) for name in names))
527
+ tests = "1 test" if len(names) == 1 else f"{len(names)} tests"
528
+ return f"{tests} of {questions}"
529
+
530
+
531
+ def free_points_warnings(blank: Mapping[str, Outcome], cfg: AssignmentConfig) -> list[str]:
532
+ """A warning naming the tests that pass on the blank notebook, in questions worth points."""
533
+
534
+ passing = [
535
+ outcome.name
536
+ for outcome in blank.values()
537
+ if outcome.passed and cfg.questions[question_id(outcome.name)].points > 0
538
+ ]
539
+
540
+ if not passing:
541
+ return []
542
+
543
+ return [
544
+ "These tests pass on the blank student notebook, so they give points for no work: "
545
+ + ", ".join(passing)
546
+ ]
547
+
548
+
549
+ def marimo_check(notebook: Path, label: str, python: str) -> list[str]:
550
+ """Run `marimo check` with `python` on `notebook`, called `label` in messages.
551
+
552
+ Returns:
553
+ Its output as a warning, if it printed anything.
554
+
555
+ Raises:
556
+ BuildError: If it reports errors.
557
+ """
558
+
559
+ result = subprocess.run(
560
+ [python, "-m", "marimo", "check", notebook.name],
561
+ capture_output=True,
562
+ text=True,
563
+ check=False,
564
+ cwd=notebook.parent,
565
+ env=clean_env(),
566
+ )
567
+ output = (result.stdout + result.stderr).strip()
568
+
569
+ if result.returncode != 0:
570
+ raise BuildError(f"`marimo check` fails on the {label}:\n{output}")
571
+
572
+ return [f"`marimo check` on the {label}:\n{output}"] if output else []
573
+
574
+
575
+ def total(results: Results) -> tuple[float, float]:
576
+ """Score and maximum, summed over the rows of `results`."""
577
+
578
+ rows = results["tests"]
579
+ return sum(row["score"] for row in rows), sum(row["max_score"] for row in rows)
580
+
581
+
582
+ def _scores(
583
+ cfg: AssignmentConfig, nb: Notebook, solution: Results, blank: Results
584
+ ) -> tuple[QuestionScore, ...]:
585
+ ours = {row.get("number"): row["score"] for row in solution["tests"]}
586
+ theirs = {row.get("number"): row["score"] for row in blank["tests"]}
587
+ tests = nb.tests_by_question()
588
+ scores = []
589
+
590
+ for q in cfg.questions.values():
591
+ public, hidden = tests.get(q.id, ([], []))
592
+ scores.append(
593
+ QuestionScore(
594
+ q.id,
595
+ q.title,
596
+ q.points,
597
+ ours.get(q.id),
598
+ theirs.get(q.id),
599
+ len(public),
600
+ len(hidden),
601
+ prompt_previews(nb, q.id) if q.manual else (),
602
+ )
603
+ )
604
+
605
+ return tuple(scores)