Skip to content

API reference

cutiepynb

Make Jupyter notebooks colorful and easier to navigate.

create_new_document(document, colors=None, *, add_toc=True, toc_title=TOC_TITLE, heading_edits=None)

Return a styled copy of a notebook dictionary.

The input is never mutated. Markdown headings receive stable, unique anchors and optional colors; code cells and fenced code examples are left untouched. heading_edits maps zero-based heading positions to a new title, a new level from 1 to 6, or both.

Source code in cutiepynb/core.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def create_new_document(
    document: Mapping[str, Any],
    colors: Optional[Sequence[str]] = None,
    *,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
    heading_edits: Optional[HeadingEdits] = None,
) -> Notebook:
    """Return a styled copy of a notebook dictionary.

    The input is never mutated. Markdown headings receive stable, unique
    anchors and optional colors; code cells and fenced code examples are left
    untouched. ``heading_edits`` maps zero-based heading positions to a new
    ``title``, a new ``level`` from 1 to 6, or both.
    """

    if "cells" not in document or not isinstance(document["cells"], list):
        raise ValueError("document must be a notebook dictionary with a 'cells' list")
    if (
        not isinstance(toc_title, str)
        or not toc_title.strip()
        or "\n" in toc_title
        or "\r" in toc_title
    ):
        raise ValueError("toc_title must be a non-empty single line")

    result: Notebook = copy.deepcopy(dict(document))
    info, cells = generate_new_cells(
        result["cells"],
        colors,
        heading_edits=heading_edits,
    )
    if add_toc and info:
        # Cell ids were added to the notebook schema in nbformat 4.5. Adding
        # one to older notebooks makes them invalid, while reusing a fixed id
        # can collide with a user-authored cell in newer notebooks.
        minor_version = result.get("nbformat_minor", 0)
        supports_cell_ids = (
            result.get("nbformat") == 4
            and isinstance(minor_version, int)
            and minor_version >= 5
        )
        cell_id = _unique_toc_cell_id(cells) if supports_cell_ids else None
        cells.insert(
            0,
            generate_contents(
                info,
                title=toc_title.strip(),
                cell_id=cell_id,
            ),
        )
    result["cells"] = cells
    return result

cutiepy_nb(file, sns_palette=None, colors=None, save=True, update_colors=None, *, output_file=None, add_toc=True, toc_title=TOC_TITLE)

Compatibility API for styling a notebook.

The transformed notebook dictionary is always returned. If save is true, it is also written to output_file or to *_chulo.ipynb. This wrapper keeps the original overwrite behavior; new applications should prefer :func:process_notebook for explicit overwrite protection.

Source code in cutiepynb/core.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def cutiepy_nb(
    file: str | Path,
    sns_palette: Optional[str] = None,
    colors: Optional[Sequence[str]] = None,
    save: bool = True,
    update_colors: Optional[Sequence[str]] = None,
    *,
    output_file: str | Path | None = None,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
) -> Notebook:
    """Compatibility API for styling a notebook.

    The transformed notebook dictionary is always returned. If ``save`` is
    true, it is also written to ``output_file`` or to ``*_chulo.ipynb``. This
    wrapper keeps the original overwrite behavior; new applications should
    prefer :func:`process_notebook` for explicit overwrite protection.
    """

    document = enchular_ipynb(
        file,
        sns_palette=sns_palette,
        colors=colors,
        update_colors=update_colors,
        add_toc=add_toc,
        toc_title=toc_title,
    )
    if save:
        save_doc_enchulado(
            document,
            file,
            output_file=output_file,
            overwrite=True,
        )
    return document

enchular_ipynb(file, sns_palette=None, colors=None, update_colors=None, *, add_toc=True, toc_title=TOC_TITLE)

Load and transform a notebook without writing it to disk.

Source code in cutiepynb/core.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def enchular_ipynb(
    file: str | Path,
    sns_palette: Optional[str] = None,
    colors: Optional[Sequence[str]] = None,
    update_colors: Optional[Sequence[str]] = None,
    *,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
) -> Notebook:
    """Load and transform a notebook without writing it to disk."""

    if sns_palette and colors is not None:
        raise ValueError("pass either sns_palette or colors, not both")
    selected_colors = _palette_colors(sns_palette) if sns_palette else colors

    path = Path(file)
    with path.open("r", encoding="utf-8") as stream:
        document = json.load(stream)

    transformed = create_new_document(
        document,
        selected_colors,
        add_toc=add_toc,
        toc_title=toc_title,
    )
    if update_colors is not None:
        transformed = update_heading_colors_in_document(transformed, update_colors)
    return transformed

