Manual Reference

On this page
  1. Importing
  2. Functions
  3. animate_image
  4. check_quality
  5. export_font
  6. export_sprites
  7. generate_fx
  8. generate_lighting_maps
  9. generate_tile_image
  10. generate_ui
  11. import_to_project
  12. init_project
  13. lint_image
  14. make_draft_from_image
  15. make_draft_image
  16. palette_ramps
  17. pixelize_image
  18. pixelize_render
  19. ramp
  20. read_aseprite
  21. recolor_sprites
  22. scaffold_project
  23. write_aseprite
  24. Exceptions
  25. Mode8Project
  26. See also

Python API

The stable names in mode8.__all__ with their signatures, plus the exception classes and Mode8Project.

Everything the CLI does is also a plain Python call. The names on this page (mode8.__all__) are the stable v1 API: their names, keyword names and defaults only change in a major release. Anything not listed here (other modules, names starting with _) is internal.

Note

This page is generated from mode8.__all__ via inspect by docs/manual/_tools/gen_reference.py. To change it, change Mode 8 (or the prose in the generator) and run the generator with --write; a test fails when this page is out of date.

Importing#

import mode8 is light: each name loads its submodule (and NumPy / Pillow) the first time you use it, and none of them import the optional mcp / starlette / uvicorn extras.

python
import mode8

report = mode8.export_sprites(["frames/hero_idle.png", "frames/hero_walk_0.png"], "out", name="hero")
print(report["files"])

Keyword names and defaults are part of the contract; positional order is only guaranteed up to the first optional parameter, so pass optional arguments by keyword. Functions that write files return a JSON-friendly report dict, like the reports the CLI prints but without the ok key, which only the CLI, MCP and Studio add. The in-memory helpers (animate_image, generate_tile_image, lint_image, pixelize_image, check_quality) work on Pillow images. Errors are raised as the exceptions below instead of being printed as an envelope.

mode8.__version__ is the release version string (1.0.0).

Functions#

FunctionModuleSummary
animate_imagemode8.animSynthesize pixel-locked frames in memory and return (frames, rig_meta).
check_qualitymode8.qualityRun the advisory quality rules on im and return {pass, score, issues, metrics, ...}.
export_fontmode8.fontExport the built-in pixel font as an AngelCode BMFont text .fnt + atlas .png + .json.
export_spritesmode8.exportLoad frame PNGs and emit engine-ready exports; returns a JSON-friendly report.
generate_fxmode8.fxWrite every frame of each effect in kinds to out_dir and return a JSON-friendly report.
generate_lighting_mapsmode8.mapsWrite <stem>_n.png (normal map) and <stem>_e.png (emission mask) for every input PNG.
generate_tile_imagemode8.tileSynthesize a tile/prop in memory and return (primary_image, extra_frames, meta).
generate_uimode8.uiGenerate UI kit pieces, 9-slice metadata JSON, Godot StyleBoxTexture + Theme .tres files, and optional contact sheet.
import_to_projectmode8.importerImport an Aseprite file, a directory of PNG frames, or a PNG sprite sheet as a project asset.
init_projectmode8.projectCreate (or complete) a project directory; never overwrites an existing config.
lint_imagemode8.lintRun pixel-art checks on an in-memory image and return a JSON-friendly report.
make_draft_from_imagemode8.draftsTurn a concept render into a draft of size: key the background, crop to the subject, area-reduce into the canvas (aspect kept, 1px transparent border, subject standing on the last row inside it) and quantize to colors OKLab clusters (default 16) or to palette.
make_draft_imagemode8.draftsReturn a shaded pose blockout (RGBA, binary alpha) colored from palette_path's material ramps.
palette_rampsmode8.rampsEvery ramp of a palette: its #ramp declarations, else the ramps derive_ramps finds.
pixelize_imagemode8.pixelizeIn-memory core: downsample, key background BEFORE palette quantization, return binary-alpha RGBA.
pixelize_rendermode8.pixelizePixelize a diffusion render on its own pixel grid and reduce it to exactly size.
rampmode8.rampsA dark → light ramp of n colors for material on palette.
read_asepritemode8.asepriteRead an .ase / .aseprite file into composited RGBA frames plus document metadata.
recolor_spritesmode8.recolorRecolor one PNG, a directory of PNGs, or a list of PNGs into out_dir; return a JSON report.
scaffold_projectmode8.startersCreate (or complete) a Mode 8 project at project_root from a genre starter template.
write_asepritemode8.asepriteWrite named frames to a valid .aseprite file and return a JSON-friendly report.

animate_image#

python
animate_image(master, rig, facing=None, rig_spec=None, frames=None, *, archetype=None)

