pixme 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pixme/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """pixme: turn a pixel-art avatar into an animated sprite. Action authors use pixme.sdk."""
2
+
3
+ __version__ = "0.2.0"
pixme/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
pixme/check.py ADDED
@@ -0,0 +1,238 @@
1
+ """The machine checks every action must pass (repo plan, section 4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from . import manifest as mf
10
+ from .render import HELPER, ActionError, action_names, build, encode, same_pixels, sprite_for
11
+ from .sdk import Frame, OutsideCanvas, hexstr
12
+
13
+ MIN_MS, MAX_MS = 40, 10_000
14
+ # Pure, deterministic stdlib modules an action may import besides pixme.sdk. No random (use s.random()).
15
+ ALLOWED_IMPORTS = {"pixme.sdk", "math", "itertools", "functools", "collections", "dataclasses", "enum", "typing", "operator", "__future__"}
16
+ # Builtins that reach files, dynamic code or arbitrary attributes. With the dunder rule this is a lint, not a sandbox.
17
+ FORBIDDEN_NAMES = set("__import__ open exec eval compile globals locals vars breakpoint input getattr setattr delattr".split())
18
+
19
+
20
+ @dataclass
21
+ class Result:
22
+ action: str
23
+ check: str
24
+ status: str # "pass", "fail" or "note"
25
+ message: str
26
+
27
+
28
+ def helper_imports(tree: ast.AST) -> set[str]:
29
+ """The shared helpers a file imports: ``_face`` for ``from _face import ...`` (actions/_face.py)."""
30
+ mods = set()
31
+ for node in ast.walk(tree):
32
+ if isinstance(node, ast.Import):
33
+ mods |= {a.name for a in node.names}
34
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
35
+ mods.add(node.module)
36
+ return {m for m in mods if HELPER.match(m)}
37
+
38
+
39
+ def check_imports(path: Path) -> list[str]:
40
+ """Static (ast) check: imports only from ALLOWED_IMPORTS and actions/_*.py helpers, no dynamic-code builtins,
41
+ no dunder attributes. Every helper the file imports, directly or through another helper, is checked the same way."""
42
+ path = Path(path)
43
+ problems, todo, seen = [], [path], {path}
44
+ while todo:
45
+ p = todo.pop(0)
46
+ where = "" if p == path else f"{p.name} "
47
+ try:
48
+ tree = ast.parse(p.read_text(), filename=str(p))
49
+ except SyntaxError as e:
50
+ problems.append(f"{where}syntax error on line {e.lineno}: {e.msg}")
51
+ continue
52
+ problems += [f"{where}{msg}" for msg in _lint(tree)]
53
+ for mod in sorted(helper_imports(tree)):
54
+ helper = path.parent / f"{mod}.py"
55
+ if not helper.is_file():
56
+ problems.append(f"{where}imports {mod}, but there is no actions/{mod}.py")
57
+ elif helper not in seen:
58
+ seen.add(helper)
59
+ todo.append(helper)
60
+ return problems
61
+
62
+
63
+ def _lint(tree: ast.AST) -> list[str]:
64
+ problems = []
65
+ for node in ast.walk(tree):
66
+ if isinstance(node, ast.Import):
67
+ mods = [a.name for a in node.names]
68
+ elif isinstance(node, ast.ImportFrom):
69
+ mod = "." * node.level + (node.module or "")
70
+ mods = [f"{mod}.{a.name}" for a in node.names] if mod == "pixme" else [mod]
71
+ else:
72
+ mods = []
73
+ if isinstance(node, ast.Name) and node.id in FORBIDDEN_NAMES:
74
+ problems.append(f"line {node.lineno}: {node.id}() is not allowed in an action")
75
+ if isinstance(node, ast.Attribute) and node.attr.startswith("__"):
76
+ problems.append(f"line {node.lineno}: dunder attribute {node.attr} is not allowed in an action")
77
+ for mod in mods:
78
+ if mod not in ALLOWED_IMPORTS and not HELPER.match(mod):
79
+ allowed = ", ".join(sorted(ALLOWED_IMPORTS - {"pixme.sdk"}))
80
+ problems.append(f"line {node.lineno}: imports {mod}; may import only pixme.sdk, {allowed} and actions/_*.py helpers")
81
+ return problems
82
+
83
+
84
+ def _diff(a: Frame, b: Frame) -> list[tuple[int, int]]:
85
+ return [(x, y) for y in range(a.height) for x in range(a.width) if a[x, y] != b[x, y]]
86
+
87
+
88
+ def check_action(root: Path, m: dict, name: str) -> list[Result]:
89
+ def r(check, status, message):
90
+ return Result(name, check, status, message)
91
+
92
+ problems = check_imports(root / "actions" / f"{name}.py")
93
+ if problems:
94
+ return [r("imports", "fail", p) for p in problems]
95
+ out = [r("imports", "pass", "only pixme.sdk, allowed stdlib and actions/_*.py helpers")]
96
+ try:
97
+ a = build(root, m, name)
98
+ except OutsideCanvas as e:
99
+ return out + [r("canvas", "fail", str(e))]
100
+ except ActionError as e:
101
+ return out + [r("build", "fail", str(e))]
102
+ except Exception as e: # the action's own bug: report it, keep checking the others
103
+ return out + [r("build", "fail", f"build(s) raised {type(e).__name__}: {e}")]
104
+
105
+ s = sprite_for(root, m, name)
106
+ base, frames = s.base, [f for f, _ in a.frames]
107
+
108
+ bad_ms = [(i, ms) for i, (_, ms) in enumerate(a.frames) if not isinstance(ms, int) or not MIN_MS <= ms <= MAX_MS]
109
+ out.append(
110
+ r("timing", "fail", "; ".join(f"frame {i}: {ms!r} ms is outside {MIN_MS}..{MAX_MS}" for i, ms in bad_ms[:5]))
111
+ if bad_ms
112
+ else r("timing", "pass", f"{len(frames)} frames, {sum(ms for _, ms in a.frames)} ms")
113
+ )
114
+
115
+ wrong = [(i, f.width, f.height) for i, f in enumerate(frames) if (f.width, f.height) != (base.width, base.height)]
116
+ if wrong:
117
+ i, w, h = wrong[0]
118
+ out.append(r("canvas", "fail", f"frame {i} is {w}x{h}; the base is {base.width}x{base.height}"))
119
+ return out # the pixel checks below assume one size
120
+ vis = s.hints.get("visible")
121
+ if vis:
122
+ # Effect pixels (a colour the base does not have: accents, new colours) must stay inside the visible box.
123
+ # Sprite colours may go anywhere, so a moved body or a hop is fine.
124
+ vx, vy, vw, vh = vis
125
+ sprite_colors = base.colors()
126
+ for i, f in enumerate(frames):
127
+ stray = [
128
+ (x, y)
129
+ for y in range(f.height)
130
+ for x in range(f.width)
131
+ if f[x, y][3] and f[x, y] not in sprite_colors and not (vx <= x < vx + vw and vy <= y < vy + vh)
132
+ ]
133
+ if stray:
134
+ c = hexstr(f[stray[0]])
135
+ msg = f"frame {i}: effect pixel {c} at {stray[0]} is outside the visible box {vis} ({len(stray)} such pixels)"
136
+ out.append(r("canvas", "fail", msg))
137
+ break
138
+ else:
139
+ out.append(r("canvas", "pass", f"inside the canvas; effects inside the visible box {vis}"))
140
+ else:
141
+ out.append(r("canvas", "pass", "inside the canvas"))
142
+
143
+ allowed = set(s.palette) | set(s.accents)
144
+ foreign = {}
145
+ for i, f in enumerate(frames):
146
+ for y in range(f.height):
147
+ for x in range(f.width):
148
+ c = f[x, y]
149
+ if c[3] and c not in allowed and c not in foreign:
150
+ foreign[c] = (i, x, y)
151
+ if foreign:
152
+ msg = ", ".join(f"{hexstr(c)} (frame {i} at {x},{y})" for c, (i, x, y) in list(foreign.items())[:5])
153
+ out.append(r("palette", "fail", f"{len(foreign)} colour(s) not in the palette or accents: {msg}"))
154
+ else:
155
+ out.append(r("palette", "pass", f"{len(allowed)} allowed colours"))
156
+
157
+ if not a.loop:
158
+ start, start_name = base, "the base"
159
+ if a.after: # starts from another action's pose: its last frame
160
+ start_name = f"the last frame of {a.after}"
161
+ try:
162
+ start = build(root, m, a.after).frames[-1][0]
163
+ except Exception as e: # a missing file, or that action's own bug
164
+ start = None
165
+ out.append(r("ends", "fail", f"after={a.after!r}, but that action does not build: {type(e).__name__}: {e}"))
166
+ for which, f, want, want_name in (("first", frames[0], start, start_name), ("last", frames[-1], base, "the base")):
167
+ d = _diff(f, want) if want is not None else []
168
+ if d:
169
+ out.append(r("ends", "fail", f"one-shot: the {which} frame is not {want_name} ({len(d)} pixels differ, first at {d[0]})"))
170
+ if not any(x.check == "ends" for x in out):
171
+ out.append(r("ends", "pass", f"starts on {start_name} and ends on the base"))
172
+ elif len(frames) > 1:
173
+ steps = [len(_diff(frames[i], frames[i + 1])) for i in range(len(frames) - 1)]
174
+ seam = len(_diff(frames[-1], frames[0]))
175
+ if seam == 0:
176
+ hold = a.frames[-1][1] + a.frames[0][1]
177
+ out.append(r("loop", "note", f"the last frame equals the first: only the timing joins (that pose holds {hold} ms at the seam)"))
178
+ elif seam <= max(steps):
179
+ out.append(r("loop", "pass", f"last -> first changes {seam} px (largest step inside: {max(steps)} px)"))
180
+ else:
181
+ out.append(
182
+ r("loop", "fail", f"last -> first changes {seam} px, more than any step inside the loop ({max(steps)} px): it jumps")
183
+ )
184
+
185
+ first = encode(a)
186
+ again = encode(build(root, m, name))
187
+ out.append(
188
+ r("determinism", "pass", "two renders give identical bytes")
189
+ if first == again
190
+ else r("determinism", "fail", "two renders differ: use s.random(), not time, dict order of sets or global state")
191
+ )
192
+
193
+ entry = m["actions"].get(name)
194
+ if entry is None:
195
+ out.append(r("built", "note", "not rendered yet (run pixme render)"))
196
+ else:
197
+ pngs, order = first
198
+ expect = [[f"frames/{name}/{i:02d}.png", ms] for i, ms in order]
199
+ disk_ok = (
200
+ entry["frames"] == expect
201
+ and entry["loop"] == a.loop
202
+ and all(same_pixels(root / f"frames/{name}/{i:02d}.png", png) for i, png in enumerate(pngs))
203
+ )
204
+ out.append(
205
+ r("built", "pass", "frames on disk match the source")
206
+ if disk_ok
207
+ else r("built", "fail", "frames on disk are stale: run pixme render")
208
+ )
209
+ return out
210
+
211
+
212
+ def check_hints(base: Frame, hints: dict) -> list[Result]:
213
+ """A NOTE when ``hints.head`` misses opaque pixels above the top of ``hints.neck``: a moved head leaves them behind."""
214
+ if "head" not in hints or "neck" not in hints:
215
+ return []
216
+ boxes = hints["head"] if isinstance(hints["head"][0], list) else [hints["head"]]
217
+ missed = [
218
+ (x, y)
219
+ for y in range(min(hints["neck"][1], base.height))
220
+ for x in range(base.width)
221
+ if base[x, y][3] and not any(bx <= x < bx + bw and by <= y < by + bh for bx, by, bw, bh in boxes)
222
+ ]
223
+ if not missed:
224
+ return []
225
+ msg = f"hints.head misses {len(missed)} opaque pixel(s) above the neck (row {hints['neck'][1]}), first at {missed[0]}"
226
+ return [Result("sprite.json", "hints", "note", msg + ": they stay behind when the head moves")]
227
+
228
+
229
+ def check(root: Path, names: list[str] | None = None) -> list[Result]:
230
+ m = mf.load(root / "sprite.json")
231
+ available = action_names(root)
232
+ results = check_hints(Frame.open(root / m["base"]), m.get("hints", {}))
233
+ for n in names or available:
234
+ if n not in available:
235
+ results.append(Result(n, "source", "fail", f"no actions/{n}.py"))
236
+ else:
237
+ results += check_action(root, m, n)
238
+ return results
pixme/cli.py ADDED
@@ -0,0 +1,167 @@
1
+ """pixme: picture -> sprite -> animated actions. Run `pixme <command> -h` for each command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import __version__
10
+ from . import manifest as mf
11
+ from .render import ActionError
12
+
13
+
14
+ def _offset(text: str) -> tuple[float, float]:
15
+ parts = [float(p) for p in text.split(",")]
16
+ if len(parts) not in (1, 2):
17
+ raise argparse.ArgumentTypeError("use N or X,Y")
18
+ return (parts[0], parts[-1])
19
+
20
+
21
+ def cmd_init(args) -> int:
22
+ from .grid import near_pairs, picture_to_base
23
+
24
+ out = Path(args.out)
25
+ if (out / "sprite.json").exists() and not args.force:
26
+ print(f"{out / 'sprite.json'} exists; use --force to replace it", file=sys.stderr)
27
+ return 1
28
+ base, (cell, ox, oy, merge) = picture_to_base(args.picture, args.cell, args.offset, args.merge, args.bg_tolerance, args.raise_by)
29
+ out.mkdir(parents=True, exist_ok=True)
30
+ (out / "actions").mkdir(exist_ok=True)
31
+ (out / "base.png").write_bytes(base.png())
32
+ mf.save(out / "sprite.json", mf.new(base.width, base.height))
33
+ how = "given" if args.cell else "detected"
34
+ colours = base.colors()
35
+ native = " (native size)" if cell == 1 and not args.cell else ""
36
+ print(
37
+ f"grid {how}: cell {cell:g} px{native}, offset {ox:g},{oy:g} -> {base.width}x{base.height}, {len(colours)} colours, merge {merge}"
38
+ )
39
+ near = near_pairs(colours, merge)
40
+ if merge and near > len(colours) / 2:
41
+ print(f"hint: {near} colour pairs are still closer than --merge {merge}: if noisy, try --merge {merge + 10}")
42
+ top, bottom, left, right = base._span()
43
+ if bottom >= 0:
44
+ print(f"opaque pixels: x {left}..{right}, y {top}..{bottom} (box [{left}, {top}, {right - left + 1}, {bottom - top + 1}])")
45
+ print(f"wrote {out / 'base.png'} and {out / 'sprite.json'}")
46
+ return 0
47
+
48
+
49
+ def cmd_render(args) -> int:
50
+ from .render import render
51
+
52
+ for name in render(Path(args.dir), args.actions or None):
53
+ print(f"rendered {name}")
54
+ return 0
55
+
56
+
57
+ def cmd_check(args) -> int:
58
+ from .check import check
59
+
60
+ results = check(Path(args.dir), args.actions or None)
61
+ for r in results:
62
+ print(f"{r.status.upper():5} {r.action:16} {r.check:12} {r.message}")
63
+ fails = sum(r.status == "fail" for r in results)
64
+ actions = len({r.action for r in results if r.check != "hints"})
65
+ print(f"\n{actions} action(s), {fails} failure(s)")
66
+ return 1 if fails else 0
67
+
68
+
69
+ def cmd_sheet(args) -> int:
70
+ from .look import sheet, sheet_base
71
+
72
+ root = Path(args.dir)
73
+ if args.base:
74
+ print(sheet_base(root, args.scale, args.small))
75
+ return 0
76
+ for name in args.actions or list(mf.load(root / "sprite.json")["actions"]):
77
+ print(sheet(root, name, args.scale, args.small))
78
+ return 0
79
+
80
+
81
+ def cmd_preview(args) -> int:
82
+ from .look import preview
83
+
84
+ print(preview(Path(args.dir)))
85
+ return 0
86
+
87
+
88
+ def cmd_map(args) -> int:
89
+ from .look import char_map
90
+ from .sdk import Frame
91
+
92
+ if len(args.rows) not in (0, 2):
93
+ raise ValueError("give two rows, Y0 Y1, or none for every row")
94
+ root = Path(args.dir)
95
+ print(char_map(Frame.open(root / mf.load(root / "sprite.json")["base"]), *args.rows))
96
+ return 0
97
+
98
+
99
+ def cmd_export(args) -> int:
100
+ from .export import export
101
+
102
+ out = Path(args.out) if args.out else None
103
+ for line in export(Path(args.dir), args.target, args.actions or None, out, args.scale, args.bg, args.hold, args.max_kb):
104
+ print(line)
105
+ return 0
106
+
107
+
108
+ def main(argv: list[str] | None = None) -> int:
109
+ p = argparse.ArgumentParser(prog="pixme", description=__doc__)
110
+ p.add_argument("--version", action="version", version=f"pixme {__version__}")
111
+ sub = p.add_subparsers(dest="command", required=True)
112
+
113
+ s = sub.add_parser("init", help="picture -> base.png + sprite.json")
114
+ s.add_argument("picture")
115
+ s.add_argument("--cell", type=float, help="cell size in picture pixels (default: detect; 1 if the picture is already native size)")
116
+ s.add_argument("--offset", type=_offset, help="where the grid starts: N or X,Y (default: detect, or 0 with --cell)")
117
+ s.add_argument("--raise", dest="raise_by", type=int, default=0, metavar="N", help="move the sprite up N rows, repeating the bottom row")
118
+ s.add_argument("--merge", type=int, help="merge colours closer than this, sum of RGB differences (default: 0 on a clean grid, else 25)")
119
+ s.add_argument("--bg-tolerance", type=int, default=40, help="how far from the corner colour still counts as background (default 40)")
120
+ s.add_argument("--out", default=".", help="sprite folder to write (default: here)")
121
+ s.add_argument("--force", action="store_true", help="replace an existing sprite.json")
122
+ s.set_defaults(fn=cmd_init)
123
+
124
+ for name, fn, text in (
125
+ ("render", cmd_render, "run actions/*.py, write frames/ and update sprite.json"),
126
+ ("check", cmd_check, "the machine checks; exit 1 on any failure"),
127
+ ("sheet", cmd_sheet, "sheets/<action>.png: every frame big, plus a strip at small size"),
128
+ ):
129
+ s = sub.add_parser(name, help=text)
130
+ s.add_argument("actions", nargs="*", metavar="ACTION", help="default: all")
131
+ s.add_argument("--dir", default=".", help="sprite folder (default: here)")
132
+ if name == "sheet":
133
+ s.add_argument("--base", action="store_true", help="sheets/_base.png: the base alone, to judge init")
134
+ s.add_argument("--scale", type=int, default=6, help="zoom for the big frames (default 6)")
135
+ s.add_argument("--small", type=int, default=32, help="size of the small strip in px (default 32)")
136
+ s.set_defaults(fn=fn)
137
+
138
+ s = sub.add_parser("preview", help="preview.html that plays every action at its real timing")
139
+ s.add_argument("--dir", default=".", help="sprite folder (default: here)")
140
+ s.set_defaults(fn=cmd_preview)
141
+
142
+ s = sub.add_parser("map", help="print the base as text: one letter per colour, with row and column numbers")
143
+ s.add_argument("rows", nargs="*", type=int, metavar="Y", help="Y0 Y1: only rows Y0 .. Y1-1 (default: all rows)")
144
+ s.add_argument("--dir", default=".", help="sprite folder (default: here)")
145
+ s.set_defaults(fn=cmd_map)
146
+
147
+ s = sub.add_parser("export", help="ready-to-use files: gif, slack, discord, sheet, apng")
148
+ s.add_argument("target", choices=("gif", "slack", "discord", "sheet", "apng"))
149
+ s.add_argument("actions", nargs="*", metavar="ACTION", help="default: all")
150
+ s.add_argument("--dir", default=".", help="sprite folder (default: here)")
151
+ s.add_argument("--out", help="folder to write (default: <dir>/export/<target>)")
152
+ s.add_argument("--scale", type=int, help="whole-number zoom (default 4; sheet 1; slack and discord fit 128 px)")
153
+ s.add_argument("--bg", help="solid #RRGGBB background for GIFs (default: transparent)")
154
+ s.add_argument("--hold", type=int, default=1200, help="ms a one-shot rests on its last frame before it loops (default 1200)")
155
+ s.add_argument("--max-kb", type=int, help="size budget in KiB (default: slack 128, discord 256, gif none)")
156
+ s.set_defaults(fn=cmd_export)
157
+
158
+ args = p.parse_args(argv)
159
+ try:
160
+ return args.fn(args)
161
+ except (ValueError, FileNotFoundError, ActionError) as e: # an action's own exception keeps its traceback
162
+ print(f"pixme {args.command}: {e}", file=sys.stderr)
163
+ return 1
164
+
165
+
166
+ if __name__ == "__main__":
167
+ sys.exit(main())