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/pdf.py ADDED
@@ -0,0 +1,676 @@
1
+ r"""PDF of the written answers, for questions graded by hand.
2
+
3
+ Typst renders the PDF in-process, from the `typst` package of the `pdf` extra. Per question
4
+ the PDF has a heading, then the `prompt_<qid>` and `answer_<qid>` cells in notebook order, so
5
+ each answer follows its own prompt. A page break separates questions. A cell that is just
6
+ `mo.md("...")` shows as Markdown with LaTeX math (through the vendored Typst packages cmarker
7
+ and mitex); any other cell shows its source. As in marimo, `\(...\)` and `\[...\]` are math,
8
+ and a paragraph that is just an `align`, `equation` or `gather` environment, starred or not, is
9
+ display math too.
10
+
11
+ The cell text reaches Typst as data in `sys.inputs`, never as Typst source. Typst cannot
12
+ recover from an error inside a document, so a cell that breaks the document is rendered again
13
+ with less: first with each failing formula shown as LaTeX source, then as plain text. A note
14
+ under the cell says so.
15
+ """
16
+
17
+ import json
18
+ import re
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from copy import replace
21
+ from dataclasses import dataclass
22
+ from enum import StrEnum
23
+ from functools import cache
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING
26
+
27
+ from mogs.grader.results import code_block
28
+ from mogs.runner import exception_summary
29
+ from mogs.source import (
30
+ Cell,
31
+ CellKind,
32
+ Notebook,
33
+ SourceError,
34
+ answer_text,
35
+ cell_source,
36
+ parse_notebook,
37
+ unanswered,
38
+ )
39
+
40
+ if TYPE_CHECKING:
41
+ import typst
42
+
43
+ # Holds `preview/<name>/<version>/` for each vendored Typst package.
44
+ PACKAGES = Path(__file__).parent / "_typst"
45
+
46
+ # mitex evaluates the Typst it converts LaTeX to, so a formula that could run Typst code shows
47
+ # as source: `\iftypst` passes Typst through, `\hspace`, `\vspace` and `\raisebox` evaluate
48
+ # their first argument (only a plain length is let through), and a `#` left in the converted
49
+ # formula starts code. mitex itself writes escaped `\#` and the calls in `ALIASES` (from
50
+ # `\text`, `\textbf`, `\textcolor`, `\color`, `$...$` inside `\text`, ...), which are dropped
51
+ # before the check. Other calls it writes (`\section`, `\footnote`, `\ref`, ...) stay
52
+ # flagged, so those formulas show as source.
53
+ ALIASES = (
54
+ "textmath|textbf|textit|textrm|texttt|textsf|textup|textmd|textnormal|emph|colortext"
55
+ "|mitexcolor|mitexcolorbox|math\\\\.equation"
56
+ )
57
+ PREAMBLE = r"""
58
+ #import "@preview/cmarker:0.1.10"
59
+ #import "@preview/mitex:0.2.7": mitex, mitex-convert
60
+
61
+ #let aliases = "#(ALIASES)\\b"
62
+ #let spacing = "\\\\(hspace|vspace|raisebox)\\*?"
63
+ #let length = regex("^\\s*-?(\\d+(\\.\\d*)?|\\.\\d+)\\s*(pt|mm|cm|in|em)\\s*$")
64
+
65
+ #let runs-code(src) = {
66
+ if src.contains("iftypst") { return true }
67
+
68
+ let commands = src.matches(regex(spacing))
69
+ let lengths = src
70
+ .matches(regex(spacing + "\\s*\\{([^{}]*)\\}"))
71
+ .filter(m => m.captures.at(1).match(length) != none)
72
+ if commands.len() != lengths.len() { return true }
73
+
74
+ mitex-convert(src).replace(regex("\\\\."), "").replace(regex(aliases), "").contains("#")
75
+ }
76
+
77
+ #let safe-math(src, block: false) = {
78
+ // mitex lacks `gather*`; its `gather` is unnumbered anyway. `raw` shows the original.
79
+ let math = src
80
+ .replace(regex("\\\\(begin|end)\\{gather\\*\\}"), m => "\\" + m.captures.at(0) + "{gather}")
81
+ if runs-code(math) { raw(src, block: block) } else { mitex(math, block: block) }
82
+ }
83
+ """.replace("ALIASES", ALIASES)
84
+
85
+ # The document. `sys.inputs.doc` is JSON: a list of questions, each `{title, parts}`, where a
86
+ # part is `{text, role, style, note}`. Images are not loaded: they show as their
87
+ # alt text.
88
+ TEMPLATE = (
89
+ PREAMBLE
90
+ + """\
91
+ #set page(paper: "us-letter", margin: 2cm)
92
+
93
+ // Typst's embedded fonts; system fonts only fill in glyphs these lack, such as CJK.
94
+ #set text(font: "Libertinus Serif", size: 11pt)
95
+ #show math.equation: set text(font: "New Computer Modern Math")
96
+ #show raw: set text(font: "DejaVu Sans Mono")
97
+
98
+ #let image-stub(source, alt: none, ..args) = {
99
+ let label = if alt == none or alt == "" { "no description" } else { alt }
100
+ emph("[Image: " + label + "]")
101
+ }
102
+
103
+ // A link to an anchor in the answer shows just its text: a missing label would stop Typst.
104
+ #let link-stub(dest, body) = if type(dest) == label { body } else { link(dest, body) }
105
+
106
+ #let markdown(text) = cmarker.render(
107
+ text,
108
+ math: safe-math,
109
+ h1-level: 2,
110
+ raw-typst: false,
111
+ set-document-title: false,
112
+ scope: (image: image-stub, link: link-stub),
113
+ )
114
+
115
+ #let show-part(part) = block(width: 100%, {
116
+ if part.style == "markdown" {
117
+ markdown(part.text)
118
+ } else if part.style == "note" {
119
+ text(fill: gray, emph(part.text))
120
+ } else {
121
+ raw(part.text, block: true)
122
+ }
123
+ if part.note != none { block(above: 0.8em, text(size: 8pt, fill: gray, part.note)) }
124
+ })
125
+
126
+ #for (index, question) in json(bytes(sys.inputs.doc)).enumerate() {
127
+ if index > 0 { pagebreak() }
128
+ heading(level: 1, question.title)
129
+
130
+ let parts = question.parts
131
+ for (at, part) in parts.enumerate() {
132
+ show-part(part)
133
+
134
+ // A rule between a prompt and the answer after it.
135
+ let next = parts.at(at + 1, default: none)
136
+ if part.role == "prompt" and next != none and next.role == "answer" {
137
+ line(length: 100%, stroke: 0.5pt + gray)
138
+ }
139
+ }
140
+ }
141
+ """
142
+ )
143
+
144
+ # One formula alone, as cmarker hands it to mitex.
145
+ FORMULA = PREAMBLE + '#safe-math(sys.inputs.formula, block: sys.inputs.display == "true")\n'
146
+
147
+ SOURCE_NOTE = "Some math in this cell could not be rendered and is shown as LaTeX source."
148
+ PLAIN_NOTE = "This cell could not be rendered and is shown as plain text."
149
+ NO_ANSWER = "No answer."
150
+
151
+ # A paragraph that marimo shows as display math without dollar signs.
152
+ ENVIRONMENT = re.compile(r"\\begin\{((?:align|equation|gather)\*?)\}.*\\end\{\1\}", re.DOTALL)
153
+ SPACES = re.compile(r"[ \t]*")
154
+ FENCE = re.compile(r" {0,3}(`{3,}|~{3,})")
155
+ BLANK_LINE = re.compile(r"\n[ \t]*\n")
156
+
157
+ type Status = Callable[[str], None]
158
+
159
+
160
+ class PdfUnavailable(Exception):
161
+ """No PDF could be made. The message says why and what to try."""
162
+
163
+
164
+ class Role(StrEnum):
165
+ """What a part of the PDF is."""
166
+
167
+ PROMPT = "prompt"
168
+ ANSWER = "answer"
169
+
170
+
171
+ class Style(StrEnum):
172
+ """How a part of the PDF is rendered."""
173
+
174
+ MARKDOWN = "markdown"
175
+ PLAIN = "plain"
176
+ NOTE = "note"
177
+
178
+
179
+ @dataclass(frozen=True, slots=True)
180
+ class Part:
181
+ """One prompt or answer cell, as it goes into the PDF.
182
+
183
+ Attributes:
184
+ text: Markdown, or plain text for `Style.PLAIN` and `Style.NOTE`.
185
+ role: Whether it is a prompt or an answer.
186
+ style: How `text` is rendered.
187
+ note: A small note under the part, or `None`.
188
+ """
189
+
190
+ text: str
191
+ role: Role
192
+ style: Style = Style.MARKDOWN
193
+ note: str | None = None
194
+
195
+
196
+ @dataclass(frozen=True, slots=True)
197
+ class Question:
198
+ """One question's page of the PDF.
199
+
200
+ Attributes:
201
+ title: The heading.
202
+ parts: The prompt and answer cells in notebook order, or a note that there is no
203
+ answer cell.
204
+ """
205
+
206
+ title: str
207
+ parts: tuple[Part, ...]
208
+
209
+
210
+ @dataclass(frozen=True, slots=True)
211
+ class Formula:
212
+ r"""A `$...$`, `$$...$$`, `\(...\)` or `\[...\]` formula in Markdown, or a bare environment.
213
+
214
+ Attributes:
215
+ start: Offset of the opening delimiter or `\begin`.
216
+ end: Offset just past the closing delimiter or `\end{...}`.
217
+ source: The LaTeX between the delimiters, or the whole environment.
218
+ display: Whether it is display math.
219
+ environment: Whether it is a bare environment, which Typst gets inside `$$`.
220
+ bracket: Whether it is written `\(...\)` or `\[...\]`, which Typst gets inside `$` or
221
+ `$$` instead.
222
+ """
223
+
224
+ start: int
225
+ end: int
226
+ source: str
227
+ display: bool
228
+ environment: bool = False
229
+ bracket: bool = False
230
+
231
+
232
+ def render_manual_pdf(
233
+ notebook: Path,
234
+ qids: Sequence[str],
235
+ titles: Mapping[str, str],
236
+ out: Path,
237
+ *,
238
+ placeholders: Mapping[str, str] | None = None,
239
+ status: Status | None = None,
240
+ ) -> Path:
241
+ """Render the prompts and answers of `qids` in `notebook` to a PDF at `out`.
242
+
243
+ Nothing is written besides `out`.
244
+
245
+ Args:
246
+ notebook: The student's notebook file.
247
+ qids: Questions to include, in order.
248
+ titles: Heading per question id; the id itself when absent.
249
+ out: Where to write the PDF.
250
+ placeholders: The text each answer cell starts with, by cell name. An answer still
251
+ equal to it, or blank, shows as "No answer."
252
+ status: Called with a short message before slow steps.
253
+
254
+ Returns:
255
+ `out`.
256
+
257
+ Raises:
258
+ PdfUnavailable: If `typst` is not installed, the notebook cannot be read, `out`
259
+ cannot be written, or Typst fails even on the plain-text document.
260
+ """
261
+
262
+ try:
263
+ import typst # noqa: F401 (only checks that the pdf extra is installed)
264
+ except ImportError as exc:
265
+ raise PdfUnavailable(
266
+ "the PDF tool is not installed (typst). Add "
267
+ '"mogs[pdf]" to the notebook\'s dependencies, or run '
268
+ '`pip install "mogs[pdf]"`'
269
+ ) from exc
270
+
271
+ try:
272
+ nb = parse_notebook(notebook.read_text(encoding="utf-8"))
273
+ except (OSError, UnicodeDecodeError, SourceError) as exc:
274
+ raise PdfUnavailable(f"the notebook cannot be read ({exc})") from exc
275
+
276
+ (status or quiet)("Creating the PDF of your written answers…")
277
+ questions = [manual_question(nb, qid, titles.get(qid, qid), placeholders or {}) for qid in qids]
278
+
279
+ # Any error left after the fallbacks is unexpected; the export then falls back to Markdown.
280
+ try:
281
+ data = _render(questions)
282
+ except Exception as exc:
283
+ raise PdfUnavailable(f"Typst failed ({exception_summary(exc)})") from exc
284
+
285
+ try:
286
+ out.write_bytes(data)
287
+ except OSError as exc:
288
+ raise PdfUnavailable(f"writing the PDF failed ({exception_summary(exc)})") from exc
289
+
290
+ return out
291
+
292
+
293
+ def _render(questions: list[Question]) -> bytes:
294
+ """The PDF of `questions`; parts that break the document are rendered with less."""
295
+
296
+ import typst
297
+
298
+ try:
299
+ return _document(questions)
300
+ except typst.TypstError:
301
+ pass
302
+
303
+ rescued = [_each_part(question, _rescue) for question in questions]
304
+
305
+ # Cells can also break the document only together, as with two headings of the same name
306
+ # and a link to them.
307
+ try:
308
+ return _document(rescued)
309
+ except typst.TypstError:
310
+ return _document([_each_part(question, _as_plain) for question in questions])
311
+
312
+
313
+ def _each_part(question: Question, change: Callable[[Part], Part]) -> Question:
314
+ return replace(question, parts=tuple(change(part) for part in question.parts))
315
+
316
+
317
+ def manual_question(
318
+ nb: Notebook, qid: str, title: str, placeholders: Mapping[str, str] | None = None
319
+ ) -> Question:
320
+ """A question's prompt and answer cells in notebook order; a note when it has no answer.
321
+
322
+ Each answer follows the prompts just before it in the notebook. A notebook built by an
323
+ older release names all prompts before the first answer, and shows them the same way.
324
+ An answer cell that is blank or still its text in `placeholders` shows as "No answer."
325
+ """
326
+
327
+ def part(cell: Cell, role: Role) -> Part:
328
+ match role:
329
+ case Role.ANSWER if unanswered(
330
+ answer_text(nb, cell), (placeholders or {}).get(cell.name)
331
+ ):
332
+ return Part(NO_ANSWER, role, Style.NOTE)
333
+ case _:
334
+ return Part(cell_markdown(nb, cell), role)
335
+
336
+ prompts = [(cell, Role.PROMPT) for cell in _plain(nb.prompt_cells(qid))]
337
+ answers = [(cell, Role.ANSWER) for cell in _plain(nb.answer_cells(qid))]
338
+ parts = tuple(
339
+ part(cell, role) for cell, role in sorted(prompts + answers, key=lambda pair: pair[0].start)
340
+ )
341
+
342
+ if not answers:
343
+ parts += (Part(f"*No answer cell `answer_{qid}` found.*", Role.ANSWER),)
344
+
345
+ match parts:
346
+ case (Part(role=Role.PROMPT, style=Style.MARKDOWN) as first, *rest):
347
+ parts = (replace(first, text=without_title_heading(first.text, title)), *rest)
348
+
349
+ return Question(title, parts)
350
+
351
+
352
+ def without_title_heading(text: str, title: str) -> str:
353
+ """`text` without a leading Markdown heading whose words `title` already has.
354
+
355
+ `## Derive the slope` goes under the title `Question 4: Derive the slope`; `## Question 4:
356
+ Derive the slope` stays under the title `Question 4`, since it says more.
357
+ """
358
+
359
+ match = re.match(r"\s*#{1,6}[ \t]+(.+?)[ \t#]*(?:\n|$)", text)
360
+
361
+ if match is None or _words(match.group(1)) not in _words(title):
362
+ return text
363
+
364
+ return text[match.end() :].lstrip("\n")
365
+
366
+
367
+ def _words(text: str) -> str:
368
+ """The words and symbols of `text` in lower case, spaced: `x + y.` → ` x + y `.
369
+
370
+ Sentence punctuation is dropped, so `Question 4:` matches `Question 4`; other symbols, such
371
+ as `+` and `-` in math, are kept.
372
+ """
373
+
374
+ return f" {' '.join(re.findall(r'\w+|[^\w\s.,:;!?]', text.casefold()))} "
375
+
376
+
377
+ def cell_markdown(nb: Notebook, cell: Cell) -> str:
378
+ """The Markdown of a cell that is just `mo.md("...")`; else its source as a code block."""
379
+
380
+ match answer_text(nb, cell):
381
+ case None:
382
+ return code_block(cell_source(nb, cell).rstrip())
383
+ case text:
384
+ return text
385
+
386
+
387
+ def find_formulas(text: str) -> list[Formula]:
388
+ r"""The `$...$`, `$$...$$`, `\(...\)` and `\[...\]` formulas in Markdown, in order.
389
+
390
+ Code spans, fenced code blocks and `\$` are skipped. A formula does not span a blank
391
+ line; a delimiter without a partner is text. A paragraph that is just an `align`,
392
+ `equation` or `gather` environment, starred or not, is a display formula, as in marimo.
393
+ """
394
+
395
+ formulas = []
396
+
397
+ for start, end in _prose(text):
398
+ index = start
399
+
400
+ while index < end:
401
+ match text[index]:
402
+ case "\\" if environment := _environment(text, start, end, index):
403
+ formulas.append(environment)
404
+ index = environment.end
405
+ case "\\" if text.startswith(("\\(", "\\["), index):
406
+ closing = "\\)" if text[index + 1] == "(" else "\\]"
407
+ close = _closing(text, index + 2, end, closing)
408
+
409
+ if close is None:
410
+ index += 2
411
+ continue
412
+
413
+ source = text[index + 2 : close]
414
+ display = closing == "\\]"
415
+ formulas.append(Formula(index, close + 2, source, display, bracket=True))
416
+ index = close + 2
417
+ case "\\":
418
+ index += 2
419
+ case "`":
420
+ run = len(text[index:end]) - len(text[index:end].lstrip("`"))
421
+ blank = BLANK_LINE.search(text, index, end)
422
+ limit = blank.start() if blank else end
423
+ close = re.compile(rf"(?<!`)`{{{run}}}(?!`)").search(text, index + run, limit)
424
+ index = close.end() if close else index + run
425
+ case "$":
426
+ width = 2 if text.startswith("$$", index) else 1
427
+ close = _closing(text, index + width, end, "$" * width)
428
+
429
+ if close is None:
430
+ index += width
431
+ continue
432
+
433
+ source = text[index + width : close]
434
+ formulas.append(Formula(index, close + width, source, width == 2))
435
+ index = close + width
436
+ case _:
437
+ index += 1
438
+
439
+ return formulas
440
+
441
+
442
+ def _environment(text: str, start: int, end: int, index: int) -> Formula | None:
443
+ """The bare environment whose paragraph starts at `index`, if there is one.
444
+
445
+ `start` and `end` bound the run of prose that holds `index`.
446
+ """
447
+
448
+ if not text.startswith("\\begin{", index) or not _paragraph_starts(text, start, index):
449
+ return None
450
+
451
+ blank = BLANK_LINE.search(text, index, end)
452
+ paragraph = text[index : blank.start() if blank else end].rstrip()
453
+ if not ENVIRONMENT.fullmatch(paragraph):
454
+ return None
455
+
456
+ return Formula(index, index + len(paragraph), paragraph, display=True, environment=True)
457
+
458
+
459
+ def _paragraph_starts(text: str, start: int, index: int) -> bool:
460
+ """Whether a paragraph starts at `index`: the prose start, or after a blank line.
461
+
462
+ Only the line before `index` is read.
463
+ """
464
+
465
+ if index == start:
466
+ return True
467
+
468
+ if text[index - 1] != "\n":
469
+ return False
470
+
471
+ line_start = max(text.rfind("\n", start, index - 1) + 1, start)
472
+
473
+ return SPACES.fullmatch(text, line_start, index - 1) is not None
474
+
475
+
476
+ def _delimited(text: str) -> str:
477
+ r"""`text` with its formulas in dollar signs, so cmarker hands them to mitex.
478
+
479
+ A bare environment goes inside `$$`; `\(...\)` and `\[...\]` become `$...$` and `$$...$$`.
480
+ """
481
+
482
+ for formula in reversed(find_formulas(text)):
483
+ before, after = text[: formula.start], text[formula.end :]
484
+
485
+ if formula.environment:
486
+ text = f"{before}$$\n{formula.source}\n$$\n{after}"
487
+ elif formula.bracket:
488
+ dollars = "$$" if formula.display else "$"
489
+ text = f"{before}{dollars}{formula.source}{dollars}{after}"
490
+
491
+ return text
492
+
493
+
494
+ def _prose(text: str) -> list[tuple[int, int]]:
495
+ """Offsets of the runs of lines outside fenced code blocks."""
496
+
497
+ runs = []
498
+ fence = None
499
+ start = 0
500
+ offset = 0
501
+
502
+ for line in text.splitlines(keepends=True):
503
+ opened = FENCE.match(line)
504
+ stripped = line.strip()
505
+
506
+ if fence is None and opened is not None:
507
+ runs.append((start, offset))
508
+ fence = opened.group(1)
509
+ elif fence is not None and set(stripped) == {fence[0]} and len(stripped) >= len(fence):
510
+ fence = None
511
+ start = offset + len(line)
512
+
513
+ offset += len(line)
514
+
515
+ if fence is None:
516
+ runs.append((start, len(text)))
517
+
518
+ return [(begin, end) for begin, end in runs if begin < end]
519
+
520
+
521
+ def _closing(text: str, start: int, end: int, delimiter: str) -> int | None:
522
+ """Offset of the `delimiter` that closes a formula opened before `start`, if any."""
523
+
524
+ index = start
525
+
526
+ while index < end:
527
+ # The delimiter first: `\)` and `\]` start with the escape character.
528
+ if text.startswith(delimiter, index):
529
+ return index
530
+ elif text[index] == "\\":
531
+ index += 2
532
+ elif BLANK_LINE.match(text, index):
533
+ return None
534
+ else:
535
+ index += 1
536
+
537
+ return None
538
+
539
+
540
+ def _rescue(part: Part) -> Part:
541
+ """`part`, or a version of it that Typst can render, with a note when it changed."""
542
+
543
+ if _renders(Question("", (part,))):
544
+ return part
545
+
546
+ text = part.text
547
+ for formula in reversed(find_formulas(text)):
548
+ if not _formula_renders(formula):
549
+ text = text[: formula.start] + _as_code(text, formula) + text[formula.end :]
550
+
551
+ shown = replace(part, text=text, style=Style.MARKDOWN, note=SOURCE_NOTE)
552
+ if text != part.text and _renders(Question("", (shown,))):
553
+ return shown
554
+
555
+ return _as_plain(part)
556
+
557
+
558
+ def _as_plain(part: Part) -> Part:
559
+ match part.style:
560
+ case Style.NOTE:
561
+ return part
562
+ case _:
563
+ return replace(part, style=Style.PLAIN, note=PLAIN_NOTE)
564
+
565
+
566
+ def _as_code(text: str, formula: Formula) -> str:
567
+ """The formula's source with its dollar signs, as a code block or a code span."""
568
+
569
+ source = text[formula.start : formula.end]
570
+
571
+ if formula.display:
572
+ return f"\n\n{code_block(source)}\n\n"
573
+
574
+ longest = max((len(run) for run in re.findall(r"`+", source)), default=0)
575
+ fence = "`" * (longest + 1)
576
+
577
+ return f"{fence} {' '.join(source.split())} {fence}"
578
+
579
+
580
+ def _renders(question: Question) -> bool:
581
+ import typst
582
+
583
+ try:
584
+ _document([question])
585
+ except typst.TypstError:
586
+ return False
587
+
588
+ return True
589
+
590
+
591
+ def _formula_renders(formula: Formula) -> bool:
592
+ import typst
593
+
594
+ inputs = {"formula": formula.source, "display": str(formula.display).lower()}
595
+
596
+ try:
597
+ _compile(FORMULA, inputs)
598
+ except typst.TypstError:
599
+ return False
600
+
601
+ return True
602
+
603
+
604
+ def _document(questions: list[Question]) -> bytes:
605
+ """The PDF of `questions`."""
606
+
607
+ def text(part: Part) -> str:
608
+ match part.style:
609
+ case Style.MARKDOWN:
610
+ return _valid(_delimited(part.text))
611
+ case Style.PLAIN | Style.NOTE:
612
+ return _valid(part.text)
613
+
614
+ def parts(parts: tuple[Part, ...]) -> list[dict[str, str | None]]:
615
+ return [{"text": text(p), "role": p.role, "style": p.style, "note": p.note} for p in parts]
616
+
617
+ doc = [{"title": _valid(q.title), "parts": parts(q.parts)} for q in questions]
618
+
619
+ return _compile(TEMPLATE, {"doc": json.dumps(doc, ensure_ascii=False)})
620
+
621
+
622
+ def _valid(text: str) -> str:
623
+ """`text` with lone surrogates, which JSON for Typst cannot carry, made `?`."""
624
+
625
+ return text.encode("utf-8", "replace").decode("utf-8")
626
+
627
+
628
+ def _compile(source: str, inputs: dict[str, str]) -> bytes:
629
+ """Compile Typst `source` to PDF with the vendored packages and Typst's own fonts.
630
+
631
+ System fonts are added only when the inputs hold a script the embedded fonts lack: a
632
+ system font with an embedded font's family name would replace it.
633
+ """
634
+
635
+ import typst
636
+
637
+ system = any(_needs_system_fonts(value) for value in inputs.values())
638
+
639
+ return typst.compile(
640
+ source.encode(),
641
+ package_path=str(PACKAGES),
642
+ font_paths=_fonts(system=system),
643
+ sys_inputs=inputs,
644
+ )
645
+
646
+
647
+ def _needs_system_fonts(text: str) -> bool:
648
+ """Whether `text` has characters from scripts Typst's embedded fonts do not cover.
649
+
650
+ A heuristic by Unicode block: Latin, Greek, Cyrillic, punctuation, arrows and math are
651
+ covered; Hebrew to the Indic and South-East Asian scripts, CJK and emoji are not.
652
+ """
653
+
654
+ return any(
655
+ 0x0590 <= point < 0x1D00 or (point >= 0x2E80 and not 0x1D400 <= point < 0x1D800)
656
+ for point in map(ord, text)
657
+ )
658
+
659
+
660
+ @cache
661
+ def _fonts(*, system: bool) -> "typst.Fonts":
662
+ """Typst's embedded fonts, plus the system's when `system`; found once per process."""
663
+
664
+ import typst
665
+
666
+ return typst.Fonts(include_system_fonts=system, include_embedded_fonts=True)
667
+
668
+
669
+ def _plain(cells: tuple[Cell, ...]) -> list[Cell]:
670
+ """Plain cells only: a function or class cell has no output to show."""
671
+
672
+ return [cell for cell in cells if cell.kind is CellKind.CELL]
673
+
674
+
675
+ def quiet(message: str) -> None:
676
+ """Status callback that shows nothing."""