Skip to content

Turn one topic into a finished Vox-style paper-collage explainer/ad video — automated end to end on Atlas Cloud + ffmpeg. An agent skill.

refactor: pluggable provider layer + rename atlas->atlas_cloud + polling auto-resubmit

Alisa08083aeaf3cedbc3
diff --git a/SKILL.md b/SKILL.md
index e5b067a..627bcbf 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -134,6 +134,7 @@ Add a `shots` array to each beat (see schema). Give each shot its own short `sce
"project": "my-film", "topic": "...", "language": "en",
"aspect": "9:16", // 16:9 | 9:16 | 1:1 | 3:4
"style": "collage",
+ "provider": "atlas_cloud", // media backend — default; pluggable (scripts/provider.py)
"theme": "american-retro", // THEME_PRESET (styles.THEME_PRESETS) — the LOOK layer
"arc": "timeline", // narrative arc (beat-layer.md) — the STORY skeleton
"video_model": "google/gemini-omni-flash/image-to-video", // Kling for real people
@@ -182,6 +183,11 @@ See `references/models-and-gotchas.md` for the full model-choice reasoning and e
API / ffmpeg gotcha (auth header, curl downloads, no-libass captions, content blocks, etc.).
Read it before debugging any failure — most failures are already documented there.
+**Backends are pluggable.** Every API call goes through a **provider** (`scripts/provider.py`);
+Atlas Cloud is the default and only backend today. Set `"provider"` in beats.json to route to a
+different backend once one is added — the stage scripts don't change. `scripts/provider.py`'s
+`run_jobs()` also does the submit/poll with **auto-resubmit on a stalled or failed job**.
+
## Advanced: element-level motion collage
The standard path animates the *whole* poster (great, automated, "living poster"). For the
diff --git a/SKILL.zh.md b/SKILL.zh.md
index c8618f5..e22f638 100644
--- a/SKILL.zh.md
+++ b/SKILL.zh.md
@@ -104,6 +104,7 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:
"project": "my-film", "topic": "...", "language": "en",
"aspect": "9:16", // 16:9 | 9:16 | 1:1 | 3:4
"style": "collage",
+ "provider": "atlas_cloud", // 媒体后端——默认;可插拔(scripts/provider.py)
"theme": "american-retro", // 主题预置(styles.THEME_PRESETS)——"看的层"
"arc": "timeline", // 叙事弧(beat-layer.md)——"故事骨架"
"video_model": "google/gemini-omni-flash/image-to-video", // 真人用 Kling
@@ -150,6 +151,10 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:
完整选型理由 + 每个 API/ffmpeg 坑(auth 头、curl 下载、无 libass 烧字幕、内容审核等)见
`references/models-and-gotchas.md`。**排查任何失败前先读它**——大多数坑已记录。
+**后端可插拔。** 所有 API 调用都走一个 **provider**(`scripts/provider.py`);Atlas Cloud 是默认、
+目前唯一的后端。在 beats.json 里设 `"provider"` 就能切到别的后端(以后加了才有)——各阶段脚本不用改。
+`provider.py` 的 `run_jobs()` 还做了提交/轮询,并在任务**卡死或失败时自动重提**。
+
## 高阶:元素级 motion collage
标准路线动的是*整张*海报(好、自动、"会动的海报")。要那种**碎片飞入组装**的 motion collage(cr7v2 那种),
diff --git a/references/models-and-gotchas.md b/references/models-and-gotchas.md
index dd0e88b..60e2d24 100644
--- a/references/models-and-gotchas.md
+++ b/references/models-and-gotchas.md
@@ -41,7 +41,7 @@ cloning (`references`), or SFX like transition whooshes.
## API gotchas (Atlas, behind a proxy)
1. **Every request MUST send a real `User-Agent` header** — default Python `urllib` UA is
- blocked by the WAF → 403 Forbidden. (`scripts/atlas.py` sets one.)
+ blocked by the WAF → 403 Forbidden. (`scripts/atlas_cloud.py` sets one.)
2. **Download generated assets with curl, not urllib** — the OSS host behind the local proxy
kills `urlretrieve` with `RemoteDisconnected`.
3. **Audio/TTS/music/video all submit via `POST /api/v1/model/generateVideo`**, image &
diff --git a/scripts/atlas.py b/scripts/atlas_cloud.py
similarity index 89%
rename from scripts/atlas.py
rename to scripts/atlas_cloud.py
index 6073e69..64a2baf 100644
--- a/scripts/atlas.py
+++ b/scripts/atlas_cloud.py
@@ -27,14 +27,14 @@ LLM_BASE = "https://api.atlascloud.ai/v1"
UA = "vox-director/0.1 (+https://atlascloud.ai)"
-class AtlasError(RuntimeError):
+class AtlasCloudError(RuntimeError):
pass
def _key() -> str:
k = os.environ.get("ATLASCLOUD_API_KEY")
if not k:
- raise AtlasError("ATLASCLOUD_API_KEY is not set. Get one at "
+ raise AtlasCloudError("ATLASCLOUD_API_KEY is not set. Get one at "
"https://www.atlascloud.ai/console/api-keys")
return k
@@ -53,7 +53,7 @@ def _post(path: str, payload: dict, base: str = MEDIA_BASE, timeout: int = 60) -
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.load(r)
except urllib.error.HTTPError as e:
- raise AtlasError(f"POST {path} -> {e.code}: {e.read().decode()[:400]}") from e
+ raise AtlasCloudError(f"POST {path} -> {e.code}: {e.read().decode()[:400]}") from e
def _get(path: str, base: str = MEDIA_BASE, timeout: int = 60, retries: int = 3) -> dict:
@@ -66,7 +66,7 @@ def _get(path: str, base: str = MEDIA_BASE, timeout: int = 60, retries: int = 3)
except (urllib.error.URLError, TimeoutError) as e: # transient
last = e
time.sleep(2 ** i)
- raise AtlasError(f"GET {path} failed after {retries} tries: {last}")
+ raise AtlasCloudError(f"GET {path} failed after {retries} tries: {last}")
# ---------------------------------------------------------------- generation
@@ -106,11 +106,11 @@ def poll(prediction_id: str, interval: int = 3, timeout_s: int = 900) -> str:
if isinstance(out, str):
out = [out]
if not out:
- raise AtlasError(f"{prediction_id}: completed but no output")
+ raise AtlasCloudError(f"{prediction_id}: completed but no output")
return out[0]
if status == "failed":
- raise AtlasError(f"{prediction_id} failed: {json.dumps(d)[:300]}")
- raise AtlasError(f"{prediction_id} timed out after {timeout_s}s")
+ raise AtlasCloudError(f"{prediction_id} failed: {json.dumps(d)[:300]}")
+ raise AtlasCloudError(f"{prediction_id} timed out after {timeout_s}s")
def image(model: str, prompt: str, **params) -> str:
@@ -135,7 +135,7 @@ def upload(file_path: str) -> str:
data = json.loads(out).get("data", {})
url = data.get("download_url") or data.get("url")
if not url:
- raise AtlasError(f"upload failed: {out[:300]}")
+ raise AtlasCloudError(f"upload failed: {out[:300]}")
return url
@@ -143,7 +143,7 @@ def download(url: str, dest: str) -> str:
"""Proxy-safe download via curl (urllib breaks on the OSS host)."""
subprocess.run(["/usr/bin/curl", "-s", "--retry", "3", "-o", dest, url], check=True)
if not os.path.exists(dest) or os.path.getsize(dest) == 0:
- raise AtlasError(f"download produced empty file: {url}")
+ raise AtlasCloudError(f"download produced empty file: {url}")
return dest
diff --git a/scripts/audio.py b/scripts/audio.py
index 75f0414..c6f35d2 100644
--- a/scripts/audio.py
+++ b/scripts/audio.py
@@ -13,9 +13,8 @@ import json
import os
import subprocess
import sys
-import time
-import atlas
+from provider import get_provider, run_jobs
# xai/tts-v1 is a clean, predictable multilingual TTS (named voices + language
# select). Seed-Audio is a general *sound* model that injects pauses/SFX and
@@ -40,60 +39,42 @@ def run(project_dir: str):
adir = os.path.join(project_dir, "audio")
os.makedirs(adir, exist_ok=True)
+ prov = get_provider(doc.get("provider"))
voice = doc.get("voice", {})
voice_id = voice.get("voice_id", "leo") # named male documentary-ish voice
language = voice.get("language", doc.get("language", "en"))
speed = float(voice.get("speed", 1.0))
- jobs = {}
+ specs = {}
for beat in doc["beats"]:
- pid = atlas.submit_media(VOICE_MODEL, text=beat["narration"], language=language,
- voice_id=voice_id, codec="mp3", sample_rate=44100, speed=speed)
- jobs[("narr", beat["id"])] = pid
- print(f"[narr {beat['id']}] submitted {pid}")
+ specs[f"narr_{beat['id']}"] = (lambda t=beat["narration"]: prov.submit_audio(
+ VOICE_MODEL, text=t, language=language, voice_id=voice_id,
+ codec="mp3", sample_rate=44100, speed=speed))
# BGM: only generate if we don't already have one (it's slow + costs more).
bgm_path = os.path.join(adir, "bgm.mp3")
if not os.path.exists(bgm_path):
music_prompt = doc.get("music", "cinematic majestic traditional Chinese guzheng erhu, warm")
- mpid = atlas.submit_media(MUSIC_MODEL, prompt=music_prompt, is_instrumental=True,
- format="mp3")
- jobs[("bgm", 0)] = mpid
- print(f"[bgm] submitted {mpid}")
+ specs["bgm"] = (lambda mp=music_prompt: prov.submit_audio(
+ MUSIC_MODEL, prompt=mp, is_instrumental=True, format="mp3"))
else:
print(f"[bgm] reuse existing {bgm_path}")
- # poll all
- done = {}
- deadline = time.time() + 600
- while len(done) < len(jobs) and time.time() < deadline:
- time.sleep(4)
- for key, pid in jobs.items():
- if key in done:
- continue
- d = atlas._get(f"/model/prediction/{pid}").get("data", {})
- st = d.get("status")
- if st in ("completed", "succeeded"):
- out = d.get("outputs") or d.get("output")
- done[key] = out[0] if isinstance(out, list) else out
- print(f"{key} done")
- elif st == "failed":
- done[key] = None
- print(f"{key} FAILED: {json.dumps(d)[:200]}")
+ done = run_jobs(prov, specs, poll_s=4, stall_s=150, max_retries=2, deadline_s=600)
# download + record
for beat in doc["beats"]:
- url = done.get(("narr", beat["id"]))
+ url = done.get(f"narr_{beat['id']}")
if url:
dest = os.path.join(adir, f"narr_{beat['id']}.mp3")
- atlas.download(url, dest)
+ prov.download(url, dest)
beat["narration_audio"] = dest
beat["narration_dur"] = round(probe_dur(dest), 2)
print(f"[narr {beat['id']}] {beat['narration_dur']}s -> {dest}")
- bgm_url = done.get(("bgm", 0))
+ bgm_url = done.get("bgm")
if bgm_url:
bgm = os.path.join(adir, "bgm.mp3")
- atlas.download(bgm_url, bgm)
+ prov.download(bgm_url, bgm)
doc["bgm_path"] = bgm
doc["bgm_dur"] = round(probe_dur(bgm), 2)
print(f"[bgm] {doc['bgm_dur']}s -> {bgm}")
diff --git a/scripts/clips.py b/scripts/clips.py
index dcf4c89..e95eb18 100644
--- a/scripts/clips.py
+++ b/scripts/clips.py
@@ -10,9 +10,8 @@ Usage: python3 clips.py <project_dir> (default: out/tang-30s)
import json
import os
import sys
-import time
-import atlas
+from provider import get_provider, run_jobs
from styles import resolve_theme
VIDEO_MODEL = "google/gemini-omni-flash/image-to-video"
@@ -108,7 +107,8 @@ def run(project_dir, only=None):
clip_dir = os.path.join(project_dir, "clips")
os.makedirs(clip_dir, exist_ok=True)
- jobs = {}
+ prov = get_provider(doc.get("provider"))
+ specs, by_key = {}, {}
for beat in doc["beats"]:
for shot, key in shots_of(beat):
if only and key not in only:
@@ -116,7 +116,7 @@ def run(project_dir, only=None):
url = shot.get("keyframe_url")
if not url and shot.get("keyframe_path") and os.path.exists(shot["keyframe_path"]):
# user-provided keyframe (e.g. hand-made collage card) -> upload it
- url = atlas.upload(shot["keyframe_path"])
+ url = prov.upload(shot["keyframe_path"])
shot["keyframe_url"] = url
print(f"[{key}] uploaded provided keyframe -> {url}")
if not url:
@@ -139,39 +139,18 @@ def run(project_dir, only=None):
params = dict(image=url, duration=dur, sound=False)
else: # gemini omni flash
params = dict(image=url, duration=dur, aspect_ratio=aspect, resolution="720p")
- pid = atlas.submit_video(model, prompt, **params)
- jobs[key] = (pid, shot)
- print(f"[{key}] submitted {pid} ({dur}s, {model.split('/')[1]})")
-
- done = {}
- deadline = time.time() + 1200
- while len(done) < len(jobs) and time.time() < deadline:
- time.sleep(5)
- for key, (pid, _) in jobs.items():
- if key in done:
- continue
- try:
- d = atlas._get(f"/model/prediction/{pid}").get("data", {})
- except atlas.AtlasError as e:
- # a failed task makes the prediction endpoint return 500 -> stop waiting
- done[key] = None
- print(f"[{key}] FAILED (poll error): {str(e)[:180]}")
- continue
- st = d.get("status")
- if st in ("completed", "succeeded"):
- out = d.get("outputs") or d.get("output")
- done[key] = out[0] if isinstance(out, list) else out
- print(f"[{key}] done")
- elif st == "failed":
- done[key] = None
- print(f"[{key}] FAILED: {d.get('error','')[:160]}")
-
- for key, (_, shot) in jobs.items():
- url = done.get(key)
+ specs[key] = (lambda m=model, p=prompt, pr=params: prov.submit_video(m, p, **pr))
+ by_key[key] = shot
+ print(f"[{key}] queued ({dur}s, {model.split('/')[1]})")
+
+ done = run_jobs(prov, specs, poll_s=5, stall_s=240, max_retries=2, deadline_s=1200)
+
+ for key, url in done.items():
if not url:
continue
dest = os.path.join(clip_dir, f"clip_{key}.mp4")
- atlas.download(url, dest)
+ prov.download(url, dest)
+ shot = by_key[key]
shot["clip_url"] = url
shot["clip_path"] = dest
print(f"[{key}] saved {dest}")
diff --git a/scripts/extract_elements.py b/scripts/extract_elements.py
index 765bedf..226eb40 100644
--- a/scripts/extract_elements.py
+++ b/scripts/extract_elements.py
@@ -16,7 +16,7 @@ import sys
from PIL import Image, ImageDraw, ImageFilter
-import atlas
+from provider import get_provider, run_jobs
RMBG = "youchuan/v8.1/remove-background"
@@ -42,6 +42,7 @@ def run(project_dir):
card = Image.open(spec["card"]).convert("RGBA")
ed = os.path.join(project_dir, "elements"); os.makedirs(ed, exist_ok=True)
+ prov = get_provider(spec.get("provider"))
for el in spec["elements"]:
name, bbox, mode = el["name"], el["bbox"], el.get("mode", "crop")
crop = card.crop(tuple(bbox))
@@ -49,10 +50,11 @@ def run(project_dir):
crop.save(raw)
out = os.path.join(ed, f"{name}.png")
if mode == "cutout":
- url = atlas.upload(raw)
- pid = atlas._post("/model/generateImage", {"model": RMBG, "image": url})["data"]["id"]
- res = atlas.poll(pid, interval=3, timeout_s=180)
- atlas.download(res, out)
+ url = prov.upload(raw)
+ res = run_jobs(prov, {name: lambda u=url: prov.remove_bg(RMBG, u)},
+ poll_s=3, stall_s=60, max_retries=2, deadline_s=180)[name]
+ if res:
+ prov.download(res, out)
elem = Image.open(out).convert("RGBA")
else:
elem = crop
diff --git a/scripts/keyframes.py b/scripts/keyframes.py
index 3366357..858ccd2 100644
--- a/scripts/keyframes.py
+++ b/scripts/keyframes.py
@@ -12,9 +12,8 @@ Usage: python3 keyframes.py <project_dir> (default: out/tang-30s)
import json
import os
import sys
-import time
-import atlas
+from provider import get_provider, run_jobs
from styles import compose_keyframe_prompt, compose_collage_prompt, resolve_theme
IMAGE_MODEL = "google/nano-banana-2/text-to-image"
@@ -45,7 +44,8 @@ def run(project_dir):
kf_dir = os.path.join(project_dir, "keyframes")
os.makedirs(kf_dir, exist_ok=True)
- jobs = {} # key -> (pid, shot_ref)
+ prov = get_provider(doc.get("provider"))
+ specs, by_key = {}, {}
for beat in doc["beats"]:
for shot, key in shots_of(beat):
if shot.get("keyframe_url"): # already generated (e.g. reused wide) -> skip
@@ -61,38 +61,18 @@ def run(project_dir):
prompt = compose_keyframe_prompt(era, scene, beat["title_cn"],
beat["title_en"], aspect)
shot["keyframe_prompt"] = prompt
- pid = atlas.submit_image(IMAGE_MODEL, prompt, aspect_ratio=aspect, resolution="2k")
- jobs[key] = (pid, shot)
- print(f"[{key}] submitted {pid}")
+ specs[key] = (lambda p=prompt: prov.submit_image(IMAGE_MODEL, p,
+ aspect_ratio=aspect, resolution="2k"))
+ by_key[key] = shot
- done = {}
- deadline = time.time() + 300
- while len(done) < len(jobs) and time.time() < deadline:
- time.sleep(3)
- for key, (pid, _) in jobs.items():
- if key in done:
- continue
- try:
- d = atlas._get(f"/model/prediction/{pid}").get("data", {})
- except atlas.AtlasError as e:
- done[key] = None
- print(f"[{key}] FAILED (poll error): {str(e)[:160]}")
- continue
- st = d.get("status")
- if st in ("completed", "succeeded"):
- out = d.get("outputs") or d.get("output")
- done[key] = out[0] if isinstance(out, list) else out
- print(f"[{key}] done")
- elif st == "failed":
- done[key] = None
- print(f"[{key}] FAILED: {d.get('error','')[:160]}")
+ done = run_jobs(prov, specs, poll_s=3, stall_s=75, max_retries=2, deadline_s=300)
- for key, (_, shot) in jobs.items():
- url = done.get(key)
+ for key, url in done.items():
if not url:
continue
dest = os.path.join(kf_dir, f"kf_{key}.jpg")
- atlas.download(url, dest)
+ prov.download(url, dest)
+ shot = by_key[key]
shot["keyframe_url"] = url
shot["keyframe_path"] = dest
print(f"[{key}] saved {dest}")
diff --git a/scripts/provider.py b/scripts/provider.py
new file mode 100644
index 0000000..6d7671e
--- /dev/null
+++ b/scripts/provider.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""
+Provider abstraction — the pluggable media backend the pipeline stages talk to.
+
+Atlas Cloud is the default and, for now, the only backend. Stages call a Provider
+(submit_image/video/audio, remove_bg, get_status, upload, download) instead of a
+concrete client, so adding a backend is: subclass Provider + one registry entry.
+Pick a backend per project with beats.json `{"provider": "atlas_cloud"}` (default).
+
+The layer is a thin in-process wrapper — zero extra network hops, so it does NOT
+slow the pipeline; the only cost is the API latency, which is unchanged.
+"""
+import time
+from abc import ABC, abstractmethod
+
+import atlas_cloud
+
+
+class ProviderError(RuntimeError):
+ pass
+
+
+class Provider(ABC):
+ """The surface the stages need. get_status normalizes every backend's polling
+ response to {status: pending|completed|failed, output: <url|None>, error}."""
+ name = "base"
+
+ @abstractmethod
+ def submit_image(self, model, prompt, **params): ...
+ @abstractmethod
+ def submit_video(self, model, prompt, **params): ...
+ @abstractmethod
+ def submit_audio(self, model, **params): ...
+ @abstractmethod
+ def remove_bg(self, model, image_url, **params): ...
+ @abstractmethod
+ def get_status(self, job_id): ...
+ @abstractmethod
+ def upload(self, path): ...
+ @abstractmethod
+ def download(self, url, dest): ...
+
+
+class AtlasCloudProvider(Provider):
+ """Wraps the atlas_cloud client — identical behavior to calling it directly."""
+ name = "atlas_cloud"
+
+ def submit_image(self, model, prompt, **params):
+ return atlas_cloud.submit_image(model, prompt, **params)
+
+ def submit_video(self, model, prompt, **params):
+ return atlas_cloud.submit_video(model, prompt, **params)
+
+ def submit_audio(self, model, **params):
+ return atlas_cloud.submit_media(model, **params)
+
+ def remove_bg(self, model, image_url, **params):
+ body = {"model": model, "image": image_url, **params}
+ return atlas_cloud._post("/model/generateImage", body)["data"]["id"]
+
+ def get_status(self, job_id):
+ try:
+ d = atlas_cloud._get(f"/model/prediction/{job_id}").get("data", {})
+ except atlas_cloud.AtlasCloudError as e:
+ return {"status": "failed", "output": None, "error": str(e)}
+ st = d.get("status")
+ if st in ("completed", "succeeded"):
+ out = d.get("outputs") or d.get("output")
+ out = out[0] if isinstance(out, list) else out
+ return {"status": "completed", "output": out, "error": None}
+ if st == "failed":
+ return {"status": "failed", "output": None, "error": d.get("error", "")}
+ return {"status": "pending", "output": None, "error": None}
+
+ def upload(self, path):
+ return atlas_cloud.upload(path)
+
+ def download(self, url, dest):
+ return atlas_cloud.download(url, dest)
+
+
+_REGISTRY = {"atlas_cloud": AtlasCloudProvider}
+
+
+def get_provider(name=None):
+ """Return a Provider instance by name (default 'atlas_cloud')."""
+ name = (name or "atlas_cloud").lower()
+ if name not in _REGISTRY:
+ raise ProviderError(f"unknown provider '{name}'; available: {list(_REGISTRY)}")
+ return _REGISTRY[name]()
+
+
+def run_jobs(prov, specs, *, poll_s=3, stall_s=90, max_retries=2, deadline_s=900):
+ """Submit + poll a batch of jobs, resubmitting any that FAIL or STALL.
+
+ specs: dict of key -> submit() callable returning a job id. A job that fails,
+ or stays pending past `stall_s`, is resubmitted (fresh id) up to `max_retries`
+ times — this is what stops one stuck prediction from wasting the whole deadline.
+ Returns key -> output URL (or None). Prints progress like the old loops did.
+ """
+ st = {}
+ for key, submit in specs.items():
+ st[key] = {"pid": submit(), "t": time.time(), "tries": 0}
+ print(f"[{key}] submitted {st[key]['pid']}")
+
+ done = {}
+ deadline = time.time() + deadline_s
+ while len(done) < len(specs) and time.time() < deadline:
+ time.sleep(poll_s)
+ now = time.time()
+ for key, submit in specs.items():
+ if key in done:
+ continue
+ s = st[key]
+ r = prov.get_status(s["pid"])
+ status = r["status"]
+ if status == "completed":
+ done[key] = r["output"]
+ print(f"[{key}] done")
+ elif status == "failed" or (status == "pending" and now - s["t"] > stall_s):
+ if s["tries"] < max_retries:
+ s["tries"] += 1
+ s["pid"] = submit()
+ s["t"] = time.time()
+ why = "failed" if status == "failed" else f"stalled>{int(stall_s)}s"
+ print(f"[{key}] {why} -> resubmit #{s['tries']} ({s['pid']})")
+ elif status == "failed":
+ done[key] = None
+ print(f"[{key}] FAILED: {(r.get('error') or '')[:120]}")
+ # stalled + out of retries: keep waiting until the deadline
+ for key in specs:
+ done.setdefault(key, None)
+ return done
diff --git a/scripts/style_bakeoff.py b/scripts/style_bakeoff.py
index efdb873..d9d09a9 100644
--- a/scripts/style_bakeoff.py
+++ b/scripts/style_bakeoff.py
@@ -15,9 +15,8 @@ Then set "collage_style": "<pick>" in beats.json, clear old keyframe_url/path,
import json
import os
import sys
-import time
-import atlas
+from provider import get_provider, run_jobs
from styles import compose_collage_prompt, STYLE_LIBRARY, THEME_PRESETS, resolve_theme
IMAGE_MODEL = "google/nano-banana-2/text-to-image"
@@ -40,37 +39,23 @@ def run(project_dir, styles=None, beat_index=0):
tcn, ten = beat.get("title_cn", ""), beat.get("title_en", "")
out = os.path.join(project_dir, "style-bakeoff"); os.makedirs(out, exist_ok=True)
- jobs = {}
+ prov = get_provider(doc.get("provider"))
+ specs = {}
for name in styles:
tp = resolve_theme(name) or {} # theme name -> full look bundle
prompt = compose_collage_prompt(scene, tcn, ten, bg, aspect,
style=tp.get("idiom", name), palette=tp.get("palette"),
type_style=tp.get("type_style"), finish=tp.get("finish"))
- jobs[name] = atlas.submit_image(IMAGE_MODEL, prompt, aspect_ratio=aspect, resolution="2k")
+ specs[name] = (lambda p=prompt: prov.submit_image(IMAGE_MODEL, p,
+ aspect_ratio=aspect, resolution="2k"))
tag = "library" if name in STYLE_LIBRARY else "custom"
- print(f"[{name}] ({tag}) submitted {jobs[name]}")
+ print(f"[{name}] ({tag}) queued")
- done, deadline = {}, time.time() + 240
- while len(done) < len(jobs) and time.time() < deadline:
- time.sleep(3)
- for name, pid in jobs.items():
- if name in done:
- continue
- try:
- d = atlas._get(f"/model/prediction/{pid}").get("data", {})
- except atlas.AtlasError as e:
- done[name] = None; print(f"[{name}] FAILED: {str(e)[:120]}"); continue
- st = d.get("status")
- if st in ("completed", "succeeded"):
- o = d.get("outputs") or d.get("output")
- done[name] = o[0] if isinstance(o, list) else o
- print(f"[{name}] done")
- elif st == "failed":
- done[name] = None; print(f"[{name}] FAILED: {d.get('error','')[:120]}")
+ done = run_jobs(prov, specs, poll_s=3, stall_s=75, max_retries=2, deadline_s=240)
for name, url in done.items():
if url:
- atlas.download(url, os.path.join(out, f"{name}.jpg"))
+ prov.download(url, os.path.join(out, f"{name}.jpg"))
print(f"\nsaved candidates to {out} — review, then set \"collage_style\" in beats.json.")
diff --git a/vox-director.skill b/vox-director.skill
index 7b3ff3e..5c93929 100644
Binary files a/vox-director.skill and b/vox-director.skill differ