Synthesize pixel-locked frames in memory and return (frames, rig_meta).

Defined in mode8.anim.

check_quality#

python
check_quality(
    im,
    palette=None,
    rules=None,
    max_orphan_ratio=0.1,
    max_jaggy_kinks=None,
    max_flat_orphan_ratio=0.005,
)

Run the advisory quality rules on im and return {pass, score, issues, metrics, ...}.

Defined in mode8.quality.

export_font#

python
export_font(
    out_dir,
    name='font',
    color=(255, 255, 255),
    outline=None,
    shadow=None,
    scale=1,
    formats=('png', 'fnt', 'json'),
    mono=False,
    charset='latin1',
    kern=True,
)

Export the built-in pixel font as an AngelCode BMFont text .fnt + atlas .png + .json.

Defined in mode8.font.

export_sprites#

python
export_sprites(
    inputs,
    out_dir,
    name='sprite',
    formats=None,
    fps=8,
    gif_scale=4,
    godot_res_prefix=None,
    animations=None,
    padding=1,
    parts=None,
    parts_legend=None,
    facing=None,
    bevel='auto',
    levels=8,
    emissive='auto',
    strength=2.0,
    master=None,
    emissive_min_chroma=0.13,
    emissive_min_lightness=0.58,
    emissive_exclude=None,
    palette=None,
    engine_options=None,
    *,
    gif_transparent=False,
    scene_kind='auto',
    actor_script=True,
    relief=2.0,
    extrude=0,
    power_of_two=False,
    box_overrides=None,
)

Load frame PNGs and emit engine-ready exports; returns a JSON-friendly report.

Defined in mode8.export.

generate_fx#

python
generate_fx(
    kinds,
    out_dir,
    source=None,
    palette=None,
    frame_count=None,
    size=None,
    seed=0,
    prefix=None,
    sheet=None,
    sheet_cols=12,
    outline='ramp',
    timing=True,
)

Write every frame of each effect in kinds to out_dir and return a JSON-friendly report.

Defined in mode8.fx.

generate_lighting_maps#

python
generate_lighting_maps(
    inputs,
    out_dir,
    parts=None,
    bevel='auto',
    strength=2.0,
    levels=8,
    emissive='auto',
    name=None,
    emissive_min_chroma=0.13,
    emissive_min_lightness=0.58,
    emissive_exclude=None,
    relief=2.0,
)

Write <stem>_n.png (normal map) and <stem>_e.png (emission mask) for every input PNG.

Defined in mode8.maps.

generate_tile_image#

python
generate_tile_image(
    kind,
    palette=None,
    size=None,
    source=None,
    variant=0,
    outline='dark',
)

Synthesize a tile/prop in memory and return (primary_image, extra_frames, meta).

Defined in mode8.tile.

generate_ui#

python
generate_ui(
    kinds,
    out_dir,
    palette=None,
    style='bevel',
    name='ui',
    formats=('png', 'json', 'godot'),
    godot_res_prefix=None,
    source=None,
    margins=None,
    sheet=None,
    size=None,
    font='builtin',
    materials=None,
    studs=False,
    preview=None,
    preview_scale=3,
    outline_black=False,
)

Generate UI kit pieces, 9-slice metadata JSON, Godot StyleBoxTexture + Theme .tres files, and optional contact sheet.

Defined in mode8.ui.

import_to_project#

python
import_to_project(
    source,
    project_root,
    name,
    cell_size=None,
    cols=None,
    rows=None,
    margin=0,
    spacing=0,
    keep_empty=False,
    frame_names=None,
    palette=None,
    master_frame=None,
    fps=8,
    art_type=None,
    actor='cli',
    layers='flatten',
)

Import an Aseprite file, a directory of PNG frames, or a PNG sprite sheet as a project asset.

Defined in mode8.importer.

init_project#

python
init_project(
    project_root,
    name=None,
    default_palette='nes_crimson_hero',
    default_size=(64, 72),
    comfy_url='http://127.0.0.1:8188',
)

Create (or complete) a project directory; never overwrites an existing config.

Defined in mode8.project.

lint_image#

python
lint_image(
    im,
    size=None,
    palette=None,
    draft=None,
    min_iou=None,
    max_colors=None,
    allow_outline_black=True,
    check_interior_black=False,
    file_label='<memory>',
    key_color=None,
    check_key_fringe=False,
    *,
    art_type=None,
    reference=None,
    palette_fit=None,
    dither_ok=False,
    min_pose_match=None,
    transparent=None,
    key_measured=None,
    tileable=False,
    reduction=None,
    refined=False,
    grid_reliable=None,
)