process_notebook(input_file, output_file=None, *, colors=None, sns_palette=None, add_toc=True, toc_title=TOC_TITLE, overwrite=False)

Transform input_file and save it, returning the output path.

When output_file is omitted, report.ipynb becomes report_chulo.ipynb. Existing output is protected unless overwrite=True is explicitly requested.

Source code in cutiepynb/core.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def process_notebook(
    input_file: str | Path,
    output_file: str | Path | None = None,
    *,
    colors: Optional[Sequence[str]] = None,
    sns_palette: Optional[str] = None,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
    overwrite: bool = False,
) -> Path:
    """Transform ``input_file`` and save it, returning the output path.

    When ``output_file`` is omitted, ``report.ipynb`` becomes
    ``report_chulo.ipynb``. Existing output is protected unless
    ``overwrite=True`` is explicitly requested.
    """

    document = enchular_ipynb(
        input_file,
        sns_palette=sns_palette,
        colors=colors,
        add_toc=add_toc,
        toc_title=toc_title,
    )
    return save_doc_enchulado(
        document,
        input_file,
        output_file=output_file,
        overwrite=overwrite,
    )

update_heading_colors_in_document(document, new_colors)

Return a copy with existing styled heading colors replaced.

Both current cutiepynb markup and spans generated by early releases are supported. The original notebook dictionary is not mutated.

Source code in cutiepynb/styles.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def update_heading_colors_in_document(
    document: Dict[str, Any],
    new_colors: Sequence[str],
) -> Dict[str, Any]:
    """Return a copy with existing styled heading colors replaced.

    Both current cutiepynb markup and spans generated by early releases are
    supported. The original notebook dictionary is not mutated.
    """

    palette = _normalise_colors(new_colors)
    updated_document = copy.deepcopy(document)

    for cell in updated_document.get("cells", []):
        if cell.get("cell_type") != "markdown":
            continue

        original_source = cell.get("source", "")
        lines = _source_as_text(original_source).splitlines(keepends=True)
        updated_lines = []
        for line in lines:
            match = _HEADING_LINE_RE.match(line)
            if not match:
                updated_lines.append(line)
                continue
            level = len(match.group("hashes").lstrip())
            color = palette[(level - 1) % len(palette)]
            updated_lines.append(
                _COLOR_IN_SPAN_RE.sub(
                    lambda color_match, selected=color: (
                        color_match.group("prefix") + selected
                    ),
                    line,
                    count=1,
                )
            )
        text = "".join(updated_lines)
        cell["source"] = _restore_source_type(text, original_source)

    return updated_document

Core helpers

cutiepynb.core

Core notebook transformations for :mod:cutiepynb.

The functions in this module deliberately operate on ordinary dictionaries. That keeps the package lightweight while remaining compatible with notebooks loaded by either :mod:json or :mod:nbformat.

generate_new_cells(cells, colors=None, *, heading_edits=None)

Return decorated cells and the headings used to build a table of contents.

Existing cutiepynb table-of-contents cells are removed, which makes the transformation safe to run more than once.

Source code in cutiepynb/core.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def generate_new_cells(
    cells: Iterable[Mapping[str, Any]],
    colors: Optional[Sequence[str]] = None,
    *,
    heading_edits: Optional[HeadingEdits] = None,
) -> Tuple[HeadingInfo, List[Cell]]:
    """Return decorated cells and the headings used to build a table of contents.

    Existing cutiepynb table-of-contents cells are removed, which makes the
    transformation safe to run more than once.
    """

    palette = _normalise_colors(colors)
    edits = _normalise_heading_edits(heading_edits)
    info: HeadingInfo = {}
    new_cells: List[Cell] = []
    seen_anchors: Dict[str, int] = {}
    heading_counter = [0]

    for cell_index, original_cell in enumerate(cells):
        if not isinstance(original_cell, Mapping):
            raise ValueError(f"cell {cell_index + 1} must be a notebook cell mapping")
        if _is_toc_cell(original_cell):
            continue

        cell = copy.deepcopy(dict(original_cell))
        if cell.get("cell_type") != "markdown":
            new_cells.append(cell)
            continue

        original_source = cell.get("source", "")
        transformed, headings = _decorate_markdown(
            _source_as_text(original_source),
            palette,
            seen_anchors,
            edits,
            heading_counter,
        )
        cell["source"] = _restore_source_type(transformed, original_source)
        new_cells.append(cell)

        for heading in headings:
            info[len(info)] = heading

    unused_edits = sorted(index for index in edits if index >= heading_counter[0])
    if unused_edits:
        index = unused_edits[0]
        raise ValueError(f"heading edit index {index} does not exist")

    return info, new_cells

