aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <hello@eugenetriguba.com>2026-05-22 03:19:26 +0000
committerEugene Triguba <hello@eugenetriguba.com>2026-05-22 03:19:26 +0000
commit604b780bbf6e0521d58bc4ff50a792422ff8de39 (patch)
tree4d5e33b6da18776a809609b5133f300ebbfac183
parentFix clean notebook exports and clean_nb missing return (diff)
downloadnb-604b780bbf6e0521d58bc4ff50a792422ff8de39.zip
Tidy export comments and types
-rw-r--r--nb/export.py12
-rw-r--r--nbs/export.ipynb204
2 files changed, 31 insertions, 185 deletions
diff --git a/nb/export.py b/nb/export.py
index e20053d..4e6bbf5 100644
--- a/nb/export.py
+++ b/nb/export.py
@@ -13,8 +13,8 @@ type PathOrFileLike = str|Path|IO[str]
# cell: 27202360
def read_nb(
- fp:PathOrFileLike, # a path or file-like object to read the notebook from
- v:int=4, # the notebook format major version to read the notebook as
+ fp:PathOrFileLike, # Where to read the notebook from.
+ v:int=4, # The notebook format major version to read the notebook as.
)->NotebookNode:
"Read in a notebook as a dictionary-like NotebookNode."
return nbformat.read(fp, as_version=v)
@@ -104,13 +104,13 @@ def fmt_export_cell(cell:dict)->dict:
# cell: 633e256b
def mk_py_mod_scaffold(
- mod:str, # The Python module name or dotted path e.g. mod.mymod.file
- src_dir:str|pathlib.Path, # The Python package source code directory scaffold
+ mod:str, # The Python module name or dotted path e.g. mod.mymod.file
+ src_dir:str|Path, # The Python package source code directory scaffold
):
"Create all intermediary __init__.py files and directories, if any, and the final .py file."
if not mod: raise ValueError('The module path cannot be empty')
- src_dir = pathlib.Path(src_dir)
- mod_file = (src_dir/pathlib.Path(*mod.split('.'))).with_suffix('.py')
+ src_dir = Path(src_dir)
+ mod_file = (src_dir/Path(*mod.split('.'))).with_suffix('.py')
mod_file.parent.mkdir(parents=True, exist_ok=True)
mod_file.touch()
pkg_dirs = list(mod_file.parents)
diff --git a/nbs/export.ipynb b/nbs/export.ipynb
index 3084d3e..939a46d 100644
--- a/nbs/export.ipynb
+++ b/nbs/export.ipynb
@@ -3,6 +3,26 @@
{
"cell_type": "code",
"execution_count": null,
+ "id": "07ebb5d3",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "The autoreload extension is already loaded. To reload it, use:\n",
+ " %reload_ext autoreload\n"
+ ]
+ }
+ ],
+ "source": [
+ "%load_ext autoreload\n",
+ "%autoreload 2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
"id": "b92ad576",
"metadata": {},
"outputs": [],
@@ -220,10 +240,12 @@
"text/plain": [
"{'cell_type': 'code',\n",
" 'execution_count': None,\n",
- " 'id': 'b92ad576',\n",
+ " 'id': '07ebb5d3',\n",
" 'metadata': {},\n",
- " 'outputs': [],\n",
- " 'source': '#| default_exp: export'}"
+ " 'outputs': [{'name': 'stdout',\n",
+ " 'output_type': 'stream',\n",
+ " 'text': 'The autoreload extension is already loaded. To reload it, use:\\n %reload_ext autoreload\\n'}],\n",
+ " 'source': '%load_ext autoreload\\n%autoreload 2'}"
]
},
"execution_count": null,
@@ -926,182 +948,6 @@
"source": [
"export_nb('export.ipynb', src_dir='../nb/')"
]
- },
- {
- "cell_type": "markdown",
- "id": "59c195b3",
- "metadata": {},
- "source": [
- "i don't understand how I'm somehow getting python files exported into the *same* directory sometimes. e.g. see 'export.py' in the same directory right now.\n",
- "\n",
- "##### 🤖Reply🤖<!-- SOLVEIT_SEPARATOR_7f3a9b2c -->\n",
- "\n",
- "The default value for `src_dir` in `export_nb` is `'.'`:\n",
- "\n",
- "```python\n",
- "def export_nb(fp, src_dir='.'):\n",
- "```\n",
- "\n",
- "So if you ever called `export_nb('export.ipynb')` without specifying `src_dir` (e.g. while testing in the REPL), it would drop `export.py` right into the current working directory — the same folder as the notebook.\n",
- "\n",
- "That's likely what happened. You can just delete the stray `export.py` file. You might also consider whether having `'.'` as the default is what you actually want, or if it'd be safer to make `src_dir` a required parameter (no default) so this can't happen accidentally."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6a271023",
- "metadata": {},
- "source": [
- "But if you read export.py, it's clear that it isn't from export_nb because it has no cell comments.\n",
- "\n",
- "##### 🤖Reply🤖<!-- SOLVEIT_SEPARATOR_7f3a9b2c -->\n",
- "\n",
- "Good point — if there are no `# cell: ...` comments, then `export_nb` didn't create it. Let me take a look at the file to see what's actually in it.\n",
- "\n",
- "\n",
- "<details class='tool-usage-details' markdown='1'>\n",
- "<summary><code>view(path=&#x27;nb/nbs/export.py&#x27;)→&#x27;Error: File not found: /app/data/nb/nbs/…&#x27;</code></summary>\n",
- "\n",
- "```json\n",
- "{\n",
- " \"id\": \"toolu_0185u2rVBZJG6ics9LDHYvTi\",\n",
- " \"call\": {\n",
- " \"function\": \"view\",\n",
- " \"arguments\": {\n",
- " \"path\": \"nb/nbs/export.py\"\n",
- " }\n",
- " },\n",
- " \"result\": \"Error: File not found: /app/data/nb/nbs/nb/nbs/export.py\"\n",
- "}\n",
- "```\n",
- "\n",
- "</details>\n",
- "\n",
- "Let me find the right path.\n",
- "\n",
- "\n",
- "<details class='tool-usage-details' markdown='1'>\n",
- "<summary><code>realpath(subpath=&#x27;/&#x27;)→&quot;{&#x27;path&#x27;: &#x27;/app/data&#x27;}&quot;</code></summary>\n",
- "\n",
- "```json\n",
- "{\n",
- " \"id\": \"toolu_01UXNtz4TuJLxzDXcQU5ygQ7\",\n",
- " \"call\": {\n",
- " \"function\": \"realpath\",\n",
- " \"arguments\": {\n",
- " \"subpath\": \"/\"\n",
- " }\n",
- " },\n",
- " \"result\": \"{'path': '/app/data'}\"\n",
- "}\n",
- "```\n",
- "\n",
- "</details>\n",
- "\n",
- "The data root is `/app/data`. The dialog path is `nb/nbs/export`. Let me look for the file.\n",
- "\n",
- "\n",
- "<details class='tool-usage-details' markdown='1'>\n",
- "<summary><code>rg(argstr=&#x27;--files -g export.py /app/data/nb&#x27;)→&#x27;/app/data/nb/nb/export.py\\n/app/data/nb/n…&#x27;</code></summary>\n",
- "\n",
- "```json\n",
- "{\n",
- " \"id\": \"toolu_01FfH6PxdZYtbwAnoQR2NsQc\",\n",
- " \"call\": {\n",
- " \"function\": \"rg\",\n",
- " \"arguments\": {\n",
- " \"argstr\": \"--files -g export.py /app/data/nb\"\n",
- " }\n",
- " },\n",
- " \"result\": \"/app/data/nb/nb/export.py\\n/app/data/nb/nbs/export.py\"\n",
- "}\n",
- "```\n",
- "\n",
- "</details>\n",
- "\n",
- "There are two `export.py` files — one at `nb/nb/export.py` and one at `nb/nbs/export.py`. Let me look at the one in the notebook's directory:\n",
- "\n",
- "\n",
- "<details class='tool-usage-details' markdown='1'>\n",
- "<summary><code>view(path=&#x27;/app/data/nb/nbs/export.py&#x27;)→&#x27;import enum,pathlib,re\\nfrom pathlib impo…&#x27;</code></summary>\n",
- "\n",
- "```json\n",
- "{\n",
- " \"id\": \"toolu_01NUNL9YfvjKLpiDqTNZ9L4t\",\n",
- " \"call\": {\n",
- " \"function\": \"view\",\n",
- " \"arguments\": {\n",
- " \"path\": \"/app/data/nb/nbs/export.py\"\n",
- " }\n",
- " },\n",
- " \"result\": \"import enum,pathlib,re\\nfrom pathlib import Path\\nfrom typing import IO\\n\\nimport nbformat\\nfrom nbformat import NotebookNode\\ntype PathOrFileLike = str|Path|IO[str]\\ndef read_nb(\\n fp:PathOrFileLike, # Where to read the notebook from.\\n v:int=4, # The notebook format major version to read the notebook as.\\n)->NotebookNode:\\n \\\"Read in a notebook as a dictionary-like NotebookNode.\\\"\\n return nbformat.read(fp, as_version=v)\\n\\nclass CellType(enum.StrEnum):\\n \\\"Possible Jupyter notebook cell types.\\\"\\n CODE = 'code'\\n MD = 'markdown'\\n RAW = 'raw'\\ndef filter_cells(\\n nb:NotebookNode, # A notebook that has been read in via `read_nb`.\\n ct:CellType, # The cells to filter down to.\\n)->list[NotebookNode]:\\n \\\"Retrieve specific cell types from a notebook.\\\"\\n return list(filter(lambda c: c['cell_type'] == ct, nb['cells']))\\ndef _mk_directive_re(\\n name:str, # The name of the directive\\n arg_re:str|None=None, # A regex pattern to match an argument for the directive\\n)->re.Pattern:\\n \\\"Compile a regex to match a directive, optionally supporting an argument.\\\"\\n arg = rf':\\\\s*{arg_re}' if arg_re else ''\\n return re.compile(rf'^\\\\s*#\\\\|\\\\s*{name}{arg}\\\\s*$')\\nDIRECTIVE_DEFAULT_EXP_RE = _mk_directive_re('default_exp', arg_re=r'(?P<module>\\\\w+(\\\\.\\\\w+)*)')\\nDIRECTIVE_EXPORT_RE = _mk_directive_re('export')\\nDIRECTIVES = [DIRECTIVE_DEFAULT_EXP_RE, DIRECTIVE_EXPORT_RE]\\ndef has_directive(src:str)->bool:\\n \\\"Check whether a line or block of source code has a nb directive.\\\"\\n return any(any(r.match(l) for r in DIRECTIVES) for l in src.splitlines())\\ndef strip_directives(src:str|list[str])->str:\\n \\\"Remove all nb directives from the source code.\\\"\\n src = src if isinstance(src, list) else src.splitlines()\\n return \\\"\\\\n\\\".join(filter(lambda l: not has_directive(l), src))\\ndef is_cell_exported(cell:NotebookNode)->bool:\\n \\\"Check whether the code cell should be exported.\\\"\\n return any(DIRECTIVE_EXPORT_RE.match(l) for l in cell['source'].splitlines())\\ndef get_default_export(cells:list[NotebookNode])->str:\\n \\\"Retrieve the `default_exp` directive argument from a list of cells.\\\"\\n matches = [\\n m.group('module')\\n for c in cells\\n for l in c['source'].splitlines()\\n if c['cell_type'] == CellType.CODE and (m:=DIRECTIVE_DEFAULT_EXP_RE.match(l))\\n ]\\n if len(matches) > 1: raise ValueError('More than one default_exp directive')\\n if len(matches) == 0: raise ValueError('Missing default_exp directive')\\n return matches[0]\\ndef find_cells_to_export(\\n fp:PathOrFileLike|NotebookNode, # Where to read the notebook from.\\n)->tuple[str,list[NotebookNode]]: # Returns the module name and list of cells to export.\\n \\\"Find the code cells in an ipynb file to export out.\\\"\\n if not isinstance(fp, NotebookNode): fp = read_nb(fp)\\n code_cells = filter_cells(fp, CellType.CODE)\\n module = get_default_export(code_cells)\\n cells = [\\n {**c, 'source': strip_directives(c['source'])}\\n for c in code_cells\\n if is_cell_exported(c)\\n ]\\n return module, cells\\ndef fmt_export_cell(cell:dict)->dict:\\n \\\"Format a code cell's source with metadata to prepare for export.\\\"\\n cell['source'] = f'# cell: {cell[\\\"id\\\"]}\\\\n' + cell['source'] + '\\\\n'\\n return cell\\ndef mk_py_mod_scaffold(\\n mod:str, # The Python module name or dotted path e.g. mod.mymod.file\\n src_dir:str|Path, # The Python package source code directory scaffold\\n):\\n \\\"Create all intermediary __init__.py files and directories, if any, and the final .py file.\\\"\\n if not mod: raise ValueError('The module path cannot be empty')\\n src_dir = Path(src_dir)\\n mod_file = (src_dir/Path(*mod.split('.'))).with_suffix('.py')\\n mod_file.parent.mkdir(parents=True, exist_ok=True)\\n mod_file.touch()\\n pkg_dirs = list(mod_file.parents)\\n for p in pkg_dirs[:pkg_dirs.index(src_dir) + 1]:\\n (p / '__init__.py').touch()\\ndef export_nb(\\n fp:PathOrFileLike|NotebookNode, # The notebook to export.\\n src_dir:str|Path='.', # The source directory to export the Python module to.\\n):\\n \\\"Export the exportable code cells to a Python file.\\\"\\n module, cells = find_cells_to_export(fp)\\n mk_py_mod_scaffold(module, src_dir)\\n exp_path = (Path(src_dir)/module).with_suffix('.py')\\n src = '\\\\n'.join(\\n ['# AUTOGENERATED! DO NOT EDIT!\\\\n'] +\\n list(map(lambda c: fmt_export_cell(c)['source'], cells))\\n )\\n Path(exp_path).write_text(src)\"\n",
- "}\n",
- "```\n",
- "\n",
- "</details>\n",
- "\n",
- "Ah, now I see! This `export.py` is clearly **solveit's own export** — it's the concatenation of all your code cells that are marked as exported (with `is_exported` flag in solveit's message metadata), just joined together with no `# cell:` comments and no `# AUTOGENERATED` header.\n",
- "\n",
- "This is solveit's built-in export mechanism, which is separate from the `export_nb` function you're building. When you mark messages as \"exported\" in solveit (the toggle in the UI), solveit generates this file automatically. It happens to write to `export.py` because your dialog is named `export`.\n",
- "\n",
- "So you have two different export systems both targeting the same module name — solveit's built-in one writing to `nb/nbs/export.py`, and your `export_nb` writing to `nb/nb/export.py` (via `src_dir='../nb/'`)."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7afcff5b",
- "metadata": {},
- "source": [
- "how can I turn off solveits? The tool I'm building also uses #| export markers.\n",
- "\n",
- "##### 🤖Reply🤖<!-- SOLVEIT_SEPARATOR_7f3a9b2c -->\n",
- "\n",
- "<details class='tool-usage-details' markdown='1'>\n",
- "<summary><code>solveit_docs()→&#x27;⚠️ This content will be truncated in you…&#x27;</code></summary>\n",
- "\n",
- "```json\n",
- "{\n",
- " \"id\": \"toolu_01LSMhJdmQQkiAgpaXu2bNRG\",\n",
- " \"call\": {\n",
- " \"function\": \"solveit_docs\",\n",
- " \"arguments\": {}\n",
- " },\n",
- " \"result\": \"<TRUNCATED>\\u2026ntent will be truncated in your next turn. Re-call this tool if you need it again.\\nIf the user wants more info, give them a link to https://gist.github.com/jph00/9e7b444aba5ecf6d14295ba2cee890c3.# Solveit Reference\\n\\n## What is Solveit?\\n\\nSolveit is a \\\"Dialog Engineering\\\" web application for interactive development. Unlike ChatGPT (pure chat) or Jupyter (pure code), Solveit combines three message types in one workspace: code execution, markdown notes, and AI prompts. Users build solutions incrementally\\u2014writing a few lines, understanding them, then continuing\\u2014rather than generating large code blocks.\\n\\nThe AI sees the full dialog context (code, outputs, notes, prompts) when responding -- but only those ABOVE the current message. Users can edit any message at any time, including AI responses\\u2014the dialog is a living document, not an append-only log.\\n\\nThe dialog is a running ipykernel instance. A \\\"dialog\\\" is like a \\\"Jupyter notebook\\\", and uses a compatible ipynb file format, but provides a superset of functionality (in particular, \\\"prompt messages\\\"). A \\\"message\\\" is like a \\\"Jupyter cell\\\", with additional attributes stored as ipynb cell metadata. Most standard jupyter functionality is supported (including cell magics like `%%js`, `%%html`, `%%bash`, and custom magics via `@line_magic`/`@cell_magic` decorators), except for ipywidgets. Cell magics can be async; if an async magic returns a FastHTML FT component, it's auto-converted to HTML.\\n\\n## Architecture\\n\\n- **Instance**: A persistent Linux container (virtual private server) with home dir at `/app/data`. Each user can have multiple instances. Instances have private URLs (for the solveit interface) and public URLs (for hosting apps on port 8000).\\n- **Dialog**: An `.ipynb` file containing messages. Each open dialog runs its own Python kernel (ipykernel). Dialogs can be organized into folders.\\n- **Kernel**: A running Python 3.12 interpreter maintaining state. Variables persist between code messages. Each dialog has its own isolated kernel. Kernels keep running when navigating away; must explicitly stop via UI or shutdown. Use `%load_ext autoreload` and `%autoreload 2` to auto-reload modules when files change. The current dialog name is available as `__dialog_name` in the kernel namespace and as the `__DIALOG_NAME` environment variable.\\n\\n### CRAFT and TEMPLATE Files\\n\\n**CRAFT.ipynb** files provide reusable AI context and auto-executed code for a folder:\\n- **Note/prompt messages** are prepended to the AI's context for all dialogs in that folder and subfolders\\n- **Code messages** are automatically executed in the kernel when opening a dialog\\n\\n\\n**CRAFT.css** and **CRAFT.js** files can be placed alongside `CRAFT.ipynb`. They follow the same parent-chain hierarchy and are injected as `<style>` and `<script type=\\\"module\\\">` tags when a dialog opens. Useful for custom theming or adding client-side behavior without touching the main app.\\n**TEMPLATE.ipynb** files serve as dialog templates\\u2014their cells are prepended to new dialogs created in that folder.\\n\\nBoth use path hierarchy: files from parent folders are included too, letting you build layered configurations (e.g., org-wide settings in root, project-specific in subfolders).\\n\\n### Optional CRAFTs (CRAFTs Folders)\\n\\nIn addition to `CRAFT.ipynb` files (which are always loaded), you can place notebooks in a `CRAFTs/` subfolder at any level of the folder hierarchy. These are **optional crafts** \\u2014 they are discovered but not automatically loaded.\\n\\nThe AI always sees optional crafts listed in its context on every prompt: only the first message and the file size are shown, wrapped in `<optional-craft-block>` tags. This gives the AI enough information to decide whether a particular optional craft is relevant to the current task. If so, the AI can call the `load_dialog` tool, which runs all its code cells in the kernel and returns the full contents.\\n\\nExample structure:\\n```\\nproject/\\n\\u251c\\u2500\\u2500 CRAFT.ipynb # Always loaded (required)\\n\\u251c\\u2500\\u2500 CRAFTs/\\n\\u2502 \\u251c\\u2500\\u2500 testing.ipynb # Optional \\u2014 AI loads on demand\\n\\u2502 \\u2514\\u2500\\u2500 advanced.ipynb # Optional \\u2014 AI loads on demand\\n\\u2514\\u2500\\u2500 my_dialog.ipynb\\n```\\n\\nOptional crafts loaded via `load_dialog` are automatically re-imported when the kernel restarts, so you don't need to re-load them manually after a restart. Solveit achieves this by scanning the dialog's prompt history for prior `load_dialog` calls and replaying them during startup.\\n\\n\\n### AUTORUN Folders\\n\\nPlace notebooks inside an `AUTORUN/` folder at the root of your instance to have them automatically opened and run on startup. Useful for persistent background processes (Discord bots, FastHTML apps, scheduled tasks). Dialogs in `AUTORUN/` folders are exempt from idle shutdown.\\n\\n## Message Types\\n\\n| Type | Purpose | Input | Output |\\n|------|---------|-------|--------|\\n| `code` | Python execution | Python source | ipynb-format output list (stream, execute_result, display_data, error) |\\n| `note` | Documentation | Markdown with optional attachments\\u2026</TRUNCATED>\"\n",
- "}\n",
- "```\n",
- "\n",
- "</details>\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "From the solveit docs: when you press `e` on a code message, it sets `is_exported=True` in the message metadata and adds a `#| export` marker. When the dialog is saved, all messages with `is_exported=True` are combined into `{dialog_name}.py` automatically.\n",
- "\n",
- "So some of your code messages have the `is_exported` flag set in their solveit metadata. Since your dialog is named `export`, solveit generates `export.py` in the same folder.\n",
- "\n",
- "To fix it: select the messages that have the export flag on (they'll have a đź”– indicator) and press `e` to toggle it off. That will stop solveit from generating its own `export.py`, and your `export_nb` tool will be the only thing producing Python files."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d20c0005",
- "metadata": {},
- "source": [
- "But will that remove the #| export marker I want in the cell source? I need it for my tool.\n",
- "\n",
- "##### 🤖Reply🤖<!-- SOLVEIT_SEPARATOR_7f3a9b2c -->\n",
- "\n",
- "Good concern. Yes, pressing `e` toggles *both* the `is_exported` metadata flag and the `#| export` text in the source together.\n",
- "\n",
- "But solveit's auto-export is driven by the **metadata flag**, not the source text. So you can keep the `#| export` text (for your tool) and just clear the metadata flag directly. I can do that for you — want me to find the messages with `is_exported` set and clear just the flag, leaving the source untouched?"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "110716b6",
- "metadata": {},
- "source": []
}
],
"metadata": {},