DenSnoychik's picture
Add 2D anime references and Python renderer for Arena
e7b8e7e verified
Raw History Blame Contribute Delete
4.1 kB
"""Inspect isolated actor animation without camera, captions or background effects."""
import json
import math
from pathlib import Path
import runpy
import cairo
import cv2
import numpy as np
WIDTH, HEIGHT = 384, 288
RATE = 12
def validate_motion(items, duration):
if not isinstance(items, list) or not 1 <= len(items) <= 24:
raise ValueError("motion requires 1–24 character beats")
for beat in items:
if not isinstance(beat, dict) or set(beat) != {"actor", "start", "end", "mode", "action"}:
raise ValueError("Motion beat must contain actor, start, end, mode and action")
if not all(isinstance(beat[key], str) and 0 < len(beat[key].strip()) <= 120 for key in ("actor", "action")):
raise ValueError("Motion needs a named actor and a concrete action")
a, b = beat["start"], beat["end"]
if (type(a) not in (int, float) or type(b) not in (int, float)
or not 0 <= a < b <= duration or not .34 <= b - a <= 10
or beat["mode"] not in ("gesture", "continuous")):
raise ValueError("Motion needs a 0.34–10 second interval and gesture or continuous mode")
def snapshot(draw, timestamp):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
context = cairo.Context(surface)
draw(context, timestamp, WIDTH, HEIGHT)
surface.flush()
source = np.ndarray((HEIGHT, WIDTH, 4), dtype=np.uint8, buffer=surface.get_data(),
strides=(surface.get_stride(), 4, 1)).copy()
surface.finish()
return source
def inspect_motion(scene, items, output):
actors = runpy.run_path(scene).get("REVIEW_ACTORS", {})
if not isinstance(actors, dict):
raise ValueError("REVIEW_ACTORS must be a dictionary")
output = Path(output)
output.mkdir(parents=True, exist_ok=True)
findings = []
for idx, beat in enumerate(items, 1):
draw = actors.get(beat["actor"])
if not callable(draw):
raise ValueError(f"Missing REVIEW_ACTORS renderer for {beat['actor']}")
count = math.ceil((beat["end"] - beat["start"]) * RATE) + 1
times = np.linspace(beat["start"], beat["end"], count)
picks = set(np.linspace(0, count - 1, min(count, 6), dtype=int))
previous = None
still = longest = active = 0
strips = []
for n, t in enumerate(times):
current = snapshot(draw, float(t))
mask = current[:, :, 3] > 12
area = int(mask.sum())
if not 80 <= area <= WIDTH * HEIGHT * .82:
raise ValueError(f"{beat['actor']} must draw a readable actor on transparency, frame {n}")
if previous is not None:
union = mask | (previous[:, :, 3] > 12)
changed = np.max(cv2.absdiff(current, previous), axis=2) > 12
moving = bool((changed & union).sum() / union.sum() >= .008)
active += int(moving)
still = 0 if moving else still + 1
longest = max(longest, still)
if n in picks:
alpha = current[:, :, 3:4].astype(np.float32) / 255
preview = np.clip(current[:, :, :3] + (1-alpha) * np.array([76, 53, 32]), 0, 255).astype(np.uint8)
cv2.putText(preview, f"{t:.2f}s", (10, HEIGHT-12), cv2.FONT_HERSHEY_SIMPLEX,
.55, (255,255,255), 1, cv2.LINE_AA)
strips.append(preview)
previous = current
fraction = active / (count-1)
hold = float(longest * (times[1]-times[0]))
passed = active >= 2 if beat["mode"] == "gesture" else fraction >= .35 and hold <= .64
filename = f"actor-{idx:02d}.jpg"
if not cv2.imwrite(str(output / filename), np.hstack(strips)):
raise RuntimeError(f"Cannot write {filename}")
findings.append({**beat, "active_fraction": round(fraction, 3),
"longest_hold_seconds": round(float(hold), 3), "strip": filename, "passed": passed})
return {"passed": all(item["passed"] for item in findings), "beats": findings}