generate_contents(info_to_add, title=TOC_TITLE, *, cell_id='cutiepynb-toc')

Build the generated table-of-contents markdown cell.

Source code in cutiepynb/core.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def generate_contents(
    info_to_add: Mapping[int, Mapping[str, Any]],
    title: str = TOC_TITLE,
    *,
    cell_id: Optional[str] = "cutiepynb-toc",
) -> Cell:
    """Build the generated table-of-contents markdown cell."""

    source = [f"{TOC_MARKER}\n", f"# {title}\n", "\n"]
    for number in sorted(info_to_add):
        source.append(format_title_index(number, info_to_add))

    cell: Cell = {
        "cell_type": "markdown",
        "metadata": {TOC_METADATA_KEY: {"role": "table-of-contents"}},
        "source": source,
    }
    if cell_id is not None:
        cell["id"] = cell_id
    return cell

create_new_document(document, colors=None, *, add_toc=True, toc_title=TOC_TITLE, heading_edits=None)

Return a styled copy of a notebook dictionary.

The input is never mutated. Markdown headings receive stable, unique anchors and optional colors; code cells and fenced code examples are left untouched. heading_edits maps zero-based heading positions to a new title, a new level from 1 to 6, or both.

Source code in cutiepynb/core.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def create_new_document(
    document: Mapping[str, Any],
    colors: Optional[Sequence[str]] = None,
    *,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
    heading_edits: Optional[HeadingEdits] = None,
) -> Notebook:
    """Return a styled copy of a notebook dictionary.

    The input is never mutated. Markdown headings receive stable, unique
    anchors and optional colors; code cells and fenced code examples are left
    untouched. ``heading_edits`` maps zero-based heading positions to a new
    ``title``, a new ``level`` from 1 to 6, or both.
    """

    if "cells" not in document or not isinstance(document["cells"], list):
        raise ValueError("document must be a notebook dictionary with a 'cells' list")
    if (
        not isinstance(toc_title, str)
        or not toc_title.strip()
        or "\n" in toc_title
        or "\r" in toc_title
    ):
        raise ValueError("toc_title must be a non-empty single line")

    result: Notebook = copy.deepcopy(dict(document))
    info, cells = generate_new_cells(
        result["cells"],
        colors,
        heading_edits=heading_edits,
    )
    if add_toc and info:
        # Cell ids were added to the notebook schema in nbformat 4.5. Adding
        # one to older notebooks makes them invalid, while reusing a fixed id
        # can collide with a user-authored cell in newer notebooks.
        minor_version = result.get("nbformat_minor", 0)
        supports_cell_ids = (
            result.get("nbformat") == 4
            and isinstance(minor_version, int)
            and minor_version >= 5
        )
        cell_id = _unique_toc_cell_id(cells) if supports_cell_ids else None
        cells.insert(
            0,
            generate_contents(
                info,
                title=toc_title.strip(),
                cell_id=cell_id,
            ),
        )
    result["cells"] = cells
    return result

format_title_index(title_numb, titles)

Format one heading as a nested Markdown table-of-contents item.

Source code in cutiepynb/core.py
393
394
395
396
397
398
399
400
401
402
403
def format_title_index(
    title_numb: int,
    titles: Mapping[int, Mapping[str, Any]],
) -> str:
    """Format one heading as a nested Markdown table-of-contents item."""

    title = titles[title_numb]
    level = int(title["level"])
    indentation = "  " * max(level - 1, 0)
    label = str(title["title"]).replace("[", r"\[").replace("]", r"\]")
    return f'{indentation}- [{label}](#{title["anchor"]})\n'

extract_info(source, titles)

Extract headings from markdown source into titles.

This compatibility helper does not modify the source. New code will usually call :func:create_new_document instead.

Source code in cutiepynb/core.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def extract_info(source: Sequence[str], titles: HeadingInfo) -> HeadingInfo:
    """Extract headings from markdown source into ``titles``.

    This compatibility helper does not modify the source. New code will
    usually call :func:`create_new_document` instead.
    """

    seen = {str(item["anchor"]): 1 for item in titles.values()}
    text = _source_as_text(source)
    fence: Optional[str] = None
    for line in text.splitlines():
        fence_match = _FENCE_RE.match(line)
        if fence_match:
            marker = fence_match.group(1)
            fence = None if fence == marker[0] else marker[0]
            continue
        match = _HEADING_RE.match(line) if fence is None else None
        if not match:
            continue
        title = _strip_cutiepynb_markup(match.group("title"))
        if title:
            anchor = _unique_anchor(title, seen)
            titles[len(titles)] = {
                "title": _plain_title(title),
                "level": len(match.group("hashes")),
                "anchor": anchor,
            }
    return titles

