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.
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#
| Function | Module | Summary |
|---|---|---|
animate_image | mode8.anim | Synthesize pixel-locked frames in memory and return (frames, rig_meta). |
check_quality | mode8.quality | Run the advisory quality rules on im and return {pass, score, issues, metrics, ...}. |
export_font | mode8.font | Export the built-in pixel font as an AngelCode BMFont text .fnt + atlas .png + .json. |
export_sprites | mode8.export | Load frame PNGs and emit engine-ready exports; returns a JSON-friendly report. |
generate_fx | mode8.fx | Write every frame of each effect in kinds to out_dir and return a JSON-friendly report. |
generate_lighting_maps | mode8.maps | Write <stem>_n.png (normal map) and <stem>_e.png (emission mask) for every input PNG. |
generate_tile_image | mode8.tile | Synthesize a tile/prop in memory and return (primary_image, extra_frames, meta). |
generate_ui | mode8.ui | Generate UI kit pieces, 9-slice metadata JSON, Godot StyleBoxTexture + Theme .tres files, and optional contact sheet. |
import_to_project | mode8.importer | Import an Aseprite file, a directory of PNG frames, or a PNG sprite sheet as a project asset. |
init_project | mode8.project | Create (or complete) a project directory; never overwrites an existing config. |
lint_image | mode8.lint | Run pixel-art checks on an in-memory image and return a JSON-friendly report. |
make_draft_from_image | mode8.drafts | 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. |
make_draft_image | mode8.drafts | Return a shaded pose blockout (RGBA, binary alpha) colored from palette_path's material ramps. |
palette_ramps | mode8.ramps | Every ramp of a palette: its #ramp declarations, else the ramps derive_ramps finds. |
pixelize_image | mode8.pixelize | In-memory core: downsample, key background BEFORE palette quantization, return binary-alpha RGBA. |
pixelize_render | mode8.pixelize | Pixelize a diffusion render on its own pixel grid and reduce it to exactly size. |
ramp | mode8.ramps | A dark → light ramp of n colors for material on palette. |
read_aseprite | mode8.aseprite | Read an .ase / .aseprite file into composited RGBA frames plus document metadata. |
recolor_sprites | mode8.recolor | Recolor one PNG, a directory of PNGs, or a list of PNGs into out_dir; return a JSON report. |
scaffold_project | mode8.starters | Create (or complete) a Mode 8 project at project_root from a genre starter template. |
write_aseprite | mode8.aseprite | Write named frames to a valid .aseprite file and return a JSON-friendly report. |
animate_image#
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#
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#
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#
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#
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#
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#
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#
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#
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#
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#
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#
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#
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#
palette_ramps(palette)Every ramp of a palette: its #ramp declarations, else the ramps derive_ramps finds.
Defined in mode8.ramps.
pixelize_image#
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#
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#
ramp(palette, material, n=None)A dark → light ramp of n colors for material on palette.
Defined in mode8.ramps.
read_aseprite#
read_aseprite(path)Read an .ase / .aseprite file into composited RGBA frames plus document metadata.
Defined in mode8.aseprite.
recolor_sprites#
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#
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#
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.
| Class | Base | Meaning | Envelope extras |
|---|---|---|---|
AssetExistsError | InputError | Creating/importing an asset whose name is already taken (extras asset, path; CLI exit 2, HTTP 409). | asset, path (the project-relative asset directory) |
ConflictError | Exception | Optimistic-concurrency failure: the file changed since the caller read it. | conflict, path, expected_sha256, actual_sha256 |
InputError | ValueError | An 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 |
LayeredAssetError | ValueError | A flat-master write was attempted on an asset that has a layer stack. | layered, asset, layer_count, hint (MCP only: how to proceed) |
NotFoundError | InputError | A 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 |
NothingToRedoError | InputError | redo with nothing left to redo on the asset (extras asset, can_undo, can_redo). | asset, can_undo, can_redo |
NothingToUndoError | InputError | undo with nothing left to undo on the asset (extras asset, can_undo, can_redo). | asset, can_undo, can_redo |
ProjectVersionError | ValueError | mode8.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.
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:
NotFoundError input file(s) not found: missing.pngMode8Project#
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.
| Method | Summary |
|---|---|
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#
- CLI Reference: each function backs a CLI command with the same names in kebab-case.
- Output Envelope and Exit Codes for how exceptions become errors.
- Stability and Versioning for what may change in a minor release.