Run pixel-art checks on an in-memory image and return a JSON-friendly report.

Defined in mode8.lint.

make_draft_from_image#

python
make_draft_from_image(image, size, palette=None, colors=None, key_color=None)

Turn a concept render into a draft of size: key the background, crop to the subject, area-reduce into the canvas (aspect kept, 1px transparent border, subject standing on the last row inside it) and quantize to colors OKLab clusters (default 16) or to palette.

Defined in mode8.drafts.

make_draft_image#

python
make_draft_image(archetype, palette_path=None, size=None, pose=None)

Return a shaded pose blockout (RGBA, binary alpha) colored from palette_path's material ramps.

Defined in mode8.drafts.

palette_ramps#

python
palette_ramps(palette)

Every ramp of a palette: its #ramp declarations, else the ramps derive_ramps finds.

Defined in mode8.ramps.

pixelize_image#

python
pixelize_image(
    im,
    size=None,
    block=None,
    palette=None,
    colors=None,
    key_color=None,
    key_tol=55,
    bg=None,
    metric='redmean',
    dither='none',
    despill=False,
)

In-memory core: downsample, key background BEFORE palette quantization, return binary-alpha RGBA.

Defined in mode8.pixelize.

pixelize_render#

python
pixelize_render(
    raw,
    size,
    *,
    fit='canvas',
    region=None,
    anchor='center',
    transparent=False,
    key_color=None,
    palette=None,
    colors=16,
    metric='oklab',
    dither='none',
    despill=True,
    outline='none',
    remove_shadow=True,
    crop_frame=None,
    margin=1,
    return_reference=False,
    grid_snap=False,
)

Pixelize a diffusion render on its own pixel grid and reduce it to exactly size.

Defined in mode8.pixelize.

ramp#

python
ramp(palette, material, n=None)

A dark → light ramp of n colors for material on palette.

Defined in mode8.ramps.

read_aseprite#

python
read_aseprite(path)

Read an .ase / .aseprite file into composited RGBA frames plus document metadata.

Defined in mode8.aseprite.

recolor_sprites#

python
recolor_sprites(
    inputs,
    out_dir,
    source_palette=None,
    target_palette=None,
    color_map=None,
    name=None,
)

Recolor one PNG, a directory of PNGs, or a list of PNGs into out_dir; return a JSON report.

Defined in mode8.recolor.

scaffold_project#

python
scaffold_project(project_root, template, name=None, force=False, *, actor='cli')

Create (or complete) a Mode 8 project at project_root from a genre starter template.

Defined in mode8.starters.

write_aseprite#

python
write_aseprite(
    out_path,
    frames,
    fps=8,
    animations=None,
    palette=None,
    layers=None,
    color_depth=32,
    base_layer_name='sprite',
    compress=True,
    base_layer=None,
)

Write named frames to a valid .aseprite file and return a JSON-friendly report.

Defined in mode8.aseprite.

Exceptions#

All of them are importable from mode8 and mode8.errors. The CLI, MCP and Studio turn them into the error envelope (error.type is the class name), so catching them in Python is the same as branching on error.type elsewhere.

ClassBaseMeaningEnvelope extras
AssetExistsErrorInputErrorCreating/importing an asset whose name is already taken (extras asset, path; CLI exit 2, HTTP 409).asset, path (the project-relative asset directory)
ConflictErrorExceptionOptimistic-concurrency failure: the file changed since the caller read it.conflict, path, expected_sha256, actual_sha256
InputErrorValueErrorAn invalid user-supplied value. extra keyword fields are reported inside error.param (the offending parameter, when known), suggestions (close matches for a mistyped name, flag or choice, best first), hint (what to do next, one sentence), fields (Studio: the unknown request-body field names), any keyword extras, e.g. path, conflicts for a mode8 init config conflict
LayeredAssetErrorValueErrorA flat-master write was attempted on an asset that has a layer stack.layered, asset, layer_count, hint (MCP only: how to proceed)
NotFoundErrorInputErrorA file, directory, project, asset, layer or job the caller named does not exist (CLI exit 2, HTTP 404).path (a missing file / directory) or asset / layer_id / job_id
NothingToRedoErrorInputErrorredo with nothing left to redo on the asset (extras asset, can_undo, can_redo).asset, can_undo, can_redo
NothingToUndoErrorInputErrorundo with nothing left to undo on the asset (extras asset, can_undo, can_redo).asset, can_undo, can_redo
ProjectVersionErrorValueErrormode8.toml declares a project format this Mode 8 cannot read (newer or invalid version).path, project_version, supported_version