create_source_anchor(source, values, colors=None)

Add a cutiepynb anchor and styling to a single heading source.

This function is retained for compatibility with the original public module. It returns notebook-style source lines.

Source code in cutiepynb/core.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
def create_source_anchor(
    source: Sequence[str],
    values: Mapping[str, Any],
    colors: Optional[Sequence[str]] = None,
) -> List[str]:
    """Add a cutiepynb anchor and styling to a single heading source.

    This function is retained for compatibility with the original public
    module. It returns notebook-style source lines.
    """

    del source  # The heading information in ``values`` is authoritative.
    level = int(values["level"])
    title = str(values["title"])
    palette = _normalise_colors(colors)
    formatted = heading_html(title, level, palette) if palette else title
    anchor = str(values["anchor"])
    return [
        f'<a class="cutiepynb-anchor" id="{anchor}"></a>\n',
        f'{"#" * level} {formatted}\n',
    ]

enchular_ipynb(file, sns_palette=None, colors=None, update_colors=None, *, add_toc=True, toc_title=TOC_TITLE)

Load and transform a notebook without writing it to disk.

Source code in cutiepynb/core.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def enchular_ipynb(
    file: str | Path,
    sns_palette: Optional[str] = None,
    colors: Optional[Sequence[str]] = None,
    update_colors: Optional[Sequence[str]] = None,
    *,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
) -> Notebook:
    """Load and transform a notebook without writing it to disk."""

    if sns_palette and colors is not None:
        raise ValueError("pass either sns_palette or colors, not both")
    selected_colors = _palette_colors(sns_palette) if sns_palette else colors

    path = Path(file)
    with path.open("r", encoding="utf-8") as stream:
        document = json.load(stream)

    transformed = create_new_document(
        document,
        selected_colors,
        add_toc=add_toc,
        toc_title=toc_title,
    )
    if update_colors is not None:
        transformed = update_heading_colors_in_document(transformed, update_colors)
    return transformed

process_notebook(input_file, output_file=None, *, colors=None, sns_palette=None, add_toc=True, toc_title=TOC_TITLE, overwrite=False)

Transform input_file and save it, returning the output path.

When output_file is omitted, report.ipynb becomes report_chulo.ipynb. Existing output is protected unless overwrite=True is explicitly requested.

Source code in cutiepynb/core.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def process_notebook(
    input_file: str | Path,
    output_file: str | Path | None = None,
    *,
    colors: Optional[Sequence[str]] = None,
    sns_palette: Optional[str] = None,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
    overwrite: bool = False,
) -> Path:
    """Transform ``input_file`` and save it, returning the output path.

    When ``output_file`` is omitted, ``report.ipynb`` becomes
    ``report_chulo.ipynb``. Existing output is protected unless
    ``overwrite=True`` is explicitly requested.
    """

    document = enchular_ipynb(
        input_file,
        sns_palette=sns_palette,
        colors=colors,
        add_toc=add_toc,
        toc_title=toc_title,
    )
    return save_doc_enchulado(
        document,
        input_file,
        output_file=output_file,
        overwrite=overwrite,
    )

cutiepy_nb(file, sns_palette=None, colors=None, save=True, update_colors=None, *, output_file=None, add_toc=True, toc_title=TOC_TITLE)

Compatibility API for styling a notebook.

The transformed notebook dictionary is always returned. If save is true, it is also written to output_file or to *_chulo.ipynb. This wrapper keeps the original overwrite behavior; new applications should prefer :func:process_notebook for explicit overwrite protection.

Source code in cutiepynb/core.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def cutiepy_nb(
    file: str | Path,
    sns_palette: Optional[str] = None,
    colors: Optional[Sequence[str]] = None,
    save: bool = True,
    update_colors: Optional[Sequence[str]] = None,
    *,
    output_file: str | Path | None = None,
    add_toc: bool = True,
    toc_title: str = TOC_TITLE,
) -> Notebook:
    """Compatibility API for styling a notebook.

    The transformed notebook dictionary is always returned. If ``save`` is
    true, it is also written to ``output_file`` or to ``*_chulo.ipynb``. This
    wrapper keeps the original overwrite behavior; new applications should
    prefer :func:`process_notebook` for explicit overwrite protection.
    """

    document = enchular_ipynb(
        file,
        sns_palette=sns_palette,
        colors=colors,
        update_colors=update_colors,
        add_toc=add_toc,
        toc_title=toc_title,
    )
    if save:
        save_doc_enchulado(
            document,
            file,
            output_file=output_file,
            overwrite=True,
        )
    return document