Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
gen: sprite-gen video — image to video through Grok Imagine with the user's own credential
Soohong Kim4ad558211660
diff --git a/scripts/generate_sprite_video.py b/scripts/generate_sprite_video.pynew file mode 100644index 0000000..4854993--- /dev/null+++ b/scripts/generate_sprite_video.py@@ -0,0 +1,15 @@+# SPDX-License-Identifier: Apache-2.0+"""Backward-compatible wrapper for sprite_gen.gen.video (`sprite-gen video`)."""++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import sprite_gen.gen.video as _impl++globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 5943786..312436d 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -11,6 +11,7 @@ MODULE_DOMAIN = {'migrate_request': 'spec','migrate_breathe': 'spec','generate_image': 'gen',+ 'video': 'gen','prepare': 'gen','extract': 'frames','cutout': 'frames',diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex d0e2d22..3817f61 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -12,7 +12,7 @@ from sprite_gen.curate import anchorfrom sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, compose_layers, export_aseprite, export_pngsfrom sprite_gen.qa import correction_loop, inspect, preview, scorefrom sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlas-from sprite_gen.gen import prepare+from sprite_gen.gen import prepare, videofrom sprite_gen.effects import recolorfrom sprite_gen.serve import serve_compose, serve_curationfrom sprite_gen.spec import migrate_breathe, migrate_request@@ -204,6 +204,10 @@ def _add_cutout(p: argparse.ArgumentParser) -> None:cutout.add_arguments(p)+def _add_video(p: argparse.ArgumentParser) -> None:+ video.add_arguments(p)++def _add_anchor(p: argparse.ArgumentParser) -> None:anchor.add_arguments(p)@@ -285,6 +289,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab_add_cutout,cutout.run,),+ "video": (+ "Animate one still into a verified mp4 via Grok Imagine (your own grok login or XAI_API_KEY).",+ _add_video,+ video.run,+ ),# The argument surface is `serve_curation.add_arguments` itself, not a copy of it: the# webview's own `--help` and this subcommand are the same declaration, so `sprite-gen# curation` cannot drift from the launch form the READMEs still document.diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.pynew file mode 100644index 0000000..ab588a2--- /dev/null+++ b/sprite_gen/gen/video.py@@ -0,0 +1,453 @@+# SPDX-License-Identifier: Apache-2.0+"""Image-to-video through Grok Imagine (xAI `POST /v1/videos/generations`).++One call = one still (+ prompt) -> one verified mp4 on disk. This is the engine+module behind `sprite-gen video`; the general `grok-imagine-video` skill is a thin+shuttle over this command.++Credentials are the user's own and never live in this repository. Two sources,+resolved in a fixed order and always reported (`auth_source`):++1. `XAI_API_KEY` - an xAI console key (the explicit, environment-level choice).+2. the grok CLI login file `~/.grok/auth.json` (SuperGrok Imagine quota via the+ OIDC access token the CLI stored at `grok login`). `GROK_HOME` relocates it.++The login token expires (about six hours, 2026-09-08 실측) and the grok CLI is the+only writer of that file, so an expired token is not refreshed here: the run+stops before uploading anything and says exactly which command refreshes it.+No silent fallback between the two sources, no retry with a different tool+(Grok Build's built-in `image_to_video` is a separate client that returns+HTTP 400 on Zero-Data-Retention teams; this direct call is what works).++Truth is the mp4 bytes on disk (`ftyp` box verified), never the API's status+string. Tokens and download URLs are never printed or written to the report.+"""++from __future__ import annotations++import argparse+import base64+import json+import mimetypes+import os+import sys+import time+import urllib.error+import urllib.request+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable++from sprite_gen.spec.runio import atomic_write_text++API_BASE = "https://api.x.ai/v1"+DEFAULT_MODEL = "grok-imagine-video-1.5"+RESOLUTIONS = ("480p", "720p", "1080p")+ASPECT_RATIOS = ("1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3")+DURATION_MIN, DURATION_MAX = 1, 15+AUTH_ENV = "XAI_API_KEY"+AUTH_SOURCE_API_KEY = "XAI_API_KEY"+AUTH_SOURCE_GROK_LOGIN = "grok-login"+POLL_INTERVAL_SECONDS = 4.0+POLL_TIMEOUT_SECONDS = int(os.environ.get("SPRITE_GEN_VIDEO_TIMEOUT_SECONDS", "600"))+HTTP_TIMEOUT_SECONDS = 120+# Every mp4/mov starts with a size-prefixed `ftyp` box: bytes 4..8 spell it.+MP4_FTYP_OFFSET = 4+MP4_FTYP = b"ftyp"+_DONE_STATUSES = ("done", "complete", "completed")+_FAILED_STATUSES = ("failed", "error", "expired")++# The refresh instruction for an expired login. The grok CLI rewrites the token+# the next time it talks to the API — measured 2026-09-08 with a one-line prompt+# (`grok -p ok`): expires_at moved from 10:56Z to 18:26Z. `grok login` is the+# full re-sign-in for a revoked or missing login.+GROK_REFRESH_COMMAND = "grok -p ok --output-format plain"+GROK_LOGIN_COMMAND = "grok login"+++def grok_home() -> Path:+ configured = os.environ.get("GROK_HOME")+ if configured is None:+ return Path.home() / ".grok"+ if not configured.strip():+ raise SystemExit("video: GROK_HOME is set but empty; refusing to guess the grok home")+ return Path(configured).expanduser().resolve()+++@dataclass(frozen=True)+class Credential:+ token: str+ source: str # AUTH_SOURCE_API_KEY | AUTH_SOURCE_GROK_LOGIN+ expires_at: str | None = None+++def _parse_expiry(raw: str) -> datetime:+ text = raw.strip()+ if text.endswith("Z"):+ text = text[:-1] + "+00:00"+ parsed = datetime.fromisoformat(text)+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed+++def _load_grok_login(auth_path: Path, *, now: datetime) -> Credential:+ if not auth_path.is_file():+ raise SystemExit(+ f"video: no xAI credential — {AUTH_ENV} is not set and there is no grok login at "+ f"{auth_path}.\n"+ f" either sign in once with `{GROK_LOGIN_COMMAND}` (SuperGrok Imagine quota, no API key), "+ f"or export {AUTH_ENV}=<your xAI console key>."+ )+ try:+ auth = json.loads(auth_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise SystemExit(f"video: cannot read grok login file {auth_path}: {exc}") from exc+ entries = [entry for entry in (auth.values() if isinstance(auth, dict) else []) if isinstance(entry, dict)]+ if len(entries) != 1:+ raise SystemExit(+ f"video: grok login file {auth_path} holds {len(entries)} account entr"+ f"{'y' if len(entries) == 1 else 'ies'}; expected exactly one — refusing to pick one silently. "+ f"Run `{GROK_LOGIN_COMMAND}` to reset it."+ )+ entry = entries[0]+ token = entry.get("key")+ if not isinstance(token, str) or not token.strip():+ raise SystemExit(f"video: grok login file {auth_path} has no access token; run `{GROK_LOGIN_COMMAND}`.")+ expires_at = entry.get("expires_at")+ if isinstance(expires_at, str) and expires_at.strip():+ try:+ expiry = _parse_expiry(expires_at)+ except ValueError as exc:+ raise SystemExit(f"video: grok login file {auth_path} has an unreadable expires_at {expires_at!r}: {exc}") from exc+ if expiry <= now:+ raise SystemExit(+ f"video: the grok login token expired at {expires_at} (now {now.isoformat()}); nothing was uploaded.\n"+ f" refresh it with any grok CLI command that reaches the API, e.g. `{GROK_REFRESH_COMMAND}`, "+ f"or sign in again with `{GROK_LOGIN_COMMAND}`. This tool never rewrites {auth_path} itself."+ )+ return Credential(token=token, source=AUTH_SOURCE_GROK_LOGIN, expires_at=expires_at if isinstance(expires_at, str) else None)+++def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | None = None) -> Credential:+ """Pick the credential in the fixed order: XAI_API_KEY, then the grok login file."""+ env = os.environ if env is None else env+ now = now or datetime.now(timezone.utc)+ api_key = (env.get(AUTH_ENV) or "").strip()+ if api_key:+ return Credential(token=api_key, source=AUTH_SOURCE_API_KEY)+ if AUTH_ENV in env and not api_key:+ raise SystemExit(f"video: {AUTH_ENV} is set but empty; unset it to use the grok login, or give it a value")+ return _load_grok_login(grok_home() / "auth.json", now=now)+++HttpCall = Callable[[str, str, str, dict | None], tuple[int, Any]]+++def http_json(method: str, url: str, token: str, body: dict | None = None) -> tuple[int, Any]:+ data = None if body is None else json.dumps(body).encode("utf-8")+ request = urllib.request.Request(url, data=data, method=method)+ request.add_header("Authorization", f"Bearer {token}")+ request.add_header("Accept", "application/json")+ if body is not None:+ request.add_header("Content-Type", "application/json")+ try:+ with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response:+ raw = response.read().decode("utf-8")+ return response.status, (json.loads(raw) if raw else {})+ except urllib.error.HTTPError as exc:+ raw = exc.read().decode("utf-8", "replace")+ try:+ return exc.code, json.loads(raw)+ except json.JSONDecodeError:+ return exc.code, {"raw": raw[:400]}+ except urllib.error.URLError as exc:+ raise SystemExit(f"video: cannot reach {url}: {exc.reason}") from exc+++def http_download(url: str, token: str) -> bytes:+ request = urllib.request.Request(url)+ try:+ with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response:+ return response.read()+ except urllib.error.HTTPError as first:+ if first.code not in (401, 403):+ raise SystemExit(f"video: download failed with HTTP {first.code}") from first+ request.add_header("Authorization", f"Bearer {token}")+ try:+ with urllib.request.urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response:+ return response.read()+ except urllib.error.HTTPError as second:+ raise SystemExit(f"video: download failed with HTTP {second.code} even with the bearer token") from second+ except urllib.error.URLError as exc:+ raise SystemExit(f"video: cannot download the clip: {exc.reason}") from exc+++def _data_url(path: Path) -> str:+ mime = mimetypes.guess_type(path.name)[0] or "image/png"+ return f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode("ascii")+++def _error_detail(body: Any) -> str:+ if not isinstance(body, dict):+ return str(body)[:300]+ parts = [f"{key}={body[key]!r}" for key in ("code", "error", "message", "status", "raw") if body.get(key)]+ return ", ".join(parts) if parts else json.dumps(body)[:300]+++def _redact_host(url: str) -> str | None:+ if not url.startswith("http"):+ return None+ parts = url.split("/")+ return parts[2] if len(parts) > 2 else None+++def verify_mp4(data: bytes) -> None:+ if len(data) < MP4_FTYP_OFFSET + len(MP4_FTYP) or data[MP4_FTYP_OFFSET : MP4_FTYP_OFFSET + len(MP4_FTYP)] != MP4_FTYP:+ raise SystemExit(+ f"video: downloaded {len(data)} bytes but they are not an mp4 (no ftyp box) — refusing to publish"+ )+++@dataclass+class VideoRequest:+ image: Path+ prompt: str+ out: Path+ duration: int = 6+ resolution: str = "720p"+ aspect_ratio: str | None = None+ model: str = DEFAULT_MODEL+ generate_audio: bool | None = None # None = API default+++@dataclass+class VideoResult:+ out: Path+ bytes: int+ model: str+ request_id: str+ auth_source: str+ elapsed_seconds: float+ polls: int+ duration_requested: int+ duration_reported: float | None = None+ host: str | None = None+ image: Path | None = None+ prompt: str = ""+ resolution: str = ""+ aspect_ratio: str | None = None+ generate_audio: bool | None = None+ extra: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ return {+ "kind": "sprite-gen-video-report",+ "provider": "grok-imagine",+ "auth_source": self.auth_source,+ "model": self.model,+ "request_id": self.request_id,+ "image": str(self.image) if self.image else None,+ "prompt": self.prompt,+ "out": str(self.out),+ "bytes": self.bytes,+ "host": self.host,+ "duration_requested": self.duration_requested,+ "duration_reported": self.duration_reported,+ "resolution": self.resolution,+ "aspect_ratio": self.aspect_ratio,+ "generate_audio": self.generate_audio,+ "elapsed_seconds": round(self.elapsed_seconds, 3),+ "polls": self.polls,+ **({"extra": self.extra} if self.extra else {}),+ }+++def _validate(request: VideoRequest) -> None:+ if not request.prompt.strip():+ raise SystemExit("video: empty prompt; pass --prompt or --prompt-file")+ if not request.image.is_file():+ raise SystemExit(f"video: still image not found: {request.image}")+ if not (DURATION_MIN <= request.duration <= DURATION_MAX):+ raise SystemExit(f"video: --duration must be {DURATION_MIN}..{DURATION_MAX} seconds, got {request.duration}")+ if request.resolution not in RESOLUTIONS:+ raise SystemExit(f"video: --resolution must be one of {', '.join(RESOLUTIONS)}, got {request.resolution!r}")+ if request.aspect_ratio is not None and request.aspect_ratio not in ASPECT_RATIOS:+ raise SystemExit(f"video: --aspect-ratio must be one of {', '.join(ASPECT_RATIOS)}, got {request.aspect_ratio!r}")+++def generate_video(+ request: VideoRequest,+ *,+ credential: Credential | None = None,+ call: HttpCall | None = None,+ download: Callable[[str, str], bytes] | None = None,+ sleep: Callable[[float], None] | None = None,+ poll_timeout: float | None = None,+) -> VideoResult:+ """Generate one clip and return a VideoResult. Raises SystemExit on any failure."""+ # Late-bound so a test that monkeypatches the module-level transport never+ # reaches the network through a default captured at definition time.+ call = call or http_json+ download = download or http_download+ sleep = sleep or time.sleep+ _validate(request)+ credential = credential or resolve_credential()+ out = request.out.expanduser().resolve()+ image = request.image.expanduser().resolve()++ body: dict[str, Any] = {+ "model": request.model,+ "prompt": request.prompt,+ "duration": request.duration,+ "resolution": request.resolution,+ "image": {"url": _data_url(image)},+ }+ if request.aspect_ratio:+ body["aspect_ratio"] = request.aspect_ratio+ if request.generate_audio is not None:+ body["generate_audio"] = request.generate_audio++ started = time.monotonic()+ status, reply = call("POST", f"{API_BASE}/videos/generations", credential.token, body)+ if status in (401, 403):+ raise SystemExit(+ f"video: xAI rejected the credential ({credential.source}) with HTTP {status}: {_error_detail(reply)}\n"+ + (+ f" the grok login token may have been revoked or rotated — run `{GROK_REFRESH_COMMAND}` or `{GROK_LOGIN_COMMAND}`."+ if credential.source == AUTH_SOURCE_GROK_LOGIN+ else f" check the {AUTH_ENV} value."+ )+ )+ request_id = reply.get("request_id") if isinstance(reply, dict) else None+ if status not in (200, 202) or not request_id:+ raise SystemExit(f"video: generation request refused (HTTP {status}): {_error_detail(reply)}")++ deadline = time.monotonic() + (POLL_TIMEOUT_SECONDS if poll_timeout is None else poll_timeout)+ polls = 0+ video_url: str | None = None+ duration_reported: float | None = None+ model_reported: str | None = None+ while True:+ polls += 1+ http, poll = call("GET", f"{API_BASE}/videos/{request_id}", credential.token, None)+ poll_status = poll.get("status") if isinstance(poll, dict) else None+ if http in (200, 202) and poll_status in _DONE_STATUSES:+ video = poll.get("video") or {}+ video_url = video.get("url") if isinstance(video, dict) else None+ duration_reported = video.get("duration") if isinstance(video, dict) else None+ model_reported = poll.get("model")+ break+ if http not in (200, 202) or poll_status in _FAILED_STATUSES:+ raise SystemExit(+ f"video: generation {request_id} ended with status={poll_status!r} (HTTP {http}): {_error_detail(poll)}"+ )+ if time.monotonic() >= deadline:+ raise SystemExit(+ f"video: generation {request_id} still {poll_status!r} after {polls} polls — poll timeout; "+ "nothing was written"+ )+ sleep(POLL_INTERVAL_SECONDS)++ if not video_url:+ raise SystemExit(f"video: generation {request_id} is done but reported no video url")+ data = download(video_url, credential.token)+ verify_mp4(data)+ elapsed = time.monotonic() - started++ out.parent.mkdir(parents=True, exist_ok=True)+ tmp = out.with_name(out.name + ".part")+ tmp.write_bytes(data)+ os.replace(tmp, out)++ return VideoResult(+ out=out,+ bytes=len(data),+ model=model_reported or request.model,+ request_id=str(request_id),+ auth_source=credential.source,+ elapsed_seconds=elapsed,+ polls=polls,+ duration_requested=request.duration,+ duration_reported=duration_reported,+ host=_redact_host(video_url),+ image=image,+ prompt=request.prompt,+ resolution=request.resolution,+ aspect_ratio=request.aspect_ratio,+ generate_audio=request.generate_audio,+ )+++def _print_json(payload: dict) -> None:+ text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"+ buffer = getattr(sys.stdout, "buffer", None)+ if buffer is not None:+ buffer.write(text.encode("utf-8"))+ buffer.flush()+ else:+ sys.stdout.write(text)+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--image", required=True, type=Path, help="the still to animate (PNG/JPEG/WebP)")+ parser.add_argument("--prompt")+ parser.add_argument("--prompt-file", type=Path)+ parser.add_argument("--out", required=True, type=Path, help="destination .mp4")+ parser.add_argument("--duration", type=int, default=6, help=f"seconds, {DURATION_MIN}..{DURATION_MAX} (default 6)")+ parser.add_argument("--resolution", choices=RESOLUTIONS, default="720p")+ parser.add_argument("--aspect-ratio", choices=ASPECT_RATIOS, default=None, help="default: the still's own ratio")+ parser.add_argument("--model", default=DEFAULT_MODEL)+ audio = parser.add_mutually_exclusive_group()+ audio.add_argument("--audio", dest="generate_audio", action="store_true", default=None, help="ask for generated audio")+ audio.add_argument("--no-audio", dest="generate_audio", action="store_false", help="silent clip")+ parser.add_argument("--report", type=Path, help="write the sprite-gen-video-report JSON here")+++def _run(args: argparse.Namespace) -> int:+ prompt = args.prompt+ if args.prompt_file:+ prompt = Path(args.prompt_file).expanduser().read_text(encoding="utf-8")+ request = VideoRequest(+ image=args.image,+ prompt=(prompt or "").strip(),+ out=args.out,+ duration=args.duration,+ resolution=args.resolution,+ aspect_ratio=args.aspect_ratio,+ model=args.model,+ generate_audio=args.generate_audio,+ )+ result = generate_video(request)+ payload = result.to_dict()+ if args.report:+ report_path = Path(args.report).expanduser().resolve()+ atomic_write_text(report_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")+ payload["report"] = str(report_path)+ _print_json(payload)+ return 0+++def _build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="sprite-gen video", description=__doc__)+ add_arguments(parser)+ return parser+++def run(**kwargs: object) -> int:+ parser = _build_parser()+ known = {action.dest for action in parser._actions if action.dest != "help"}+ unexpected = set(kwargs) - known+ if unexpected:+ raise TypeError(f"unexpected keyword argument(s): {', '.join(sorted(unexpected))}")+ namespace = argparse.Namespace(**{dest: kwargs.get(dest, parser.get_default(dest)) for dest in known})+ return _run(namespace)+++def main(argv: list[str] | None = None) -> int:+ return _run(_build_parser().parse_args(argv))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/gen/test_video.py b/tests/gen/test_video.pynew file mode 100644index 0000000..f8b2dfa--- /dev/null+++ b/tests/gen/test_video.py@@ -0,0 +1,271 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video` contract: credential resolution, the api.x.ai call shape,+verified mp4 publishing, and loud failures. No network — the HTTP layer is a fake."""++from __future__ import annotations++import json+from datetime import datetime, timedelta, timezone+from pathlib import Path++import pytest+from PIL import Image++from sprite_gen.gen import video++NOW = datetime(2026, 9, 8, 12, 0, tzinfo=timezone.utc)+MP4 = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64+++def _still(tmp_path: Path) -> Path:+ path = tmp_path / "still.png"+ Image.new("RGBA", (8, 8), (255, 120, 0, 255)).save(path)+ return path+++def _login_file(tmp_path: Path, *, expires_at: str | None = "2026-09-08T18:00:00.000000Z", key: str = "tok") -> Path:+ home = tmp_path / "grokhome"+ home.mkdir(exist_ok=True)+ entry = {"key": key, "auth_mode": "oidc"}+ if expires_at is not None:+ entry["expires_at"] = expires_at+ (home / "auth.json").write_text(json.dumps({"https://auth.x.ai::client": entry}), encoding="utf-8")+ return home+++class _FakeApi:+ """Scripted xAI: one POST reply, then a sequence of poll replies."""++ def __init__(self, post=(200, {"request_id": "req-1"}), polls=None):+ self.post = post+ self.polls = list(polls or [(200, {"status": "done", "video": {"url": "https://vidgen.x.ai/v/1.mp4", "duration": 6.0}, "model": "grok-imagine-video-1.5"})])+ self.calls: list[tuple[str, str, str, dict | None]] = []+ self.downloads: list[str] = []+ self.payload = MP4++ def call(self, method, url, token, body):+ self.calls.append((method, url, token, body))+ if method == "POST":+ return self.post+ return self.polls.pop(0) if len(self.polls) > 1 else self.polls[0]++ def download(self, url, token):+ self.downloads.append(url)+ return self.payload+++def _request(tmp_path: Path, **overrides) -> video.VideoRequest:+ kwargs = dict(image=_still(tmp_path), prompt="camera locked, gentle idle sway", out=tmp_path / "clip.mp4")+ kwargs.update(overrides)+ return video.VideoRequest(**kwargs)+++# --- credential resolution -------------------------------------------------+++def test_api_key_env_wins_over_grok_login(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path)))+ cred = video.resolve_credential(env={"XAI_API_KEY": "xai-console"}, now=NOW)+ assert cred == video.Credential(token="xai-console", source=video.AUTH_SOURCE_API_KEY)+++def test_grok_login_is_used_when_no_api_key(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path, key="oidc-token")))+ cred = video.resolve_credential(env={}, now=NOW)+ assert cred.source == video.AUTH_SOURCE_GROK_LOGIN+ assert cred.token == "oidc-token"+ assert cred.expires_at == "2026-09-08T18:00:00.000000Z"+++def test_expired_grok_login_fails_before_upload_with_refresh_prescription(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path, expires_at="2026-09-08T10:56:34.899829Z")))+ with pytest.raises(SystemExit, match="expired at 2026-09-08T10:56:34") as excinfo:+ video.resolve_credential(env={}, now=NOW)+ message = str(excinfo.value)+ assert video.GROK_REFRESH_COMMAND in message+ assert video.GROK_LOGIN_COMMAND in message+ assert "never rewrites" in message+++def test_missing_login_and_key_prescribes_both_setups(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "nowhere"))+ with pytest.raises(SystemExit, match="no xAI credential") as excinfo:+ video.resolve_credential(env={}, now=NOW)+ assert "grok login" in str(excinfo.value) and "XAI_API_KEY" in str(excinfo.value)+++def test_empty_api_key_env_is_refused_not_ignored(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path)))+ with pytest.raises(SystemExit, match="XAI_API_KEY is set but empty"):+ video.resolve_credential(env={"XAI_API_KEY": " "}, now=NOW)+++def test_login_file_with_two_accounts_is_refused(tmp_path: Path, monkeypatch) -> None:+ home = _login_file(tmp_path)+ (home / "auth.json").write_text(json.dumps({"a": {"key": "1"}, "b": {"key": "2"}}), encoding="utf-8")+ monkeypatch.setenv("GROK_HOME", str(home))+ with pytest.raises(SystemExit, match="holds 2 account entries"):+ video.resolve_credential(env={}, now=NOW)+++def test_login_without_expiry_is_accepted(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path, expires_at=None)))+ assert video.resolve_credential(env={}, now=NOW).expires_at is None+++# --- generation ------------------------------------------------------------+++def test_generate_video_posts_data_url_polls_and_publishes_verified_mp4(tmp_path: Path) -> None:+ api = _FakeApi(polls=[(200, {"status": "pending", "progress": 10}), (200, {"status": "done", "video": {"url": "https://vidgen.x.ai/v/1.mp4", "duration": 6.0}, "model": "grok-imagine-video-1.5"})])+ slept: list[float] = []+ cred = video.Credential(token="tok", source=video.AUTH_SOURCE_GROK_LOGIN)++ result = video.generate_video(+ _request(tmp_path, aspect_ratio="1:1", generate_audio=False),+ credential=cred, call=api.call, download=api.download, sleep=slept.append,+ )++ method, url, token, body = api.calls[0]+ assert (method, url, token) == ("POST", f"{video.API_BASE}/videos/generations", "tok")+ assert body["model"] == video.DEFAULT_MODEL+ assert body["duration"] == 6 and body["resolution"] == "720p" and body["aspect_ratio"] == "1:1"+ assert body["generate_audio"] is False+ assert body["image"]["url"].startswith("data:image/png;base64,")+ assert "output" not in body # no upload_url: the direct call is what works on ZDR teams+ assert api.calls[1][:2] == ("GET", f"{video.API_BASE}/videos/req-1")+ assert slept == [video.POLL_INTERVAL_SECONDS]+ assert api.downloads == ["https://vidgen.x.ai/v/1.mp4"]+ assert result.out.read_bytes() == MP4+ assert not result.out.with_name("clip.mp4.part").exists()+ payload = result.to_dict()+ assert payload["kind"] == "sprite-gen-video-report"+ assert payload["auth_source"] == "grok-login"+ assert payload["request_id"] == "req-1"+ assert payload["host"] == "vidgen.x.ai"+ assert payload["duration_reported"] == 6.0 and payload["duration_requested"] == 6+ assert payload["polls"] == 2+ # Secrets never reach the report: no token, no full download URL.+ dumped = json.dumps(payload)+ assert "tok" not in dumped.replace("token", "") and "vidgen.x.ai/v/1.mp4" not in dumped+++def test_audio_default_is_left_to_the_api(tmp_path: Path) -> None:+ api = _FakeApi()+ video.generate_video(_request(tmp_path), credential=video.Credential("t", "XAI_API_KEY"), call=api.call, download=api.download, sleep=lambda s: None)+ assert "generate_audio" not in api.calls[0][3] and "aspect_ratio" not in api.calls[0][3]+++ ("post", "polls", "expected"),+ [+ ((200, {"error": "quota"}), None, "generation request refused"),+ ((400, {"code": "invalid-argument", "error": "Zero Data Retention teams must provide output.upload_url"}), None, "refused \\(HTTP 400\\)"),+ ((403, {"code": "unauthenticated:bad-credentials", "error": "The OAuth2 access token could not be validated."}), None, "rejected the credential \\(grok-login\\) with HTTP 403"),+ ((200, {"request_id": "r"}), [(200, {"status": "failed", "error": "nsfw"})], "status='failed'"),+ ((200, {"request_id": "r"}), [(200, {"status": "expired"})], "status='expired'"),+ ((200, {"request_id": "r"}), [(500, {"raw": "boom"})], "HTTP 500"),+ ((200, {"request_id": "r"}), [(200, {"status": "done", "video": {}})], "reported no video url"),+ ],+)+def test_api_failures_are_named_and_write_nothing(tmp_path: Path, post, polls, expected) -> None:+ api = _FakeApi(post=post, polls=polls)+ request = _request(tmp_path)+ with pytest.raises(SystemExit, match=expected):+ video.generate_video(request, credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN), call=api.call, download=api.download, sleep=lambda s: None)+ assert not request.out.exists()+ assert not list(tmp_path.glob("*.part"))+++def test_bad_credential_prescribes_refresh_for_login_and_check_for_key(tmp_path: Path) -> None:+ api = _FakeApi(post=(403, {"error": "bad"}))+ with pytest.raises(SystemExit, match=video.GROK_REFRESH_COMMAND.split()[0]):+ video.generate_video(_request(tmp_path), credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN), call=api.call, download=api.download, sleep=lambda s: None)+ with pytest.raises(SystemExit, match="check the XAI_API_KEY value"):+ video.generate_video(_request(tmp_path), credential=video.Credential("t", video.AUTH_SOURCE_API_KEY), call=api.call, download=api.download, sleep=lambda s: None)+++def test_poll_timeout_fails_loud(tmp_path: Path, monkeypatch) -> None:+ api = _FakeApi(polls=[(200, {"status": "pending"})])+ clock = {"t": 0.0}+ monkeypatch.setattr(video.time, "monotonic", lambda: clock["t"])++ def sleep(seconds: float) -> None:+ clock["t"] += seconds++ request = _request(tmp_path)+ with pytest.raises(SystemExit, match="poll timeout"):+ video.generate_video(request, credential=video.Credential("t", "XAI_API_KEY"), call=api.call, download=api.download, sleep=sleep, poll_timeout=10)+ assert not request.out.exists()+++def test_non_mp4_download_is_refused(tmp_path: Path) -> None:+ api = _FakeApi()+ api.payload = b"<html>not a video</html>"+ request = _request(tmp_path)+ with pytest.raises(SystemExit, match="not an mp4"):+ video.generate_video(request, credential=video.Credential("t", "XAI_API_KEY"), call=api.call, download=api.download, sleep=lambda s: None)+ assert not request.out.exists()+++ ("overrides", "expected"),+ [+ ({"duration": 0}, "--duration must be 1..15"),+ ({"duration": 16}, "--duration must be 1..15"),+ ({"resolution": "4k"}, "--resolution must be one of"),+ ({"aspect_ratio": "21:9"}, "--aspect-ratio must be one of"),+ ({"prompt": " "}, "empty prompt"),+ ],+)+def test_request_validation_runs_before_any_call(tmp_path: Path, overrides, expected) -> None:+ api = _FakeApi()+ with pytest.raises(SystemExit, match=expected):+ video.generate_video(_request(tmp_path, **overrides), credential=video.Credential("t", "XAI_API_KEY"), call=api.call, download=api.download)+ assert api.calls == []+++def test_missing_still_fails_before_any_call(tmp_path: Path) -> None:+ api = _FakeApi()+ with pytest.raises(SystemExit, match="still image not found"):+ video.generate_video(video.VideoRequest(image=tmp_path / "nope.png", prompt="p", out=tmp_path / "o.mp4"), credential=video.Credential("t", "XAI_API_KEY"), call=api.call, download=api.download)+ assert api.calls == []+++# --- CLI ---------------------------------------------------------------------+++def test_cli_run_writes_report_and_defaults(tmp_path: Path, monkeypatch) -> None:+ api = _FakeApi()+ monkeypatch.setattr(video, "resolve_credential", lambda **_: video.Credential("t", video.AUTH_SOURCE_API_KEY))+ monkeypatch.setattr(video, "http_json", api.call)+ monkeypatch.setattr(video, "http_download", api.download)+ monkeypatch.setattr(video.time, "sleep", lambda s: None)+ out = tmp_path / "clip.mp4"+ report = tmp_path / "report.json"++ rc = video.run(image=_still(tmp_path), prompt="sway", prompt_file=None, out=out, duration=6, resolution="720p", aspect_ratio=None, model=video.DEFAULT_MODEL, generate_audio=None, report=report)++ assert rc == 0+ assert out.read_bytes() == MP4+ payload = json.loads(report.read_text(encoding="utf-8"))+ assert payload["auth_source"] == "XAI_API_KEY" and payload["out"] == str(out.resolve())+++def test_cli_parser_shape() -> None:+ parser = video._build_parser()+ args = parser.parse_args(["--image", "a.png", "--prompt", "p", "--out", "o.mp4"])+ assert args.duration == 6 and args.resolution == "720p" and args.aspect_ratio is None and args.generate_audio is None+ assert parser.parse_args(["--image", "a.png", "--out", "o.mp4", "--no-audio"]).generate_audio is False+ assert parser.parse_args(["--image", "a.png", "--out", "o.mp4", "--audio"]).generate_audio is True+ with pytest.raises(SystemExit):+ parser.parse_args(["--image", "a.png", "--out", "o.mp4", "--resolution", "4k"])+++def test_unified_cli_exposes_video() -> None:+ from sprite_gen import cli++ assert "video" in cli.COMMANDS+ parser = cli._build_parser()+ args = parser.parse_args(["video", "--image", "a.png", "--prompt", "p", "--out", "o.mp4"])+ assert args.command == "video"diff --git a/tests/packaging/test_package_surface.py b/tests/packaging/test_package_surface.pyindex d7fdb55..075cdb0 100644--- a/tests/packaging/test_package_surface.py+++ b/tests/packaging/test_package_surface.py@@ -37,6 +37,7 @@ PACKAGE_RUN_MODULES = ["serve_curation","slice_sheet","unpack_atlas",+ "video",]CLI_HELPERS = [