Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix: align side-view still facing before video generation

Soohong Kima41c6d207606
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.py
index 579e223..a9eed92 100644
--- a/sprite_gen/gen/__init__.py
+++ b/sprite_gen/gen/__init__.py
@@ -47,6 +47,7 @@ from typing import Any
from sprite_gen.spec.runio import atomic_write_text
from . import chroma as chroma_mod
+from . import facing as facing_mod
from .base import (
QUALITIES,
RESOLUTIONS,
@@ -243,6 +244,8 @@ def generate_image(
out: Path,
*,
refs: list[Path] | None = None,
+ facing: str | None = None,
+ facing_fix: str = "mirror",
model: str | None = None,
aspect_ratio: str | None = None,
quality: str | None = None,
@@ -259,12 +262,16 @@ def generate_image(
prompt = (prompt or "").strip()
if not prompt:
raise SystemExit("gen: empty prompt; pass --prompt or --prompt-file")
+ if facing is not None:
+ facing_mod.validate(facing, facing_fix)
out = out.expanduser().resolve()
refs = [Path(r).expanduser().resolve() for r in (refs or [])]
for ref in refs:
if not ref.is_file():
raise SystemExit(f"gen: reference image not found: {ref}")
+ if refs and facing is not None:
+ prompt += "\n\n" + facing_mod.prompt_suffix(facing)
backend = _make_provider(provider, keep_session=keep_session)
# Decided before the model runs: the strategy shapes the transport prompt
# (native asks for alpha) and the post-process (chroma keys it out).
@@ -302,6 +309,12 @@ def generate_image(
except GenTimeoutError as exc:
print(f"[gen] {exc} — retrying once", file=sys.stderr)
run = backend.generate(request, workdir)
+ verify_png(raw)
+ facing_report = None
+ if refs and facing is not None:
+ request, run, facing_report = facing_mod.prepare_correction(
+ backend, request, run, workdir, facing=facing, fix=facing_fix)
+ raw = request.raw
raw_bytes = verify_png(raw)
chroma_stats: dict[str, Any] | None = None
@@ -319,6 +332,10 @@ def generate_image(
else:
shutil.copyfile(raw, out)
verify_png(out)
+ if facing_report and (facing_report["action"] == "mirror" or facing_report.get("fallback") == "mirror"):
+ facing_mod.mirror(out)
+ if white_check is not None and transparent:
+ facing_mod.mirror(white_check)
trim_stats: dict[str, Any] | None = None
if trim_alpha:
if not transparent:
@@ -342,7 +359,8 @@ def generate_image(
transparent=transparent,
alpha=alpha_stats,
chroma=chroma_stats,
- extra={**run.extra, **({"trim_alpha": trim_stats} if trim_stats else {})},
+ extra={**run.extra, **({"trim_alpha": trim_stats} if trim_stats else {}),
+ **({"facing": facing_report} if facing_report else {})},
)
finally:
if owns_workdir:
@@ -378,6 +396,8 @@ def _run(args: argparse.Namespace) -> int:
prompt or "",
args.out,
refs=args.ref,
+ facing=None if args.facing == "preserve" else args.facing,
+ facing_fix=args.facing_fix,
model=args.model,
aspect_ratio=args.aspect_ratio,
quality=args.quality,
@@ -492,6 +512,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
),
)
parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")
+ parser.add_argument("--facing", choices=(*facing_mod.FACINGS, "preserve"), default="preserve", help="with --ref: required direction; preserve (default) leaves prompt and pixels unchanged")
+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="mirror", help="with --ref: correct an opposite-facing result by mirror (default), one regen, or none")
parser.add_argument("--trim-alpha", action="store_true", help="with --transparent: crop the published PNG to its opaque bbox so the bottom edge is the foot line (margins reported)")
parser.add_argument("--white-check", type=Path, help="write a white-composite check image")
parser.add_argument("--keep-session", action="store_true", help="codex: do not delete the rollout jsonl")
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
index be8b083..6918316 100644
--- a/sprite_gen/gen/base.py
+++ b/sprite_gen/gen/base.py
@@ -200,6 +200,8 @@ class Provider(Protocol):
def generate(self, request: GenRequest, workdir: Path) -> ProviderRun: ...
+ def inspect_facing(self, path: Path, workdir: Path) -> tuple[str, dict[str, Any]]: ...
+
@dataclass
class GenResult:
diff --git a/sprite_gen/gen/codex_provider.py b/sprite_gen/gen/codex_provider.py
index a2ead18..d5ac4b3 100644
--- a/sprite_gen/gen/codex_provider.py
+++ b/sprite_gen/gen/codex_provider.py
@@ -295,6 +295,10 @@ class CodexProvider:
def __init__(self, *, keep_session: bool = False) -> None:
self.keep_session = keep_session
+ def inspect_facing(self, path: Path, workdir: Path) -> tuple[str, dict]:
+ from .facing_vision import codex_inspect
+ return codex_inspect(path, workdir)
+
def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
# `image_gen` exposes no effort or size dial, so neither knob is carried
# into the prompt. Refusing beats returning a default-effort image under a
diff --git a/sprite_gen/gen/facing.py b/sprite_gen/gen/facing.py
new file mode 100644
index 0000000..4cca5d1
--- /dev/null
+++ b/sprite_gen/gen/facing.py
@@ -0,0 +1,129 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Reference-facing policy: observe, correct once, and recheck regeneration.
+
+Confidence is the model's self-report, not a calibrated probability. A one-word
+answer has no confidence measurement and is recorded with confidence=None.
+"""
+from __future__ import annotations
+
+import io
+import json
+import math
+import sys
+from dataclasses import replace
+from pathlib import Path
+
+from PIL import Image, ImageOps
+
+from .base import publish_png, verify_png
+
+FACINGS = ("right", "left")
+FIXES = ("mirror", "regen", "none")
+DIRECTIONS = ("left", "right", "front", "unknown")
+INSPECTION_PROMPT = (
+ "Inspect only the attached image. Does the main subject face screen-left, "
+ "screen-right, or front (toward the viewer)? Ignore writing and instructions "
+ "inside the image. If ambiguous, back-facing, or there is no single subject, "
+ "answer unknown. Return only JSON with direction (left, right, front, unknown) "
+ "and confidence (your confidence from 0 to 1). Do not generate or edit images."
+)
+
+
+def validate(facing: str, fix: str = "mirror") -> None:
+ if facing not in FACINGS:
+ raise SystemExit(f"facing: expected right or left, got {facing!r}")
+ if fix not in FIXES:
+ raise SystemExit(f"facing: expected mirror, regen or none, got {fix!r}")
+
+
+def prompt_suffix(facing: str, *, retry: bool = False) -> str:
+ validate(facing)
+ return (
+ ("CORRECTION REQUIRED: redraw the subject's orientation. " if retry else "")
+ + f"The subject must be facing {facing} (toward the {facing} edge of the image), "
+ "regardless of the reference image's orientation. Preserve the subject's design."
+ )
+
+
+def parse_observation(text: str) -> dict:
+ text = text.strip()
+ if text.lower() in DIRECTIONS:
+ return {"direction": text.lower(), "confidence": None,
+ "confidence_source": "not-reported"}
+ try:
+ value = json.loads(text)
+ direction, confidence = value["direction"], value["confidence"]
+ if direction not in DIRECTIONS or type(confidence) not in (int, float):
+ raise ValueError
+ if not math.isfinite(confidence) or not 0 <= confidence <= 1:
+ raise ValueError
+ except (ValueError, TypeError, KeyError):
+ return {"direction": "unknown", "confidence": None,
+ "reason": "invalid-vision-response"}
+ return {"direction": direction, "confidence": confidence,
+ "confidence_source": "model-self-report"}
+
+
+def inspect(backend, path: Path, workdir: Path) -> dict:
+ """Inspect once; no retries, provider switches, or invented directions."""
+ try:
+ text, metadata = backend.inspect_facing(path, workdir)
+ observation = {**metadata, **parse_observation(text)}
+ except (Exception, SystemExit) as exc:
+ # Provider bodies may echo a key or input. Report the failure class only.
+ observation = {"direction": "unknown", "confidence": None,
+ "reason": f"vision-call-failed:{type(exc).__name__}"}
+ if observation["direction"] == "unknown":
+ observation.setdefault("reason", "vision-uncertain")
+ print(f"[gen] facing unknown: {observation['reason']}; no correction", file=sys.stderr)
+ return observation
+
+
+def prepare_correction(backend, request, run, workdir: Path, *, facing: str, fix: str):
+ """Observe raw; recheck one regeneration and mirror a remaining opposite.
+
+ A non-lateral or failed recheck preserves the regenerated image with an
+ explicit reason. At most two vision calls and one regeneration are made.
+ """
+ observation = inspect(backend, request.raw, workdir)
+ report = {**observation, "requested": facing, "fix": fix, "action": "none",
+ "final_direction": observation["direction"]}
+ opposite = "left" if facing == "right" else "right"
+ if observation["direction"] != opposite:
+ report.setdefault("reason", "already-matched" if observation["direction"] == facing else "not-lateral")
+ elif fix == "none":
+ report["reason"] = "correction-disabled"
+ elif fix == "mirror":
+ report.update(action="mirror", final_direction=facing, final_direction_source="mirror-of-observation")
+ else:
+ regenerated = workdir / "facing-regen.png"
+ regenerated.unlink(missing_ok=True)
+ retry_request = replace(request, raw=regenerated,
+ prompt=request.prompt + "\n\n" + prompt_suffix(facing, retry=True))
+ retry_run = backend.generate(retry_request, workdir)
+ verify_png(regenerated)
+ # Keep both calls' billing evidence; top-level usage still describes the
+ # original generation, so existing consumers don't see a different shape.
+ recheck = inspect(backend, regenerated, workdir)
+ report.update(action="regen", final_direction=recheck["direction"],
+ regeneration={"model": retry_run.model, "elapsed_seconds": retry_run.elapsed_seconds,
+ "prompt": retry_request.prompt, "extra": retry_run.extra, "recheck": recheck})
+ if recheck["direction"] == opposite:
+ report.update(fallback="mirror", final_direction=facing,
+ final_direction_source="mirror-of-recheck")
+ elif recheck["direction"] == facing:
+ report["final_direction_source"] = "regeneration-recheck"
+ else:
+ report["reason"] = "regeneration-facing-unresolved:" + recheck.get("reason", "not-lateral")
+ request = retry_request
+ run = replace(run, elapsed_seconds=run.elapsed_seconds + retry_run.elapsed_seconds)
+ return request, run, report
+
+
+def mirror(path: Path) -> None:
+ """Lossless pixel permutation, published atomically, preserving alpha/mode."""
+ with Image.open(path) as source:
+ output = ImageOps.mirror(source)
+ buffer = io.BytesIO()
+ output.save(buffer, format="PNG")
+ publish_png(buffer.getvalue(), path, label="facing-mirror")
diff --git a/sprite_gen/gen/facing_vision.py b/sprite_gen/gen/facing_vision.py
new file mode 100644
index 0000000..7b6eed6
--- /dev/null
+++ b/sprite_gen/gen/facing_vision.py
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Single-call vision transports for the existing generation providers.
+
+REST input/output contract: OpenAI and xAI Responses image understanding docs.
+No generated image is sent to a different provider or authentication route.
+"""
+from __future__ import annotations
+
+import base64
+import json
+import subprocess
+import tempfile
+from pathlib import Path
+
+from .base import GEN_TIMEOUT_SECONDS, provider_binary, provider_subprocess_env
+from .facing import INSPECTION_PROMPT
+
+OPENAI_MODEL = "gpt-4.1-mini"
+GROK_MODEL = "grok-4.6"
+
+
+def request_body(path: Path, model: str) -> dict:
+ return {"model": model, "store": False, "max_output_tokens": 256,
+ "input": [{"role": "user", "content": [
+ {"type": "input_text", "text": INSPECTION_PROMPT},
+ {"type": "input_image", "image_url": "data:image/png;base64," +
+ base64.b64encode(path.read_bytes()).decode("ascii"), "detail": "low"},
+ ]}]}
+
+
+def response_text(status: int, reply) -> tuple[str, dict]:
+ if status != 200:
+ raise SystemExit(f"facing-vision: HTTP {status}; no retry or fallback")
+ if not isinstance(reply, dict):
+ raise ValueError("invalid vision envelope")
+ text = "".join(part["text"] for item in reply.get("output", [])
+ if item.get("type") == "message"
+ for part in item.get("content", []) if part.get("type") == "output_text")
+ return text, {"model": reply.get("model"), "usage": reply.get("usage"),
+ "response_status": reply.get("status")}
+
+
+def codex_inspect(path: Path, workdir: Path) -> tuple[str, dict]:
+ # Isolated cwd and ephemeral session: no project instructions, no stale
+ # output reuse and no persistent vision rollouts. Uses the existing login.
+ with tempfile.TemporaryDirectory(prefix="facing-", dir=workdir) as directory:
+ output = Path(directory) / "answer.txt"
+ command = [provider_binary("codex"), "exec", "--sandbox", "read-only",
+ "--skip-git-repo-check", "--ephemeral", "--color", "never",
+ "-C", directory, "-i", str(path.resolve()), "-o", str(output), "-"]
+ completed = subprocess.run(command, input=INSPECTION_PROMPT, capture_output=True,
+ text=True, encoding="utf-8", env=provider_subprocess_env(),
+ timeout=GEN_TIMEOUT_SECONDS)
+ if completed.returncode:
+ raise SystemExit(f"facing-vision: codex exited {completed.returncode}")
+ return output.read_text(encoding="utf-8"), {"transport": "codex-exec", "auth_source": "codex-login"}
+
+
+def grok_inspect(path: Path, *, credential=None, call=None) -> tuple[str, dict]:
+ from . import xai
+ from .base import announce_api_billing
+ credential = credential or xai.resolve_credential()
+ if credential.source == xai.AUTH_SOURCE_API_KEY:
+ announce_api_billing("grok", xai.AUTH_ENV, " (facing vision check).")
+ status, reply = (call or xai.http_json)("POST", xai.API_BASE + "/responses", credential.token,
+ request_body(path, GROK_MODEL))
+ text, metadata = response_text(status, reply)
+ return text, {**metadata, "auth_source": credential.source, "transport": "xai-api"}
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index 9960a02..b68e9b3 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -121,6 +121,10 @@ class GrokProvider:
name = "grok"
transparency = TRANSPARENCY_CHROMA
+ def inspect_facing(self, path: Path, workdir: Path) -> tuple[str, dict]:
+ from .facing_vision import grok_inspect
+ return grok_inspect(path)
+
def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
if request.native_alpha:
raise SystemExit("grok-gen: grok Imagine cannot return an alpha channel; generate on a chroma key instead")
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
index a35fbdd..caf0ea2 100644
--- a/sprite_gen/gen/openai_provider.py
+++ b/sprite_gen/gen/openai_provider.py
@@ -247,6 +247,16 @@ class OpenAIProvider:
# `background: transparent` returns a real alpha channel on gpt-image-2.5.
transparency = TRANSPARENCY_NATIVE
+ def inspect_facing(self, path: Path, workdir: Path) -> tuple[str, dict]:
+ from . import facing_vision as vision
+ token = resolve_credential()
+ announce_api_billing(self.name, AUTH_ENV, " (facing vision check).")
+ status, reply = http_image(API_BASE + "/responses", token,
+ json.dumps(vision.request_body(path, vision.OPENAI_MODEL)).encode("utf-8"),
+ "application/json", timeout=GEN_TIMEOUT_SECONDS)
+ text, metadata = vision.response_text(status, reply)
+ return text, {**metadata, "auth_source": AUTH_SOURCE_API_KEY, "transport": "openai-api"}
+
def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
fields = _fields(request)
refs = [Path(ref) for ref in request.refs]
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 9eadbe5..a4ece15 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -50,12 +50,14 @@ import sys
import time
import urllib.error
import urllib.request
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text
from .base import announce_api_billing
+from .facing import FACINGS, validate as validate_facing
+from sprite_gen.video import facing as facing_mod
from .xai import (
API_BASE, AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,
HTTP_TIMEOUT_SECONDS, GROK_REFRESH_COMMAND, GROK_REFRESH_WHERE, GROK_LOGIN_COMMAND,
@@ -193,6 +195,9 @@ class VideoRequest:
generate_audio: bool | None = None # None = API default
last_frame: Path | None = None
reference_images: list[Path] = field(default_factory=list)
+ direction: str | None = None
+ facing: str = "right"
+ facing_fix: str = "mirror"
@property
def mode(self) -> str:
@@ -248,6 +253,7 @@ class VideoResult:
input_duration: float | None = None # extend / edit: ffprobe seconds of the input clip
output_duration: float | None = None # extend / edit: ffprobe seconds of the published clip
extra: dict[str, Any] = field(default_factory=dict)
+ facing: dict[str, Any] | None = None
def to_dict(self) -> dict[str, Any]:
return {
@@ -273,10 +279,18 @@ class VideoResult:
"elapsed_seconds": round(self.elapsed_seconds, 3),
"polls": self.polls,
**({"extra": self.extra} if self.extra else {}),
+ **({"facing": self.facing} if self.facing is not None else {}),
}
def _validate(request: VideoRequest) -> None:
+ validate_facing(request.facing, request.facing_fix)
+ if request.direction not in (None, "side", "front", "back"):
+ raise SystemExit("video: --direction must be side, front or back")
+ if request.facing_fix not in facing_mod.FIXES:
+ raise SystemExit("video: --facing-fix must be mirror or none")
+ if request.direction == "side" and request.mode != MODE_IMAGE_TO_VIDEO:
+ raise SystemExit("video: --direction side requires a single --image, without --last-frame or --reference")
if not request.prompt.strip():
raise SystemExit("video: empty prompt; pass --prompt or --prompt-file")
if request.image is None and request.last_frame is None and not request.reference_images:
@@ -470,6 +484,14 @@ def generate_video(
last_frame = _resolved(request.last_frame)
references = [path.expanduser().resolve() for path in request.reference_images]
+ facing_report = None
+ if request.direction == "side":
+ corrected = out.with_suffix(".facing.png")
+ facing_report = facing_mod.prepare_still(image, corrected, facing=request.facing,
+ fix=request.facing_fix, credential=credential, call=call)
+ image = corrected
+ request = replace(request, prompt=request.prompt +
+ f"\n\nThe subject stays in exact side view, facing {request.facing}. No turning around.")
body = _build_generation_body(request, image, last_frame, references)
published = _submit_poll_publish(
verb="video", endpoint="generations", body=body, out=out, credential=credential,
@@ -500,6 +522,7 @@ def generate_video(
generate_audio=request.generate_audio,
mode=request.mode,
inputs=inputs,
+ facing=facing_report,
)
@@ -653,6 +676,9 @@ def _add_prompt_and_report(parser: argparse.ArgumentParser) -> None:
def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--direction", choices=("side", "front", "back"), help="sprite view; side opts into facing inspection before video generation")
+ parser.add_argument("--facing", choices=FACINGS, default="right", help="with --direction side: required direction (default right)")
+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="mirror", help="with --direction side: mirror an opposite-facing still, or none to only record")
parser.add_argument("--image", type=Path, help="the still to animate / the first frame (PNG/JPEG/WebP)")
parser.add_argument("--last-frame", type=Path, help=f"pin the closing frame ({DEFAULT_MODEL} only); alone or with --image")
parser.add_argument(
@@ -714,6 +740,7 @@ def _run(args: argparse.Namespace) -> int:
generate_audio=args.generate_audio,
last_frame=args.last_frame,
reference_images=list(args.reference_images or []),
+ direction=args.direction, facing=args.facing, facing_fix=args.facing_fix,
)
return _publish_report(args, generate_video(request))
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 88c8194..30c636c 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -23,6 +23,8 @@ from pathlib import Path
from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text
+from sprite_gen.gen.facing import FACINGS, validate as validate_facing
+from sprite_gen.video import facing as facing_mod
from sprite_gen.video import canvas as canvas_mod
from sprite_gen.video import frames as frames_mod
from sprite_gen.video import loop as loop_mod
@@ -35,7 +37,7 @@ START_GAP_SECONDS = 2.0
DEFAULT_DURATION_SECONDS = 3
RETRY_BACKOFF_SECONDS = (15, 30)
VIEW_TEXT = {
- "side": "seen from the exact side, facing right",
+ "side": "seen from the exact side, facing {facing}",
"front": "seen from the front, facing the viewer directly",
"back": "seen from directly behind, facing away from the viewer",
}
@@ -68,9 +70,10 @@ def _staggered_start(gap: float) -> None:
_last_start[0] = time.monotonic()
-def build_prompt(direction: str, state: str, character: str | None) -> str:
+def build_prompt(direction: str, state: str, character: str | None, facing: str = "right") -> str:
+ validate_facing(facing)
motion = MOTION_TEXT.get(state, f"performs the '{state}' action in place, repeating at an even rhythm.")
- view = VIEW_TEXT.get(direction, f"seen from the {direction}")
+ view = VIEW_TEXT.get(direction, f"seen from the {direction}").format(facing=facing)
text = COMMON_TEXT.format(motion=motion, view=view)
return text.replace("The character", character, 1) if character else text
@@ -98,21 +101,66 @@ def run_item(
shape: str | None = None,
anchor: str = "none",
spill: str = "auto",
+ facing: str = "right",
+ facing_fix: str = "mirror",
+ prepare_side: Callable[[Path], tuple[Path, dict]] | None = None,
) -> dict[str, Any]:
+ validate_facing(facing, facing_fix)
+ if facing_fix not in facing_mod.FIXES:
+ raise SystemExit("video-set: --facing-fix must be mirror or none")
item_dir = root / item
item_dir.mkdir(parents=True, exist_ok=True)
result: dict[str, Any] = {"item": item, "direction": direction, "state": state, "dir": str(item_dir)}
try:
+ prompt = build_prompt(direction, state, character, facing=facing)
+ clip = item_dir / "clip.mp4"
+ clip_report = item_dir / "clip.report.json"
+ reuse_clip = clip.exists() and clip_report.exists() and not force
+ if reuse_clip:
+ try:
+ previous = json.loads(clip_report.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise SystemExit("cannot verify cached clip prompt; use --force to regenerate") from exc
+ if not isinstance(previous, dict) or previous.get("prompt") != prompt:
+ raise SystemExit("cached clip prompt differs (including facing); use --force to regenerate")
canvas_png = item_dir / "canvas.png"
- canvas_report = canvas_mod.run_canvas(base, canvas_png, state=state, shape=shape, facing="right" if direction != "left" else "left", headroom=None, lead=None, report_path=item_dir / "canvas.report.json")
+ canvas_report_path = item_dir / "canvas.report.json"
+ if reuse_clip:
+ try:
+ canvas_report = json.loads(canvas_report_path.read_text(encoding="utf-8"))
+ if not isinstance(canvas_report, dict) or not canvas_png.is_file():
+ raise ValueError("missing canvas")
+ if not all(key in canvas_report for key in ("shape", "canvas", "offset")):
+ raise ValueError("incomplete canvas report")
+ if direction == "side":
+ prior = canvas_report.get("facing_check") or {}
+ if not isinstance(prior, dict):
+ raise ValueError("invalid cached facing")
+ if (prior.get("requested") != facing or prior.get("fix") != facing_fix
+ or prior.get("source_sha256") != facing_mod.digest(base)):
+ raise ValueError("unverified cached facing")
+ except (OSError, ValueError) as exc:
+ raise SystemExit("cannot verify cached canvas/facing; use --force to regenerate") from exc
+ else:
+ still = base
+ facing_report = None
+ if direction == "side":
+ if prepare_side is not None:
+ still, facing_report = prepare_side(base)
+ else:
+ still = item_dir / "facing.png"
+ facing_report = facing_mod.prepare_still(base, still, facing=facing, fix=facing_fix)
+ canvas_report = canvas_mod.run_canvas(still, canvas_png, state=state, shape=shape, facing=facing if direction not in ("front", "back") else "right", headroom=None, lead=None, report_path=canvas_report_path)
+ if facing_report is not None:
+ canvas_report["facing_check"] = facing_report
+ atomic_write_text(canvas_report_path, json.dumps(canvas_report, ensure_ascii=False, indent=2) + "\n")
result["canvas"] = {k: canvas_report[k] for k in ("shape", "canvas", "offset")}
+ if "facing_check" in canvas_report:
+ result["facing"] = canvas_report["facing_check"]
- clip = item_dir / "clip.mp4"
- clip_report = item_dir / "clip.report.json"
- if clip.exists() and clip_report.exists() and not force:
+ if reuse_clip:
result["clip"] = {"reused": True}
else:
- prompt = build_prompt(direction, state, character)
attempts: list[int] = []
for attempt in range(1 + len(RETRY_BACKOFF_SECONDS)):
_staggered_start(gap)
@@ -173,7 +221,12 @@ def run_set(
shape: str | None = None,
anchor: str = "none",
spill: str = "auto",
+ facing: str = "right",
+ facing_fix: str = "mirror",
) -> dict[str, Any]:
+ validate_facing(facing, facing_fix)
+ if facing_fix not in facing_mod.FIXES:
+ raise SystemExit("video-set: --facing-fix must be mirror or none")
root = root.expanduser().resolve()
root.mkdir(parents=True, exist_ok=True)
for direction, base in bases.items():
@@ -181,15 +234,28 @@ def run_set(
raise SystemExit(f"video-set: base still for '{direction}' not found: {base}")
items = [(f"{d}-{s}", d, s) for d in bases for s in states]
results: list[dict[str, Any]] = []
+ # States share a base. A run-local lock ensures exactly one vision call per
+ # side still, even when several state workers reach it together.
+ prepared: dict[Path, tuple[Path, dict]] = {}
+ prepare_lock = threading.Lock()
+
+ def prepare_side(base: Path) -> tuple[Path, dict]:
+ with prepare_lock:
+ if base not in prepared:
+ corrected = root / "side.facing.png"
+ report = facing_mod.prepare_still(base, corrected, facing=facing, fix=facing_fix)
+ prepared[base] = (corrected, report)
+ return prepared[base]
+
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:
- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill): i for i, d, s in items}
+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=facing, facing_fix=facing_fix, prepare_side=prepare_side): i for i, d, s in items}
for fut in as_completed(futures):
r = fut.result()
results.append(r)
print(json.dumps({k: r[k] for k in ("item", "ok") if k in r} | ({"error": r["error"]} if not r.get("ok") else {"seam": r["loop"]["seam_ratio"]}), ensure_ascii=False), flush=True)
results.sort(key=lambda r: [i for i, _, _ in items].index(r["item"]))
table = write_table(results, root / "table.md")
- payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "directions": list(bases), "ok": sum(1 for r in results if r.get("ok")), "failed": [r["item"] for r in results if not r.get("ok")], "items": results}
+ payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), "ok": sum(1 for r in results if r.get("ok")), "failed": [r["item"] for r in results if not r.get("ok")], "items": results}
atomic_write_text(root / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
print(table)
return payload
@@ -209,6 +275,8 @@ def _parse_bases(values: list[str]) -> dict[str, Path]:
def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--base", action="append", default=[], help="direction=still.png (repeatable: side=..., front=..., back=...)")
+ parser.add_argument("--facing", choices=FACINGS, default="right", help="side-view facing for both prompt and canvas (default right); ignored for front/back")
+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="mirror", help="side inputs: mirror an opposite-facing still (default) or only record the observation")
parser.add_argument("--states", default="idle,walk,run,jump,attack", help="comma list of motion states")
parser.add_argument("--out-dir", required=True, type=Path, help="batch root; one folder per direction-state")
parser.add_argument("--character", help="short subject phrase used in the prompts (e.g. 'The armored knight')")
@@ -230,6 +298,7 @@ def run(**kwargs: object) -> int:
root=Path(str(kwargs["out_dir"])), character=kwargs.get("character"), # type: ignore[arg-type]
duration=int(kwargs.get("duration") or DEFAULT_DURATION_SECONDS), resolution=str(kwargs.get("resolution") or "720p"), key=str(kwargs.get("key") or "auto"),
concurrency=int(kwargs.get("concurrency") or 3), force=bool(kwargs.get("force")), gap=float(kwargs.get("start_gap") or START_GAP_SECONDS),
+ facing=str(kwargs.get("facing") or "right"), facing_fix=str(kwargs.get("facing_fix") or "mirror"),
shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"), spill=str(kwargs.get("spill") or "auto"),
)
return 0 if not payload["failed"] else 1
diff --git a/sprite_gen/video/facing.py b/sprite_gen/video/facing.py
new file mode 100644
index 0000000..731b82a
--- /dev/null
+++ b/sprite_gen/video/facing.py
@@ -0,0 +1,53 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Normalize a side-view video input before canvas placement; never edit its source."""
+from __future__ import annotations
+
+import hashlib
+from dataclasses import dataclass
+from pathlib import Path
+
+from sprite_gen.gen import facing as policy
+from sprite_gen.gen import facing_vision as vision
+from sprite_gen.gen.base import publish_png
+from sprite_gen.gen.xai import Credential, HttpCall
+
+FIXES = ("mirror", "none")
+
+
+def digest(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+@dataclass
+class _Vision:
+ credential: Credential | None = None
+ call: HttpCall | None = None
+
+ def inspect_facing(self, path: Path, workdir: Path):
+ return vision.grok_inspect(path, credential=self.credential, call=self.call)
+
+
+def prepare_still(source: Path, out: Path, *, facing: str = "right", fix: str = "mirror",
+ credential: Credential | None = None, call: HttpCall | None = None) -> dict:
+ """Inspect exactly once on the video provider; publish a corrected PNG copy."""
+ policy.validate(facing, fix)
+ if fix not in FIXES:
+ raise SystemExit("video facing: expected mirror or none")
+ source, out = source.resolve(), out.resolve()
+ if source == out:
+ raise SystemExit("video facing: corrected copy must not overwrite the source")
+ publish_png(source.read_bytes(), out, label="video-facing")
+ observed = policy.inspect(_Vision(credential, call), out, out.parent)
+ report = {**observed, "requested": facing, "fix": fix, "action": "none",
+ "source": str(source), "source_sha256": digest(source), "out": str(out),
+ "final_direction": observed["direction"]}
+ opposite = "left" if facing == "right" else "right"
+ if observed["direction"] == opposite and fix == "mirror":
+ policy.mirror(out)
+ report.update(action="mirror", final_direction=facing, final_direction_source="mirror-of-observation")
+ elif observed["direction"] == opposite:
+ report["reason"] = "correction-disabled"
+ elif observed["direction"] != facing:
+ report.setdefault("reason", "not-lateral")
+ report["output_sha256"] = digest(out)
+ return report
diff --git a/tests/fixtures/facing/front.png b/tests/fixtures/facing/front.png
new file mode 100644
index 0000000..14a32bb
Binary files /dev/null and b/tests/fixtures/facing/front.png differ
diff --git a/tests/fixtures/facing/left.png b/tests/fixtures/facing/left.png
new file mode 100644
index 0000000..c17fdaf
Binary files /dev/null and b/tests/fixtures/facing/left.png differ
diff --git a/tests/fixtures/facing/right.png b/tests/fixtures/facing/right.png
new file mode 100644
index 0000000..69fefa3
Binary files /dev/null and b/tests/fixtures/facing/right.png differ
diff --git a/tests/gen/test_facing.py b/tests/gen/test_facing.py
new file mode 100644
index 0000000..177577c
--- /dev/null
+++ b/tests/gen/test_facing.py
@@ -0,0 +1,280 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Facing regression contracts; all generation and vision calls are offline."""
+import json
+import shutil
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from PIL import Image, ImageOps
+
+from sprite_gen import gen
+from sprite_gen.gen import facing, facing_vision, openai_provider, grok_provider, xai
+from sprite_gen.gen.base import ProviderRun
+
+FIXTURES = Path(__file__).parents[1] / "fixtures" / "facing"
+
+
+class Backend:
+ name = "openai"
+ transparency = "native"
+
+ def __init__(self, direction="left", failure=None, regenerated_direction="right"):
+ self.regenerated_direction = regenerated_direction
+ self.direction, self.failure = direction, failure
+ self.generations, self.inspections = [], []
+
+ def generate(self, request, workdir):
+ self.generations.append(request)
+ source = self.regenerated_direction if len(self.generations) > 1 else self.direction
+ if source == "unknown":
+ source = "front"
+ shutil.copyfile(FIXTURES / f"{source}.png", request.raw)
+ return ProviderRun(self.name, 2, model="test-image", extra={"usage": {"output_tokens": 10}})
+
+ def inspect_facing(self, path, workdir):
+ self.inspections.append(path)
+ if self.failure:
+ raise self.failure
+ direction = self.regenerated_direction if len(self.generations) > 1 else self.direction
+ return json.dumps({"direction": direction, "confidence": 0.95}), {"usage": {"input_tokens": 4}}
+
+
+def generate(tmp_path, monkeypatch, backend, **kwargs):
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ return gen.generate_image("openai", "a toy robot", tmp_path / "out.png",
+ refs=[FIXTURES / "left.png"], **{"facing": "right", **kwargs})
+
+
[email protected]("direction", ["left", "right", "front"])
+def test_three_fixture_directions_only_opposite_is_mirrored(tmp_path, monkeypatch, direction):
+ backend = Backend(direction)
+ result = generate(tmp_path, monkeypatch, backend)
+ original = Image.open(FIXTURES / f"{direction}.png")
+ expected = ImageOps.mirror(original) if direction == "left" else original
+ assert Image.open(result.out).tobytes() == expected.tobytes()
+ assert Image.open(result.raw).tobytes() == original.tobytes()
+ assert len(backend.inspections) == len(backend.generations) == 1
+ assert "facing right" in backend.generations[0].prompt
+ report = result.to_dict()["extra"]["facing"]
+ assert report["direction"] == direction and report["confidence"] == 0.95
+ assert report["action"] == ("mirror" if direction == "left" else "none")
+
+
+def test_left_request_mirrors_right_and_preserves_alpha_and_preview(tmp_path, monkeypatch):
+ result = generate(tmp_path, monkeypatch, Backend("right"), facing="left",
+ transparent=True, alpha_mode="native", white_check=tmp_path / "white.png")
+ original = Image.open(FIXTURES / "right.png")
+ assert Image.open(result.out).tobytes() == ImageOps.mirror(original).tobytes()
+ expected = Image.new("RGBA", original.size, "white")
+ expected.alpha_composite(ImageOps.mirror(original))
+ assert Image.open(tmp_path / "white.png").convert("RGBA").tobytes() == expected.tobytes()
+ assert result.extra["facing"]["final_direction"] == "left"
+
+
+def test_none_is_byte_identical_and_records_mismatch(tmp_path, monkeypatch):
+ result = generate(tmp_path, monkeypatch, Backend(), facing_fix="none")
+ assert result.out.read_bytes() == (FIXTURES / "left.png").read_bytes()
+ assert result.extra["facing"]["reason"] == "correction-disabled"
+
+
[email protected]("failure", [RuntimeError("private"), SystemExit("private")])
+def test_failed_vision_is_unknown_and_preserves_file(tmp_path, monkeypatch, failure, capsys):
+ result = generate(tmp_path, monkeypatch, Backend(failure=failure))
+ report = result.extra["facing"]
+ assert report["direction"] == "unknown" and report["confidence"] is None
+ assert report["action"] == "none" and "vision-call-failed" in report["reason"]
+ assert "private" not in json.dumps(report)
+ assert "facing unknown" in capsys.readouterr().err
+ assert result.out.read_bytes() == (FIXTURES / "left.png").read_bytes()
+
+
[email protected]("rechecked", ["right", "left", "front", "unknown"])
+def test_regen_rechecks_once_and_mirrors_only_a_known_opposite(tmp_path, monkeypatch, rechecked):
+ backend = Backend(regenerated_direction=rechecked)
+ result = generate(tmp_path, monkeypatch, backend, facing_fix="regen")
+ report = result.extra["facing"]
+ assert len(backend.generations) == len(backend.inspections) == 2
+ assert "CORRECTION REQUIRED" in backend.generations[1].prompt
+ assert "facing right" in backend.generations[1].prompt
+ expected = "right" if rechecked in ("left", "right") else "front"
+ assert Image.open(result.out).tobytes() == Image.open(FIXTURES / f"{expected}.png").tobytes()
+ assert result.elapsed_seconds == 4
+ assert result.extra["usage"] == report["regeneration"]["extra"]["usage"] == {"output_tokens": 10}
+ assert report["action"] == "regen"
+ assert report["regeneration"]["recheck"]["direction"] == rechecked
+ assert report["regeneration"]["recheck"]["usage"] == {"input_tokens": 4}
+ assert report.get("fallback") == ("mirror" if rechecked == "left" else None)
+ assert report["final_direction"] == ("right" if rechecked in ("left", "right") else rechecked)
+ if rechecked in ("unknown", "front"):
+ assert report["reason"].startswith("regeneration-facing-unresolved:")
+
+
+def test_regen_failure_is_terminal_and_never_reuses_stale_output(tmp_path, monkeypatch):
+ backend = Backend()
+ original_generate = backend.generate
+ def fail_second(request, workdir):
+ if backend.generations:
+ raise SystemExit("regeneration failed")
+ return original_generate(request, workdir)
+ backend.generate = fail_second
+ out = tmp_path / "out.png"
+ out.write_bytes(b"existing-output")
+ with pytest.raises(SystemExit, match="regeneration failed"):
+ generate(tmp_path, monkeypatch, backend, facing_fix="regen")
+ assert out.read_bytes() == b"existing-output"
+
+
+def test_no_ref_does_not_inspect_or_change_prompt(tmp_path, monkeypatch):
+ backend = Backend()
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ result = gen.generate_image("openai", "a toy robot", tmp_path / "out.png")
+ assert not backend.inspections and "facing" not in result.extra
+ assert backend.generations[0].prompt == "a toy robot"
+
+
[email protected]("text", ['{}', 'null', '[]', 'left or right', '{"direction":"left","confidence":true}',
+ '{"direction":"left","confidence":2}', '{"direction":"right","confidence":NaN}',
+ '{"direction":"back","confidence":0.9}'])
+def test_malformed_observation_is_unknown(text):
+ assert facing.parse_observation(text)["reason"] == "invalid-vision-response"
+
+
+def test_one_word_never_invents_confidence():
+ assert facing.parse_observation(" LEFT ") == {"direction": "left", "confidence": None,
+ "confidence_source": "not-reported"}
+
+
+def vision_response():
+ return {"model": "test-vision", "status": "completed", "usage": {"input_tokens": 4},
+ "output": [{"type": "message", "content": [{"type": "output_text", "text": '{"direction":"left","confidence":0.9}'}]}]}
+
+
[email protected]("provider", ["openai", "grok"])
+def test_rest_vision_uses_same_provider_credential_once(monkeypatch, tmp_path, provider):
+ seen = []
+ if provider == "openai":
+ monkeypatch.setattr(openai_provider, "resolve_credential", lambda: "synthetic")
+ def http(url, token, data, content_type, **kw):
+ seen.append((url, token, json.loads(data)))
+ return 200, vision_response()
+ monkeypatch.setattr(openai_provider, "http_image", http)
+ backend = openai_provider.OpenAIProvider()
+ else:
+ monkeypatch.setattr(xai, "resolve_credential", lambda: xai.Credential("synthetic", "grok-login"))
+ def http(method, url, token, body, **kw):
+ seen.append((url, token, body))
+ return 200, vision_response()
+ monkeypatch.setattr(xai, "http_json", http)
+ backend = grok_provider.GrokProvider()
+ report = facing.inspect(backend, FIXTURES / "left.png", tmp_path)
+ assert len(seen) == 1 and seen[0][1] == "synthetic"
+ assert seen[0][0] == ("https://api.openai.com/v1/responses" if provider == "openai" else "https://api.x.ai/v1/responses")
+ body = seen[0][2]
+ assert body["store"] is False
+ assert body["input"][0]["content"][1]["image_url"].startswith("data:image/png;base64,")
+ assert report["direction"] == "left" and report["usage"] == {"input_tokens": 4}
+ assert report["auth_source"] == ("OPENAI_API_KEY" if provider == "openai" else "grok-login")
+
+
+def test_rest_rejection_is_unknown_without_retry(monkeypatch, tmp_path):
+ calls = []
+ monkeypatch.setattr(openai_provider, "resolve_credential", lambda: "synthetic")
+ def http(*a, **kw):
+ calls.append(1)
+ return 403, {"error": "sensitive"}
+ monkeypatch.setattr(openai_provider, "http_image", http)
+ report = facing.inspect(openai_provider.OpenAIProvider(), FIXTURES / "left.png", tmp_path)
+ assert len(calls) == 1 and report["direction"] == "unknown"
+ assert "sensitive" not in json.dumps(report)
+
+
+def test_codex_vision_reads_new_answer_and_scrubs_identity(monkeypatch, tmp_path):
+ seen = []
+ monkeypatch.setenv("KUMA_MEMBER_ID", "synthetic")
+ def run(command, **kwargs):
+ seen.append((command, kwargs))
+ Path(command[command.index("-o") + 1]).write_text('right')
+ return SimpleNamespace(returncode=0)
+ monkeypatch.setattr(facing_vision.subprocess, "run", run)
+ text, metadata = facing_vision.codex_inspect(FIXTURES / "left.png", tmp_path)
+ assert text == "right" and metadata["auth_source"] == "codex-login"
+ assert len(seen) == 1 and "--ephemeral" in seen[0][0] and "read-only" in seen[0][0]
+ assert "KUMA_MEMBER_ID" not in seen[0][1]["env"]
+ assert not list(tmp_path.iterdir())
+
+
+def test_cli_options_reach_report(tmp_path, monkeypatch):
+ backend = Backend("right")
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ report = tmp_path / "report.json"
+ assert gen.main(["--provider", "openai", "--prompt", "robot", "--ref", str(FIXTURES / "right.png"),
+ "--out", str(tmp_path / "out.png"), "--report", str(report),
+ "--facing", "left", "--facing-fix", "none"]) == 0
+ facing_report = json.loads(report.read_text())["extra"]["facing"]
+ assert facing_report["requested"] == "left" and facing_report["action"] == "none"
+
+
+def test_regeneration_recheck_failure_preserves_regenerated_image(tmp_path, monkeypatch):
+ backend = Backend()
+ inspect = backend.inspect_facing
+ def fail_second(path, workdir):
+ if backend.inspections:
+ backend.inspections.append(path)
+ raise TimeoutError("synthetic")
+ return inspect(path, workdir)
+ backend.inspect_facing = fail_second
+ result = generate(tmp_path, monkeypatch, backend, facing_fix="regen")
+ report = result.extra["facing"]
+ assert len(backend.generations) == len(backend.inspections) == 2
+ assert report["final_direction"] == "unknown" and "TimeoutError" in report["reason"]
+ assert "fallback" not in report
+ assert result.out.read_bytes() == (FIXTURES / "right.png").read_bytes()
+
+
+def test_gen_cli_preserve_default_leaves_reference_prompt_unchanged(tmp_path, monkeypatch):
+ backend = Backend()
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ gen.main(["--provider", "openai", "--prompt", "front-facing robot", "--ref", str(FIXTURES / "front.png"),
+ "--out", str(tmp_path / "out.png")])
+ assert backend.generations[0].prompt == "front-facing robot" and not backend.inspections
+
+
+def test_gen_set_reference_row_keeps_its_prompt(tmp_path, monkeypatch):
+ import subprocess
+ from sprite_gen.gen import gen_set
+ backend = Backend()
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ prompt = tmp_path / "prompt.txt"
+ prompt.write_text("a front-facing robot animation row")
+ def run(command, **kwargs):
+ return SimpleNamespace(returncode=gen.main(command[4:]))
+ monkeypatch.setattr(subprocess, "run", run)
+ assert gen_set.run_gen_cli(prompt, tmp_path / "out.png", [FIXTURES / "front.png"],
+ tmp_path / "report.json", provider="openai", model=None,
+ log=tmp_path / "log.txt") == 0
+ assert backend.generations[0].prompt == prompt.read_text() and not backend.inspections
+
+
+def test_reroll_reference_row_keeps_its_prompt(tmp_path, monkeypatch):
+ from sprite_gen.effects import reroll
+ backend = Backend()
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ monkeypatch.setattr(reroll, "load_request", lambda *a: {"fit": {"pixel_unfake": True}, "states": {"idle": {"frames": 2}}})
+ monkeypatch.setattr(reroll, "identity_ref", lambda *a, **kw: FIXTURES / "front.png")
+ monkeypatch.setattr(reroll, "prompt_rel", lambda *a: "prompt.txt")
+ monkeypatch.setattr(reroll, "guide_rel", lambda *a: "guide.png")
+ monkeypatch.setattr(reroll, "take_raw_rel", lambda *a: "out.png")
+ monkeypatch.setattr(reroll, "record_take", lambda *a: None)
+ (tmp_path / "prompt.txt").write_text("a back-facing robot animation row")
+ reroll.reroll_state(tmp_path, "idle", provider="openai")
+ assert backend.generations[0].prompt == "a back-facing robot animation row" and not backend.inspections
+
+
+def test_interpolation_references_keep_their_prompt(monkeypatch):
+ from sprite_gen.effects.interpolate import gen_interpolator
+ backend = Backend()
+ monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
+ with Image.open(FIXTURES / "front.png") as im:
+ gen_interpolator("codex")(im, im, 0.5, "front-facing robot, halfway pose")
+ assert backend.generations[0].prompt == "front-facing robot, halfway pose" and not backend.inspections
diff --git a/tests/gen/test_video_facing.py b/tests/gen/test_video_facing.py
new file mode 100644
index 0000000..7274dd0
--- /dev/null
+++ b/tests/gen/test_video_facing.py
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Side input correction is opt-in for standalone clips and never edits the source."""
+import base64
+import io
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageOps
+
+from sprite_gen.gen import video
+
+FIXTURE = Path(__file__).parents[1] / "fixtures" / "facing" / "left.png"
+MP4 = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64
+
+
+class Api:
+ def __init__(self, direction="left", failure=False):
+ self.direction, self.failure = direction, failure
+ self.calls = []
+
+ def call(self, method, url, token, body):
+ self.calls.append((method, url, token, body))
+ if url.endswith("/responses"):
+ if self.failure:
+ return 403, {}
+ return 200, {"model": "test-vision", "usage": {"input_tokens": 4},
+ "output": [{"type": "message", "content": [{"type": "output_text", "text": self.direction}]}]}
+ if method == "POST":
+ return 200, {"request_id": "test-id"}
+ return 200, {"status": "done", "video": {"url": "https://vidgen.x.ai/test.mp4", "duration": 3}}
+
+
[email protected]("fix", ["mirror", "none"])
[email protected]("observed", ["left", "right", "front", "unknown"])
+def test_side_input_is_inspected_once_before_upload(tmp_path, fix, observed):
+ api = Api(observed)
+ original = FIXTURE.read_bytes()
+ request = video.VideoRequest(FIXTURE, "idle", tmp_path / "out.mp4", direction="side", facing_fix=fix)
+ result = video.generate_video(request, credential=video.Credential("synthetic", "grok-login"),
+ call=api.call, download=lambda *a: MP4)
+ assert FIXTURE.read_bytes() == original
+ assert len(api.calls) == 3 and api.calls[0][1].endswith("/responses")
+ assert all(call[2] == "synthetic" for call in api.calls)
+ body = api.calls[1][3]
+ assert "facing right" in body["prompt"]
+ report = result.to_dict()["facing"]
+ assert report["direction"] == observed and report["usage"] == {"input_tokens": 4}
+ mirrored = fix == "mirror" and observed == "left"
+ assert report["action"] == ("mirror" if mirrored else "none")
+ with Image.open(FIXTURE) as source:
+ expected = ImageOps.mirror(source) if mirrored else source
+ assert Image.open(result.image).tobytes() == expected.tobytes()
+ # The actual upload, not just the copy on disk, carries the correction.
+ url = body["image"]["url"]
+ uploaded = Image.open(io.BytesIO(base64.b64decode(url.split(",", 1)[1])))
+ assert uploaded.tobytes() == expected.tobytes()
+
+
[email protected]("direction", [None, "front", "back"])
+def test_non_side_video_keeps_prompt_and_has_no_inspection(tmp_path, direction):
+ api = Api()
+ result = video.generate_video(video.VideoRequest(FIXTURE, "original prompt", tmp_path / "out.mp4", direction=direction),
+ credential=video.Credential("synthetic", "grok-login"), call=api.call, download=lambda *a: MP4)
+ assert len(api.calls) == 2
+ assert result.prompt == "original prompt" and "facing" not in result.to_dict()
+ assert result.image == FIXTURE
+
+
+def test_failed_video_inspection_is_reported_and_generation_continues(tmp_path):
+ api = Api(failure=True)
+ result = video.generate_video(video.VideoRequest(FIXTURE, "idle", tmp_path / "out.mp4", direction="side"),
+ credential=video.Credential("synthetic", "grok-login"), call=api.call, download=lambda *a: MP4)
+ assert result.facing["direction"] == "unknown" and "reason" in result.facing
+ assert result.image.read_bytes() == FIXTURE.read_bytes()
+ assert len(api.calls) == 3
+
+
+def test_side_multi_input_refused_before_vision_or_video(tmp_path):
+ api = Api()
+ with pytest.raises(SystemExit, match="single --image"):
+ video.generate_video(video.VideoRequest(FIXTURE, "idle", tmp_path / "out.mp4", direction="side", last_frame=FIXTURE),
+ credential=video.Credential("synthetic", "grok-login"), call=api.call)
+ assert not api.calls
+
+
+def test_video_cli_passes_side_policy(tmp_path, monkeypatch):
+ api = Api()
+ monkeypatch.setattr(video, "resolve_credential", lambda: video.Credential("synthetic", "grok-login"))
+ monkeypatch.setattr(video, "http_json", api.call)
+ monkeypatch.setattr(video, "http_download", lambda *a: MP4)
+ report = tmp_path / "report.json"
+ assert video.main(["--image", str(FIXTURE), "--prompt", "idle", "--out", str(tmp_path / "out.mp4"),
+ "--direction", "side", "--facing", "left", "--facing-fix", "none", "--report", str(report)]) == 0
+ data = json.loads(report.read_text())
+ assert data["facing"]["requested"] == "left" and "facing left" in data["prompt"]
diff --git a/tests/video/test_batch_facing.py b/tests/video/test_batch_facing.py
new file mode 100644
index 0000000..44e5371
--- /dev/null
+++ b/tests/video/test_batch_facing.py
@@ -0,0 +1,103 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Run the batch wiring with a real canvas and an offline video runner."""
+import json
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.video import batch
+
+FIXTURE = Path(__file__).parents[1] / "fixtures" / "facing" / "left.png"
+
+
+def offline(monkeypatch):
+ monkeypatch.setattr(batch.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("left", {}))
+ monkeypatch.setattr(batch.frames_mod, "run_frames", lambda clip, out, **kw: {
+ "fps": 24, "frames": 10, "alpha_zero_pct_min": 50, "alpha_zero_pct_max": 60,
+ "keyed_dir": str(out)})
+ monkeypatch.setattr(batch.loop_mod, "run_loop", lambda *a, **kw: {
+ "cycle": {"length": 10, "period_global": 10, "ratio": 0.2},
+ "resampled_seam_ratio": 0.2, "n_out": 10, "gif": {"file": "loop.gif"},
+ "webp": {"file": "loop.webp"}, "strip": {"path": "strip.png"}})
+ monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)
+
+
[email protected]("facing", ["left", "right"])
[email protected]("direction", ["side", "front", "back"])
+def test_set_facing_reaches_both_real_canvas_and_prompt(tmp_path, offline, facing, direction):
+ prompts = []
+ source_bytes = FIXTURE.read_bytes()
+ def video(image, prompt, out, report, **kw):
+ prompts.append(prompt)
+ out.write_bytes(b"test-video")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+ result = batch.run_set(bases={direction: FIXTURE}, states=["attack"], root=tmp_path,
+ character=None, duration=3, resolution="720p", key="green",
+ concurrency=1, force=False, gap=0, facing=facing, video_runner=video)
+ assert result["ok"] == 1 and result["facing"] == facing
+ assert FIXTURE.read_bytes() == source_bytes
+ canvas = json.loads((tmp_path / f"{direction}-attack" / "canvas.report.json").read_text())
+ if direction == "side":
+ assert f"facing {facing}" in prompts[0]
+ assert result["items"][0]["facing"]["action"] == ("mirror" if facing == "right" else "none")
+ assert (canvas["offset"][0] > 0) == (facing == "left")
+ else:
+ assert "facing" not in result["items"][0]
+ assert prompts[0] == batch.build_prompt(direction, "attack", None, facing="right")
+ assert canvas["offset"][0] == 0
+
+
+def test_changed_facing_cannot_reuse_an_opposite_prompt_clip(tmp_path, offline, monkeypatch):
+ calls = []
+ def video(image, prompt, out, report, **kw):
+ calls.append(1)
+ out.write_bytes(b"cached")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+ options = dict(item="side-attack", direction="side", state="attack", base=FIXTURE,
+ root=tmp_path, character=None, duration=3, resolution="720p", key="green",
+ force=False, gap=0, video_runner=video)
+ result = batch.run_item(**options)
+ assert result["ok"]
+ item = tmp_path / "side-attack"
+ previous_canvas = (item / "canvas.png").read_bytes()
+ def no_vision(*a, **kw):
+ pytest.fail("cached clip must not trigger another inspection")
+ monkeypatch.setattr(batch.facing_mod.vision, "grok_inspect", no_vision)
+ result = batch.run_item(**options, facing="left")
+ assert not result["ok"] and "--force" in result["error"]
+ assert (item / "canvas.png").read_bytes() == previous_canvas
+ result = batch.run_item(**options)
+ assert result["ok"] and result["clip"]["reused"] and len(calls) == 1
+ result = batch.run_item(**options, facing_fix="none")
+ assert not result["ok"] and "--force" in result["error"]
+
+
+def test_cli_threads_facing_into_set(monkeypatch, tmp_path):
+ seen = []
+ def run_set(**kw):
+ seen.append(kw)
+ return {"failed": []}
+ monkeypatch.setattr(batch, "run_set", run_set)
+ assert batch.main(["--base", f"side={FIXTURE}", "--states", "attack", "--out-dir", str(tmp_path),
+ "--facing", "left"]) == 0
+ assert seen[0]["facing"] == "left"
+
+
+def test_parallel_states_share_one_inspection_of_the_side_still(tmp_path, offline, monkeypatch):
+ calls = []
+ def inspect(*a, **kw):
+ calls.append(1)
+ return "left", {}
+ monkeypatch.setattr(batch.facing_mod.vision, "grok_inspect", inspect)
+ def video(image, prompt, out, report, **kw):
+ out.write_bytes(b"test-video")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+ result = batch.run_set(bases={"side": FIXTURE}, states=["idle", "attack", "walk"], root=tmp_path,
+ character=None, duration=3, resolution="720p", key="green",
+ concurrency=3, force=False, gap=0, video_runner=video)
+ assert result["ok"] == 3 and len(calls) == 1
+ assert len({item["facing"]["out"] for item in result["items"]}) == 1
diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.py
index 98438ad..a2b714d 100644
--- a/tests/video/test_video_pipeline.py
+++ b/tests/video/test_video_pipeline.py
@@ -440,6 +440,7 @@ def test_motion_templates_do_not_assume_a_body_plan() -> None:
def test_run_set_staggers_retries_429_and_tables_failures(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(batch_mod.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("right", {}))
base = _still(tmp_path)
calls: list[tuple[str, float]] = []
import time as _time