AssetExistsError is also a Python FileExistsError, so an older except FileExistsError still catches it. InputError and its subclasses keep their extras in .extra (a dict). ConflictError has .path, .expected_sha256 and .actual_sha256; LayeredAssetError has .asset and .layer_count; ProjectVersionError has .path, .project_version and .supported_version.

python
import mode8

try:
    mode8.export_sprites(["missing.png"], "out", name="hero")
except mode8.InputError as exc:  # NotFoundError is an InputError too
    print(type(exc).__name__, exc)

It prints:

text
NotFoundError input file(s) not found: missing.png

Mode8Project#

Mode8Project(root) opens a project directory (one with mode8.toml) and is what the CLI, MCP server and Studio use underneath. Every write is journaled and undoable, and most writes accept expected_sha256 for conflict detection. See Project Format for the files it manages.

MethodSummary
add_layer(name, image=None, layer_name=None, layer_id=None, index=None, visible=True, opacity=255, *, expected_sha256=None, actor='human')Insert a layer (default: blank, on top). A flat asset is promoted in the same entry.
apply_overrides(name, rig_frames)Compose saved overrides over fresh rig frames.
asset_dir(name)
asset_summary(name)One asset's summary row: size, palette, art_type, master_sha256, flags, counts, stale, undo state.
can_redo(name)
can_undo(name)
candidate_dir(job_id)
compact_entry(e)A journal entry as reported by every history surface (no snapshot / patch internals).
create_asset(name, master=None, size=None, palette=None, draft=None, provenance=None, actor='cli')
delete_layer(name, layer_id, *, expected_sha256=None, actor='human')Remove one layer (never the last one) and re-flatten master.png.
duplicate_layer(name, layer_id, *, expected_sha256=None, actor='human')Copy a layer (pixels + visibility + opacity) to just above itself.
flatten_asset_layers(name, *, expected_sha256=None, actor='human')Drop the layer stack, keeping master.png (= its flattened composite).
get_asset(name)
get_layers(name)Layer stack bottom → top (each with its PNG sha256), or None if not layered.
history(name=None, limit=50)Journal entries (oldest first), optionally filtered to the asset name; last limit.
history_report(name, limit=20){asset, count, entries, can_undo, can_redo}: the last limit (1..500) journal entries of name (oldest first), the shape of MCP mode8_project_history and Studio GET .../history.
init_layers(name, base_name='Base', *, expected_sha256=None, actor='human')Promote the flat master.png into a one-layer stack (layer id base).
is_frames_stale(name)True if frames exist but were generated from different master/rig/parts.
list_assets()
load_config()
merge_layer_down(name, layer_id, *, expected_sha256=None, actor='human')Composite layer_id onto the layer directly below it and remove it.
record_frames_generated(name, frames, rig_name=None, actor='cli')Write derived frames/*.png (overrides composed in) and record input hashes.
redo(name, actor='human')Re-apply the most recently undone operation on the asset name.
rel(path)
reorder_layers(name, order, *, expected_sha256=None, actor='human')Reorder the stack; order (bottom → top) must be a permutation of the layer ids.
resolve_path(rel_path)Resolve a project-relative path, refusing anything that escapes the root.
save_config(cfg)
save_layer(name, layer_id, image, expected_layer_sha256=None, update_pins=False, *, expected_sha256=None, actor='human', op='layer_edit')Replace one layer's pixels and re-flatten master.png (optionally OR-ing pins).
save_layer_stack(name, layers, images, expected_sha256=None, actor='human')Save layers/ (json + pngs) and flatten visible layers into master.png.
save_master(name, image, expected_sha256=None, actor='cli', op='save_master', provenance_patch=None, update_pins=False, on_layers='error')Atomically replace master.png (journaled, snapshot-backed).
save_override(name, frame_name, edited_frame, rig_frame, actor='human')Store the sparse diff between rig_frame and edited_frame.
set_layer_props(name, layer_id, *, layer_name=None, visible=None, opacity=None, expected_sha256=None, actor='human')Rename / show-hide / change opacity of one layer and re-flatten master.png.
snapshot_path(sha, ext='.png')Path of a content-addressed snapshot, or None for an invalid digest.
transform_layers(name, fn, op, *, expected_sha256=None, actor='human', provenance_patch=None)Apply fn to every layer (or to the flat master) and re-flatten, as one entry.
undo(name, actor='human')Revert the most recent not-yet-undone operation on the asset name (any actor's).
wrap_shift(name, dx, dy, *, expected_sha256=None, actor='human')Toroidally shift master, every layer, pins.png and parts.png in one entry.

Read-only properties: history_path, meta_dir, snapshots_dir.

See also#