feat: release 1.5.8 - one continuity plan for H3 clips
This commit is contained in:
@@ -4,4 +4,4 @@
|
||||
# reads this; pyproject.toml is kept in sync for the build (hatchling dynamic
|
||||
# version reads this file). PR #47: hard-coded literals drifted twice
|
||||
# (1.3.2 shipped reporting 1.2.1; 1.4.1's /api/health still said 1.4.0).
|
||||
__version__ = "1.5.7"
|
||||
__version__ = "1.5.8"
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
"""Project continuity ledger: one timed film plan shared by every H3 clip.
|
||||
|
||||
The MiniMax compiler phrases a clip. This module decides the facts it must
|
||||
keep — style, bindings, camera, lighting, and what changed after the previous
|
||||
shot — so neighboring clips are slices of one plan.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.llm import LLMClient, extract_json
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
|
||||
logger = logging.getLogger("calliope.continuity")
|
||||
|
||||
PLAN_TIMEOUT_SEC = 25.0
|
||||
CRITIC_TIMEOUT_SEC = 15.0
|
||||
|
||||
OVERVIEW_KEYS = ("style", "pace", "soundscape", "camera_grammar", "lighting")
|
||||
REQUIREMENT_KEYS = (
|
||||
"style",
|
||||
"subjects",
|
||||
"actions",
|
||||
"dialogue",
|
||||
"sound",
|
||||
"camera",
|
||||
"lighting",
|
||||
"spatial",
|
||||
"scene",
|
||||
)
|
||||
SHOT_KEYS = (
|
||||
"window",
|
||||
"action",
|
||||
"speakers",
|
||||
"camera",
|
||||
"lighting",
|
||||
"spatial",
|
||||
"state_after",
|
||||
)
|
||||
_MEDIA_SUFFIXES = {
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".webp",
|
||||
".gif",
|
||||
".mp4",
|
||||
".webm",
|
||||
".mov",
|
||||
".mkv",
|
||||
".avi",
|
||||
".m4v",
|
||||
}
|
||||
|
||||
_PLAN_SYSTEM = """You write one continuity ledger for a whole short film.
|
||||
Return a single JSON object and nothing else:
|
||||
{
|
||||
"overview": {"style": "", "pace": "", "soundscape": "", "camera_grammar": "", "lighting": ""},
|
||||
"requirements": {
|
||||
"style": "", "subjects": "", "actions": "", "dialogue": "", "sound": "",
|
||||
"camera": "", "lighting": "", "spatial": "", "scene": ""
|
||||
},
|
||||
"shots": [
|
||||
{
|
||||
"clip_id": 0,
|
||||
"window": "00:00.000-00:06.000",
|
||||
"action": "",
|
||||
"speakers": "",
|
||||
"camera": "",
|
||||
"lighting": "",
|
||||
"spatial": "",
|
||||
"state_after": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
Rules:
|
||||
- One shot per clip_id in the board, same playback order. Do not invent clip ids.
|
||||
- requirements: nine short locked lines. Accept later paraphrase; do not leave a bucket blank when the board states it.
|
||||
- speakers bind each dialogue line to the person who says it. Do not move a line.
|
||||
- camera and lighting name the move and the light state. state_after is what changed for the next shot.
|
||||
- A clip marked REALIZED already has footage. Keep its action, speakers, camera, and lighting aligned with that footage; do not restage it.
|
||||
- Reference image and video paths are identity and motion. Do not recast a subject because a location description mentions someone else.
|
||||
"""
|
||||
|
||||
_CRITIC_SYSTEM = """You check one clip prompt against a film continuity plan.
|
||||
Nine checks: style, subjects, actions, dialogue, sound, camera, lighting, spatial relations, scene.
|
||||
Accept paraphrase and compatible elaboration.
|
||||
Report only failures: omission, wrong subject binding, wrong speaker–dialogue binding, contradiction, or a shot-order conflict with the neighbor shots.
|
||||
Return JSON only: {"ok": true, "notes": []} when it holds, or {"ok": false, "notes": ["short failure", ...]}.
|
||||
No second draft. No praise.
|
||||
"""
|
||||
|
||||
|
||||
def media_paths(values: dict[str, Any] | None) -> list[str]:
|
||||
"""Path-like strings in a clip form, in stable key order."""
|
||||
if not isinstance(values, dict):
|
||||
return []
|
||||
found: list[str] = []
|
||||
for key in sorted(values, key=lambda item: str(item)):
|
||||
raw = values[key]
|
||||
if not isinstance(raw, str):
|
||||
continue
|
||||
text = raw.strip()
|
||||
if not text:
|
||||
continue
|
||||
suffix = Path(text).suffix.lower()
|
||||
if suffix in _MEDIA_SUFFIXES or "/" in text or "\\" in text:
|
||||
found.append(text)
|
||||
return found
|
||||
|
||||
|
||||
def _ts(seconds: float) -> str:
|
||||
seconds = max(0.0, float(seconds))
|
||||
whole = int(seconds)
|
||||
millis = int(round((seconds - whole) * 1000))
|
||||
if millis >= 1000:
|
||||
whole += 1
|
||||
millis -= 1000
|
||||
minutes, secs = divmod(whole, 60)
|
||||
return f"{minutes:02d}:{secs:02d}.{millis:03d}"
|
||||
|
||||
|
||||
def _as_int(value: Any) -> int | None:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _clip_dialog_text(clip: dict[str, Any]) -> str:
|
||||
covered = clip.get("dialog_lines_covered")
|
||||
dialog = clip.get("dialog") or ""
|
||||
if not covered:
|
||||
return ""
|
||||
if isinstance(covered, str):
|
||||
try:
|
||||
covered = json.loads(covered)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return ""
|
||||
if not isinstance(covered, list):
|
||||
return ""
|
||||
lines = [ln for ln in str(dialog).splitlines() if ln.strip()]
|
||||
picked = [
|
||||
lines[i - 1]
|
||||
for i in covered
|
||||
if isinstance(i, int) and 1 <= i <= len(lines)
|
||||
]
|
||||
return "\n".join(picked)
|
||||
|
||||
|
||||
def _input_values(clip: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = clip.get("video_settings_json")
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(raw) if isinstance(raw, str) else raw
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return {}
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
values = data.get("input_values")
|
||||
return values if isinstance(values, dict) else {}
|
||||
|
||||
|
||||
def _clip_ref_paths(
|
||||
clip: dict[str, Any], live_refs: dict[int, list[str]] | None
|
||||
) -> list[str]:
|
||||
stored = media_paths(_input_values(clip))
|
||||
cid = int(clip["id"])
|
||||
if not live_refs or cid not in live_refs:
|
||||
return stored
|
||||
live = [p.strip() for p in live_refs[cid] if isinstance(p, str) and p.strip()]
|
||||
if live == stored:
|
||||
return stored
|
||||
return live
|
||||
|
||||
|
||||
def load_board(project_id: int) -> dict[str, Any]:
|
||||
"""Screenplay, shots, cast, and places for one project."""
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute(
|
||||
"SELECT id, title, idea, genre, tone, continuity_json FROM projects WHERE id = ?",
|
||||
(project_id,),
|
||||
).fetchone()
|
||||
if not project:
|
||||
raise ValueError(f"Project {project_id} not found")
|
||||
clips = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"""
|
||||
SELECT c.*, s.order_index AS scene_order, s.heading, s.action, s.dialog,
|
||||
s.location_id, s.env_image_path
|
||||
FROM clips c JOIN scenes s ON s.id = c.scene_id
|
||||
WHERE c.project_id = ?
|
||||
ORDER BY s.order_index, c.order_index, c.id
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
]
|
||||
characters = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"""
|
||||
SELECT id, name, appearance, consistency_prompt, sheet_path, portrait_path
|
||||
FROM characters WHERE project_id = ? ORDER BY id
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
]
|
||||
locations = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"""
|
||||
SELECT id, name, description, consistency_prompt, reference_image_path
|
||||
FROM locations WHERE project_id = ? ORDER BY id
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
]
|
||||
return {
|
||||
"project": row_to_dict(project),
|
||||
"clips": clips,
|
||||
"characters": characters,
|
||||
"locations": locations,
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def basis_hash(
|
||||
board: dict[str, Any], live_refs: dict[int, list[str]] | None = None
|
||||
) -> str:
|
||||
"""Fingerprint of script text, clip order, and reference paths."""
|
||||
clips = []
|
||||
for clip in board["clips"]:
|
||||
clips.append(
|
||||
{
|
||||
"id": int(clip["id"]),
|
||||
"scene_order": int(clip.get("scene_order") or 0),
|
||||
"order_index": int(clip.get("order_index") or 0),
|
||||
"heading": clip.get("heading") or "",
|
||||
"action": clip.get("action") or "",
|
||||
"dialog": clip.get("dialog") or "",
|
||||
"description": clip.get("description") or "",
|
||||
"shot_size": clip.get("shot_size") or "",
|
||||
"dialog_lines_covered": clip.get("dialog_lines_covered") or "",
|
||||
"refs": _clip_ref_paths(clip, live_refs),
|
||||
"env_image_path": clip.get("env_image_path") or "",
|
||||
"clip_path": clip.get("clip_path") or "",
|
||||
}
|
||||
)
|
||||
characters = [
|
||||
{
|
||||
"id": int(c["id"]),
|
||||
"name": c.get("name") or "",
|
||||
"appearance": c.get("appearance") or "",
|
||||
"consistency_prompt": c.get("consistency_prompt") or "",
|
||||
"sheet_path": c.get("sheet_path") or "",
|
||||
"portrait_path": c.get("portrait_path") or "",
|
||||
}
|
||||
for c in board["characters"]
|
||||
]
|
||||
locations = [
|
||||
{
|
||||
"id": int(loc["id"]),
|
||||
"name": loc.get("name") or "",
|
||||
"description": loc.get("description") or "",
|
||||
"consistency_prompt": loc.get("consistency_prompt") or "",
|
||||
"reference_image_path": loc.get("reference_image_path") or "",
|
||||
}
|
||||
for loc in board["locations"]
|
||||
]
|
||||
payload = json.dumps(
|
||||
{"clips": clips, "characters": characters, "locations": locations},
|
||||
sort_keys=True,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
return hashlib.sha256(payload.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def deterministic_plan(board: dict[str, Any]) -> dict[str, Any]:
|
||||
"""A locked plan built from the board when the plan model is unavailable."""
|
||||
project = board["project"]
|
||||
names = ", ".join(c.get("name") or "" for c in board["characters"] if c.get("name"))
|
||||
places = ", ".join(loc.get("name") or "" for loc in board["locations"] if loc.get("name"))
|
||||
style = (project.get("tone") or project.get("genre") or "cinematic").strip()
|
||||
cursor = 0.0
|
||||
shots = []
|
||||
for clip in board["clips"]:
|
||||
dur = float(clip.get("duration_sec") or 6)
|
||||
start, end = cursor, cursor + dur
|
||||
cursor = end
|
||||
action = (clip.get("description") or clip.get("action") or clip.get("heading") or "").strip()
|
||||
shots.append(
|
||||
{
|
||||
"clip_id": int(clip["id"]),
|
||||
"window": f"{_ts(start)}-{_ts(end)}",
|
||||
"action": action[:500],
|
||||
"speakers": _clip_dialog_text(clip)[:500],
|
||||
"camera": (clip.get("shot_size") or "").strip(),
|
||||
"lighting": "",
|
||||
"spatial": "",
|
||||
"state_after": "",
|
||||
}
|
||||
)
|
||||
return {
|
||||
"overview": {
|
||||
"style": style[:400],
|
||||
"pace": "Hold the pace of the shot list.",
|
||||
"soundscape": "",
|
||||
"camera_grammar": "Keep screen direction consistent with the previous shot.",
|
||||
"lighting": "Keep the lighting state until a shot's action changes it.",
|
||||
},
|
||||
"requirements": {
|
||||
"style": style[:400],
|
||||
"subjects": (names or "Use only the reference images supplied for each clip.")[:400],
|
||||
"actions": "Perform each clip's action in playback order.",
|
||||
"dialogue": "Keep each line with the speaker written on that clip.",
|
||||
"sound": "",
|
||||
"camera": "Keep each clip's camera move and the film's screen direction.",
|
||||
"lighting": "Do not change lighting between neighbors unless the shot says so.",
|
||||
"spatial": (places or "Keep subjects on the sides established by the previous shot.")[:400],
|
||||
"scene": (project.get("idea") or project.get("title") or "")[:400],
|
||||
},
|
||||
"shots": shots,
|
||||
"based_on": "",
|
||||
}
|
||||
|
||||
|
||||
def normalize_plan(raw: dict[str, Any], board: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Coerce a model plan onto the board's clip ids. Missing shots stay stubs."""
|
||||
base = deterministic_plan(board)
|
||||
overview = raw.get("overview") if isinstance(raw.get("overview"), dict) else {}
|
||||
for key in OVERVIEW_KEYS:
|
||||
val = str(overview.get(key) or "").strip()
|
||||
if val:
|
||||
base["overview"][key] = val[:400]
|
||||
req = raw.get("requirements") if isinstance(raw.get("requirements"), dict) else {}
|
||||
for key in REQUIREMENT_KEYS:
|
||||
if key in req:
|
||||
base["requirements"][key] = str(req.get(key) or "").strip()[:400]
|
||||
by_id: dict[int, dict[str, Any]] = {}
|
||||
for shot in raw.get("shots") or []:
|
||||
if not isinstance(shot, dict):
|
||||
continue
|
||||
cid = _as_int(shot.get("clip_id"))
|
||||
if cid is None:
|
||||
continue
|
||||
by_id[cid] = shot
|
||||
merged = []
|
||||
for stub in base["shots"]:
|
||||
src = by_id.get(stub["clip_id"])
|
||||
row = dict(stub)
|
||||
if src:
|
||||
for key in SHOT_KEYS:
|
||||
if key in src:
|
||||
row[key] = str(src.get(key) or "").strip()[:500]
|
||||
row["clip_id"] = stub["clip_id"]
|
||||
merged.append(row)
|
||||
base["shots"] = merged
|
||||
return base
|
||||
|
||||
|
||||
def _parse_stored(raw: Any) -> dict[str, Any] | None:
|
||||
if not isinstance(raw, str) or not raw.strip():
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(data, dict) or not isinstance(data.get("shots"), list):
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def _persist(project_id: int, plan: dict[str, Any]) -> None:
|
||||
stored = {
|
||||
"overview": plan.get("overview") or {},
|
||||
"requirements": plan.get("requirements") or {},
|
||||
"shots": plan.get("shots") or [],
|
||||
"based_on": plan.get("based_on") or "",
|
||||
}
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE projects SET continuity_json = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(json.dumps(stored, ensure_ascii=False), project_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _board_digest(board: dict[str, Any]) -> str:
|
||||
project = board["project"]
|
||||
lines = [
|
||||
f"Title: {project.get('title') or ''}",
|
||||
f"Idea: {project.get('idea') or ''}",
|
||||
f"Genre: {project.get('genre') or ''}",
|
||||
f"Tone: {project.get('tone') or ''}",
|
||||
"Characters:",
|
||||
]
|
||||
for c in board["characters"]:
|
||||
lines.append(
|
||||
f"- {c.get('name')}: appearance={c.get('appearance') or ''}; "
|
||||
f"consistency={c.get('consistency_prompt') or ''}; "
|
||||
f"sheet={c.get('sheet_path') or ''}; portrait={c.get('portrait_path') or ''}"
|
||||
)
|
||||
lines.append("Locations:")
|
||||
for loc in board["locations"]:
|
||||
lines.append(
|
||||
f"- {loc.get('name')}: {loc.get('description') or ''}; "
|
||||
f"consistency={loc.get('consistency_prompt') or ''}; "
|
||||
f"image={loc.get('reference_image_path') or ''}"
|
||||
)
|
||||
lines.append("Shots in playback order:")
|
||||
for clip in board["clips"]:
|
||||
realized = ""
|
||||
if clip.get("clip_path"):
|
||||
realized = f" REALIZED footage={clip['clip_path']}"
|
||||
lines.append(
|
||||
f"- clip_id={clip['id']} #{clip.get('scene_order')}.{clip.get('order_index')} "
|
||||
f"{clip.get('heading') or ''}{realized}"
|
||||
)
|
||||
lines.append(f" description: {clip.get('description') or ''}")
|
||||
lines.append(f" scene action: {clip.get('action') or ''}")
|
||||
lines.append(f" dialogue: {clip.get('dialog') or ''}")
|
||||
lines.append(f" lines covered: {clip.get('dialog_lines_covered') or ''}")
|
||||
lines.append(f" shot size: {clip.get('shot_size') or ''}")
|
||||
lines.append(f" refs: {', '.join(_clip_ref_paths(clip, None))}")
|
||||
text = "\n".join(lines)
|
||||
if len(text) > 14000:
|
||||
text = text[:14000] + "\n[board truncated]"
|
||||
return text
|
||||
|
||||
|
||||
async def _llm_plan(board: dict[str, Any]) -> dict[str, Any]:
|
||||
client = LLMClient.for_role("video", timeout=PLAN_TIMEOUT_SEC)
|
||||
try:
|
||||
raw = await client.chat(
|
||||
[
|
||||
{"role": "system", "content": _PLAN_SYSTEM},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Write the continuity ledger for this board.\n\n" + _board_digest(board),
|
||||
},
|
||||
],
|
||||
temperature=0.2,
|
||||
)
|
||||
data = extract_json(raw)
|
||||
finally:
|
||||
await client.close()
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("continuity plan was not a JSON object")
|
||||
return data
|
||||
|
||||
|
||||
async def ensure_continuity_plan(
|
||||
project_id: int,
|
||||
*,
|
||||
force: bool = False,
|
||||
live_refs: dict[int, list[str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Return the project's plan, rewriting it when the board hash is stale.
|
||||
|
||||
A dead model falls back to a deterministic plan. The call never raises for
|
||||
model failures.
|
||||
"""
|
||||
board = load_board(project_id)
|
||||
basis = basis_hash(board, live_refs)
|
||||
stored = _parse_stored(board["project"].get("continuity_json"))
|
||||
if stored and not force and stored.get("based_on") == basis:
|
||||
stored["refreshed"] = False
|
||||
return stored
|
||||
try:
|
||||
plan = normalize_plan(await _llm_plan(board), board)
|
||||
except Exception as exc:
|
||||
logger.warning("Continuity plan refresh failed (%s); using the board plan", exc)
|
||||
plan = deterministic_plan(board)
|
||||
plan["based_on"] = basis
|
||||
_persist(project_id, plan)
|
||||
plan["refreshed"] = True
|
||||
return plan
|
||||
|
||||
|
||||
def continuity_lock_text(plan: dict[str, Any] | None, clip_id: int) -> str:
|
||||
"""Binding slice for one clip: this shot plus its neighbors."""
|
||||
if not plan:
|
||||
return ""
|
||||
shots = [s for s in (plan.get("shots") or []) if isinstance(s, dict)]
|
||||
idx = next(
|
||||
(i for i, shot in enumerate(shots) if _as_int(shot.get("clip_id")) == int(clip_id)),
|
||||
None,
|
||||
)
|
||||
lines = [
|
||||
"These lines are binding.",
|
||||
"Phrase them into the six H3 sections.",
|
||||
"Do not recast a subject, move a dialogue line to another speaker, or change lighting or screen direction.",
|
||||
"Reference images and the reference video remain the identity and motion source.",
|
||||
]
|
||||
overview = plan.get("overview") if isinstance(plan.get("overview"), dict) else {}
|
||||
for key in OVERVIEW_KEYS:
|
||||
val = str((overview or {}).get(key) or "").strip()
|
||||
if val:
|
||||
lines.append(f"Film {key}: {val}")
|
||||
req = plan.get("requirements") if isinstance(plan.get("requirements"), dict) else {}
|
||||
for key in REQUIREMENT_KEYS:
|
||||
val = str((req or {}).get(key) or "").strip()
|
||||
if val:
|
||||
lines.append(f"Locked {key}: {val}")
|
||||
if idx is None:
|
||||
lines.append("This clip has no shot row; keep the locks above.")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _fmt(label: str, shot: dict[str, Any]) -> str:
|
||||
return (
|
||||
f"{label} clip {shot.get('clip_id')} window {shot.get('window') or ''}: "
|
||||
f"action={shot.get('action') or ''}; speakers={shot.get('speakers') or ''}; "
|
||||
f"camera={shot.get('camera') or ''}; lighting={shot.get('lighting') or ''}; "
|
||||
f"spatial={shot.get('spatial') or ''}; after={shot.get('state_after') or ''}"
|
||||
)
|
||||
|
||||
if idx > 0:
|
||||
lines.append(_fmt("Previous shot", shots[idx - 1]))
|
||||
lines.append(_fmt("This shot", shots[idx]))
|
||||
if idx + 1 < len(shots):
|
||||
lines.append(_fmt("Next shot", shots[idx + 1]))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _unavailable(exc: BaseException) -> dict[str, Any]:
|
||||
reason = str(exc).strip() or exc.__class__.__name__
|
||||
return {
|
||||
"ok": False,
|
||||
"notes": [f"Continuity critic unavailable: {reason[:180]}"],
|
||||
"unavailable": True,
|
||||
}
|
||||
|
||||
|
||||
async def critique_prompt(
|
||||
prompt: str, plan: dict[str, Any] | None, clip_id: int
|
||||
) -> dict[str, Any]:
|
||||
"""Score one candidate. Failures only. A dead judge never raises."""
|
||||
if not plan:
|
||||
return {"ok": True, "notes": []}
|
||||
client = LLMClient.for_role("video", timeout=CRITIC_TIMEOUT_SEC)
|
||||
try:
|
||||
raw = await client.chat(
|
||||
[
|
||||
{"role": "system", "content": _CRITIC_SYSTEM},
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
"Plan slice:\n"
|
||||
+ continuity_lock_text(plan, clip_id)
|
||||
+ "\n\nCandidate prompt:\n"
|
||||
+ (prompt or "")
|
||||
),
|
||||
},
|
||||
],
|
||||
temperature=0.0,
|
||||
)
|
||||
data = extract_json(raw)
|
||||
except Exception as exc:
|
||||
logger.warning("Continuity critic failed (%s)", exc)
|
||||
return _unavailable(exc)
|
||||
finally:
|
||||
await client.close()
|
||||
if not isinstance(data, dict):
|
||||
return _unavailable(ValueError("critic returned no JSON object"))
|
||||
notes: list[str] = []
|
||||
for item in data.get("notes") or []:
|
||||
text = str(item).strip()
|
||||
if text:
|
||||
notes.append(text[:300])
|
||||
notes = notes[:9]
|
||||
ok = bool(data.get("ok")) and not notes
|
||||
return {"ok": ok, "notes": notes}
|
||||
@@ -144,6 +144,7 @@ ROLE_TOOLS: dict[str, list[str]] = {
|
||||
"add_scene",
|
||||
"delete_scene",
|
||||
"reorder_scenes",
|
||||
"refresh_continuity_plan",
|
||||
"ask_user",
|
||||
],
|
||||
"assets": [
|
||||
|
||||
@@ -202,6 +202,30 @@ def register(registry: ToolRegistry) -> None:
|
||||
destructive=True,
|
||||
)
|
||||
)
|
||||
registry.register(
|
||||
ToolDefinition(
|
||||
name="refresh_continuity_plan",
|
||||
description=(
|
||||
"Write or refresh the project's continuity ledger: one timed "
|
||||
"plan for every clip (style, speaker bindings, camera, lighting, "
|
||||
"what changes after each shot). Call this after generate_script "
|
||||
"or break_into_shots, before rendering, so later clip prompts "
|
||||
"are slices of the same film. force=true rewrites even when the "
|
||||
"board hash still matches."
|
||||
),
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"force": {
|
||||
"type": "boolean",
|
||||
"description": "Rewrite the plan even if the board hash matches (default true)",
|
||||
},
|
||||
},
|
||||
},
|
||||
executor=t_refresh_continuity_plan,
|
||||
category="script",
|
||||
)
|
||||
)
|
||||
registry.register(
|
||||
ToolDefinition(
|
||||
name="add_clip",
|
||||
@@ -814,6 +838,22 @@ async def t_break_into_shots(ctx: ToolContext, args: dict[str, Any]) -> dict[str
|
||||
}
|
||||
|
||||
|
||||
async def t_refresh_continuity_plan(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Rewrite the project continuity ledger from the current board."""
|
||||
from calliope.agent.continuity import ensure_continuity_plan
|
||||
|
||||
if not ctx.project_id:
|
||||
return {"ok": False, "error": "Link a project before refreshing the continuity plan"}
|
||||
force = bool(args.get("force", True))
|
||||
plan = await ensure_continuity_plan(int(ctx.project_id), force=force)
|
||||
return {
|
||||
"ok": True,
|
||||
"based_on": plan.get("based_on") or "",
|
||||
"shots": len(plan.get("shots") or []),
|
||||
"refreshed": bool(plan.get("refreshed")),
|
||||
}
|
||||
|
||||
|
||||
async def t_add_clip(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
|
||||
conn = _db()
|
||||
try:
|
||||
|
||||
@@ -114,7 +114,39 @@ class LLMClient:
|
||||
|
||||
async def chat(
|
||||
self,
|
||||
messages: list[dict[str, str]],
|
||||
messages: list[dict[str, Any]],
|
||||
temperature: float = 0.7,
|
||||
response_format: dict[str, str] | None = None,
|
||||
extra_body: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
outbound = messages
|
||||
if self._text_only and _has_image_parts(messages):
|
||||
outbound = _strip_image_parts(messages)
|
||||
try:
|
||||
return await self._chat_collect(
|
||||
outbound, temperature, response_format, extra_body
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
body = exc.response.text[:500] if exc.response is not None else ""
|
||||
if _has_image_parts(outbound) and _looks_like_image_rejection(
|
||||
exc.response.status_code, body
|
||||
):
|
||||
logger.warning(
|
||||
"Endpoint rejected image parts (%s); retrying text-only", body[:200]
|
||||
)
|
||||
self._text_only = True
|
||||
_TEXT_ONLY_ENDPOINTS.add(self.base_url)
|
||||
return await self._chat_collect(
|
||||
_strip_image_parts(outbound),
|
||||
temperature,
|
||||
response_format,
|
||||
extra_body,
|
||||
)
|
||||
raise
|
||||
|
||||
async def _chat_collect(
|
||||
self,
|
||||
messages: list[dict[str, Any]],
|
||||
temperature: float = 0.7,
|
||||
response_format: dict[str, str] | None = None,
|
||||
extra_body: dict[str, Any] | None = None,
|
||||
@@ -389,6 +421,9 @@ class LLMClient:
|
||||
reasoning = delta.get("reasoning_content")
|
||||
if reasoning:
|
||||
yield {"type": "reasoning", "content": reasoning}
|
||||
usage = chunk.get("usage")
|
||||
if isinstance(usage, dict) and usage:
|
||||
yield {"type": "usage", "usage": usage}
|
||||
for tc in delta.get("tool_calls") or []:
|
||||
idx = tc.get("index", 0)
|
||||
acc = tool_acc.get(idx)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -650,9 +651,10 @@ def scene_video_prompt(scene: dict[str, Any], characters: list[dict[str, Any]])
|
||||
# MiniMax H3 full-reference (ref2video) prompt profile
|
||||
# ---------------------------------------------------------------------------
|
||||
# Condensed from MiniMax's VIDEO_PROMPT_WRITING_GUIDE_ref_en.md, adapted to
|
||||
# Calliope's single-scene clips: each subject's reference image is wired into
|
||||
# the workflow's generic (Input:image) slots in node-id order, and that order
|
||||
# defines the <Subject N> / <Picture N> numbering below.
|
||||
# Calliope's single-scene clips. Image slots are (Input:image) in node-id
|
||||
# order and that order is <Subject N> / <Picture N>. Video slots are
|
||||
# (Input:video) and become <Video N>. The files the user put in those slots
|
||||
# are the identity and motion source; story text only fills an empty slot.
|
||||
|
||||
MINIMAX_H3_REF_SYSTEM = (
|
||||
"You rewrite scene descriptions into MiniMax H3's full-reference video prompt format. "
|
||||
@@ -667,26 +669,39 @@ MINIMAX_H3_REF_SYSTEM = (
|
||||
"non_diegetic_music:\n"
|
||||
"\n"
|
||||
"Rules:\n"
|
||||
"1. subject_definitions: one line per referenced subject supplied in the user message, "
|
||||
"1. subject_definitions: one line per referenced image supplied in the user message, "
|
||||
"keeping its exact <Subject N> index. Form: '<Subject N> is the <description> in "
|
||||
"<Picture N>, with <key visual features to preserve>.' <Picture N> is the reference "
|
||||
"image wired to slot N — cite it inside the subject line, never as a standalone entry.\n"
|
||||
"image wired to slot N — cite it inside the subject line, never as a standalone entry. "
|
||||
"Describe what is actually in that picture: face, hair, wardrobe, armor, weapons, "
|
||||
"colors, body, and setting. When a picture is attached, those pixels win over the "
|
||||
"story names. Do not replace a supplied image with a story character or location "
|
||||
"that is not that file. If a subject has no written appearance and you cannot see "
|
||||
"the picture, lock the line to the picture and do not invent a different identity.\n"
|
||||
"2. summary: one short English paragraph starting with '[reference generation]' that "
|
||||
"states what happens using the <Subject N> labels.\n"
|
||||
"states what happens using the <Subject N> labels. When a <Video N> is supplied, "
|
||||
"say that its camera and physical performance drive the motion.\n"
|
||||
"3. retention_analysis: one line per subject: '<Subject N> (appears in [Shot 1]…): "
|
||||
"fully_preserved - <which defined features are retained>.'\n"
|
||||
"4. detailed_description: the main body, 120–300 words. Open with one or two style "
|
||||
"fully_preserved - <which defined features are retained>.' One line per reference "
|
||||
"video: '<Video N> (motion across [Shot 1]…): motion_preserved - <camera, timing, "
|
||||
"and physical action kept from the clip>.'\n"
|
||||
"4. detailed_description: the main body, 150–350 words. Open with one or two style "
|
||||
"sentences (lighting, palette, medium) BEFORE '[Shot 1]'. '[Shot 1]' has no timestamp; "
|
||||
"later cuts use '[Shot N] At MM:SS.mmm, …'. For clips under ~8 seconds prefer a single "
|
||||
"shot. Introduce each <Subject N> at its first visible appearance with its referenced "
|
||||
"features, position, and action; reuse the label afterwards. Describe only what is "
|
||||
"visible except sound/dialogue.\n"
|
||||
"shot. Introduce each <Subject N> at its first visible appearance with the features "
|
||||
"visible in its picture, plus position and action; reuse the label afterwards. When "
|
||||
"a reference video is supplied, state the camera move and the body action taken from "
|
||||
"its frames. Describe only what is visible except sound/dialogue.\n"
|
||||
"5. Dialogue: give each speaker a stable ID in order of first speech — '<Subject N> (S1) "
|
||||
"says, <d>[English] …</d>'. A speaker with no defined subject uses a stable voice "
|
||||
"description, e.g. 'A narrator (S2) says, <d>[English] …</d>'. Keep the original "
|
||||
"language of every line inside <d> and tag it, e.g. [English], [Chinese].\n"
|
||||
"6. overall_soundscape: ambience and physical sounds across the clip, or 'N/A'. "
|
||||
"non_diegetic_music: audience-only score (instrumentation, tempo), or 'N/A'.\n"
|
||||
"7. Reference videos: one subject_definitions line per <Video N> supplied in the "
|
||||
"user message. Form: '<Video N> is the motion reference, with <camera and action "
|
||||
"to preserve>.' Never drop a supplied video. Do not invent a <Video N> that was "
|
||||
"not supplied.\n"
|
||||
"Write everything in English except dialogue/lyrics inside <d> and visible on-screen text."
|
||||
)
|
||||
|
||||
@@ -694,74 +709,154 @@ MINIMAX_H3_REF_SYSTEM = (
|
||||
def _subject_roster_lines(subjects: list[dict[str, Any]]) -> str:
|
||||
lines = []
|
||||
for s in subjects:
|
||||
appearance = (s.get("appearance") or "").strip()
|
||||
if not appearance:
|
||||
appearance = (
|
||||
f"no written description — describe Picture {s['index']} from the "
|
||||
"attached image; do not substitute another character or location"
|
||||
)
|
||||
file_bit = ""
|
||||
path = str(s.get("path") or "").strip()
|
||||
if path:
|
||||
file_bit = f", file {Path(path).name}"
|
||||
lines.append(
|
||||
f"<Subject {s['index']}> = {s['kind']} \"{s.get('name') or 'unnamed'}\" "
|
||||
f"(reference image slot {s['index']}): {s.get('appearance') or 'no description'}"
|
||||
f"(reference image slot {s['index']}{file_bit}): {appearance}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _video_roster_lines(videos: list[dict[str, Any]]) -> str:
|
||||
lines = []
|
||||
for v in videos:
|
||||
name = v.get("name") or Path(str(v.get("path") or "")).name or "clip"
|
||||
lines.append(
|
||||
f"<Video {v['index']}> = motion reference \"{name}\" "
|
||||
f"(reference video slot {v['index']}). Preserve its camera movement, "
|
||||
"timing, and physical performance. Do not drop this label."
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_minimax_h3_ref_messages(
|
||||
scene: dict[str, Any], subjects: list[dict[str, Any]]
|
||||
) -> list[dict[str, str]]:
|
||||
scene: dict[str, Any],
|
||||
subjects: list[dict[str, Any]],
|
||||
videos: list[dict[str, Any]] | None = None,
|
||||
media_parts: list[dict[str, Any]] | None = None,
|
||||
continuity: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""LLM messages that rewrite a scene into H3's six-section ref format.
|
||||
|
||||
subjects: ordered roster — index N corresponds to ref image slot N.
|
||||
subjects: ordered image roster — index N is ref image slot N.
|
||||
videos: ordered ``(Input:video)`` clips — index N is ``<Video N>``.
|
||||
media_parts: optional vision parts (picture labels + image_url frames)
|
||||
appended after the text so a vision model sees the actual files.
|
||||
"""
|
||||
videos = videos or []
|
||||
roster = _subject_roster_lines(subjects) or (
|
||||
"(no reference images — describe subjects from the action text)"
|
||||
)
|
||||
video_roster = _video_roster_lines(videos) or "(no reference video)"
|
||||
lock = (continuity or "").strip()
|
||||
lock_block = ""
|
||||
if lock:
|
||||
lock_block = (
|
||||
"\nContinuity ledger (binding — phrase these facts into the six "
|
||||
"sections; do not recast a subject, move a dialogue line, or change "
|
||||
"lighting or screen direction):\n"
|
||||
f"{lock}\n"
|
||||
)
|
||||
user = f"""Rewrite this scene into MiniMax H3 full-reference format.
|
||||
|
||||
The reference images and videos below are what the user wired into this clip.
|
||||
They decide who is on screen and how the shot moves. The scene action decides
|
||||
what happens. When a picture or video frame disagrees with a story name, the
|
||||
file wins. Be specific about visible clothing, armor, weapons, face, hair, and colors.
|
||||
{lock_block}
|
||||
Scene heading: {scene.get('heading') or '(none)'}
|
||||
Scene duration: ~{scene.get('duration_sec') or 6} seconds
|
||||
|
||||
Action (visual base for detailed_description):
|
||||
Action (what happens — not a replacement for the reference files):
|
||||
{scene.get('action') or '(none)'}
|
||||
|
||||
Dialogue (raw 'SPEAKER: line' format; optional '(delivery cue)' after the speaker —
|
||||
map speakers to subjects by name and keep cues as delivery direction):
|
||||
{scene.get('dialog') or '(none)'}
|
||||
|
||||
Referenced subjects (keep these exact indices):
|
||||
Referenced images (keep these exact <Subject N> indices; Picture N is image N):
|
||||
{roster}
|
||||
|
||||
Referenced videos (keep these exact <Video N> labels):
|
||||
{video_roster}
|
||||
"""
|
||||
content: str | list[dict[str, Any]] = user
|
||||
if media_parts:
|
||||
content = [{"type": "text", "text": user}, *media_parts]
|
||||
return [
|
||||
{"role": "system", "content": MINIMAX_H3_REF_SYSTEM},
|
||||
{"role": "user", "content": user},
|
||||
{"role": "user", "content": content},
|
||||
]
|
||||
|
||||
|
||||
def minimax_h3_ref_fallback(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> str:
|
||||
def minimax_h3_ref_fallback(
|
||||
scene: dict[str, Any],
|
||||
subjects: list[dict[str, Any]],
|
||||
videos: list[dict[str, Any]] | None = None,
|
||||
) -> str:
|
||||
"""Deterministic six-section H3 prompt — used when the LLM rewrite fails."""
|
||||
videos = videos or []
|
||||
defs = []
|
||||
retention = []
|
||||
for s in subjects:
|
||||
name = s.get("name") or "unnamed"
|
||||
desc = (s.get("appearance") or "").strip()
|
||||
defs.append(
|
||||
f"<Subject {s['index']}> is the {s['kind']} \"{name}\" in "
|
||||
f"<Picture {s['index']}>" + (f", {desc}." if desc else ".")
|
||||
)
|
||||
if desc:
|
||||
defs.append(
|
||||
f"<Subject {s['index']}> is the {s['kind']} \"{name}\" in "
|
||||
f"<Picture {s['index']}>, {desc}."
|
||||
)
|
||||
else:
|
||||
defs.append(
|
||||
f"<Subject {s['index']}> is the reference image in "
|
||||
f"<Picture {s['index']}> (\"{name}\"). Preserve its visible identity, "
|
||||
"wardrobe, proportions, and materials."
|
||||
)
|
||||
retention.append(
|
||||
f"<Subject {s['index']}> (appears in [Shot 1]): fully_preserved - "
|
||||
f"the referenced appearance of \"{name}\" is retained."
|
||||
)
|
||||
for v in videos:
|
||||
name = v.get("name") or "clip"
|
||||
defs.append(
|
||||
f"<Video {v['index']}> is the motion reference \"{name}\". "
|
||||
"Preserve its camera movement, action timing, and physical performance."
|
||||
)
|
||||
retention.append(
|
||||
f"<Video {v['index']}> (motion across [Shot 1]): motion_preserved - "
|
||||
"camera path, timing, and physical performance from the reference video "
|
||||
"are retained."
|
||||
)
|
||||
|
||||
heading = (scene.get("heading") or "").strip()
|
||||
action = (scene.get("action") or "").strip()
|
||||
labels = ", ".join(f"<Subject {s['index']}>" for s in subjects)
|
||||
summary = (
|
||||
f"[reference generation] {heading or 'A scene'} featuring {labels}."
|
||||
if labels
|
||||
else f"[reference generation] {heading or 'A scene'}."
|
||||
)
|
||||
video_labels = ", ".join(f"<Video {v['index']}>" for v in videos)
|
||||
if labels:
|
||||
summary = f"[reference generation] {heading or 'A scene'} featuring {labels}."
|
||||
else:
|
||||
summary = f"[reference generation] {heading or 'A scene'}."
|
||||
if video_labels:
|
||||
summary += f" Motion and camera follow {video_labels}."
|
||||
|
||||
body = (
|
||||
"The target video is in a cinematic style consistent with the reference images, "
|
||||
"with coherent lighting and natural motion.\n"
|
||||
f"[Shot 1] {heading} {action}".strip()
|
||||
)
|
||||
if video_labels:
|
||||
body += (
|
||||
f"\nThe physical performance, camera path, and timing follow {video_labels}."
|
||||
)
|
||||
|
||||
# Map 'SPEAKER: line' rows onto subjects by name; assign speaker IDs in speech order.
|
||||
# An optional delivery cue — 'MIA (whispering): line' — is kept as performance direction.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Enqueue per-clip video generation jobs (a scene expands into many clips)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
@@ -8,6 +9,16 @@ import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.continuity import (
|
||||
continuity_lock_text,
|
||||
critique_prompt,
|
||||
ensure_continuity_plan,
|
||||
media_paths,
|
||||
)
|
||||
from calliope.agent.harness.log import (
|
||||
_image_attachment_data_url,
|
||||
_video_attachment_frames,
|
||||
)
|
||||
from calliope.agent.llm import LLMClient
|
||||
from calliope.agent.prompts import (
|
||||
build_minimax_h3_ref_messages,
|
||||
@@ -16,7 +27,7 @@ from calliope.agent.prompts import (
|
||||
)
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.roles import input_has_role
|
||||
from calliope.comfyui.smart_fill import ref_image_slots, smart_fill_inputs
|
||||
from calliope.comfyui.smart_fill import ref_image_slots, ref_video_slots, smart_fill_inputs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
@@ -25,69 +36,215 @@ from calliope.queue.manager import queue_manager
|
||||
logger = logging.getLogger("calliope.video_agent")
|
||||
|
||||
|
||||
def _h3_subjects(
|
||||
def _path_key(path: str) -> str:
|
||||
try:
|
||||
return str(Path(path).resolve()).casefold()
|
||||
except OSError:
|
||||
return str(path).casefold()
|
||||
|
||||
|
||||
def _paths_equal(a: str, b: str) -> bool:
|
||||
return bool(a and b) and _path_key(a) == _path_key(b)
|
||||
|
||||
|
||||
def _form_media_path(values: dict[str, Any], node_id: Any) -> str | None:
|
||||
"""A non-blank string the user stored on this workflow node."""
|
||||
raw = values.get(str(node_id))
|
||||
if raw is None:
|
||||
raw = values.get(node_id)
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
text = raw.strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _story_image_roster(
|
||||
characters: list[dict[str, Any]],
|
||||
location: dict[str, Any] | None,
|
||||
loc_image: str | None,
|
||||
inputs: list[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""Ordered subject roster + ref image paths for the H3 ref profile.
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Story images in fill order: scene characters, then the location.
|
||||
|
||||
Order = ref wiring order: scene characters first (scene order), then the
|
||||
location. Capped at the workflow's generic (Input:image) slot count so
|
||||
<Subject N> always matches an actually-wired reference image.
|
||||
Used only for image slots the user left empty.
|
||||
"""
|
||||
subjects: list[dict[str, Any]] = []
|
||||
paths: list[str] = []
|
||||
roster: list[dict[str, Any]] = []
|
||||
for c in characters:
|
||||
img = c.get("sheet_path") or c.get("portrait_path")
|
||||
if not img:
|
||||
continue
|
||||
subjects.append(
|
||||
roster.append(
|
||||
{
|
||||
"index": len(subjects) + 1,
|
||||
"kind": "character",
|
||||
"name": c.get("name"),
|
||||
"appearance": c.get("consistency_prompt") or c.get("appearance") or "",
|
||||
"path": img,
|
||||
}
|
||||
)
|
||||
paths.append(img)
|
||||
if loc_image:
|
||||
loc = location or {}
|
||||
subjects.append(
|
||||
roster.append(
|
||||
{
|
||||
"index": len(subjects) + 1,
|
||||
"kind": "location",
|
||||
"name": loc.get("name"),
|
||||
"appearance": loc.get("consistency_prompt") or loc.get("description") or "",
|
||||
"path": loc_image,
|
||||
}
|
||||
)
|
||||
paths.append(loc_image)
|
||||
cap = len(ref_image_slots(inputs))
|
||||
return subjects[:cap], paths[:cap]
|
||||
return roster
|
||||
|
||||
|
||||
def resolve_h3_references(
|
||||
inputs: list[dict[str, Any]],
|
||||
values: dict[str, Any],
|
||||
characters: list[dict[str, Any]],
|
||||
location: dict[str, Any] | None,
|
||||
loc_image: str | None,
|
||||
) -> tuple[list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
||||
"""Image subjects, image paths, and video refs for an H3 prompt.
|
||||
|
||||
Each ``(Input:image)`` slot uses the file the user put there. An empty
|
||||
slot falls back to the story image that would have filled that same index
|
||||
(characters, then location). Each ``(Input:video)`` slot the user filled
|
||||
becomes ``<Video N>``. Story text never replaces a file the user chose.
|
||||
"""
|
||||
roster = _story_image_roster(characters, location, loc_image)
|
||||
subjects: list[dict[str, Any]] = []
|
||||
image_paths: list[str] = []
|
||||
for index, slot in enumerate(ref_image_slots(inputs)):
|
||||
user_path = _form_media_path(values, slot["nodeId"])
|
||||
if user_path:
|
||||
matched = next(
|
||||
(item for item in roster if _paths_equal(item["path"], user_path)),
|
||||
None,
|
||||
)
|
||||
if matched:
|
||||
subject = {
|
||||
"kind": matched["kind"],
|
||||
"name": matched.get("name"),
|
||||
"appearance": matched.get("appearance") or "",
|
||||
"path": user_path,
|
||||
}
|
||||
else:
|
||||
subject = {
|
||||
"kind": "reference",
|
||||
"name": Path(user_path).stem or "reference",
|
||||
"appearance": "",
|
||||
"path": user_path,
|
||||
}
|
||||
elif index < len(roster):
|
||||
item = roster[index]
|
||||
subject = {
|
||||
"kind": item["kind"],
|
||||
"name": item.get("name"),
|
||||
"appearance": item.get("appearance") or "",
|
||||
"path": item["path"],
|
||||
}
|
||||
user_path = item["path"]
|
||||
else:
|
||||
continue
|
||||
subject["index"] = len(subjects) + 1
|
||||
subjects.append(subject)
|
||||
image_paths.append(user_path)
|
||||
videos: list[dict[str, Any]] = []
|
||||
for slot in ref_video_slots(inputs):
|
||||
user_path = _form_media_path(values, slot["nodeId"])
|
||||
if not user_path:
|
||||
continue
|
||||
videos.append(
|
||||
{
|
||||
"index": len(videos) + 1,
|
||||
"path": user_path,
|
||||
"name": Path(user_path).name,
|
||||
}
|
||||
)
|
||||
return subjects, image_paths, videos
|
||||
|
||||
|
||||
def _reference_signature(image_paths: list[str], video_paths: list[str]) -> str:
|
||||
"""Fingerprint of the files a draft was written against. Empty when none."""
|
||||
parts: list[str] = []
|
||||
if image_paths:
|
||||
parts.append("img=" + ",".join(image_paths))
|
||||
if video_paths:
|
||||
parts.append("vid=" + ",".join(video_paths))
|
||||
return "|".join(parts)
|
||||
|
||||
|
||||
async def _reference_media_parts(
|
||||
subjects: list[dict[str, Any]],
|
||||
videos: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Vision parts for the files under assets_dir. Missing files stay text-only."""
|
||||
parts: list[dict[str, Any]] = []
|
||||
for subject in subjects:
|
||||
path = str(subject.get("path") or "")
|
||||
url = _image_attachment_data_url(path)
|
||||
if not url:
|
||||
continue
|
||||
parts.append(
|
||||
{
|
||||
"type": "text",
|
||||
"text": (
|
||||
f"Picture {subject['index']} is <Subject {subject['index']}>. "
|
||||
"Describe the visible identity in this image."
|
||||
),
|
||||
}
|
||||
)
|
||||
parts.append({"type": "image_url", "image_url": {"url": url}})
|
||||
for video in videos:
|
||||
frames = await asyncio.to_thread(_video_attachment_frames, str(video.get("path") or ""))
|
||||
if not frames:
|
||||
continue
|
||||
parts.append(
|
||||
{
|
||||
"type": "text",
|
||||
"text": (
|
||||
f"<Video {video['index']}> frames, in time order. "
|
||||
"Take camera, timing, and physical action from these frames."
|
||||
),
|
||||
}
|
||||
)
|
||||
for ts, url in frames:
|
||||
parts.append(
|
||||
{"type": "text", "text": f"<Video {video['index']}> at {ts:.2f}s"}
|
||||
)
|
||||
parts.append({"type": "image_url", "image_url": {"url": url}})
|
||||
return parts
|
||||
|
||||
|
||||
async def _h3_rewrite(
|
||||
scene: dict[str, Any],
|
||||
subjects: list[dict[str, Any]],
|
||||
*,
|
||||
videos: list[dict[str, Any]] | None = None,
|
||||
continuity: str | None = None,
|
||||
timeout: float = 120.0,
|
||||
) -> str:
|
||||
"""LLM rewrite into H3's six-section format, deterministic template on failure.
|
||||
|
||||
The timeout bounds the whole wait for a dead endpoint before the template
|
||||
kicks in — the preview path passes a short value so the UI fails fast.
|
||||
Reference images and video frames are attached when the files are readable
|
||||
under assets_dir; a text-only endpoint still receives the file roster.
|
||||
"""
|
||||
videos = videos or []
|
||||
media_parts = await _reference_media_parts(subjects, videos)
|
||||
client = LLMClient.for_role("video", timeout=timeout)
|
||||
try:
|
||||
return await client.chat(
|
||||
build_minimax_h3_ref_messages(scene, subjects),
|
||||
build_minimax_h3_ref_messages(
|
||||
scene,
|
||||
subjects,
|
||||
videos=videos,
|
||||
media_parts=media_parts or None,
|
||||
continuity=continuity,
|
||||
),
|
||||
temperature=0.4,
|
||||
extra_body=settings.h3_rewrite_extra_body or None,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("MiniMax H3 prompt rewrite failed (%s); using fallback template", exc)
|
||||
return minimax_h3_ref_fallback(scene, subjects)
|
||||
return minimax_h3_ref_fallback(scene, subjects, videos)
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
@@ -236,13 +393,19 @@ def _stored_prompt_draft(clip: dict[str, Any]) -> str | None:
|
||||
return draft if isinstance(draft, str) and draft.strip() else None
|
||||
|
||||
|
||||
def _clip_prompt_hash(clip: dict[str, Any]) -> str:
|
||||
def _clip_prompt_hash(
|
||||
clip: dict[str, Any], *, references: str = "", ledger: str = ""
|
||||
) -> str:
|
||||
"""Cheap fingerprint of the inputs a draft was based on (stale detection).
|
||||
|
||||
Combines the scene's content fingerprint with the clip's own fields, so an
|
||||
edit to either invalidates saved drafts. Keeps the scene-only fields in the
|
||||
basis (heading/action/dialog/location/characters) so legacy drafts saved
|
||||
against scene-level hashes invalidate consistently.
|
||||
against scene-level hashes invalidate consistently. ``references`` is the
|
||||
resolved image/video file signature — changing a ref on the clip form
|
||||
invalidates a draft that was written against different files. Empty
|
||||
references keep the historical hash. ``ledger`` is the continuity plan's
|
||||
``based_on`` hash; a new plan invalidates a draft written against the old one.
|
||||
"""
|
||||
basis = "|".join(
|
||||
str(clip.get(k) or "")
|
||||
@@ -253,20 +416,53 @@ def _clip_prompt_hash(clip: dict[str, Any]) -> str:
|
||||
str(clip.get(k) or "")
|
||||
for k in ("description", "shot_size", "duration_sec", "order_index")
|
||||
)
|
||||
return hashlib.sha256(
|
||||
(basis + "|" + chars + "|clip:" + clip_basis).encode()
|
||||
).hexdigest()[:16]
|
||||
payload = basis + "|" + chars + "|clip:" + clip_basis
|
||||
if references:
|
||||
payload += "|refs:" + references
|
||||
# Empty ledger keeps the historical hash so drafts saved before a plan
|
||||
# existed still match until a plan hash is actually stored.
|
||||
if ledger:
|
||||
payload += "|ledger:" + ledger
|
||||
return hashlib.sha256(payload.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def _merged_form_values(
|
||||
clip: dict[str, Any], override: dict[str, Any] | None
|
||||
) -> dict[str, Any]:
|
||||
"""Saved clip form values, with the live request winning on each node."""
|
||||
values = dict(_stored_input_values(clip))
|
||||
if override:
|
||||
values.update({k: v for k, v in override.items() if v not in (None, "")})
|
||||
return values
|
||||
|
||||
|
||||
async def _critique_or_unavailable(
|
||||
prompt: str, plan: dict[str, Any] | None, clip_id: int
|
||||
) -> dict[str, Any]:
|
||||
"""Critic result. A raised judge becomes ok=false, never a 500."""
|
||||
try:
|
||||
return await critique_prompt(prompt, plan, clip_id)
|
||||
except Exception as exc:
|
||||
logger.warning("Continuity critic failed (%s)", exc)
|
||||
reason = str(exc).strip() or exc.__class__.__name__
|
||||
return {
|
||||
"ok": False,
|
||||
"notes": [f"Continuity critic unavailable: {reason[:180]}"],
|
||||
"unavailable": True,
|
||||
}
|
||||
|
||||
|
||||
async def preview_clip_prompt(
|
||||
project_id: int,
|
||||
clip_id: int,
|
||||
workflow_id: int | None = None,
|
||||
input_values: dict[str, Any] | None = None,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Resolve the exact prompt a Generate would send — without enqueueing.
|
||||
|
||||
Returns {"prompt": str, "profile": str, "from_draft": bool, "based_on": str}
|
||||
so the UI can show/edit/save it before the user commits to a render.
|
||||
Returns {"prompt", "profile", "from_draft", "based_on"} and, for an H3
|
||||
workflow, "critic": {"ok", "notes"}. The critic never blocks Generate.
|
||||
"""
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
@@ -314,30 +510,53 @@ async def preview_clip_prompt(
|
||||
raise ValueError("No enabled video workflow found — configure one in Settings")
|
||||
inputs = parse_dynamic_inputs(_workflow_json(workflow))
|
||||
profile = workflow.get("prompt_profile") or "prose"
|
||||
based_on = _clip_prompt_hash({**clip, "character_ids": [c["id"] for c in characters]})
|
||||
form_values = _merged_form_values(clip, input_values)
|
||||
subjects, _image_paths, videos = resolve_h3_references(
|
||||
inputs, form_values, characters, loc_row, loc_image
|
||||
)
|
||||
ref_sig = _reference_signature(_image_paths, [v["path"] for v in videos])
|
||||
hash_clip = {**clip, "character_ids": [c["id"] for c in characters]}
|
||||
|
||||
if profile == "minimax_h3_ref":
|
||||
# Fresh saved draft short-circuits the LLM call
|
||||
draft = _stored_prompt_draft(clip)
|
||||
if draft:
|
||||
meta = _clip_video_settings(clip).get("prompt_draft_meta") or {}
|
||||
if meta.get("based_on") == based_on:
|
||||
return {
|
||||
"prompt": draft,
|
||||
"profile": profile,
|
||||
"from_draft": True,
|
||||
"based_on": based_on,
|
||||
}
|
||||
subjects, _ = _h3_subjects(characters, loc_row, loc_image, inputs)
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{"message": f"H3 prompt rewrite · scene {clip.get('scene_order_index')} clip {clip.get('order_index')}", "project_id": project_id},
|
||||
plan = await ensure_continuity_plan(
|
||||
project_id, live_refs={clip_id: media_paths(form_values)}
|
||||
)
|
||||
# Preview is interactive — fail fast to the deterministic template
|
||||
# instead of making the user wait out a dead endpoint.
|
||||
prompt = await _h3_rewrite(scene, subjects, timeout=30.0)
|
||||
else:
|
||||
prompt = scene_video_prompt(scene, characters)
|
||||
ledger = str(plan.get("based_on") or "")
|
||||
based_on = _clip_prompt_hash(hash_clip, references=ref_sig, ledger=ledger)
|
||||
lock = continuity_lock_text(plan, clip_id)
|
||||
# A fresh draft skips the compiler. The critic still runs so the modal
|
||||
# can show continuity notes. Regenerate passes force=True.
|
||||
draft = _stored_prompt_draft(clip)
|
||||
from_draft = False
|
||||
meta = _clip_video_settings(clip).get("prompt_draft_meta") or {}
|
||||
if draft and not force and meta.get("based_on") == based_on:
|
||||
prompt = draft
|
||||
from_draft = True
|
||||
else:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{"message": f"H3 prompt rewrite · scene {clip.get('scene_order_index')} clip {clip.get('order_index')}", "project_id": project_id},
|
||||
)
|
||||
# Preview is interactive — fail fast to the deterministic template
|
||||
# instead of making the user wait out a dead endpoint.
|
||||
prompt = await _h3_rewrite(
|
||||
scene, subjects, videos=videos, continuity=lock, timeout=30.0
|
||||
)
|
||||
critic = await _critique_or_unavailable(prompt, plan, clip_id)
|
||||
# A dead judge must not 500. Drop a compiled candidate for the
|
||||
# template; keep a draft the user already saved.
|
||||
if critic.get("unavailable") and not from_draft:
|
||||
prompt = minimax_h3_ref_fallback(scene, subjects, videos)
|
||||
return {
|
||||
"prompt": prompt,
|
||||
"profile": profile,
|
||||
"from_draft": from_draft,
|
||||
"based_on": based_on,
|
||||
"critic": {"ok": bool(critic.get("ok")), "notes": list(critic.get("notes") or [])},
|
||||
}
|
||||
|
||||
based_on = _clip_prompt_hash(hash_clip, references=ref_sig)
|
||||
prompt = scene_video_prompt(scene, characters)
|
||||
return {"prompt": prompt, "profile": profile, "from_draft": False, "based_on": based_on}
|
||||
|
||||
|
||||
@@ -395,6 +614,7 @@ async def enqueue_video_jobs(
|
||||
)
|
||||
conn = get_db(settings.db_path)
|
||||
jobs: list[dict[str, Any]] = []
|
||||
continuity_plan: dict[str, Any] | None = None
|
||||
try:
|
||||
clips = _fetch_clips(conn, project_id, scene_ids=scene_ids, clip_ids=clip_ids)
|
||||
|
||||
@@ -471,15 +691,42 @@ async def enqueue_video_jobs(
|
||||
{k: v for k, v in input_values_override.items() if v not in (None, "")}
|
||||
)
|
||||
if profile == "minimax_h3_ref":
|
||||
subjects, ref_paths = _h3_subjects(characters, loc_row, loc_image, inputs)
|
||||
if continuity_plan is None:
|
||||
live_refs = None
|
||||
if input_values_override:
|
||||
live_refs = {
|
||||
int(c["id"]): media_paths(
|
||||
{
|
||||
**_stored_input_values(c),
|
||||
**{
|
||||
k: v
|
||||
for k, v in input_values_override.items()
|
||||
if v not in (None, "")
|
||||
},
|
||||
}
|
||||
)
|
||||
for c in clips
|
||||
}
|
||||
continuity_plan = await ensure_continuity_plan(
|
||||
project_id, live_refs=live_refs
|
||||
)
|
||||
subjects, ref_paths, videos = resolve_h3_references(
|
||||
inputs, extra_values, characters, loc_row, loc_image
|
||||
)
|
||||
ref_sig = _reference_signature(ref_paths, [v["path"] for v in videos])
|
||||
ledger = str((continuity_plan or {}).get("based_on") or "")
|
||||
lock = continuity_lock_text(continuity_plan, int(clip["id"]))
|
||||
# Prompt precedence: explicit request → saved (fresh) draft → LLM.
|
||||
# Batch enqueue compiles from the ledger and does not run the critic.
|
||||
explicit_prompt = (prompts or {}).get(clip["id"])
|
||||
fresh_draft = None
|
||||
if explicit_prompt is None:
|
||||
candidate = _stored_prompt_draft(clip)
|
||||
if candidate:
|
||||
meta = _clip_video_settings(clip).get("prompt_draft_meta") or {}
|
||||
if meta.get("based_on") == _clip_prompt_hash(hash_input):
|
||||
if meta.get("based_on") == _clip_prompt_hash(
|
||||
hash_input, references=ref_sig, ledger=ledger
|
||||
):
|
||||
fresh_draft = candidate
|
||||
if explicit_prompt is not None:
|
||||
prompt = explicit_prompt
|
||||
@@ -493,11 +740,14 @@ async def enqueue_video_jobs(
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
prompt = await _h3_rewrite(scene, subjects)
|
||||
prompt = await _h3_rewrite(
|
||||
scene, subjects, videos=videos, continuity=lock
|
||||
)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt,
|
||||
ref_images=ref_paths,
|
||||
ref_videos=[v["path"] for v in videos],
|
||||
duration=duration,
|
||||
extra=extra_values,
|
||||
)
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
``prose`` (default) sends the classic flat prose paragraph. ``minimax_h3_ref``
|
||||
rewrites the scene into MiniMax H3's six-section full-reference format at
|
||||
video-enqueue time (see calliope.agent.prompts).
|
||||
video-enqueue time (see calliope.agent.prompts). The rewrite reads the clip
|
||||
form's ``(Input:image)`` and ``(Input:video)`` files; story images only fill
|
||||
slots the user left empty.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ CREATE TABLE IF NOT EXISTS projects (
|
||||
target_duration TEXT,
|
||||
cover_path TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'draft',
|
||||
continuity_json TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
@@ -369,6 +370,8 @@ async def migrate_db(db_path: Path) -> None:
|
||||
project_cols = {r[1] for r in conn.execute("PRAGMA table_info(projects)").fetchall()}
|
||||
if "cover_path" not in project_cols:
|
||||
conn.execute("ALTER TABLE projects ADD COLUMN cover_path TEXT")
|
||||
if "continuity_json" not in project_cols:
|
||||
conn.execute("ALTER TABLE projects ADD COLUMN continuity_json TEXT")
|
||||
# Legacy canvases carry generic titles ("Untitled Canvas" or an older
|
||||
# iteration's "Project canvas"); name them after what they show
|
||||
# (project, else session). New canvases derive at create time.
|
||||
|
||||
@@ -259,3 +259,8 @@ class PreviewPromptRequest(BaseModel):
|
||||
scene_id: int | None = None
|
||||
clip_id: int | None = None
|
||||
workflow_id: int | None = None
|
||||
# Live Video-tab form values. Image and video slots here are the files the
|
||||
# H3 rewrite must describe; they win over the saved clip setup.
|
||||
input_values: dict[str, Any] | None = None
|
||||
# Skip a fresh saved draft and rewrite from the current references.
|
||||
force: bool = False
|
||||
|
||||
@@ -97,7 +97,11 @@ async def preview_prompt(project_id: int, payload: PreviewPromptRequest) -> dict
|
||||
clip_id = int(row["id"])
|
||||
try:
|
||||
return await preview_clip_prompt(
|
||||
project_id, clip_id, workflow_id=payload.workflow_id
|
||||
project_id,
|
||||
clip_id,
|
||||
workflow_id=payload.workflow_id,
|
||||
input_values=payload.input_values,
|
||||
force=payload.force,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
Reference in New Issue
Block a user