From 9165848a89b0f5c8ee709d62ed44efd21636b2b3 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 16:10:05 -0500 Subject: [PATCH 1/2] feat: name otter-assign syntax when no notebook calls mogs.assignment --- src/mogs/build.py | 43 +++++++++++++++++-- tests/test_build.py | 101 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 4 deletions(-) diff --git a/src/mogs/build.py b/src/mogs/build.py index c61c603..32d2964 100644 --- a/src/mogs/build.py +++ b/src/mogs/build.py @@ -72,6 +72,12 @@ SCRIPTS = ("setup.sh", "run_autograder") ZIP_FILES = (*SCRIPTS, "bundle.json", "requirements.txt") ZIP_DATE = (1980, 1, 1, 0, 0, 0) +PORTING_URL = "https://mogs.kristia.de/porting" +# Otter Assign's own markers. Its solution and `# HIDDEN` markers are left out: mogs uses them +# too. +OTTER_RE = re.compile( + r"(? Path: case [path]: return path case []: + otter = _otter_hint( + [*sorted(assignment_dir.glob("*.py")), *sorted(assignment_dir.glob("*.ipynb"))] + ) raise BuildError( - f"No notebook in {assignment_dir} calls `mogs.assignment(...)`. Add a cell with " - "that call, or start a new assignment with `mogs init`." + f"No notebook in {assignment_dir} calls `mogs.assignment(...)`. " + + ( + otter + or "Add a cell with that call, or start a new assignment with `mogs init`." + ) ) case _: names = "\n".join(f" {path.name}" for path in candidates) @@ -228,13 +240,36 @@ def source_notebook(path: Path) -> Path: if not _is_notebook(path.read_text(encoding="utf-8", errors="replace")): raise BuildError( - f"{path} does not call `mogs.assignment(...)`. Pass the source notebook or the " - "assignment folder." + f"{path} does not call `mogs.assignment(...)`. " + + (_otter_hint([path]) or "Pass the source notebook or the assignment folder.") ) return path +def _otter_hint(paths: Iterable[Path]) -> str | None: + """Where the first of `paths` with an Otter Assign marker has it, and where to read on. + + Returns: + The hint, or `None` when no file has such a marker. + """ + + for path in paths: + if not path.is_file(): + continue + + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + for number, line in enumerate(lines, start=1): + found = OTTER_RE.search(line) + if found: + return ( + f"{path}:{number} has `{found.group()}`, which is otter-assign syntax. " + f"Port the notebook to mogs by hand: {PORTING_URL}" + ) + + return None + + def _is_notebook(text: str) -> bool: """A source notebook: it calls `assignment(...)`, under any name its imports give it. diff --git a/tests/test_build.py b/tests/test_build.py index 2b4f78d..18bb934 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -20,6 +20,7 @@ failure_report, find_notebook, free_points_warnings, + source_notebook, ) from mogs.cli import main, report from mogs.config import AssignmentConfig, ConfigError, Question, read_config @@ -332,6 +333,106 @@ def test_no_candidate(tmp_path): find_notebook(tmp_path) +# What `marimo convert` makes of an otter-assign notebook's raw cells. +CONVERTED_OTTER = """import marimo + +app = marimo.App() + + +@app.cell +def _(hw01): + # ASSIGNMENT CONFIG + _name: hw01 + return + + +@app.cell +def _(q1): + # BEGIN QUESTION + _name: q1 + points: 2 + + +if __name__ == "__main__": + app.run() +""" + + +def test_no_candidate_names_otter_syntax(tmp_path): + (tmp_path / "hw.py").write_text(CONVERTED_OTTER, encoding="utf-8") + + with pytest.raises(BuildError) as raised: + find_notebook(tmp_path) + + message = str(raised.value) + assert f"{tmp_path / 'hw.py'}:8 " in message + assert "`# ASSIGNMENT CONFIG`" in message + assert "otter-assign" in message + assert "https://mogs.kristia.de/porting" in message + + +@pytest.mark.parametrize( + "marker", + [ + "# BEGIN QUESTION", + "# END QUESTION", + "# BEGIN TESTS", + "# END TESTS", + '""" # BEGIN PROMPT', + "# BEGIN TEST CONFIG", + ], +) +def test_no_candidate_names_each_otter_marker(tmp_path, marker): + text = f'x = 1\n\n\n@app.cell\ndef _():\n """\n {marker}\n """\n' + (tmp_path / "hw.py").write_text(text, encoding="utf-8") + + with pytest.raises(BuildError, match=r"hw\.py:7 .*otter-assign"): + find_notebook(tmp_path) + + +def test_no_candidate_names_otter_syntax_in_an_unparsable_cell(tmp_path): + text = 'app._unparsable_cell(\n r"""\n # BEGIN QUESTION\n name: q1\n """,\n)\n' + (tmp_path / "hw.py").write_text(text, encoding="utf-8") + + with pytest.raises(BuildError, match=r"hw\.py:3 .*`# BEGIN QUESTION`"): + find_notebook(tmp_path) + + +def test_no_candidate_names_otter_syntax_in_an_ipynb(tmp_path): + cells = [ + {"cell_type": "markdown", "metadata": {}, "source": ["# Homework 1\n"]}, + {"cell_type": "raw", "metadata": {}, "source": ["# BEGIN QUESTION\n", "name: q1\n"]}, + ] + notebook = {"cells": cells, "metadata": {}, "nbformat": 4, "nbformat_minor": 5} + (tmp_path / "hw.ipynb").write_text(json.dumps(notebook, indent=1), encoding="utf-8") + + with pytest.raises(BuildError) as raised: + find_notebook(tmp_path) + + message = str(raised.value) + assert f"{tmp_path / 'hw.ipynb'}:" in message + assert "`# BEGIN QUESTION`" in message + assert "https://mogs.kristia.de/porting" in message + + +def test_no_candidate_ignores_solution_markers(tmp_path): + text = "def f():\n # BEGIN SOLUTION\n return 1\n # END SOLUTION\n" + (tmp_path / "hw.py").write_text(text, encoding="utf-8") + + with pytest.raises(BuildError) as raised: + find_notebook(tmp_path) + + assert "otter" not in str(raised.value) + + +def test_source_notebook_names_otter_syntax(tmp_path): + path = tmp_path / "hw.py" + path.write_text(CONVERTED_OTTER, encoding="utf-8") + + with pytest.raises(BuildError, match=r"hw\.py:8 .*otter-assign.*/porting"): + source_notebook(path) + + def test_find_notebook_ignores_other_scripts(tmp_path): folder = demo_copy(tmp_path / "demo") (folder / "helper.py").write_text( From cce67fcdea04286428a965f05768a190ca30cb73 Mon Sep 17 00:00:00 2001 From: Agustinus Kristiadi Date: Thu, 26 Nov 2026 16:11:55 -0500 Subject: [PATCH 2/2] docs: add a page on porting from Otter Assign --- docs/src/components/Header.astro | 1 + docs/src/content/docs/instructors.md | 1 + docs/src/content/docs/porting.md | 141 +++++++++++++++++++++++++++ docs/src/llms.ts | 2 +- docs/src/routeData.ts | 2 +- 5 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 docs/src/content/docs/porting.md diff --git a/docs/src/components/Header.astro b/docs/src/components/Header.astro index af12322..7f458cc 100644 --- a/docs/src/components/Header.astro +++ b/docs/src/components/Header.astro @@ -4,6 +4,7 @@ import SocialIcons from '@astrojs/starlight/components/SocialIcons.astro'; const links = [ { label: 'Instructors', href: '/instructors/' }, + { label: 'Porting', href: '/porting/' }, { label: 'Students', href: '/students/' }, ]; const path = Astro.url.pathname; diff --git a/docs/src/content/docs/instructors.md b/docs/src/content/docs/instructors.md index ea17ad8..0b6f1de 100644 --- a/docs/src/content/docs/instructors.md +++ b/docs/src/content/docs/instructors.md @@ -15,6 +15,7 @@ hw1/ `mogs build ` turns it into a student notebook and an autograder zip. [`examples/demo`](https://github.com/wiseodd/mogs/tree/main/examples/demo) is a complete example. See also [marimo's official tutorial](https://docs.marimo.io/getting_started/quickstart/). +To port an Otter Assign notebook, see [Porting from Otter](/porting/). ## Start diff --git a/docs/src/content/docs/porting.md b/docs/src/content/docs/porting.md new file mode 100644 index 0000000..70705bb --- /dev/null +++ b/docs/src/content/docs/porting.md @@ -0,0 +1,141 @@ +--- +title: Porting from Otter +description: Port an Otter Assign notebook to mogs. +--- + +mogs covers a subset of [Otter Assign](https://otter-grader.readthedocs.io/en/latest/otter_assign/)'s v1 notebook format, and the port is done by hand. +Read the [instructor guide](/instructors/) first. + +## Convert + +Turn the Jupyter notebook into a marimo notebook: + +```bash +marimo convert notebook.ipynb -o notebook.py +``` + +Otter's raw cells come out as code cells that hold the YAML, or as unparsable cells when the YAML isn't valid Python. +Move their settings into `mogs.assignment(...)` and `mogs.grade(...)`, then delete them. +Until the notebook calls `mogs.assignment(...)`, `mogs build` names the file and line of the first Otter marker. + +The conversion keeps the test expressions but drops their saved outputs. +Keep the `.ipynb` open to read the expected values. + +## Mapping + +| Otter | mogs | +| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `# ASSIGNMENT CONFIG` raw cell | A cell with one `mogs.assignment(...)` call. | +| `name` | `name=`. | +| `files` | `files=`. The files go to students and to Gradescope. | +| `autograder_files`, `student_files` | None. | +| `requirements` as a list | `dependencies` in the notebook's header. | +| `requirements` as a file | `requirements="requirements.txt"`, or `dependencies` in the header. | +| `environment` | None. Gradescope installs with uv. | +| `python_version` | `python="3.13"`. | +| `seed`, `# SEED` | None. | +| `init_cell`, `check_cell`, `check_all_cell` | None needed. The grade cell shows each public test's result. | +| `export_cell` | None needed. The student notebook ends with an **Export submission** button. | +| `solutions_pdf`, `template_pdf` | None. | +| `generate`, `show_hidden`, `show_stdout` | None. Students see the public test results and their scores. | +| `points_possible`, `score_threshold` | None. The total is the sum of the question points. | +| `save_environment`, `variables`, `runs_on` | None. | +| `# BEGIN QUESTION` raw cell | A `mogs.grade("q1", points=2)` cell after the question's tests. | +| question `name` | The question id, letters and digits only: `q1a` works, `q1_a` and `q1-a` don't. | +| question `points` | `points=`. It is required. | +| `manual: true` | A question without tests. See [Written answers](/instructors/#written-answers). | +| `all_or_nothing` | None. | +| `# BEGIN PROMPT` raw cell | `` inside the Markdown answer cell. | +| `""" # BEGIN PROMPT` in a code cell | `# PROMPT:` lines between `# BEGIN SOLUTION` and `# END SOLUTION`. | +| `# BEGIN SOLUTION` raw cell | `# BEGIN SOLUTION` and `# END SOLUTION` inside the answer cell. | +| `# BEGIN SOLUTION` in a code cell | The same. | +| solution in a Markdown cell | `` and `` inside `mo.md(...)`. | +| `# SOLUTION` at the end of a line | The same, except that a line other than an assignment, `return` or `yield` is removed, not replaced with `...`. | +| `# SOLUTION NO PROMPT`, `# BEGIN SOLUTION NO PROMPT` | None. The block becomes `...`, or the `# PROMPT:` lines. | +| `# BEGIN TESTS` raw cell | A cell of functions named `test__`. | +| test cell with a saved output | `assert expression == output`. | +| exception-format test (`ok_format: false`) | A function named `test__` with no arguments. It calls the answer functions itself. | +| `# HIDDEN` on a test cell | `# HIDDEN` as the first line of a cell of hidden tests. | +| per-test `points` | None. A question's points are split evenly across its tests. | +| `success_message` | None. | +| `failure_message` | The assert's message: `assert x == 1, "x should be 1"`. | +| `# IGNORE` | A cell named `instructor` or `instructor_`. | +| `# BEGIN PLUGIN` | None. | + +## Answers are functions + +A test can read functions, names from the setup cell, and names from `# HIDDEN` cells. +It can't read a variable that a regular cell defines. +An Otter question that asks for `answer = ...` becomes a function that returns the answer: + +```python +@app.function +def answer(): + return 42 # SOLUTION +``` + +See [Notebook](/instructors/#notebook) for why. + +## Example + +An Otter question with one public and one hidden test, as cells: + +```text +[raw] # BEGIN QUESTION + name: q1 + points: 2 +[markdown] **Question 1.** Write `square(x)`. +[raw] # BEGIN SOLUTION +[code] def square(x): + return x * x # SOLUTION +[raw] # END SOLUTION +[raw] # BEGIN TESTS +[code] square(3) +[output] 9 +[code] # HIDDEN + square(-2) +[output] 4 +[raw] # END TESTS +[raw] # END QUESTION +``` + +The same question in mogs: + +```python +@app.cell(hide_code=True) +def _(): + mo.md(r""" + **Question 1.** Write `square(x)`. + """) + return + + +@app.function +def square(x): + return x * x # SOLUTION + + +@app.cell +def _(): + def test_q1_positive(): + assert square(3) == 9 + + return + + +@app.cell +def _(): + # HIDDEN + def test_q1_negative(): + assert square(-2) == 4 + + return + + +@app.cell +def _(): + mogs.grade("q1", points=2) + return +``` + +Each test is worth 1 point. diff --git a/docs/src/llms.ts b/docs/src/llms.ts index 6693802..fa1ae47 100644 --- a/docs/src/llms.ts +++ b/docs/src/llms.ts @@ -1,7 +1,7 @@ import { getCollection, type CollectionEntry } from 'astro:content'; // The pages in llms.txt, in header order. Each has a Markdown copy at `/.md`. -export const PAGES = ['index', 'instructors', 'students']; +export const PAGES = ['index', 'instructors', 'porting', 'students']; export async function pages(): Promise[]> { const entries = await getCollection('docs'); diff --git a/docs/src/routeData.ts b/docs/src/routeData.ts index e597f34..c1fd263 100644 --- a/docs/src/routeData.ts +++ b/docs/src/routeData.ts @@ -4,7 +4,7 @@ import { PAGES } from './llms'; export const onRequest = defineRouteMiddleware((context) => { const route = context.locals.starlightRoute; - // Three pages, linked from the header: no left sidebar. + // Pages linked from the header: no left sidebar. route.hasSidebar = false; // Point agents that fetch the HTML at the page's Markdown copy.