Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/src/components/Header.astro
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/instructors.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ hw1/
`mogs build <directory name>` 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

Expand Down
141 changes: 141 additions & 0 deletions docs/src/content/docs/porting.md
Original file line number Diff line number Diff line change
@@ -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 | `<!-- PROMPT: ... -->` 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 | `<!-- BEGIN SOLUTION -->` and `<!-- END SOLUTION -->` 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_<qid>_<name>`. |
| test cell with a saved output | `assert expression == output`. |
| exception-format test (`ok_format: false`) | A function named `test_<qid>_<name>` 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_<anything>`. |
| `# 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.
2 changes: 1 addition & 1 deletion docs/src/llms.ts
Original file line number Diff line number Diff line change
@@ -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 `/<id>.md`.
export const PAGES = ['index', 'instructors', 'students'];
export const PAGES = ['index', 'instructors', 'porting', 'students'];

export async function pages(): Promise<CollectionEntry<'docs'>[]> {
const entries = await getCollection('docs');
Expand Down
2 changes: 1 addition & 1 deletion docs/src/routeData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
43 changes: 39 additions & 4 deletions src/mogs/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"(?<![\w#])# (?:ASSIGNMENT CONFIG|(?:BEGIN|END) (?:QUESTION|TESTS|PROMPT|TEST CONFIG))\b"
)
# Otter's timestamp in the zip name, e.g. 2026_09_30T12_30_41_890583.
STAMP = "%Y_%m_%dT%H_%M_%S_%f"

Expand Down Expand Up @@ -203,9 +209,15 @@ def find_notebook(assignment_dir: Path) -> 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)
Expand All @@ -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.

Expand Down
101 changes: 101 additions & 0 deletions tests/test_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Loading