Calliope 1.1.0: publish backend, web, and example workflows
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Calliope backend package
|
||||
@@ -0,0 +1 @@
|
||||
# Agentic layer for Calliope
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Enqueue character/location image generation jobs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.prompts import character_image_prompt, location_image_prompt
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.smart_fill import smart_fill_inputs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
|
||||
def _has_text_inputs(inputs: list[dict[str, Any]]) -> bool:
|
||||
return any(inp.get("kind") in ("text", "textarea") for inp in inputs)
|
||||
|
||||
|
||||
def _sanitize_input_overrides(extra: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""Drop null/blank overrides so empty shared Text Prompt cannot wipe the entity prompt."""
|
||||
if not extra:
|
||||
return None
|
||||
cleaned: dict[str, Any] = {}
|
||||
for k, v in extra.items():
|
||||
if v is None:
|
||||
continue
|
||||
if isinstance(v, str) and not v.strip():
|
||||
continue
|
||||
cleaned[str(k)] = v
|
||||
return cleaned or None
|
||||
|
||||
|
||||
def _get_enabled_workflow(kind: str = "image", workflow_id: int | None = None) -> dict[str, Any] | None:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if workflow_id:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE id = ? AND is_enabled = 1", (workflow_id,)
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE kind = ? AND is_enabled = 1 ORDER BY id ASC LIMIT 1",
|
||||
(kind,),
|
||||
).fetchone()
|
||||
return row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def enqueue_asset_jobs(
|
||||
project_id: int,
|
||||
*,
|
||||
character_ids: list[int] | None = None,
|
||||
location_ids: list[int] | None = None,
|
||||
missing_only: bool = True,
|
||||
workflow_id: int | None = None,
|
||||
input_values_override: dict[str, Any] | None = None,
|
||||
asset_target: str = "sheet",
|
||||
prompt_override: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{"message": "Preparing asset generation from saved image prompts…", "project_id": project_id},
|
||||
)
|
||||
workflow = _get_enabled_workflow("image", workflow_id)
|
||||
workflow_json = json.loads(workflow["workflow_json"]) if workflow else {}
|
||||
inputs = parse_dynamic_inputs(workflow_json) if workflow_json else []
|
||||
target = asset_target if asset_target in {"sheet", "portrait"} else "sheet"
|
||||
input_values_override = _sanitize_input_overrides(input_values_override)
|
||||
has_override = bool(input_values_override)
|
||||
allow_empty_prompt = has_override or not _has_text_inputs(inputs)
|
||||
|
||||
conn = get_db(settings.db_path)
|
||||
jobs: list[dict[str, Any]] = []
|
||||
skipped: list[str] = []
|
||||
try:
|
||||
chars = conn.execute(
|
||||
"SELECT * FROM characters WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
locs = conn.execute(
|
||||
"SELECT * FROM locations WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
|
||||
for row in chars:
|
||||
c = row_to_dict(row)
|
||||
if character_ids is not None and c["id"] not in character_ids:
|
||||
continue
|
||||
existing = c.get("sheet_path") if target == "sheet" else c.get("portrait_path")
|
||||
if missing_only and existing:
|
||||
continue
|
||||
prompt = (prompt_override or "").strip() or character_image_prompt(c, kind=target)
|
||||
if not prompt.strip() and not allow_empty_prompt:
|
||||
skipped.append(c.get("name") or str(c["id"]))
|
||||
continue
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt or None,
|
||||
extra=input_values_override,
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="image",
|
||||
workflow_id=workflow["id"] if workflow else None,
|
||||
payload={
|
||||
"input_values": values,
|
||||
"character_id": c["id"],
|
||||
"asset_target": target,
|
||||
"prompt": prompt,
|
||||
},
|
||||
)
|
||||
jobs.append(job)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "image",
|
||||
"message": f"{c.get('name')} · {target}",
|
||||
},
|
||||
)
|
||||
|
||||
# Only enqueue locations when not doing a character-only generate
|
||||
enqueue_locs = location_ids is not None or character_ids is None
|
||||
if enqueue_locs:
|
||||
for row in locs:
|
||||
loc = row_to_dict(row)
|
||||
if location_ids is not None and loc["id"] not in location_ids:
|
||||
continue
|
||||
if character_ids is not None and location_ids is None:
|
||||
# Character-scoped call — skip locations
|
||||
continue
|
||||
if missing_only and loc.get("reference_image_path"):
|
||||
continue
|
||||
prompt = (prompt_override or "").strip() or location_image_prompt(loc)
|
||||
if not prompt.strip() and not allow_empty_prompt:
|
||||
skipped.append(loc.get("name") or str(loc["id"]))
|
||||
continue
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt or None,
|
||||
extra=input_values_override,
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="image",
|
||||
workflow_id=workflow["id"] if workflow else None,
|
||||
payload={
|
||||
"input_values": values,
|
||||
"location_id": loc["id"],
|
||||
"prompt": prompt,
|
||||
},
|
||||
)
|
||||
jobs.append(job)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "image",
|
||||
"message": f"{loc.get('name')} · environment",
|
||||
},
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if skipped:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": f"Skipped (empty image prompt): {', '.join(skipped)}",
|
||||
},
|
||||
)
|
||||
return jobs
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from calliope.config import settings
|
||||
|
||||
logger = logging.getLogger("calliope.llm")
|
||||
|
||||
|
||||
class LLMClient:
|
||||
def __init__(self) -> None:
|
||||
self.base_url = settings.llm_base_url.rstrip("/")
|
||||
self.model = settings.llm_model
|
||||
self.api_key = settings.llm_api_key
|
||||
self.client = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
return headers
|
||||
|
||||
async def chat(self, messages: list[dict[str, str]], temperature: float = 0.7, response_format: dict[str, str] | None = None) -> str:
|
||||
payload: dict[str, Any] = {
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
}
|
||||
if response_format:
|
||||
payload["response_format"] = response_format
|
||||
|
||||
url = f"{self.base_url}/chat/completions"
|
||||
logger.info("LLM request to %s with model %s", url, self.model)
|
||||
resp = await self.client.post(url, headers=self._headers(), json=payload)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
return content.strip()
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
|
||||
def extract_json(text: str) -> dict[str, Any]:
|
||||
"""Extract JSON object from a markdown code block or raw text."""
|
||||
text = text.strip()
|
||||
if text.startswith("```"):
|
||||
# Strip fenced code block
|
||||
lines = text.splitlines()
|
||||
if lines[0].startswith("```"):
|
||||
lines = lines[1:]
|
||||
if lines and lines[-1].startswith("```"):
|
||||
lines = lines[:-1]
|
||||
text = "\n".join(lines).strip()
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
async def generate_structured(messages: list[dict[str, str]], temperature: float = 0.7) -> dict[str, Any]:
|
||||
client = LLMClient()
|
||||
try:
|
||||
response_format = {"type": "json_object"}
|
||||
text = await client.chat(messages, temperature=temperature, response_format=response_format)
|
||||
return extract_json(text)
|
||||
finally:
|
||||
await client.close()
|
||||
@@ -0,0 +1,489 @@
|
||||
"""Prompts for Calliope story / script / asset generation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
STORY_GENERATION_SYSTEM = (
|
||||
"You are a story development assistant for an AI video studio. "
|
||||
"You output ONLY a single valid JSON object. "
|
||||
"HARD RULE: the beats array length must equal required_beat_count from the user message. "
|
||||
"Returning fewer beats is a failure. Longer target runtimes require many fine-grained beats."
|
||||
)
|
||||
|
||||
SCRIPT_GENERATION_SYSTEM = (
|
||||
"You are a screenwriter for short-form AI video. "
|
||||
"Write a scene-by-scene script that uses the provided characters and locations. "
|
||||
"Each scene's action is fed directly into a video generation model, so it must be a "
|
||||
"rich, multi-sentence cinematic description — never a single short sentence. "
|
||||
"Always respond with a single valid JSON object. "
|
||||
"HARD RULE: the scenes array length must equal required_scene_count from the user message. "
|
||||
"Returning fewer scenes is a failure. Respect the user's chosen scene count."
|
||||
)
|
||||
|
||||
|
||||
def estimate_target_seconds(target_duration: str | None) -> int:
|
||||
"""Best-effort parse of free-text duration into seconds."""
|
||||
text = (target_duration or "").strip().lower()
|
||||
if not text:
|
||||
return 30
|
||||
|
||||
# Explicit "N scenes" -> ~8s each as a coarse floor for beat planning
|
||||
scenes_m = re.search(r"(\d+)\s*scenes?", text)
|
||||
if scenes_m and "min" not in text and "sec" not in text:
|
||||
return max(30, int(scenes_m.group(1)) * 8)
|
||||
|
||||
minutes = 0.0
|
||||
seconds = 0.0
|
||||
for m in re.finditer(r"(\d+(?:\.\d+)?)\s*(min|mins|minutes?|m)\b", text):
|
||||
minutes += float(m.group(1))
|
||||
for m in re.finditer(r"(\d+(?:\.\d+)?)\s*(sec|secs|seconds?|s)\b", text):
|
||||
seconds += float(m.group(1))
|
||||
|
||||
if minutes or seconds:
|
||||
return max(15, int(minutes * 60 + seconds))
|
||||
|
||||
bare = re.search(r"\b(\d+(?:\.\d+)?)\b", text)
|
||||
if bare:
|
||||
n = float(bare.group(1))
|
||||
if "medium" in text or n >= 2:
|
||||
if n <= 30:
|
||||
return int(n * 60)
|
||||
if n <= 180:
|
||||
return int(n)
|
||||
|
||||
if "medium" in text:
|
||||
return 120
|
||||
if "short" in text or "brief" in text:
|
||||
return 30
|
||||
if "long" in text or "feature" in text:
|
||||
return 180
|
||||
return 60
|
||||
|
||||
|
||||
def recommend_beat_count(target_duration: str | None) -> int:
|
||||
"""
|
||||
Story beats for the AI video pipeline (~12s of narrative weight each).
|
||||
30s -> 4, 2 min -> 10, 5 min -> 25, 10 min -> 50 (capped at 60).
|
||||
"""
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
return max(4, min(60, round(secs / 12)))
|
||||
|
||||
|
||||
def recommend_scene_count(target_duration: str | None) -> int:
|
||||
"""Video scenes (~7s each) for the target runtime."""
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
return max(4, min(90, round(secs / 7)))
|
||||
|
||||
|
||||
def story_generation_user_prompt(
|
||||
title: str | None,
|
||||
idea: str | None,
|
||||
genre: str | None,
|
||||
tone: str | None,
|
||||
target_duration: str | None,
|
||||
) -> str:
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
beat_n = recommend_beat_count(target_duration)
|
||||
return f"""Create a story brief for an AI-generated video.
|
||||
|
||||
required_beat_count: {beat_n}
|
||||
estimated_runtime_seconds: {secs}
|
||||
target_duration_text: {target_duration or "short (~30 seconds)"}
|
||||
|
||||
Title: {title or "Untitled"}
|
||||
Idea: {idea or "No idea provided."}
|
||||
Genre: {genre or "Not specified"}
|
||||
Tone: {tone or "cinematic, atmospheric"}
|
||||
|
||||
=== HARD CONSTRAINTS (non-negotiable) ===
|
||||
1. The JSON field "beats" MUST contain EXACTLY {beat_n} objects.
|
||||
2. order_index must run 1, 2, 3, ... {beat_n} with no gaps.
|
||||
3. Do NOT summarize into a short arc. Do NOT return 5-8 beats for a long runtime.
|
||||
4. For ~{secs}s (~{secs // 60} min), beats are fine-grained plot steps (~12 seconds of story weight each) so Script can later expand into many short video clips.
|
||||
5. Cover full arc across all {beat_n} beats: setup, rising complications, midpoint turn, escalation, climax, resolution — spread across the whole list, not compressed into the first few items.
|
||||
6. If you are unsure, add more concrete incident beats rather than fewer abstract ones.
|
||||
|
||||
=== OUTPUT SCHEMA (JSON only) ===
|
||||
{{
|
||||
"title": "a compelling story title",
|
||||
"logline": "one sentence hook",
|
||||
"beats": [
|
||||
{{"order_index": 1, "title": "Beat title", "description": "what happens visually / dramatically"}}
|
||||
],
|
||||
"characters": [
|
||||
{{
|
||||
"name": "Name",
|
||||
"role": "protagonist|antagonist|supporting",
|
||||
"age": "approximate age",
|
||||
"appearance": "concise visual description for image generation",
|
||||
"personality": "concise personality traits"
|
||||
}}
|
||||
],
|
||||
"locations": [
|
||||
{{
|
||||
"name": "Location name",
|
||||
"description": "concise visual description for image generation"
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
Keep descriptions visual and concrete. Characters and locations should be reusable across scenes.
|
||||
FINAL CHECK before responding: beats.length == {beat_n}. If not, fix it."""
|
||||
|
||||
|
||||
def build_story_messages(
|
||||
title: str | None,
|
||||
idea: str | None,
|
||||
genre: str | None,
|
||||
tone: str | None,
|
||||
target_duration: str | None,
|
||||
) -> list[dict[str, str]]:
|
||||
return [
|
||||
{"role": "system", "content": STORY_GENERATION_SYSTEM},
|
||||
{
|
||||
"role": "user",
|
||||
"content": story_generation_user_prompt(title, idea, genre, tone, target_duration),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def build_script_messages(
|
||||
*,
|
||||
title: str,
|
||||
idea: str | None,
|
||||
beats: list[dict[str, Any]],
|
||||
characters: list[dict[str, Any]],
|
||||
locations: list[dict[str, Any]],
|
||||
target_duration: str | None,
|
||||
scene_count: int | None = None,
|
||||
) -> list[dict[str, str]]:
|
||||
secs = estimate_target_seconds(target_duration)
|
||||
recommended = recommend_scene_count(target_duration)
|
||||
# Honor an explicit / existing count (e.g. user added empty scenes before regenerate)
|
||||
scene_n = max(recommended, int(scene_count)) if scene_count and scene_count > 0 else recommended
|
||||
# Stretch runtime floor when the user asked for more clips than duration alone implies
|
||||
secs = max(secs, scene_n * 6)
|
||||
duration_hint = max(4, round(secs / scene_n))
|
||||
char_lines = "\n".join(
|
||||
f"- id={c['id']} {c['name']} ({c.get('role') or ''}): {c.get('appearance') or ''}"
|
||||
for c in characters
|
||||
)
|
||||
loc_lines = "\n".join(
|
||||
f"- id={l['id']} {l['name']}: {l.get('description') or ''}" for l in locations
|
||||
)
|
||||
beat_lines = "\n".join(
|
||||
f"- {b.get('order_index')}. {b.get('title')}: {b.get('description')}" for b in beats
|
||||
)
|
||||
user = f"""Write a scene script for this project.
|
||||
|
||||
Title: {title}
|
||||
Idea: {idea or ''}
|
||||
Target duration: {target_duration or 'short (~30-60 seconds)'}
|
||||
Estimated runtime: ~{secs} seconds
|
||||
required_scene_count: {scene_n}
|
||||
|
||||
Story beats:
|
||||
{beat_lines or '(none)'}
|
||||
|
||||
Characters:
|
||||
{char_lines or '(none)'}
|
||||
|
||||
Locations:
|
||||
{loc_lines or '(none)'}
|
||||
|
||||
=== HARD CONSTRAINTS (non-negotiable) ===
|
||||
1. The JSON field "scenes" MUST contain EXACTLY {scene_n} objects.
|
||||
2. order_index must run 1, 2, 3, ... {scene_n} with no gaps.
|
||||
3. Do NOT collapse back to fewer scenes. The user expanded the script to {scene_n} clips — fill all of them.
|
||||
4. Sum of duration_sec across all scenes should be approximately {secs} (within ±15%).
|
||||
5. Prefer short scenes (5–10s) — this is for AI video clips. Spread the beat arc across all {scene_n} scenes.
|
||||
|
||||
=== ACTION DETAIL (this text IS the video prompt — users copy it straight into the generator) ===
|
||||
Each scene's "action" is fed verbatim to an AI video generator. Write 4–6 vivid present-tense
|
||||
sentences (~80–130 words) per scene as ONE flowing natural-English paragraph — no bullet points,
|
||||
no labeled fragments (do NOT write "Shot:", "Lighting:", etc.), no line breaks. Rules:
|
||||
1. ONE SHOT PER SCENE. A clip is only {duration_hint} seconds — describe a single continuous
|
||||
camera setup with at most one simple action beat (one entrance, one gesture, one reveal).
|
||||
If a beat needs more room, split it across multiple scenes instead of compressing it.
|
||||
2. SHOT & MOTION. Name the framing and camera move (wide establishing, slow push-in, handheld
|
||||
tracking, low angle, rack focus) AND what visibly moves in frame — video models need motion:
|
||||
gestures, turning heads, hair and fabric, drifting dust, sweeping flashlight beams, an
|
||||
expression shifting. A static description produces a static clip.
|
||||
3. CHARACTER ANCHORS. The first time each character appears in a scene, attach a 3–8 word
|
||||
visual anchor taken from their description above (hair, outfit, one distinguishing
|
||||
feature), e.g. "MIA, a teenage girl with a chestnut ponytail and yellow rain jacket,".
|
||||
Later mentions in the same scene use the plain name. Never invent new appearance details —
|
||||
reuse these anchors so every clip matches the same face and wardrobe.
|
||||
4. ENVIRONMENT & CONTINUITY. Concrete set details, props, weather, time-of-day — consistent
|
||||
with the location description and with earlier scenes set in the same location.
|
||||
5. LIGHTING & MOOD. Named light sources, color palette, emotional tone of the moment.
|
||||
Describe only what is VISIBLE (no inner thoughts; no sounds or music — dialogue covers audio).
|
||||
Vary shot types across scenes — do not write {scene_n} identical wide shots.
|
||||
|
||||
=== DIALOGUE ===
|
||||
Keep lines short and natural. When delivery matters for performance, add a brief cue in
|
||||
parentheses after the speaker name, e.g. "MIA (whispering): line" or "LIAM (hushed, excited): line".
|
||||
|
||||
Respond ONLY with JSON:
|
||||
{{
|
||||
"scenes": [
|
||||
{{
|
||||
"order_index": 1,
|
||||
"heading": "INT. LOCATION - TIME",
|
||||
"action": "Wide establishing shot, slow push-in through the cracked main doorway. MIA, a teenage girl with a chestnut ponytail and yellow rain jacket, steps into the dusty main hall, lantern held high, its warm glow catching drifting dust motes around her cautious, widening eyes. She freezes mid-step, fingers tightening on the lantern handle as she looks up. Overturned desks and a collapsed chalkboard fill the frame; moonlight cuts through shattered windows in pale blue shafts. The mood is hushed and uneasy, shadows pooling at the edges of the lantern light.",
|
||||
"dialog": "MIA (whispering): line\\nNARRATOR: line",
|
||||
"duration_sec": 5,
|
||||
"character_ids": [1],
|
||||
"location_id": 1
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
Use only the provided character_ids and location_ids.
|
||||
FINAL CHECK before responding: scenes.length == {scene_n}, and every action is a flowing prose
|
||||
paragraph of 4–6 sentences (~80–130 words) covering ONE shot, with a character anchor at each
|
||||
character's first mention (no bullets, no labels, no invented appearances). If not, fix it."""
|
||||
return [
|
||||
{"role": "system", "content": SCRIPT_GENERATION_SYSTEM},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def character_sheet_prompt(character: dict[str, Any]) -> str:
|
||||
"""Transparent character-sheet template — what ComfyUI receives for turnarounds."""
|
||||
name = (character.get("name") or "Unnamed").strip()
|
||||
role = (character.get("role") or "character").strip()
|
||||
age = (character.get("age") or "unspecified age").strip()
|
||||
appearance = (character.get("appearance") or "no appearance notes yet").strip()
|
||||
personality = (character.get("personality") or "").strip()
|
||||
personality_line = f"Personality cues (visual only): {personality}\n" if personality else ""
|
||||
return (
|
||||
f"CHARACTER SHEET — {name}\n"
|
||||
f"Role: {role}. Age: {age}.\n"
|
||||
f"Appearance: {appearance}\n"
|
||||
f"{personality_line}"
|
||||
f"\n"
|
||||
f"Layout: single cinematic character reference sheet on a clean neutral backdrop, "
|
||||
f"multiple panels — front full body, side full body, back full body, three-quarter, "
|
||||
f"and a head close-up. Same face, hair, body proportions, and outfit in every panel. "
|
||||
f"Neutral standing pose, even studio lighting, high detail, no text watermarks, "
|
||||
f"no extra characters."
|
||||
)
|
||||
|
||||
|
||||
def character_portrait_prompt(character: dict[str, Any]) -> str:
|
||||
"""Transparent portrait template — face/upper-body lock for consistency."""
|
||||
name = (character.get("name") or "Unnamed").strip()
|
||||
role = (character.get("role") or "character").strip()
|
||||
age = (character.get("age") or "unspecified age").strip()
|
||||
appearance = (character.get("appearance") or "no appearance notes yet").strip()
|
||||
return (
|
||||
f"CHARACTER PORTRAIT — {name}\n"
|
||||
f"Role: {role}. Age: {age}.\n"
|
||||
f"Appearance: {appearance}\n"
|
||||
f"\n"
|
||||
f"Shot: cinematic head-and-shoulders portrait, eye-level, soft key light, "
|
||||
f"shallow depth of field, sharp facial features, consistent wardrobe collar/shoulders, "
|
||||
f"plain muted background, photoreal or high-end concept art, no text."
|
||||
)
|
||||
|
||||
|
||||
def location_reference_prompt(location: dict[str, Any]) -> str:
|
||||
"""Transparent environment reference template."""
|
||||
name = (location.get("name") or "Unnamed place").strip()
|
||||
description = (location.get("description") or "no description yet").strip()
|
||||
return (
|
||||
f"ENVIRONMENT REFERENCE — {name}\n"
|
||||
f"Description: {description}\n"
|
||||
f"\n"
|
||||
f"Shot: wide establishing concept art, cinematic atmosphere, clear readable space "
|
||||
f"for characters to stand in, consistent lighting and materials, no people, no text."
|
||||
)
|
||||
|
||||
|
||||
def character_image_prompt(character: dict[str, Any], *, kind: str = "sheet") -> str:
|
||||
"""
|
||||
Prefer the user-edited consistency_prompt when present.
|
||||
Otherwise fill the published template (never invent a hidden LLM prompt).
|
||||
"""
|
||||
saved = (character.get("consistency_prompt") or "").strip()
|
||||
if saved:
|
||||
return saved
|
||||
if kind == "portrait":
|
||||
return character_portrait_prompt(character)
|
||||
return character_sheet_prompt(character)
|
||||
|
||||
|
||||
def location_image_prompt(location: dict[str, Any]) -> str:
|
||||
saved = (location.get("consistency_prompt") or "").strip()
|
||||
if saved:
|
||||
return saved
|
||||
return location_reference_prompt(location)
|
||||
|
||||
|
||||
def scene_video_prompt(scene: dict[str, Any], characters: list[dict[str, Any]]) -> str:
|
||||
char_bits = ", ".join(
|
||||
f"{c.get('name')}: {c.get('consistency_prompt') or c.get('appearance') or ''}"
|
||||
for c in characters
|
||||
)
|
||||
parts = [
|
||||
scene.get("heading") or "",
|
||||
scene.get("action") or "",
|
||||
f"featuring {char_bits}" if char_bits else "",
|
||||
"cinematic motion, coherent continuity",
|
||||
]
|
||||
return ". ".join(p for p in parts if p)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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.
|
||||
|
||||
MINIMAX_H3_REF_SYSTEM = (
|
||||
"You rewrite scene descriptions into MiniMax H3's full-reference video prompt format. "
|
||||
"Output ONLY the rewritten prompt as plain text — no markdown fences, no commentary. "
|
||||
"The output must contain exactly these six sections in this order, each starting with "
|
||||
"its header on its own line:\n"
|
||||
"subject_definitions:\n"
|
||||
"summary:\n"
|
||||
"retention_analysis:\n"
|
||||
"detailed_description:\n"
|
||||
"overall_soundscape:\n"
|
||||
"non_diegetic_music:\n"
|
||||
"\n"
|
||||
"Rules:\n"
|
||||
"1. subject_definitions: one line per referenced subject 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"
|
||||
"2. summary: one short English paragraph starting with '[reference generation]' that "
|
||||
"states what happens using the <Subject N> labels.\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 "
|
||||
"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"
|
||||
"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"
|
||||
"Write everything in English except dialogue/lyrics inside <d> and visible on-screen text."
|
||||
)
|
||||
|
||||
|
||||
def _subject_roster_lines(subjects: list[dict[str, Any]]) -> str:
|
||||
lines = []
|
||||
for s in subjects:
|
||||
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'}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_minimax_h3_ref_messages(
|
||||
scene: dict[str, Any], subjects: list[dict[str, Any]]
|
||||
) -> list[dict[str, str]]:
|
||||
"""LLM messages that rewrite a scene into H3's six-section ref format.
|
||||
|
||||
subjects: ordered roster — index N corresponds to ref image slot N.
|
||||
"""
|
||||
roster = _subject_roster_lines(subjects) or (
|
||||
"(no reference images — describe subjects from the action text)"
|
||||
)
|
||||
user = f"""Rewrite this scene into MiniMax H3 full-reference format.
|
||||
|
||||
Scene heading: {scene.get('heading') or '(none)'}
|
||||
Scene duration: ~{scene.get('duration_sec') or 6} seconds
|
||||
|
||||
Action (visual base for detailed_description):
|
||||
{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):
|
||||
{roster}
|
||||
"""
|
||||
return [
|
||||
{"role": "system", "content": MINIMAX_H3_REF_SYSTEM},
|
||||
{"role": "user", "content": user},
|
||||
]
|
||||
|
||||
|
||||
def minimax_h3_ref_fallback(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> str:
|
||||
"""Deterministic six-section H3 prompt — used when the LLM rewrite fails."""
|
||||
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 ".")
|
||||
)
|
||||
retention.append(
|
||||
f"<Subject {s['index']}> (appears in [Shot 1]): fully_preserved - "
|
||||
f"the referenced appearance of \"{name}\" is 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'}."
|
||||
)
|
||||
|
||||
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()
|
||||
)
|
||||
|
||||
# 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.
|
||||
dialog_lines = []
|
||||
speaker_ids: dict[str, int] = {}
|
||||
name_to_subject = {(s.get("name") or "").strip().lower(): s["index"] for s in subjects}
|
||||
for raw in (scene.get("dialog") or "").splitlines():
|
||||
if ":" not in raw:
|
||||
continue
|
||||
speaker, line = raw.split(":", 1)
|
||||
speaker, line = speaker.strip(), line.strip()
|
||||
if not line:
|
||||
continue
|
||||
cue_m = re.search(r"\(([^)]*)\)\s*$", speaker)
|
||||
cue = cue_m.group(1).strip() if cue_m else ""
|
||||
base = re.sub(r"\s*\([^)]*\)\s*$", "", speaker).strip() or speaker
|
||||
key = base.lower()
|
||||
if key not in speaker_ids:
|
||||
speaker_ids[key] = len(speaker_ids) + 1
|
||||
sid = speaker_ids[key]
|
||||
subj_idx = name_to_subject.get(key)
|
||||
who = f"<Subject {subj_idx}> (S{sid})" if subj_idx else f"{base.title()} (S{sid})"
|
||||
dialog_lines.append(f"{who} says{f' {cue}' if cue else ''}, <d>[English] {line}</d>")
|
||||
if dialog_lines:
|
||||
body += "\n" + "\n".join(dialog_lines)
|
||||
|
||||
return (
|
||||
"subject_definitions:\n" + ("\n".join(defs) if defs else "N/A") + "\n\n"
|
||||
"summary:\n" + summary + "\n\n"
|
||||
"retention_analysis:\n" + ("\n".join(retention) if retention else "N/A") + "\n\n"
|
||||
"detailed_description:\n" + body + "\n\n"
|
||||
"overall_soundscape:\nN/A\n\n"
|
||||
"non_diegetic_music:\nN/A"
|
||||
)
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Generate scene scripts via LLM and persist them."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.llm import generate_structured
|
||||
from calliope.agent.prompts import build_script_messages, recommend_scene_count
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
|
||||
|
||||
def _persist_scenes(
|
||||
conn,
|
||||
project_id: int,
|
||||
scenes: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
created: list[dict[str, Any]] = []
|
||||
for scene in scenes:
|
||||
loc_id = scene.get("location_id")
|
||||
env_path = None
|
||||
if loc_id:
|
||||
loc = conn.execute(
|
||||
"SELECT reference_image_path FROM locations WHERE id = ? AND project_id = ?",
|
||||
(loc_id, project_id),
|
||||
).fetchone()
|
||||
if loc:
|
||||
env_path = loc["reference_image_path"]
|
||||
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO scenes
|
||||
(project_id, order_index, heading, action, dialog, duration_sec, location_id, env_image_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
scene.get("order_index", 0),
|
||||
scene.get("heading"),
|
||||
scene.get("action"),
|
||||
scene.get("dialog"),
|
||||
scene.get("duration_sec"),
|
||||
loc_id,
|
||||
env_path,
|
||||
),
|
||||
)
|
||||
scene_id = cur.lastrowid
|
||||
for cid in scene.get("character_ids") or []:
|
||||
exists = conn.execute(
|
||||
"SELECT id FROM characters WHERE id = ? AND project_id = ?",
|
||||
(cid, project_id),
|
||||
).fetchone()
|
||||
if exists:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)",
|
||||
(scene_id, cid),
|
||||
)
|
||||
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
|
||||
created.append(row_to_dict(row))
|
||||
return created
|
||||
|
||||
|
||||
async def generate_script(
|
||||
project_id: int,
|
||||
*,
|
||||
replace: bool = True,
|
||||
scene_count: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking", {"message": "Writing scene script…", "project_id": project_id}
|
||||
)
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not project:
|
||||
raise ValueError("Project not found")
|
||||
p = row_to_dict(project)
|
||||
beats = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM story_beats WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
]
|
||||
characters = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM characters WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
locations = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM locations WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
|
||||
existing_n = conn.execute(
|
||||
"SELECT COUNT(*) AS n FROM scenes WHERE project_id = ?",
|
||||
(project_id,),
|
||||
).fetchone()["n"]
|
||||
recommended = recommend_scene_count(p.get("target_duration"))
|
||||
# Prefer explicit request, else keep at least the board the user already built
|
||||
requested = scene_count if scene_count and scene_count > 0 else existing_n
|
||||
required_scenes = max(recommended, int(requested)) if requested else recommended
|
||||
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": f"Writing {required_scenes} scenes "
|
||||
f"(board had {existing_n}; duration suggests {recommended})…",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
|
||||
messages = build_script_messages(
|
||||
title=p["title"],
|
||||
idea=p.get("idea"),
|
||||
beats=beats,
|
||||
characters=characters,
|
||||
locations=locations,
|
||||
target_duration=p.get("target_duration"),
|
||||
scene_count=required_scenes,
|
||||
)
|
||||
result = await generate_structured(messages, temperature=0.7)
|
||||
scenes_out = result.get("scenes") or []
|
||||
|
||||
if len(scenes_out) < required_scenes:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": (
|
||||
f"Model returned {len(scenes_out)} scenes; "
|
||||
f"required {required_scenes}. Retrying…"
|
||||
),
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
retry_messages = [
|
||||
messages[0],
|
||||
{
|
||||
"role": "user",
|
||||
"content": messages[1]["content"]
|
||||
+ (
|
||||
f"\n\nPREVIOUS ATTEMPT FAILED: it only had {len(scenes_out)} scenes. "
|
||||
f"You MUST return exactly {required_scenes} scenes this time."
|
||||
),
|
||||
},
|
||||
]
|
||||
result = await generate_structured(retry_messages, temperature=0.5)
|
||||
scenes_out = result.get("scenes") or []
|
||||
if len(scenes_out) < required_scenes:
|
||||
raise ValueError(
|
||||
f"Script returned {len(scenes_out)} scenes but {required_scenes} were required. "
|
||||
"Add scenes again and retry, or raise target duration."
|
||||
)
|
||||
|
||||
if replace:
|
||||
scene_ids = [
|
||||
r["id"]
|
||||
for r in conn.execute(
|
||||
"SELECT id FROM scenes WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
for sid in scene_ids:
|
||||
conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (sid,))
|
||||
conn.execute("DELETE FROM scenes WHERE project_id = ?", (project_id,))
|
||||
|
||||
created = _persist_scenes(conn, project_id, scenes_out)
|
||||
|
||||
conn.execute(
|
||||
"UPDATE projects SET status = 'in_progress', updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(project_id,),
|
||||
)
|
||||
conn.commit()
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": f"Script written — {len(created)} scenes",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
return {"ok": True, "scenes": created, "generated": result}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Enqueue per-scene video generation jobs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from calliope.agent.llm import LLMClient
|
||||
from calliope.agent.prompts import (
|
||||
build_minimax_h3_ref_messages,
|
||||
minimax_h3_ref_fallback,
|
||||
scene_video_prompt,
|
||||
)
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs
|
||||
from calliope.comfyui.smart_fill import ref_image_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
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
logger = logging.getLogger("calliope.video_agent")
|
||||
|
||||
|
||||
def _h3_subjects(
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
subjects: list[dict[str, Any]] = []
|
||||
paths: list[str] = []
|
||||
for c in characters:
|
||||
img = c.get("sheet_path") or c.get("portrait_path")
|
||||
if not img:
|
||||
continue
|
||||
subjects.append(
|
||||
{
|
||||
"index": len(subjects) + 1,
|
||||
"kind": "character",
|
||||
"name": c.get("name"),
|
||||
"appearance": c.get("consistency_prompt") or c.get("appearance") or "",
|
||||
}
|
||||
)
|
||||
paths.append(img)
|
||||
if loc_image:
|
||||
loc = location or {}
|
||||
subjects.append(
|
||||
{
|
||||
"index": len(subjects) + 1,
|
||||
"kind": "location",
|
||||
"name": loc.get("name"),
|
||||
"appearance": loc.get("consistency_prompt") or loc.get("description") or "",
|
||||
}
|
||||
)
|
||||
paths.append(loc_image)
|
||||
cap = len(ref_image_slots(inputs))
|
||||
return subjects[:cap], paths[:cap]
|
||||
|
||||
|
||||
async def _h3_rewrite(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> str:
|
||||
"""LLM rewrite into H3's six-section format, deterministic template on failure."""
|
||||
client = LLMClient()
|
||||
try:
|
||||
return await client.chat(
|
||||
build_minimax_h3_ref_messages(scene, subjects), temperature=0.4
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("MiniMax H3 prompt rewrite failed (%s); using fallback template", exc)
|
||||
return minimax_h3_ref_fallback(scene, subjects)
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
def _get_workflow(workflow_id: int | None = None) -> dict[str, Any] | None:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if workflow_id:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE id = ? AND is_enabled = 1", (workflow_id,)
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE kind = 'video' AND is_enabled = 1 ORDER BY id ASC LIMIT 1"
|
||||
).fetchone()
|
||||
if not row:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM workflows WHERE is_enabled = 1 ORDER BY id ASC LIMIT 1"
|
||||
).fetchone()
|
||||
return row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def enqueue_video_jobs(
|
||||
project_id: int,
|
||||
*,
|
||||
scene_ids: list[int] | None = None,
|
||||
workflow_id: int | None = None,
|
||||
input_values_override: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
await event_bus.publish(
|
||||
"agent.thinking", {"message": "Queuing video jobs…", "project_id": project_id}
|
||||
)
|
||||
conn = get_db(settings.db_path)
|
||||
jobs: list[dict[str, Any]] = []
|
||||
try:
|
||||
query = "SELECT * FROM scenes WHERE project_id = ?"
|
||||
params: list[Any] = [project_id]
|
||||
if scene_ids:
|
||||
placeholders = ",".join("?" * len(scene_ids))
|
||||
query += f" AND id IN ({placeholders})"
|
||||
params.extend(scene_ids)
|
||||
query += " ORDER BY order_index"
|
||||
scenes = [row_to_dict(r) for r in conn.execute(query, params).fetchall()]
|
||||
|
||||
for scene in scenes:
|
||||
# Supersede leftover pending jobs so a re-Generate always starts fresh
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = 'superseded by new generate',
|
||||
completed_at = CURRENT_TIMESTAMP
|
||||
WHERE scene_id = ? AND kind = 'video' AND status = 'pending'
|
||||
""",
|
||||
(scene["id"],),
|
||||
)
|
||||
# Clear prior clip so UI shows generating instead of the old video
|
||||
conn.execute(
|
||||
"UPDATE scenes SET video_path = NULL WHERE id = ?",
|
||||
(scene["id"],),
|
||||
)
|
||||
# Commit BEFORE enqueue: queue_manager.enqueue writes on its own
|
||||
# connection, and holding this transaction open across that call
|
||||
# self-deadlocks (sqlite3.OperationalError: database is locked).
|
||||
conn.commit()
|
||||
|
||||
wf_id = workflow_id or scene.get("workflow_id")
|
||||
workflow = _get_workflow(wf_id)
|
||||
workflow_json = json.loads(workflow["workflow_json"]) if workflow else {}
|
||||
inputs = parse_dynamic_inputs(workflow_json) if workflow_json else []
|
||||
|
||||
char_rows = conn.execute(
|
||||
"""
|
||||
SELECT c.* FROM characters c
|
||||
JOIN scene_characters sc ON sc.character_id = c.id
|
||||
WHERE sc.scene_id = ?
|
||||
""",
|
||||
(scene["id"],),
|
||||
).fetchall()
|
||||
characters = [row_to_dict(r) for r in char_rows]
|
||||
char_image = next(
|
||||
(c.get("sheet_path") or c.get("portrait_path") for c in characters if c.get("sheet_path") or c.get("portrait_path")),
|
||||
None,
|
||||
)
|
||||
loc_image = scene.get("env_image_path")
|
||||
loc_row: dict[str, Any] | None = None
|
||||
if scene.get("location_id"):
|
||||
row = conn.execute(
|
||||
"SELECT name, description, consistency_prompt, reference_image_path "
|
||||
"FROM locations WHERE id = ?",
|
||||
(scene["location_id"],),
|
||||
).fetchone()
|
||||
if row:
|
||||
loc_row = row_to_dict(row)
|
||||
if not loc_image:
|
||||
loc_image = loc_row["reference_image_path"]
|
||||
|
||||
profile = (workflow or {}).get("prompt_profile") or "prose"
|
||||
if profile == "minimax_h3_ref":
|
||||
subjects, ref_paths = _h3_subjects(characters, loc_row, loc_image, inputs)
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"message": f"H3 prompt rewrite · scene {scene.get('order_index')}",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
prompt = await _h3_rewrite(scene, subjects)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt,
|
||||
ref_images=ref_paths,
|
||||
duration=scene.get("duration_sec"),
|
||||
extra=input_values_override,
|
||||
)
|
||||
else:
|
||||
prompt = scene_video_prompt(scene, characters)
|
||||
values = smart_fill_inputs(
|
||||
inputs,
|
||||
prompt=prompt,
|
||||
character_image=char_image,
|
||||
location_image=loc_image,
|
||||
extra=input_values_override,
|
||||
)
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind="video",
|
||||
workflow_id=workflow["id"] if workflow else None,
|
||||
scene_id=scene["id"],
|
||||
payload={"input_values": values, "prompt": prompt},
|
||||
)
|
||||
if workflow and not scene.get("workflow_id"):
|
||||
conn.execute(
|
||||
"UPDATE scenes SET workflow_id = ? WHERE id = ?",
|
||||
(workflow["id"], scene["id"]),
|
||||
)
|
||||
# Never hold a write lock across awaits (event publish below).
|
||||
conn.commit()
|
||||
jobs.append(job)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "video",
|
||||
"message": f"Scene · {scene.get('heading') or scene.get('order_index')}",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jobs
|
||||
@@ -0,0 +1,5 @@
|
||||
"""ComfyUI integration package."""
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.patcher import patch_workflow
|
||||
|
||||
__all__ = ["parse_dynamic_inputs", "parse_dynamic_outputs", "patch_workflow"]
|
||||
@@ -0,0 +1,135 @@
|
||||
"""ComfyUI HTTP client: upload, prompt, poll, download."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.comfyui.registry import IMAGE_CLASSES, AUDIO_CLASSES
|
||||
|
||||
logger = logging.getLogger("calliope.comfyui")
|
||||
|
||||
|
||||
class ComfyUIClient:
|
||||
def __init__(self, base_url: str | None = None) -> None:
|
||||
self.base_url = (base_url or settings.comfyui_base_url).rstrip("/")
|
||||
self.client_id = str(uuid.uuid4())
|
||||
self._http = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._http.aclose()
|
||||
|
||||
async def health(self) -> bool:
|
||||
try:
|
||||
resp = await self._http.get(f"{self.base_url}/system_stats")
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def upload_image(self, path: Path, subfolder: str = "calliope") -> str:
|
||||
data = path.read_bytes()
|
||||
files = {"image": (path.name, data, "application/octet-stream")}
|
||||
form = {"overwrite": "true", "subfolder": subfolder}
|
||||
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
|
||||
resp.raise_for_status()
|
||||
result = resp.json()
|
||||
name = result.get("name", path.name)
|
||||
sub = result.get("subfolder") or subfolder
|
||||
return f"{sub}/{name}" if sub else name
|
||||
|
||||
async def upload_audio(self, path: Path, subfolder: str = "calliope") -> str:
|
||||
data = path.read_bytes()
|
||||
files = {"image": (path.name, data, "application/octet-stream")} # Comfy uses image field
|
||||
form = {"overwrite": "true", "subfolder": subfolder, "type": "input"}
|
||||
resp = await self._http.post(f"{self.base_url}/upload/image", files=files, data=form)
|
||||
resp.raise_for_status()
|
||||
result = resp.json()
|
||||
name = result.get("name", path.name)
|
||||
sub = result.get("subfolder") or subfolder
|
||||
return f"{sub}/{name}" if sub else name
|
||||
|
||||
async def prepare_media_inputs(self, workflow: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Upload local file paths referenced in LoadImage/LoadAudio nodes."""
|
||||
for _node_id, node in workflow.items():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
class_type = node.get("class_type", "")
|
||||
inputs = node.get("inputs") or {}
|
||||
if class_type in IMAGE_CLASSES:
|
||||
image = inputs.get("image")
|
||||
if isinstance(image, str) and self._looks_like_local_path(image):
|
||||
path = Path(image)
|
||||
if path.exists():
|
||||
inputs["image"] = await self.upload_image(path)
|
||||
node["inputs"] = inputs
|
||||
elif class_type in AUDIO_CLASSES:
|
||||
audio = inputs.get("audio")
|
||||
if isinstance(audio, str) and self._looks_like_local_path(audio):
|
||||
path = Path(audio)
|
||||
if path.exists():
|
||||
inputs["audio"] = await self.upload_audio(path)
|
||||
node["inputs"] = inputs
|
||||
return workflow
|
||||
|
||||
@staticmethod
|
||||
def _looks_like_local_path(value: str) -> bool:
|
||||
if value.startswith("http://") or value.startswith("https://"):
|
||||
return False
|
||||
p = Path(value)
|
||||
return p.is_absolute() or "/" in value or "\\" in value
|
||||
|
||||
async def queue_prompt(self, workflow: dict[str, Any]) -> str:
|
||||
payload = {"prompt": workflow, "client_id": self.client_id}
|
||||
resp = await self._http.post(f"{self.base_url}/prompt", json=payload)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
prompt_id = data.get("prompt_id")
|
||||
if not prompt_id:
|
||||
raise RuntimeError(f"ComfyUI /prompt missing prompt_id: {data}")
|
||||
return prompt_id
|
||||
|
||||
async def get_history(self, prompt_id: str) -> dict[str, Any] | None:
|
||||
resp = await self._http.get(f"{self.base_url}/history/{prompt_id}")
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get(prompt_id)
|
||||
|
||||
async def download_image(
|
||||
self,
|
||||
filename: str,
|
||||
subfolder: str = "",
|
||||
folder_type: str = "output",
|
||||
dest: Path | None = None,
|
||||
) -> Path:
|
||||
params = {"filename": filename, "subfolder": subfolder, "type": folder_type}
|
||||
resp = await self._http.get(f"{self.base_url}/view", params=params)
|
||||
resp.raise_for_status()
|
||||
if dest is None:
|
||||
dest = settings.assets_dir / "comfy_downloads" / filename
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(resp.content)
|
||||
return dest
|
||||
|
||||
async def interrupt(self) -> None:
|
||||
try:
|
||||
await self._http.post(f"{self.base_url}/interrupt")
|
||||
except Exception as exc:
|
||||
logger.warning("ComfyUI interrupt failed: %s", exc)
|
||||
|
||||
def extract_outputs(self, history: dict[str, Any]) -> list[dict[str, str]]:
|
||||
outputs: list[dict[str, str]] = []
|
||||
for _node_id, node_out in (history.get("outputs") or {}).items():
|
||||
for key in ("images", "gifs", "videos"):
|
||||
for item in node_out.get(key) or []:
|
||||
outputs.append(
|
||||
{
|
||||
"filename": item.get("filename", ""),
|
||||
"subfolder": item.get("subfolder", ""),
|
||||
"type": item.get("type", "output"),
|
||||
}
|
||||
)
|
||||
return outputs
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Dry-run placeholder asset generation when ComfyUI is offline."""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _png_chunk(chunk_type: bytes, data: bytes) -> bytes:
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ chunk_type
|
||||
+ data
|
||||
+ struct.pack(">I", zlib.crc32(chunk_type + data) & 0xFFFFFFFF)
|
||||
)
|
||||
|
||||
|
||||
def write_placeholder_png(dest: Path, width: int = 512, height: int = 512, label: str = "dry-run") -> Path:
|
||||
"""Write a minimal solid-color PNG (no Pillow dependency)."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Dark purple-ish RGB
|
||||
r, g, b = 40, 30, 70
|
||||
raw = b""
|
||||
for _y in range(height):
|
||||
raw += b"\x00" # filter none
|
||||
raw += bytes([r, g, b]) * width
|
||||
compressed = zlib.compress(raw, 9)
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
png = b"\x89PNG\r\n\x1a\n"
|
||||
png += _png_chunk(b"IHDR", ihdr)
|
||||
png += _png_chunk(b"IDAT", compressed)
|
||||
png += _png_chunk(b"IEND", b"")
|
||||
dest.write_bytes(png)
|
||||
# Write a tiny sidecar note
|
||||
dest.with_suffix(".txt").write_text(f"Calliope dry-run placeholder: {label}\n", encoding="utf-8")
|
||||
return dest
|
||||
|
||||
|
||||
def write_placeholder_mp4(dest: Path, label: str = "dry-run") -> Path:
|
||||
"""Write a tiny stub file with .mp4 extension (not a real video codec)."""
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Minimal ftyp box so some players recognize container; still a stub.
|
||||
data = (
|
||||
b"\x00\x00\x00\x18ftypmp42"
|
||||
b"\x00\x00\x00\x00mp42isom"
|
||||
+ f"Calliope dry-run stub: {label}".encode("utf-8")
|
||||
)
|
||||
dest.write_bytes(data)
|
||||
return dest
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Parse ComfyUI API-format workflows for (Input[:role]) / (Output[:role]) titled nodes."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.registry import (
|
||||
ComfyOutputKind,
|
||||
IMAGE_CLASSES,
|
||||
AUDIO_CLASSES,
|
||||
class_to_input_kind,
|
||||
class_to_output_kind,
|
||||
)
|
||||
from calliope.comfyui.roles import (
|
||||
normalize_input_role,
|
||||
normalize_output_role,
|
||||
parse_title_tag,
|
||||
)
|
||||
|
||||
|
||||
def extract_default_value(node: dict[str, Any]) -> str | int | float | None:
|
||||
class_type = node.get("class_type", "")
|
||||
inputs = node.get("inputs") or {}
|
||||
if class_type in IMAGE_CLASSES or class_type in AUDIO_CLASSES:
|
||||
return None
|
||||
if isinstance(inputs.get("text"), str):
|
||||
return inputs["text"]
|
||||
value = inputs.get("value")
|
||||
if isinstance(value, (str, int, float)):
|
||||
return value
|
||||
if isinstance(inputs.get("int"), (int, float)):
|
||||
return inputs["int"]
|
||||
if isinstance(inputs.get("float"), (int, float)):
|
||||
return inputs["float"]
|
||||
return None
|
||||
|
||||
|
||||
def parse_dynamic_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
results: list[dict[str, Any]] = []
|
||||
for node_id, node in workflow.items():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
title = (node.get("_meta") or {}).get("title") or ""
|
||||
kind, role, label = parse_title_tag(title)
|
||||
if kind != "input":
|
||||
continue
|
||||
results.append(
|
||||
{
|
||||
"nodeId": str(node_id),
|
||||
"label": label or node.get("class_type", node_id),
|
||||
"role": normalize_input_role(role),
|
||||
"kind": class_to_input_kind(node.get("class_type", "")),
|
||||
"defaultValue": extract_default_value(node),
|
||||
"required": True,
|
||||
}
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def parse_dynamic_outputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
results: list[dict[str, Any]] = []
|
||||
for node_id, node in workflow.items():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
title = (node.get("_meta") or {}).get("title") or ""
|
||||
kind, role, label = parse_title_tag(title)
|
||||
if kind != "output":
|
||||
continue
|
||||
out_kind: ComfyOutputKind = class_to_output_kind(node.get("class_type", ""))
|
||||
canon = normalize_output_role(role)
|
||||
if canon == "video":
|
||||
out_kind = "video"
|
||||
elif canon == "image":
|
||||
out_kind = "image"
|
||||
results.append(
|
||||
{
|
||||
"nodeId": str(node_id),
|
||||
"label": label or node.get("class_type", node_id),
|
||||
"role": canon,
|
||||
"kind": out_kind,
|
||||
}
|
||||
)
|
||||
return results
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Patch user values into ComfyUI API-format workflow by nodeId."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.registry import class_to_patch_field
|
||||
|
||||
|
||||
def patch_workflow(
|
||||
base: dict[str, Any],
|
||||
values_by_node_id: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
patched = copy.deepcopy(base)
|
||||
for node_id, value in values_by_node_id.items():
|
||||
if value is None:
|
||||
continue
|
||||
key = str(node_id)
|
||||
node = patched.get(key)
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
inputs = dict(node.get("inputs") or {})
|
||||
field = class_to_patch_field(node.get("class_type", ""))
|
||||
if field == "text" and "text" not in inputs and "value" in inputs:
|
||||
field = "value"
|
||||
if field == "value" and "text" in inputs and "value" not in inputs:
|
||||
field = "text"
|
||||
inputs[field] = value
|
||||
node["inputs"] = inputs
|
||||
patched[key] = node
|
||||
return patched
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Prompt profiles: how scene prompts are formatted for a workflow's model.
|
||||
|
||||
``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).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
PROFILES = ("prose", "minimax_h3_ref")
|
||||
|
||||
DEFAULT_PROFILE = "prose"
|
||||
|
||||
|
||||
def detect_prompt_profile(workflow_json: dict[str, Any]) -> str:
|
||||
"""Suggest a prompt profile from the workflow's node classes.
|
||||
|
||||
Deterministic class-type check (not title guessing): any MiniMaxH3* node
|
||||
(e.g. ``MiniMaxH3ReferenceToVideo``) means the workflow expects the H3
|
||||
full-reference prompt format.
|
||||
"""
|
||||
for node in workflow_json.values():
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if str(node.get("class_type", "")).startswith("MiniMaxH3"):
|
||||
return "minimax_h3_ref"
|
||||
return DEFAULT_PROFILE
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Unified class_type → kind + patch-field registry (MuseAgent port)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
ComfyInputKind = Literal["text", "textarea", "number", "image", "image_url", "audio"]
|
||||
ComfyOutputKind = Literal["image", "video", "other"]
|
||||
PatchField = Literal["image", "url", "audio", "text", "value", "int", "float"]
|
||||
|
||||
TEXT_AREA_CLASSES = frozenset(
|
||||
{
|
||||
"CLIPTextEncode",
|
||||
"Note",
|
||||
"ShowText",
|
||||
"ImpactWildcardProcessor",
|
||||
"PrimitiveStringMultiline",
|
||||
"PrimitiveString",
|
||||
}
|
||||
)
|
||||
NUMBER_CLASSES = frozenset(
|
||||
{"INT", "FLOAT", "PrimitiveInt", "PrimitiveFloat", "KSampler", "KSamplerAdvanced"}
|
||||
)
|
||||
IMAGE_CLASSES = frozenset({"LoadImage", "ImageLoader", "ETN_LoadImageBase64"})
|
||||
IMAGE_URL_CLASSES = frozenset({"Load Image From Url (mtb)"})
|
||||
AUDIO_CLASSES = frozenset({"LoadAudio", "VHS_LoadAudio"})
|
||||
VIDEO_OUTPUT_CLASSES = frozenset(
|
||||
{"VHS_VideoCombine", "SaveVideo", "VideoOutput", "AnimateDiffCombine"}
|
||||
)
|
||||
IMAGE_OUTPUT_CLASSES = frozenset(
|
||||
{"SaveImage", "PreviewImage", "SaveImageWebsocket", "ETN_SendImageWebSocket"}
|
||||
)
|
||||
|
||||
|
||||
def class_to_input_kind(class_type: str) -> ComfyInputKind:
|
||||
if class_type in IMAGE_CLASSES:
|
||||
return "image"
|
||||
if class_type in IMAGE_URL_CLASSES:
|
||||
return "image_url"
|
||||
if class_type in AUDIO_CLASSES:
|
||||
return "audio"
|
||||
if class_type in NUMBER_CLASSES:
|
||||
return "number"
|
||||
if class_type in TEXT_AREA_CLASSES:
|
||||
return "textarea"
|
||||
lower = class_type.lower()
|
||||
if "image" in lower or "load" in lower:
|
||||
return "image"
|
||||
if "audio" in lower:
|
||||
return "audio"
|
||||
if "int" in lower or "float" in lower or "seed" in lower:
|
||||
return "number"
|
||||
if "text" in lower or "clip" in lower or "prompt" in lower:
|
||||
return "textarea"
|
||||
return "text"
|
||||
|
||||
|
||||
def class_to_patch_field(class_type: str) -> PatchField:
|
||||
if class_type in IMAGE_CLASSES:
|
||||
return "image"
|
||||
if class_type in IMAGE_URL_CLASSES:
|
||||
return "url"
|
||||
if class_type in AUDIO_CLASSES:
|
||||
return "audio"
|
||||
if class_type in {"CLIPTextEncode", "Note", "ShowText", "ImpactWildcardProcessor"}:
|
||||
return "text"
|
||||
if class_type.startswith("Primitive"):
|
||||
return "value"
|
||||
kind = class_to_input_kind(class_type)
|
||||
if kind == "image":
|
||||
return "image"
|
||||
if kind == "image_url":
|
||||
return "url"
|
||||
if kind == "audio":
|
||||
return "audio"
|
||||
if kind == "textarea":
|
||||
return "text"
|
||||
return "value"
|
||||
|
||||
|
||||
def class_to_output_kind(class_type: str) -> ComfyOutputKind:
|
||||
if class_type in VIDEO_OUTPUT_CLASSES or "video" in class_type.lower():
|
||||
return "video"
|
||||
if class_type in IMAGE_OUTPUT_CLASSES or "image" in class_type.lower():
|
||||
return "image"
|
||||
return "other"
|
||||
@@ -0,0 +1,85 @@
|
||||
"""ComfyUI node title role tags: (Input:prompt), (Output:image), etc."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
# Title tag: (Input), (Input:prompt), (Output:image), …
|
||||
_TITLE_TAG_RE = re.compile(
|
||||
r"\((?P<kind>Input|Output)(?::(?P<role>[a-zA-Z0-9_-]+))?\)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Canonical role → accepted aliases (all lowercased).
|
||||
INPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
|
||||
"prompt": frozenset({"prompt", "positive"}),
|
||||
"negative": frozenset({"negative", "neg"}),
|
||||
"width": frozenset({"width", "w"}),
|
||||
"height": frozenset({"height", "h"}),
|
||||
"character": frozenset({"character", "char", "portrait", "sheet", "face", "ref"}),
|
||||
"location": frozenset({"location", "loc", "environment", "env", "background", "scene"}),
|
||||
"image": frozenset({"image", "img"}),
|
||||
"seed": frozenset({"seed"}),
|
||||
"duration": frozenset({"duration", "dur", "length", "seconds"}),
|
||||
}
|
||||
|
||||
OUTPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
|
||||
"image": frozenset({"image", "img"}),
|
||||
"video": frozenset({"video", "vid"}),
|
||||
}
|
||||
|
||||
|
||||
def parse_title_tag(title: str) -> tuple[str | None, str | None, str]:
|
||||
"""Return (kind, role, label) from a Comfy node title.
|
||||
|
||||
kind is ``\"input\"`` / ``\"output\"`` or None if no tag.
|
||||
role is the lowercase role string or None for plain ``(Input)`` / ``(Output)``.
|
||||
label is the display name with the tag stripped.
|
||||
"""
|
||||
if not title:
|
||||
return None, None, ""
|
||||
match = _TITLE_TAG_RE.search(title)
|
||||
if not match:
|
||||
return None, None, title.strip()
|
||||
kind = match.group("kind").lower()
|
||||
role_raw = match.group("role")
|
||||
role = role_raw.lower() if role_raw else None
|
||||
stripped = _TITLE_TAG_RE.sub("", title).strip()
|
||||
# Title is only the tag, e.g. "(Input:prompt)" → use role as display label.
|
||||
if stripped:
|
||||
label = stripped
|
||||
elif role:
|
||||
label = role
|
||||
else:
|
||||
label = kind
|
||||
return kind, role, label
|
||||
|
||||
|
||||
def normalize_input_role(role: str | None) -> str | None:
|
||||
"""Map an alias to its canonical input role, or return the role as-is if unknown."""
|
||||
if not role:
|
||||
return None
|
||||
r = role.lower().strip()
|
||||
for canonical, aliases in INPUT_ROLE_ALIASES.items():
|
||||
if r in aliases or r == canonical:
|
||||
return canonical
|
||||
return r
|
||||
|
||||
|
||||
def normalize_output_role(role: str | None) -> str | None:
|
||||
if not role:
|
||||
return None
|
||||
r = role.lower().strip()
|
||||
for canonical, aliases in OUTPUT_ROLE_ALIASES.items():
|
||||
if r in aliases or r == canonical:
|
||||
return canonical
|
||||
return r
|
||||
|
||||
|
||||
def input_has_role(inp: dict[str, Any], *canonical_roles: str) -> bool:
|
||||
"""True if this parsed input's role matches any of the canonical roles (incl. aliases)."""
|
||||
role = normalize_input_role(inp.get("role"))
|
||||
if not role:
|
||||
return False
|
||||
wanted = {normalize_input_role(c) for c in canonical_roles}
|
||||
return role in wanted
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Smart-fill ComfyUI dynamic inputs from project/scene context via role tags."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.roles import input_has_role
|
||||
|
||||
|
||||
def _find_by_role(inputs: list[dict[str, Any]], *roles: str) -> dict[str, Any] | None:
|
||||
for inp in inputs:
|
||||
if input_has_role(inp, *roles):
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def _find_all_by_role(inputs: list[dict[str, Any]], *roles: str) -> list[dict[str, Any]]:
|
||||
"""All inputs matching any of the roles, sorted by numeric node id.
|
||||
|
||||
Node-id order is the documented ref-slot order: for multi-reference
|
||||
workflows (e.g. MiniMax H3 ref2video), ``(Input:image)`` slots are filled
|
||||
in this order and it defines ``<Subject N>`` numbering in the prompt.
|
||||
"""
|
||||
matches = [inp for inp in inputs if input_has_role(inp, *roles)]
|
||||
return sorted(matches, key=lambda i: int(i["nodeId"]))
|
||||
|
||||
|
||||
def ref_image_slots(inputs: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Generic ``(Input:image)`` ref slots in documented fill order (node id).
|
||||
|
||||
For multi-reference workflows (e.g. MiniMax H3 ref2video) these slots are
|
||||
filled in this order and it defines ``<Subject N>`` prompt numbering.
|
||||
"""
|
||||
return _find_all_by_role(inputs, "image")
|
||||
|
||||
|
||||
def _legacy_prompt_node(inputs: list[dict[str, Any]]) -> dict[str, Any] | None:
|
||||
"""Deprecated: untagged (Input) text nodes — prefer (Input:prompt)."""
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") not in ("text", "textarea"):
|
||||
continue
|
||||
label = (inp.get("label") or "").lower()
|
||||
if "negative" in label:
|
||||
continue
|
||||
if any(k in label for k in ("prompt", "positive", "text")):
|
||||
return inp
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("text", "textarea"):
|
||||
label = (inp.get("label") or "").lower()
|
||||
if "negative" not in label:
|
||||
return inp
|
||||
return None
|
||||
|
||||
|
||||
def smart_fill_inputs(
|
||||
inputs: list[dict[str, Any]],
|
||||
*,
|
||||
prompt: str | None = None,
|
||||
negative_prompt: str | None = None,
|
||||
character_image: str | None = None,
|
||||
location_image: str | None = None,
|
||||
ref_images: list[str] | None = None,
|
||||
duration: int | float | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build valuesByNodeId from workflow dynamic inputs + context.
|
||||
|
||||
Mapping is driven by Comfy title role tags, e.g. ``(Input:prompt)``.
|
||||
See ``AGENTS.md`` / README for the role contract.
|
||||
|
||||
Order: non-blank defaults → role-based context → shared extras (non-blank).
|
||||
User/form ``extra`` wins so regenerating a clip keeps the settings they edited.
|
||||
Blank extras are skipped so an empty shared Text Prompt cannot wipe context.
|
||||
"""
|
||||
values: dict[str, Any] = {}
|
||||
for inp in inputs:
|
||||
node_id = str(inp["nodeId"])
|
||||
default = inp.get("defaultValue")
|
||||
if default is None:
|
||||
continue
|
||||
if isinstance(default, str) and not default.strip():
|
||||
continue
|
||||
values[node_id] = default
|
||||
|
||||
if prompt:
|
||||
target = _find_by_role(inputs, "prompt") or _legacy_prompt_node(inputs)
|
||||
if target:
|
||||
values[str(target["nodeId"])] = prompt
|
||||
|
||||
if negative_prompt:
|
||||
target = _find_by_role(inputs, "negative")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = negative_prompt
|
||||
else:
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("text", "textarea") and "negative" in (
|
||||
inp.get("label") or ""
|
||||
).lower():
|
||||
values[str(inp["nodeId"])] = negative_prompt
|
||||
break
|
||||
|
||||
if character_image:
|
||||
target = _find_by_role(inputs, "character")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = character_image
|
||||
else:
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("image", "image_url"):
|
||||
label = (inp.get("label") or "").lower()
|
||||
if any(
|
||||
k in label
|
||||
for k in ("character", "portrait", "reference", "sheet", "face", "ref")
|
||||
) and not any(k in label for k in ("env", "location", "background", "scene")):
|
||||
values[str(inp["nodeId"])] = character_image
|
||||
break
|
||||
|
||||
if location_image:
|
||||
target = _find_by_role(inputs, "location")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = location_image
|
||||
else:
|
||||
for inp in inputs:
|
||||
if inp.get("role"):
|
||||
continue
|
||||
if inp.get("kind") in ("image", "image_url"):
|
||||
label = (inp.get("label") or "").lower()
|
||||
if any(
|
||||
k in label
|
||||
for k in ("env", "location", "background", "scene", "setting")
|
||||
):
|
||||
values[str(inp["nodeId"])] = location_image
|
||||
break
|
||||
|
||||
if ref_images:
|
||||
for inp, path in zip(ref_image_slots(inputs), ref_images):
|
||||
values[str(inp["nodeId"])] = path
|
||||
|
||||
if duration is not None:
|
||||
target = _find_by_role(inputs, "duration")
|
||||
if target:
|
||||
values[str(target["nodeId"])] = duration
|
||||
|
||||
if extra:
|
||||
for k, v in extra.items():
|
||||
if v is None:
|
||||
continue
|
||||
if isinstance(v, str) and not str(v).strip():
|
||||
continue
|
||||
values[str(k)] = v
|
||||
|
||||
return values
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
# calliope-backend/ — permanent home for config + default data (never %TEMP%)
|
||||
# PyInstaller-frozen exe: __file__ points inside the bundle (_internal/), which is
|
||||
# not where a portable app should keep user data. Anchor config + default data
|
||||
# NEXT TO the exe instead, so the app folder stays self-contained and writable.
|
||||
# Dev (non-frozen) resolution is unchanged.
|
||||
if getattr(sys, "frozen", False):
|
||||
BACKEND_ROOT = Path(sys.executable).resolve().parent
|
||||
else:
|
||||
BACKEND_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
CONFIG_FILE = BACKEND_ROOT / "calliope_config.json"
|
||||
DEFAULT_DATA_DIR = BACKEND_ROOT / "data"
|
||||
DEFAULT_ASSETS_DIR = DEFAULT_DATA_DIR / "assets"
|
||||
|
||||
|
||||
def _strip_path_str(value: str | Path | None) -> str | None:
|
||||
"""Normalize path strings; strip accidental wrapping quotes from UI paste."""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
if not s or s.lower() in {"none", "null"}:
|
||||
return None
|
||||
if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
|
||||
s = s[1:-1].strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def normalize_path(value: str | Path | None) -> Path | None:
|
||||
cleaned = _strip_path_str(value)
|
||||
if cleaned is None:
|
||||
return None
|
||||
return Path(cleaned)
|
||||
|
||||
|
||||
def is_ephemeral_path(path: Path | str | None) -> bool:
|
||||
"""True for OS temp / pytest TemporaryDirectory paths — never use as default storage."""
|
||||
if path is None:
|
||||
return False
|
||||
try:
|
||||
resolved = Path(path).resolve()
|
||||
except OSError:
|
||||
resolved = Path(path)
|
||||
parts_lower = {p.lower() for p in resolved.parts}
|
||||
if "temp" in parts_lower or "tmp" in parts_lower:
|
||||
# Windows %TEMP% and Unix /tmp
|
||||
temp_root = Path(tempfile.gettempdir()).resolve()
|
||||
try:
|
||||
resolved.relative_to(temp_root)
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
# pytest-style .../Temp/tmpXXXX
|
||||
name = resolved.name.lower()
|
||||
if name.startswith("tmp") and len(name) > 3:
|
||||
return True
|
||||
for parent in resolved.parents:
|
||||
if parent.name.lower().startswith("tmp") and parent.parent.resolve() == temp_root:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="CALLIOPE_",
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 8247
|
||||
data_dir: Path = DEFAULT_DATA_DIR
|
||||
assets_dir: Path = DEFAULT_ASSETS_DIR
|
||||
db_name: str = "calliope.db"
|
||||
|
||||
llm_base_url: str = "http://127.0.0.1:11434/v1"
|
||||
llm_model: str = "llama3.2"
|
||||
llm_api_key: str | None = None
|
||||
|
||||
comfyui_base_url: str = "http://127.0.0.1:8188"
|
||||
# Comfy is HTTP-only (upload / prompt / history / view). No local input/output dirs.
|
||||
|
||||
queue_concurrency: int = 1
|
||||
queue_poll_interval_sec: float = 2.0
|
||||
queue_max_retries: int = 2
|
||||
dry_run: bool = False # off by default — real ComfyUI jobs
|
||||
|
||||
@property
|
||||
def db_path(self) -> Path:
|
||||
return self.data_dir / self.db_name
|
||||
|
||||
def ensure_storage_dirs(self) -> None:
|
||||
self.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.assets_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def to_public_dict(self) -> dict[str, Any]:
|
||||
"""Return settings that are safe to expose to the frontend."""
|
||||
return {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"data_dir": str(self.data_dir),
|
||||
"assets_dir": str(self.assets_dir),
|
||||
"db_name": self.db_name,
|
||||
"llm_base_url": self.llm_base_url,
|
||||
"llm_model": self.llm_model,
|
||||
"llm_api_key": bool(self.llm_api_key),
|
||||
"comfyui_base_url": self.comfyui_base_url,
|
||||
"queue_concurrency": self.queue_concurrency,
|
||||
"queue_poll_interval_sec": self.queue_poll_interval_sec,
|
||||
"queue_max_retries": self.queue_max_retries,
|
||||
"dry_run": bool(self.dry_run),
|
||||
}
|
||||
|
||||
def _apply_storage_paths(self, data_dir: Path | None, assets_dir: Path | None) -> None:
|
||||
if data_dir is not None:
|
||||
if is_ephemeral_path(data_dir):
|
||||
data_dir = DEFAULT_DATA_DIR
|
||||
self.data_dir = data_dir
|
||||
if assets_dir is not None:
|
||||
if is_ephemeral_path(assets_dir):
|
||||
assets_dir = DEFAULT_ASSETS_DIR
|
||||
self.assets_dir = assets_dir
|
||||
# Keep assets under data when data moved and assets still ephemeral
|
||||
if is_ephemeral_path(self.assets_dir):
|
||||
self.assets_dir = self.data_dir / "assets"
|
||||
|
||||
def load_config_file(self) -> None:
|
||||
if not CONFIG_FILE.exists():
|
||||
self.data_dir = DEFAULT_DATA_DIR
|
||||
self.assets_dir = DEFAULT_ASSETS_DIR
|
||||
self.dry_run = False
|
||||
self.ensure_storage_dirs()
|
||||
return
|
||||
|
||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
path_keys = {"data_dir", "assets_dir"}
|
||||
# Ignore legacy comfyui_input_dir / comfyui_output_dir if present in old configs.
|
||||
skip_keys = {"comfyui_input_dir", "comfyui_output_dir"}
|
||||
for key, value in data.items():
|
||||
if key in skip_keys:
|
||||
continue
|
||||
if key in path_keys:
|
||||
value = normalize_path(value)
|
||||
if key == "dry_run":
|
||||
value = bool(value)
|
||||
if hasattr(self, key) and key not in {"data_dir", "assets_dir"}:
|
||||
setattr(self, key, value)
|
||||
|
||||
data_dir = normalize_path(data.get("data_dir")) or DEFAULT_DATA_DIR
|
||||
assets_dir = normalize_path(data.get("assets_dir")) or (data_dir / "assets")
|
||||
self._apply_storage_paths(data_dir, assets_dir)
|
||||
self.dry_run = bool(data.get("dry_run", False))
|
||||
self.ensure_storage_dirs()
|
||||
|
||||
# Auto-heal poisoned config (temp paths / quoted dirs / legacy comfy dirs) back to disk
|
||||
needs_rewrite = is_ephemeral_path(normalize_path(data.get("data_dir"))) or any(
|
||||
isinstance(data.get(k), str) and str(data.get(k)).startswith('"')
|
||||
for k in ("data_dir", "assets_dir")
|
||||
if data.get(k)
|
||||
)
|
||||
if needs_rewrite or "comfyui_input_dir" in data or "comfyui_output_dir" in data:
|
||||
self.save_config_file()
|
||||
|
||||
def save_config_file(self) -> None:
|
||||
# Never persist pytest / OS temp storage as the real data home
|
||||
if is_ephemeral_path(self.data_dir):
|
||||
self.data_dir = DEFAULT_DATA_DIR
|
||||
if is_ephemeral_path(self.assets_dir):
|
||||
self.assets_dir = self.data_dir / "assets"
|
||||
self.dry_run = bool(self.dry_run)
|
||||
self.ensure_storage_dirs()
|
||||
|
||||
data = {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"data_dir": str(self.data_dir),
|
||||
"assets_dir": str(self.assets_dir),
|
||||
"db_name": self.db_name,
|
||||
"llm_base_url": self.llm_base_url,
|
||||
"llm_model": self.llm_model,
|
||||
"llm_api_key": self.llm_api_key,
|
||||
"comfyui_base_url": self.comfyui_base_url,
|
||||
"queue_concurrency": self.queue_concurrency,
|
||||
"queue_poll_interval_sec": self.queue_poll_interval_sec,
|
||||
"queue_max_retries": self.queue_max_retries,
|
||||
"dry_run": bool(self.dry_run),
|
||||
}
|
||||
CONFIG_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
settings = Settings()
|
||||
settings.load_config_file()
|
||||
@@ -0,0 +1,225 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
idea TEXT,
|
||||
genre TEXT,
|
||||
tone TEXT,
|
||||
target_duration TEXT,
|
||||
cover_path TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'draft',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS story_beats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
order_index INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS characters (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
role TEXT,
|
||||
age TEXT,
|
||||
appearance TEXT,
|
||||
personality TEXT,
|
||||
portrait_path TEXT,
|
||||
sheet_path TEXT,
|
||||
consistency_prompt TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS locations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
reference_image_path TEXT,
|
||||
consistency_prompt TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scenes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
beat_id INTEGER REFERENCES story_beats(id) ON DELETE SET NULL,
|
||||
order_index INTEGER NOT NULL,
|
||||
heading TEXT,
|
||||
action TEXT,
|
||||
dialog TEXT,
|
||||
duration_sec INTEGER,
|
||||
workflow_id INTEGER,
|
||||
env_image_path TEXT,
|
||||
location_id INTEGER,
|
||||
video_path TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scene_characters (
|
||||
scene_id INTEGER NOT NULL REFERENCES scenes(id) ON DELETE CASCADE,
|
||||
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (scene_id, character_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS workflows (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK(kind IN ('image', 'video')),
|
||||
workflow_json TEXT NOT NULL,
|
||||
input_node_map TEXT,
|
||||
output_node_name TEXT,
|
||||
input_schema TEXT,
|
||||
output_schema TEXT,
|
||||
description TEXT,
|
||||
prompt_profile TEXT NOT NULL DEFAULT 'prose',
|
||||
is_enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
scene_id INTEGER REFERENCES scenes(id) ON DELETE SET NULL,
|
||||
kind TEXT NOT NULL,
|
||||
workflow_id INTEGER REFERENCES workflows(id) ON DELETE SET NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
payload_json TEXT,
|
||||
output_paths_json TEXT,
|
||||
error TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
started_at TIMESTAMP,
|
||||
completed_at TIMESTAMP,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def get_db(db_path: Path) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(db_path, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
# WAL: readers never block writers (the UI polls jobs/settings constantly),
|
||||
# and busy_timeout makes writers wait instead of erroring on contention.
|
||||
conn.execute("PRAGMA journal_mode = WAL")
|
||||
conn.execute("PRAGMA busy_timeout = 10000")
|
||||
conn.execute("PRAGMA foreign_keys = ON")
|
||||
return conn
|
||||
|
||||
|
||||
def _sqlite_connect(path: Path) -> sqlite3.Connection:
|
||||
return sqlite3.connect(path)
|
||||
|
||||
|
||||
async def migrate_db(db_path: Path) -> None:
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.executescript(SCHEMA)
|
||||
# Additive migrations for existing DBs
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(workflows)").fetchall()}
|
||||
if "input_schema" not in cols:
|
||||
conn.execute("ALTER TABLE workflows ADD COLUMN input_schema TEXT")
|
||||
if "output_schema" not in cols:
|
||||
conn.execute("ALTER TABLE workflows ADD COLUMN output_schema TEXT")
|
||||
if "description" not in cols:
|
||||
conn.execute("ALTER TABLE workflows ADD COLUMN description TEXT")
|
||||
if "prompt_profile" not in cols:
|
||||
conn.execute(
|
||||
"ALTER TABLE workflows ADD COLUMN prompt_profile TEXT NOT NULL DEFAULT 'prose'"
|
||||
)
|
||||
scene_cols = {r[1] for r in conn.execute("PRAGMA table_info(scenes)").fetchall()}
|
||||
if "location_id" not in scene_cols:
|
||||
conn.execute("ALTER TABLE scenes ADD COLUMN location_id INTEGER")
|
||||
if "video_path" not in scene_cols:
|
||||
conn.execute("ALTER TABLE scenes ADD COLUMN video_path TEXT")
|
||||
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")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def row_to_dict(row: sqlite3.Row) -> dict[str, Any]:
|
||||
return {key: row[key] for key in row.keys()}
|
||||
|
||||
|
||||
# Columns that store absolute asset paths. When the app folder moves, these
|
||||
# still point at the old install root and /api/file rejects them (403).
|
||||
_PATH_COLUMNS = {
|
||||
"projects": ["cover_path"],
|
||||
"characters": ["portrait_path", "sheet_path"],
|
||||
"locations": ["reference_image_path"],
|
||||
"scenes": ["env_image_path", "video_path"],
|
||||
}
|
||||
|
||||
|
||||
def _rebase_path(value: Any, data_dir: Path, assets_dir: Path) -> str | None:
|
||||
"""Rebase an absolute path from a previous install location onto current dirs.
|
||||
|
||||
Returns the rebased path, or None when the value is not a stale absolute
|
||||
path (relative, already under data_dir, or has no 'assets' segment).
|
||||
"""
|
||||
if not value or not isinstance(value, str):
|
||||
return None
|
||||
p = Path(value)
|
||||
if not p.is_absolute():
|
||||
return None
|
||||
try:
|
||||
p.resolve().relative_to(data_dir.resolve())
|
||||
return None # already under the current install
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
parts_lower = [seg.lower() for seg in p.parts]
|
||||
if "assets" not in parts_lower:
|
||||
return None
|
||||
idx = len(parts_lower) - 1 - parts_lower[::-1].index("assets")
|
||||
rel = Path(*p.parts[idx + 1 :])
|
||||
if not rel.parts:
|
||||
return None
|
||||
return str(assets_dir / rel)
|
||||
|
||||
|
||||
def rebase_stale_asset_paths(conn: sqlite3.Connection, data_dir: Path, assets_dir: Path) -> int:
|
||||
"""Rewrite stored asset paths left over from a previous install location.
|
||||
|
||||
Call after migrate_db (needs all columns to exist). Returns the number of
|
||||
rewritten values; caller commits.
|
||||
"""
|
||||
count = 0
|
||||
for table, columns in _PATH_COLUMNS.items():
|
||||
for col in columns:
|
||||
rows = conn.execute(f"SELECT id, {col} FROM {table} WHERE {col} IS NOT NULL").fetchall()
|
||||
for row in rows:
|
||||
new = _rebase_path(row[col], data_dir, assets_dir)
|
||||
if new and new != row[col]:
|
||||
conn.execute(f"UPDATE {table} SET {col} = ? WHERE id = ?", (new, row["id"]))
|
||||
count += 1
|
||||
rows = conn.execute(
|
||||
"SELECT id, output_paths_json FROM jobs WHERE output_paths_json IS NOT NULL"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
try:
|
||||
paths = json.loads(row["output_paths_json"] or "[]")
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if not isinstance(paths, list):
|
||||
continue
|
||||
new_paths = [_rebase_path(p, data_dir, assets_dir) or p for p in paths]
|
||||
if new_paths != paths:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET output_paths_json = ? WHERE id = ?",
|
||||
(json.dumps(new_paths), row["id"]),
|
||||
)
|
||||
count += 1
|
||||
return count
|
||||
@@ -0,0 +1,3 @@
|
||||
from calliope.events.bus import EventBus, event_bus
|
||||
|
||||
__all__ = ["EventBus", "event_bus"]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""In-process SSE event bus."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
|
||||
class EventBus:
|
||||
def __init__(self) -> None:
|
||||
self._subscribers: list[asyncio.Queue[dict[str, Any]]] = []
|
||||
self._lock = asyncio.Lock()
|
||||
self.recent: list[dict[str, Any]] = []
|
||||
|
||||
async def subscribe(self) -> asyncio.Queue[dict[str, Any]]:
|
||||
q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=256)
|
||||
async with self._lock:
|
||||
self._subscribers.append(q)
|
||||
return q
|
||||
|
||||
async def unsubscribe(self, q: asyncio.Queue[dict[str, Any]]) -> None:
|
||||
async with self._lock:
|
||||
if q in self._subscribers:
|
||||
self._subscribers.remove(q)
|
||||
|
||||
async def publish(self, event_type: str, data: dict[str, Any] | None = None) -> None:
|
||||
event = {
|
||||
"type": event_type,
|
||||
"data": data or {},
|
||||
"ts": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
self.recent.append(event)
|
||||
if len(self.recent) > 200:
|
||||
self.recent = self.recent[-200:]
|
||||
async with self._lock:
|
||||
dead: list[asyncio.Queue[dict[str, Any]]] = []
|
||||
for q in self._subscribers:
|
||||
try:
|
||||
q.put_nowait(event)
|
||||
except asyncio.QueueFull:
|
||||
dead.append(q)
|
||||
for q in dead:
|
||||
self._subscribers.remove(q)
|
||||
|
||||
def format_sse(self, event: dict[str, Any]) -> str:
|
||||
return f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"
|
||||
|
||||
|
||||
event_bus = EventBus()
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Film export: stitch a project's scene clips into one mp4 via ffmpeg.
|
||||
|
||||
Pipeline (validated on real clips — do not reinvent): normalize each clip →
|
||||
0.5s crossfades (xfade/acrossfade) → loudness normalize. ComfyUI is never
|
||||
involved; export jobs run locally against files on disk.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from calliope import config
|
||||
from calliope.comfyui.dry_run import write_placeholder_mp4
|
||||
from calliope.db import get_db, row_to_dict
|
||||
|
||||
logger = logging.getLogger("calliope.export")
|
||||
|
||||
# Normalization targets — every clip is conformed to these before stitching.
|
||||
EXPORT_WIDTH = 1920
|
||||
EXPORT_HEIGHT = 1080
|
||||
EXPORT_FPS = 30
|
||||
XFADE_SEC = 0.5
|
||||
PROGRESS_MIN_INTERVAL_SEC = 1.0
|
||||
|
||||
_running: dict[int, asyncio.subprocess.Process] = {}
|
||||
|
||||
|
||||
def kill_running(job_id: int) -> bool:
|
||||
"""Kill the ffmpeg process for a running export job. False when none."""
|
||||
proc = _running.get(job_id)
|
||||
if not proc or proc.returncode is not None:
|
||||
return False
|
||||
try:
|
||||
proc.kill()
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _require_binary(name: str) -> str:
|
||||
path = shutil.which(name)
|
||||
if not path:
|
||||
raise RuntimeError(f"{name} not found on PATH — install ffmpeg to enable film export.")
|
||||
return path
|
||||
|
||||
|
||||
def slugify(title: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
|
||||
return slug or "film"
|
||||
|
||||
|
||||
def collect_clips(project_id: int) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""Scenes in story order, split into (with video_path, without)."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
scenes = [row_to_dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
with_clip = [s for s in scenes if s.get("video_path")]
|
||||
skipped = [s for s in scenes if not s.get("video_path")]
|
||||
return with_clip, skipped
|
||||
|
||||
|
||||
def _project_title(project_id: int) -> str:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT title FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
return row["title"] if row else f"project-{project_id}"
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
async def probe(path: str | Path) -> dict[str, Any]:
|
||||
"""ffprobe a clip: duration (float seconds) and has_audio (bool)."""
|
||||
ffprobe = _require_binary("ffprobe")
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
ffprobe,
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration:stream=codec_type",
|
||||
"-of",
|
||||
"json",
|
||||
str(path),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
out, err = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
tail = err.decode("utf-8", "replace")[-500:]
|
||||
raise RuntimeError(f"ffprobe failed for {path}: {tail}")
|
||||
data = json.loads(out.decode("utf-8", "replace") or "{}")
|
||||
duration = float((data.get("format") or {}).get("duration") or 0.0)
|
||||
has_audio = any(s.get("codec_type") == "audio" for s in data.get("streams") or [])
|
||||
return {"duration": duration, "has_audio": has_audio}
|
||||
|
||||
|
||||
def build_ffmpeg_cmd(
|
||||
clips: list[dict[str, Any]],
|
||||
probes: list[dict[str, Any]],
|
||||
dest: str | Path,
|
||||
) -> list[str]:
|
||||
"""Assemble the validated normalize → xfade → loudnorm ffmpeg command."""
|
||||
if not clips:
|
||||
raise RuntimeError("No clips to export")
|
||||
if len(clips) != len(probes):
|
||||
raise ValueError("clips and probes must align")
|
||||
|
||||
n = len(clips)
|
||||
ffmpeg = shutil.which("ffmpeg") or "ffmpeg"
|
||||
cmd: list[str] = [ffmpeg, "-nostdin", "-nostats", "-progress", "pipe:1", "-y"]
|
||||
for clip in clips:
|
||||
cmd += ["-i", str(clip["video_path"])]
|
||||
# Silent clips get a lavfi silence donor input, appended after the clip inputs
|
||||
# so input indices for real clips stay 0..n-1.
|
||||
lavfi_index: dict[int, int] = {}
|
||||
next_index = n
|
||||
for i, p in enumerate(probes):
|
||||
if not p["has_audio"]:
|
||||
lavfi_index[i] = next_index
|
||||
next_index += 1
|
||||
cmd += ["-f", "lavfi", "-i", "anullsrc=cl=stereo:r=48000"]
|
||||
|
||||
v_chain = (
|
||||
f"scale={EXPORT_WIDTH}:{EXPORT_HEIGHT}:force_original_aspect_ratio=decrease,"
|
||||
f"pad={EXPORT_WIDTH}:{EXPORT_HEIGHT}:(ow-iw)/2:(oh-ih)/2,"
|
||||
f"setsar=1,fps={EXPORT_FPS},settb=AVTB"
|
||||
)
|
||||
a_chain = "aformat=sample_rates=48000:channel_layouts=stereo"
|
||||
|
||||
filters: list[str] = []
|
||||
for i, p in enumerate(probes):
|
||||
filters.append(f"[{i}:v]{v_chain}[v{i}]")
|
||||
if p["has_audio"]:
|
||||
filters.append(f"[{i}:a]{a_chain}[a{i}]")
|
||||
else:
|
||||
filters.append(
|
||||
f"[{lavfi_index[i]}:a]atrim=duration={float(p['duration']):.3f},"
|
||||
f"asetpts=PTS-STARTPTS,{a_chain}[a{i}]"
|
||||
)
|
||||
|
||||
durations = [float(p["duration"]) for p in probes]
|
||||
if n == 1:
|
||||
# Single clip: no crossfade, but same normalize + loudness treatment.
|
||||
filters.append("[v0]format=yuv420p[vout]")
|
||||
filters.append("[a0]loudnorm=I=-16:TP=-1.5:LRA=11[aout]")
|
||||
else:
|
||||
for k in range(1, n):
|
||||
offset = sum(durations[:k]) - k * XFADE_SEC
|
||||
vin = "[v0]" if k == 1 else f"[x{k - 1}]"
|
||||
ain = "[a0]" if k == 1 else f"[c{k - 1}]"
|
||||
filters.append(
|
||||
f"{vin}[v{k}]xfade=transition=fade:duration={XFADE_SEC}:offset={offset:.3f}[x{k}]"
|
||||
)
|
||||
filters.append(f"{ain}[a{k}]acrossfade=d={XFADE_SEC}:c1=tri:c2=tri[c{k}]")
|
||||
# format=yuv420p AFTER the final xfade — the chain renegotiates to
|
||||
# yuv444p otherwise and players choke on the result.
|
||||
filters.append(f"[x{n - 1}]format=yuv420p[vout]")
|
||||
filters.append(f"[c{n - 1}]loudnorm=I=-16:TP=-1.5:LRA=11[aout]")
|
||||
|
||||
cmd += ["-filter_complex", ";".join(filters)]
|
||||
cmd += ["-map", "[vout]", "-map", "[aout]"]
|
||||
cmd += [
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"medium",
|
||||
"-crf",
|
||||
"20",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"192k",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
str(dest),
|
||||
]
|
||||
return cmd
|
||||
|
||||
|
||||
async def run_export(
|
||||
job: dict[str, Any],
|
||||
payload: dict[str, Any],
|
||||
bus: Any,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
) -> list[str]:
|
||||
"""Run one export job; returns the output mp4 path list."""
|
||||
project_id = job["project_id"]
|
||||
job_id = job["id"]
|
||||
clips, skipped = collect_clips(project_id)
|
||||
if not clips:
|
||||
raise RuntimeError("No scene clips to export — generate videos first")
|
||||
|
||||
for scene in skipped:
|
||||
heading = (scene.get("heading") or f"Scene {scene.get('order_index')}").strip()
|
||||
await bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"kind": "export",
|
||||
"message": f"Skipping scene «{heading}» — no clip",
|
||||
},
|
||||
)
|
||||
|
||||
dest_dir = Path(config.settings.assets_dir) / str(project_id) / "export"
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
dest = dest_dir / f"{slugify(_project_title(project_id))}-job{job_id}.mp4"
|
||||
|
||||
if dry_run:
|
||||
write_placeholder_mp4(dest, label=f"job-{job_id}-export")
|
||||
return [str(dest)]
|
||||
|
||||
_require_binary("ffmpeg")
|
||||
probes = [await probe(clip["video_path"]) for clip in clips]
|
||||
durations = [float(p["duration"]) for p in probes]
|
||||
total_us = (sum(durations) - XFADE_SEC * max(0, len(clips) - 1)) * 1_000_000
|
||||
|
||||
cmd = build_ffmpeg_cmd(clips, probes, dest)
|
||||
logger.info("Export job %s: %s", job_id, " ".join(cmd))
|
||||
|
||||
await bus.publish(
|
||||
"job.progress",
|
||||
{"job_id": job_id, "kind": "export", "percent": 0.0, "message": "Exporting film…"},
|
||||
)
|
||||
last_publish = time.monotonic()
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
_running[job_id] = proc
|
||||
try:
|
||||
assert proc.stdout is not None and proc.stderr is not None
|
||||
# Drain stderr concurrently — a full pipe buffer would deadlock ffmpeg.
|
||||
stderr_task = asyncio.create_task(proc.stderr.read())
|
||||
while True:
|
||||
line = await proc.stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
text = line.decode("utf-8", "replace").strip()
|
||||
if not text.startswith("out_time_us="):
|
||||
continue
|
||||
try:
|
||||
out_us = int(text.split("=", 1)[1])
|
||||
except ValueError:
|
||||
continue
|
||||
now = time.monotonic()
|
||||
if now - last_publish < PROGRESS_MIN_INTERVAL_SEC:
|
||||
continue
|
||||
last_publish = now
|
||||
percent = min(99.0, max(0.0, out_us / total_us * 100.0)) if total_us > 0 else 0.0
|
||||
await bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"kind": "export",
|
||||
"percent": round(percent, 1),
|
||||
"message": "Exporting film…",
|
||||
},
|
||||
)
|
||||
stderr_bytes = await stderr_task
|
||||
returncode = await proc.wait()
|
||||
finally:
|
||||
_running.pop(job_id, None)
|
||||
|
||||
if returncode != 0:
|
||||
tail = stderr_bytes.decode("utf-8", "replace")[-2000:]
|
||||
raise RuntimeError(f"ffmpeg export failed (exit {returncode}): {tail}")
|
||||
return [str(dest)]
|
||||
@@ -0,0 +1,120 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, migrate_db, rebase_stale_asset_paths
|
||||
from calliope.queue.worker import queue_worker
|
||||
from calliope.routers import (
|
||||
assets,
|
||||
events,
|
||||
jobs,
|
||||
playground,
|
||||
projects,
|
||||
scenes,
|
||||
settings as settings_router,
|
||||
story,
|
||||
workflows,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("calliope")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
settings.assets_dir.mkdir(parents=True, exist_ok=True)
|
||||
await migrate_db(settings.db_path)
|
||||
# Folder moved? Stored asset paths still point at the old install root —
|
||||
# rebase them onto the current data dir before serving anything.
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rebased = rebase_stale_asset_paths(conn, settings.data_dir, settings.assets_dir)
|
||||
if rebased:
|
||||
conn.commit()
|
||||
logger.info(
|
||||
"Rebased %s asset path(s) from a previous install location onto %s",
|
||||
rebased,
|
||||
settings.data_dir,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
await queue_worker.start()
|
||||
logger.info("Calliope started — db=%s dry_run=%s", settings.db_path, settings.dry_run)
|
||||
yield
|
||||
await queue_worker.stop()
|
||||
logger.info("Calliope shutting down")
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(title="Calliope", version="1.1.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(projects.router, prefix="/api/projects", tags=["projects"])
|
||||
app.include_router(settings_router.router, prefix="/api/settings", tags=["settings"])
|
||||
app.include_router(story.router, prefix="/api/projects", tags=["story"])
|
||||
app.include_router(scenes.router, prefix="/api/projects", tags=["scenes"])
|
||||
app.include_router(assets.router, prefix="/api", tags=["assets"])
|
||||
app.include_router(workflows.router, prefix="/api/workflows", tags=["workflows"])
|
||||
app.include_router(jobs.router, prefix="/api/jobs", tags=["jobs"])
|
||||
app.include_router(playground.router, prefix="/api/playground", tags=["playground"])
|
||||
app.include_router(events.router, prefix="/api/events", tags=["events"])
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health() -> dict:
|
||||
return {"status": "ok", "version": "1.1.0", "dry_run": settings.dry_run}
|
||||
|
||||
# Catch unknown /api/* before StaticFiles — otherwise POST falls through and
|
||||
# returns a confusing 405 Method Not Allowed from the file server.
|
||||
@app.api_route(
|
||||
"/api/{full_path:path}",
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
|
||||
include_in_schema=False,
|
||||
)
|
||||
async def api_not_found(full_path: str) -> None:
|
||||
raise HTTPException(status_code=404, detail=f"API route not found: /api/{full_path}")
|
||||
|
||||
static_dir = Path(__file__).resolve().parent / "static"
|
||||
if static_dir.exists():
|
||||
app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def main() -> int:
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Calliope backend server")
|
||||
parser.add_argument("--host", default=None, help="Bind host (default: from config)")
|
||||
parser.add_argument("--port", type=int, default=None, help="Bind port (default: from config)")
|
||||
args = parser.parse_args()
|
||||
|
||||
host = args.host or settings.host
|
||||
port = args.port or settings.port
|
||||
|
||||
app = create_app()
|
||||
uvicorn = __import__("uvicorn")
|
||||
uvicorn.run(app, host=host, port=port)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
# Models package
|
||||
@@ -0,0 +1,188 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class ProjectCreate(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
idea: str | None = None
|
||||
genre: str | None = None
|
||||
tone: str | None = None
|
||||
target_duration: str | None = None
|
||||
|
||||
|
||||
class ProjectUpdate(BaseModel):
|
||||
title: str | None = Field(None, min_length=1, max_length=200)
|
||||
idea: str | None = None
|
||||
genre: str | None = None
|
||||
tone: str | None = None
|
||||
target_duration: str | None = None
|
||||
cover_path: str | None = None
|
||||
status: str | None = None
|
||||
|
||||
|
||||
class ProjectStats(BaseModel):
|
||||
scene_count: int
|
||||
character_count: int
|
||||
asset_ready_count: int
|
||||
asset_total_count: int
|
||||
|
||||
|
||||
class Project(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
idea: str | None
|
||||
genre: str | None
|
||||
tone: str | None
|
||||
target_duration: str | None
|
||||
cover_path: str | None = None
|
||||
status: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
stats: ProjectStats | None = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class ProjectList(BaseModel):
|
||||
projects: list[Project]
|
||||
|
||||
|
||||
class ProjectStats(BaseModel):
|
||||
scene_count: int = 0
|
||||
character_count: int = 0
|
||||
asset_ready_count: int = 0
|
||||
asset_total_count: int = 0
|
||||
|
||||
|
||||
class BeatCreate(BaseModel):
|
||||
order_index: int = 0
|
||||
title: str = Field(..., min_length=1)
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class BeatUpdate(BaseModel):
|
||||
order_index: int | None = None
|
||||
title: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class CharacterCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
role: str | None = None
|
||||
age: str | None = None
|
||||
appearance: str | None = None
|
||||
personality: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
|
||||
|
||||
class CharacterUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
role: str | None = None
|
||||
age: str | None = None
|
||||
appearance: str | None = None
|
||||
personality: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
portrait_path: str | None = None
|
||||
sheet_path: str | None = None
|
||||
|
||||
|
||||
class LocationCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
description: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
|
||||
|
||||
class LocationUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
consistency_prompt: str | None = None
|
||||
reference_image_path: str | None = None
|
||||
|
||||
|
||||
class SceneCreate(BaseModel):
|
||||
order_index: int = 0
|
||||
heading: str | None = None
|
||||
action: str | None = None
|
||||
dialog: str | None = None
|
||||
duration_sec: int | None = None
|
||||
workflow_id: int | None = None
|
||||
env_image_path: str | None = None
|
||||
beat_id: int | None = None
|
||||
character_ids: list[int] = Field(default_factory=list)
|
||||
location_id: int | None = None
|
||||
|
||||
|
||||
class SceneUpdate(BaseModel):
|
||||
order_index: int | None = None
|
||||
heading: str | None = None
|
||||
action: str | None = None
|
||||
dialog: str | None = None
|
||||
duration_sec: int | None = None
|
||||
workflow_id: int | None = None
|
||||
env_image_path: str | None = None
|
||||
beat_id: int | None = None
|
||||
character_ids: list[int] | None = None
|
||||
location_id: int | None = None
|
||||
video_path: str | None = None
|
||||
|
||||
|
||||
class SceneReorder(BaseModel):
|
||||
scene_ids: list[int]
|
||||
|
||||
|
||||
class WorkflowCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
kind: Literal["image", "video"] = "image"
|
||||
workflow_json: dict[str, Any]
|
||||
description: str | None = None
|
||||
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
|
||||
|
||||
|
||||
class WorkflowUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
kind: Literal["image", "video"] | None = None
|
||||
description: str | None = None
|
||||
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
|
||||
is_enabled: bool | None = None
|
||||
|
||||
|
||||
class WorkflowAnalyze(BaseModel):
|
||||
workflow_json: dict[str, Any]
|
||||
|
||||
|
||||
class JobCreate(BaseModel):
|
||||
scene_id: int | None = None
|
||||
kind: str
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
character_id: int | None = None
|
||||
location_id: int | None = None
|
||||
|
||||
|
||||
class GenerateAssetsRequest(BaseModel):
|
||||
character_ids: list[int] | None = None
|
||||
location_ids: list[int] | None = None
|
||||
missing_only: bool = True
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
# For characters: which image slot to write. Default/UI is "sheet" only
|
||||
# (sheet includes face close-up). "portrait" remains for legacy queued jobs.
|
||||
asset_target: str | None = "sheet"
|
||||
# Optional one-shot prompt override (must still be user-visible text from the UI).
|
||||
prompt: str | None = None
|
||||
|
||||
|
||||
class GenerateScenesRequest(BaseModel):
|
||||
replace: bool = True
|
||||
# When set (or inferred from existing scenes), regenerate must produce at least this many.
|
||||
scene_count: int | None = None
|
||||
|
||||
|
||||
class GenerateVideosRequest(BaseModel):
|
||||
scene_ids: list[int] | None = None
|
||||
workflow_id: int | None = None
|
||||
input_values: dict[str, Any] | None = None
|
||||
@@ -0,0 +1,4 @@
|
||||
from calliope.queue.manager import QueueManager, queue_manager
|
||||
from calliope.queue.worker import QueueWorker, queue_worker
|
||||
|
||||
__all__ = ["QueueManager", "queue_manager", "QueueWorker", "queue_worker"]
|
||||
@@ -0,0 +1,187 @@
|
||||
"""SQLite-backed job queue manager."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from calliope import config
|
||||
from calliope.db import get_db, row_to_dict
|
||||
|
||||
logger = logging.getLogger("calliope.queue")
|
||||
|
||||
|
||||
class QueueManager:
|
||||
def __init__(self) -> None:
|
||||
self.paused = False
|
||||
|
||||
def reset_stale_jobs(self) -> int:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"UPDATE jobs SET status = 'pending', started_at = NULL WHERE status = 'running'"
|
||||
)
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def enqueue(
|
||||
self,
|
||||
*,
|
||||
project_id: int,
|
||||
kind: str,
|
||||
workflow_id: int | None = None,
|
||||
scene_id: int | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO jobs (project_id, scene_id, kind, workflow_id, status, payload_json)
|
||||
VALUES (?, ?, ?, ?, 'pending', ?)
|
||||
""",
|
||||
(project_id, scene_id, kind, workflow_id, json.dumps(payload or {})),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def claim_next(self) -> dict[str, Any] | None:
|
||||
if self.paused:
|
||||
return None
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1"
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
job_id = row["id"]
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'running', started_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND status = 'pending'
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
claimed = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
return row_to_dict(claimed) if claimed else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def mark_done(self, job_id: int, output_paths: list[str]) -> None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'done', output_paths_json = ?, error = NULL,
|
||||
completed_at = CURRENT_TIMESTAMP WHERE id = ?
|
||||
""",
|
||||
(json.dumps(output_paths), job_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def mark_failed(self, job_id: int, error: str) -> None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = ?, completed_at = CURRENT_TIMESTAMP,
|
||||
retry_count = retry_count + 1 WHERE id = ?
|
||||
""",
|
||||
(error[:2000], job_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def retry(self, job_id: int) -> dict[str, Any] | None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'pending', error = NULL, started_at = NULL,
|
||||
completed_at = NULL WHERE id = ?
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
return row_to_dict(
|
||||
conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def cancel(self, job_id: int) -> bool:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = 'cancelled',
|
||||
completed_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND status IN ('pending', 'running')
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def list_jobs(
|
||||
self, project_id: int | None = None, status: str | None = None, limit: int = 100
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
clauses: list[str] = []
|
||||
params: list[Any] = []
|
||||
if project_id is not None:
|
||||
clauses.append("project_id = ?")
|
||||
params.append(project_id)
|
||||
if status:
|
||||
clauses.append("status = ?")
|
||||
params.append(status)
|
||||
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
params.append(limit)
|
||||
rows = conn.execute(
|
||||
f"SELECT * FROM jobs {where} ORDER BY created_at DESC LIMIT ?",
|
||||
params,
|
||||
).fetchall()
|
||||
return [row_to_dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def get_job(self, job_id: int) -> dict[str, Any] | None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
return row_to_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def delete_job(self, job_id: int) -> dict[str, Any] | None:
|
||||
"""Remove job row. Returns the deleted job dict, or None if missing."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
job = row_to_dict(row)
|
||||
conn.execute("DELETE FROM jobs WHERE id = ?", (job_id,))
|
||||
conn.commit()
|
||||
return job
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
queue_manager = QueueManager()
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Background queue worker loop."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from calliope import config
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
from calliope.comfyui.dry_run import write_placeholder_mp4, write_placeholder_png
|
||||
from calliope.comfyui.patcher import patch_workflow
|
||||
from calliope.db import get_db
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.export.runner import run_export
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
logger = logging.getLogger("calliope.worker")
|
||||
|
||||
|
||||
class QueueWorker:
|
||||
def __init__(self) -> None:
|
||||
self._task: asyncio.Task | None = None
|
||||
self._stop = asyncio.Event()
|
||||
|
||||
async def start(self) -> None:
|
||||
reset = queue_manager.reset_stale_jobs()
|
||||
if reset:
|
||||
logger.info("Reset %s stale running jobs to pending", reset)
|
||||
self._stop.clear()
|
||||
self._task = asyncio.create_task(self._loop(), name="calliope-queue-worker")
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._stop.set()
|
||||
if self._task:
|
||||
await asyncio.wait([self._task], timeout=5)
|
||||
|
||||
async def _loop(self) -> None:
|
||||
logger.info("Queue worker started")
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
if queue_manager.paused:
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
continue
|
||||
job = queue_manager.claim_next()
|
||||
if not job:
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
continue
|
||||
await event_bus.publish(
|
||||
"job.started",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"project_id": job.get("project_id"),
|
||||
"message": self._job_label(job),
|
||||
},
|
||||
)
|
||||
try:
|
||||
outputs = await self._run_job(job)
|
||||
queue_manager.mark_done(job["id"], outputs)
|
||||
if job["kind"] == "export":
|
||||
self._mark_project_completed(job["project_id"])
|
||||
await event_bus.publish(
|
||||
"job.completed",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"outputs": outputs,
|
||||
"project_id": job["project_id"],
|
||||
"message": f"{self._job_label(job)} · {len(outputs)} file(s)",
|
||||
},
|
||||
)
|
||||
if outputs:
|
||||
await event_bus.publish(
|
||||
"asset.ready",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"paths": outputs,
|
||||
"project_id": job["project_id"],
|
||||
"message": f"Saved {self._job_label(job)}",
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Job %s failed", job["id"])
|
||||
queue_manager.mark_failed(job["id"], str(exc))
|
||||
await event_bus.publish(
|
||||
"job.failed",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": job["kind"],
|
||||
"error": str(exc),
|
||||
"project_id": job.get("project_id"),
|
||||
"message": f"{self._job_label(job)} failed",
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Worker loop error")
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
logger.info("Queue worker stopped")
|
||||
|
||||
async def _run_job(self, job: dict[str, Any]) -> list[str]:
|
||||
payload = json.loads(job["payload_json"] or "{}")
|
||||
project_id = job["project_id"]
|
||||
kind = job["kind"]
|
||||
use_dry = bool(config.settings.dry_run)
|
||||
|
||||
if kind == "export":
|
||||
# Export stitches local clips with ffmpeg — never touches ComfyUI,
|
||||
# and dry-run writes an mp4 placeholder (not the default PNG).
|
||||
return await run_export(job, payload, event_bus, dry_run=use_dry)
|
||||
|
||||
client = ComfyUIClient(config.settings.comfyui_base_url)
|
||||
try:
|
||||
if use_dry:
|
||||
return await self._dry_run(job, payload)
|
||||
|
||||
healthy = await client.health()
|
||||
if not healthy:
|
||||
raise RuntimeError(
|
||||
f"ComfyUI unreachable at {config.settings.comfyui_base_url}. "
|
||||
"Start ComfyUI, or enable Dry-run in Settings only for placeholder testing."
|
||||
)
|
||||
|
||||
workflow_id = job.get("workflow_id") or payload.get("workflow_id")
|
||||
workflow = self._load_workflow(workflow_id)
|
||||
if not workflow:
|
||||
raise RuntimeError("No workflow found for job")
|
||||
|
||||
input_values = payload.get("input_values") or {}
|
||||
patched = patch_workflow(workflow, input_values)
|
||||
patched = await client.prepare_media_inputs(patched)
|
||||
prompt_id = await client.queue_prompt(patched)
|
||||
|
||||
history = await self._poll_history(client, prompt_id)
|
||||
if not history:
|
||||
raise RuntimeError("Timed out waiting for ComfyUI history")
|
||||
|
||||
status = history.get("status") or {}
|
||||
if status.get("status_str") == "error" or status.get("completed") is False:
|
||||
messages = status.get("messages") or []
|
||||
raise RuntimeError(f"ComfyUI error: {messages}")
|
||||
|
||||
outputs_meta = client.extract_outputs(history)
|
||||
dest_dir = config.settings.assets_dir / str(project_id) / kind
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
paths: list[str] = []
|
||||
for meta in outputs_meta:
|
||||
filename = meta["filename"]
|
||||
dest = dest_dir / filename
|
||||
await client.download_image(
|
||||
filename,
|
||||
subfolder=meta.get("subfolder", ""),
|
||||
folder_type=meta.get("type", "output"),
|
||||
dest=dest,
|
||||
)
|
||||
paths.append(str(dest))
|
||||
|
||||
self._apply_outputs_to_entities(job, payload, paths)
|
||||
return paths
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
async def _dry_run(self, job: dict[str, Any], payload: dict[str, Any]) -> list[str]:
|
||||
project_id = job["project_id"]
|
||||
kind = job["kind"]
|
||||
dest_dir = config.settings.assets_dir / str(project_id) / kind
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
label = f"job-{job['id']}-{kind}"
|
||||
if kind == "video":
|
||||
path = write_placeholder_mp4(dest_dir / f"{label}.mp4", label=label)
|
||||
else:
|
||||
path = write_placeholder_png(dest_dir / f"{label}.png", label=label)
|
||||
paths = [str(path)]
|
||||
self._apply_outputs_to_entities(job, payload, paths)
|
||||
await asyncio.sleep(0.3)
|
||||
return paths
|
||||
|
||||
async def _poll_history(self, client: ComfyUIClient, prompt_id: str) -> dict[str, Any] | None:
|
||||
attempts = int(600 / max(config.settings.queue_poll_interval_sec, 0.5))
|
||||
for _ in range(attempts):
|
||||
if self._stop.is_set():
|
||||
return None
|
||||
history = await client.get_history(prompt_id)
|
||||
if history:
|
||||
return history
|
||||
await asyncio.sleep(config.settings.queue_poll_interval_sec)
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"prompt_id": prompt_id,
|
||||
"message": f"Waiting on ComfyUI ({prompt_id[:8]}…)",
|
||||
},
|
||||
)
|
||||
return None
|
||||
|
||||
def _mark_project_completed(self, project_id: int) -> None:
|
||||
"""A finished export closes the project lifecycle."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE projects SET status = 'completed' WHERE id = ? AND status != 'completed'",
|
||||
(project_id,),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def _load_workflow(self, workflow_id: int | None) -> dict[str, Any] | None:
|
||||
if not workflow_id:
|
||||
return None
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT workflow_json FROM workflows WHERE id = ?", (workflow_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return json.loads(row["workflow_json"])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def _job_label(self, job: dict[str, Any]) -> str:
|
||||
payload = json.loads(job.get("payload_json") or "{}")
|
||||
kind = job.get("kind") or "job"
|
||||
if kind == "export":
|
||||
return "Export film"
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
if payload.get("character_id"):
|
||||
row = conn.execute(
|
||||
"SELECT name FROM characters WHERE id = ?", (payload["character_id"],)
|
||||
).fetchone()
|
||||
name = row["name"] if row else f"#{payload['character_id']}"
|
||||
target = payload.get("asset_target") or "sheet"
|
||||
return f"{name} · {target}"
|
||||
if payload.get("location_id"):
|
||||
row = conn.execute(
|
||||
"SELECT name FROM locations WHERE id = ?", (payload["location_id"],)
|
||||
).fetchone()
|
||||
name = row["name"] if row else f"#{payload['location_id']}"
|
||||
return f"{name} · environment"
|
||||
if job.get("scene_id"):
|
||||
row = conn.execute(
|
||||
"SELECT heading, order_index FROM scenes WHERE id = ?", (job["scene_id"],)
|
||||
).fetchone()
|
||||
if row:
|
||||
heading = (row["heading"] or f"Scene {row['order_index']}").strip()
|
||||
return f"Scene · {heading}"
|
||||
return f"Scene #{job['scene_id']}"
|
||||
finally:
|
||||
conn.close()
|
||||
return f"{kind} #{job.get('id')}"
|
||||
|
||||
def _apply_outputs_to_entities(
|
||||
self, job: dict[str, Any], payload: dict[str, Any], paths: list[str]
|
||||
) -> None:
|
||||
if not paths:
|
||||
return
|
||||
primary = paths[0]
|
||||
character_id = payload.get("character_id")
|
||||
location_id = payload.get("location_id")
|
||||
scene_id = job.get("scene_id")
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
if character_id:
|
||||
target = payload.get("asset_target") or "sheet"
|
||||
if target == "portrait":
|
||||
# Legacy jobs only — UI no longer generates portraits
|
||||
conn.execute(
|
||||
"UPDATE characters SET portrait_path = ? WHERE id = ?",
|
||||
(primary, character_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE characters SET sheet_path = ? WHERE id = ?",
|
||||
(primary, character_id),
|
||||
)
|
||||
if location_id:
|
||||
conn.execute(
|
||||
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
|
||||
(primary, location_id),
|
||||
)
|
||||
if scene_id and job["kind"] == "video":
|
||||
conn.execute(
|
||||
"UPDATE scenes SET video_path = ? WHERE id = ?",
|
||||
(primary, scene_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
queue_worker = QueueWorker()
|
||||
@@ -0,0 +1 @@
|
||||
# Routers package
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from calliope.agent.asset_agent import enqueue_asset_jobs
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import GenerateAssetsRequest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/assets")
|
||||
async def list_assets(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
characters = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM characters WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
locations = [
|
||||
row_to_dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM locations WHERE project_id = ?", (project_id,)
|
||||
).fetchall()
|
||||
]
|
||||
return {"characters": characters, "locations": locations}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/generate-assets")
|
||||
async def generate_assets(project_id: int, payload: GenerateAssetsRequest) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone():
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
finally:
|
||||
conn.close()
|
||||
jobs = await enqueue_asset_jobs(
|
||||
project_id,
|
||||
character_ids=payload.character_ids,
|
||||
location_ids=payload.location_ids,
|
||||
missing_only=payload.missing_only,
|
||||
workflow_id=payload.workflow_id,
|
||||
input_values_override=payload.input_values,
|
||||
asset_target=payload.asset_target or "sheet",
|
||||
prompt_override=payload.prompt,
|
||||
)
|
||||
return {"ok": True, "jobs": jobs}
|
||||
|
||||
|
||||
@router.get("/file")
|
||||
async def get_asset_file(path: str = Query(...)) -> FileResponse:
|
||||
assets_root = settings.assets_dir.resolve()
|
||||
target = Path(path).resolve()
|
||||
try:
|
||||
target.relative_to(assets_root)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=403, detail="Path outside assets directory") from exc
|
||||
if not target.exists() or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
return FileResponse(target)
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from calliope.events.bus import event_bus
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def events_stream(request: Request):
|
||||
async def generator():
|
||||
q = await event_bus.subscribe()
|
||||
try:
|
||||
# Send recent backlog
|
||||
for event in event_bus.recent[-20:]:
|
||||
yield event_bus.format_sse(event)
|
||||
while True:
|
||||
if await request.is_disconnected():
|
||||
break
|
||||
try:
|
||||
event = await asyncio.wait_for(q.get(), timeout=15.0)
|
||||
yield event_bus.format_sse(event)
|
||||
except asyncio.TimeoutError:
|
||||
yield ": keepalive\n\n"
|
||||
finally:
|
||||
await event_bus.unsubscribe(q)
|
||||
|
||||
return StreamingResponse(
|
||||
generator(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from calliope.agent.video_agent import enqueue_video_jobs
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.export.runner import kill_running
|
||||
from calliope.models.schemas import GenerateVideosRequest, JobCreate
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(job)
|
||||
out["payload"] = json.loads(job.get("payload_json") or "{}")
|
||||
out["output_paths"] = json.loads(job.get("output_paths_json") or "[]")
|
||||
out.pop("payload_json", None)
|
||||
out.pop("output_paths_json", None)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_jobs(
|
||||
project_id: int | None = None,
|
||||
status: str | None = None,
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
) -> list[dict[str, Any]]:
|
||||
return [_job_public(j) for j in queue_manager.list_jobs(project_id, status, limit)]
|
||||
|
||||
|
||||
@router.get("/queue-status")
|
||||
async def queue_status() -> dict[str, Any]:
|
||||
return {"paused": queue_manager.paused}
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause_queue() -> dict[str, Any]:
|
||||
queue_manager.paused = True
|
||||
return {"ok": True, "paused": True}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume_queue() -> dict[str, Any]:
|
||||
queue_manager.paused = False
|
||||
return {"ok": True, "paused": False}
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/generate-videos")
|
||||
async def generate_videos(
|
||||
project_id: int, payload: GenerateVideosRequest | None = None
|
||||
) -> dict[str, Any]:
|
||||
body = payload or GenerateVideosRequest()
|
||||
jobs = await enqueue_video_jobs(
|
||||
project_id,
|
||||
scene_ids=body.scene_ids,
|
||||
workflow_id=body.workflow_id,
|
||||
input_values_override=body.input_values,
|
||||
)
|
||||
return {"ok": True, "jobs": [_job_public(j) for j in jobs]}
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/export")
|
||||
async def export_film(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) AS n FROM scenes WHERE project_id = ? AND video_path IS NOT NULL",
|
||||
(project_id,),
|
||||
).fetchone()
|
||||
if not row or row["n"] == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No scene clips to export — generate videos first",
|
||||
)
|
||||
# Supersede leftover pending exports so a re-Export always starts fresh
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'failed', error = 'superseded by new export',
|
||||
completed_at = CURRENT_TIMESTAMP
|
||||
WHERE project_id = ? AND kind = 'export' AND status = 'pending'
|
||||
""",
|
||||
(project_id,),
|
||||
)
|
||||
# Commit BEFORE enqueue: queue_manager.enqueue writes on its own connection.
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
job = queue_manager.enqueue(project_id=project_id, kind="export", payload={})
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"kind": "export",
|
||||
"message": "Export film",
|
||||
"project_id": project_id,
|
||||
},
|
||||
)
|
||||
return {"ok": True, "job": _job_public(job)}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_job(payload: JobCreate, project_id: int = Query(...)) -> dict[str, Any]:
|
||||
job = queue_manager.enqueue(
|
||||
project_id=project_id,
|
||||
kind=payload.kind,
|
||||
workflow_id=payload.workflow_id,
|
||||
scene_id=payload.scene_id,
|
||||
payload={
|
||||
"input_values": payload.input_values or {},
|
||||
"character_id": payload.character_id,
|
||||
"location_id": payload.location_id,
|
||||
},
|
||||
)
|
||||
return _job_public(job)
|
||||
|
||||
|
||||
@router.get("/{job_id}")
|
||||
async def get_job(job_id: int) -> dict[str, Any]:
|
||||
job = queue_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return _job_public(job)
|
||||
|
||||
|
||||
@router.post("/{job_id}/retry")
|
||||
async def retry_job(job_id: int) -> dict[str, Any]:
|
||||
job = queue_manager.retry(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
return _job_public(job)
|
||||
|
||||
|
||||
@router.post("/{job_id}/cancel")
|
||||
async def cancel_job(job_id: int) -> dict[str, Any]:
|
||||
job = queue_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not cancellable")
|
||||
ok = queue_manager.cancel(job_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=404, detail="Job not cancellable")
|
||||
if job["kind"] == "export":
|
||||
# Export runs local ffmpeg, not Comfy — kill the process instead.
|
||||
kill_running(job_id)
|
||||
else:
|
||||
client = ComfyUIClient()
|
||||
try:
|
||||
await client.interrupt()
|
||||
finally:
|
||||
await client.close()
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,395 @@
|
||||
"""Standalone ComfyUI playground — generate freely, attach favorites to projects."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, File, HTTPException, UploadFile
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from calliope import config
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.queue.manager import queue_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
PLAYGROUND_STATUS = "system"
|
||||
PLAYGROUND_TITLE = "Playground Scratch"
|
||||
|
||||
|
||||
class PlaygroundGenerate(BaseModel):
|
||||
workflow_id: int
|
||||
input_values: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class PlaygroundAttach(BaseModel):
|
||||
path: str
|
||||
project_id: int
|
||||
target: Literal["character_sheet", "location", "scene"]
|
||||
character_id: int | None = None
|
||||
location_id: int | None = None
|
||||
scene_id: int | None = None
|
||||
|
||||
|
||||
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(job)
|
||||
out["payload"] = json.loads(job.get("payload_json") or "{}")
|
||||
out["output_paths"] = json.loads(job.get("output_paths_json") or "[]")
|
||||
out.pop("payload_json", None)
|
||||
out.pop("output_paths_json", None)
|
||||
return out
|
||||
|
||||
|
||||
def ensure_playground_project(conn) -> int:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM projects WHERE status = ? ORDER BY id ASC LIMIT 1",
|
||||
(PLAYGROUND_STATUS,),
|
||||
).fetchone()
|
||||
if row:
|
||||
return int(row["id"])
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO projects (title, idea, status)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(
|
||||
PLAYGROUND_TITLE,
|
||||
"System scratch for ComfyUI playground jobs — hidden from project list",
|
||||
PLAYGROUND_STATUS,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def _assert_path_in_assets(path: str) -> Path:
|
||||
assets_root = config.settings.assets_dir.resolve()
|
||||
target = Path(path).resolve()
|
||||
try:
|
||||
target.relative_to(assets_root)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=403, detail="Path outside assets directory") from exc
|
||||
if not target.exists() or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
return target
|
||||
|
||||
|
||||
def _safe_unlink_asset(path_str: str) -> bool:
|
||||
"""Delete a file if it resolves under assets_dir. Missing files count as already gone."""
|
||||
assets_root = config.settings.assets_dir.resolve()
|
||||
try:
|
||||
target = Path(path_str).resolve()
|
||||
target.relative_to(assets_root)
|
||||
except (ValueError, OSError):
|
||||
return False
|
||||
if not target.is_file():
|
||||
return False
|
||||
try:
|
||||
target.unlink()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
UPLOAD_KIND_BY_EXT: dict[str, str] = {
|
||||
".png": "image",
|
||||
".jpg": "image",
|
||||
".jpeg": "image",
|
||||
".webp": "image",
|
||||
".gif": "image",
|
||||
".bmp": "image",
|
||||
".mp4": "video",
|
||||
".webm": "video",
|
||||
".mov": "video",
|
||||
".mkv": "video",
|
||||
".mp3": "audio",
|
||||
".wav": "audio",
|
||||
".flac": "audio",
|
||||
".ogg": "audio",
|
||||
".m4a": "audio",
|
||||
}
|
||||
|
||||
UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1MB
|
||||
UPLOAD_MAX_BYTES = 500 * 1024 * 1024 # 500MB
|
||||
_UPLOAD_PREFIX_RE = re.compile(r"^[0-9a-f]{8}-")
|
||||
|
||||
|
||||
def _kind_for_ext(ext: str) -> str | None:
|
||||
return UPLOAD_KIND_BY_EXT.get(ext.lower())
|
||||
|
||||
|
||||
def _uploads_dir() -> Path:
|
||||
return config.settings.assets_dir / "uploads"
|
||||
|
||||
|
||||
def _safe_upload_name(filename: str) -> str:
|
||||
return re.sub(r"[^A-Za-z0-9._-]", "_", filename)
|
||||
|
||||
|
||||
def _upload_display_name(filename: str) -> str:
|
||||
"""Strip the uuid prefix written at upload time (``deadbeef-name.png`` → ``name.png``)."""
|
||||
if _UPLOAD_PREFIX_RE.match(filename):
|
||||
return filename[9:]
|
||||
return filename
|
||||
|
||||
|
||||
def _clear_entity_refs(conn, paths: list[str]) -> None:
|
||||
"""If playground outputs were attached to entities, clear those path columns."""
|
||||
for path in paths:
|
||||
conn.execute("UPDATE characters SET portrait_path = NULL WHERE portrait_path = ?", (path,))
|
||||
conn.execute("UPDATE characters SET sheet_path = NULL WHERE sheet_path = ?", (path,))
|
||||
conn.execute(
|
||||
"UPDATE locations SET reference_image_path = NULL WHERE reference_image_path = ?",
|
||||
(path,),
|
||||
)
|
||||
conn.execute("UPDATE scenes SET video_path = NULL WHERE video_path = ?", (path,))
|
||||
|
||||
|
||||
@router.get("/project")
|
||||
async def playground_project() -> dict[str, Any]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (pid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/jobs")
|
||||
async def list_playground_jobs(limit: int = 50) -> list[dict[str, Any]]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
return [_job_public(j) for j in queue_manager.list_jobs(pid, None, limit)]
|
||||
|
||||
|
||||
@router.delete("/jobs/{job_id}")
|
||||
async def delete_playground_job(job_id: int) -> dict[str, Any]:
|
||||
"""Delete a playground job row and its output files under assets_dir."""
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
job = queue_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
if int(job["project_id"]) != int(pid):
|
||||
raise HTTPException(status_code=403, detail="Not a playground job")
|
||||
|
||||
paths = json.loads(job.get("output_paths_json") or "[]")
|
||||
if not isinstance(paths, list):
|
||||
paths = []
|
||||
|
||||
deleted_files: list[str] = []
|
||||
missing_files: list[str] = []
|
||||
for p in paths:
|
||||
if not isinstance(p, str) or not p.strip():
|
||||
continue
|
||||
if _safe_unlink_asset(p):
|
||||
deleted_files.append(p)
|
||||
else:
|
||||
missing_files.append(p)
|
||||
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
_clear_entity_refs(conn, [p for p in paths if isinstance(p, str)])
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
removed = queue_manager.delete_job(job_id)
|
||||
if not removed:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
await event_bus.publish(
|
||||
"job.deleted",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"source": "playground",
|
||||
"deleted_files": deleted_files,
|
||||
"missing_files": missing_files,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"job_id": job_id,
|
||||
"deleted_files": deleted_files,
|
||||
"missing_files": missing_files,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/uploads")
|
||||
async def upload_media(file: UploadFile = File(...)) -> dict[str, Any]:
|
||||
"""Store a client-provided media file under assets_dir/uploads for use as a job input."""
|
||||
original = Path(file.filename or "upload").name
|
||||
ext = Path(original).suffix.lower()
|
||||
kind = _kind_for_ext(ext)
|
||||
if kind is None:
|
||||
allowed = " ".join(sorted(UPLOAD_KIND_BY_EXT))
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unsupported file type '{ext or '(none)'}'. Allowed extensions: {allowed}",
|
||||
)
|
||||
|
||||
uploads = _uploads_dir()
|
||||
uploads.mkdir(parents=True, exist_ok=True)
|
||||
dest = uploads / f"{uuid4().hex[:8]}-{_safe_upload_name(original)}"
|
||||
|
||||
size = 0
|
||||
try:
|
||||
with dest.open("wb") as out:
|
||||
while chunk := await file.read(UPLOAD_CHUNK_SIZE):
|
||||
size += len(chunk)
|
||||
if size > UPLOAD_MAX_BYTES:
|
||||
raise HTTPException(status_code=413, detail="File too large (max 500MB)")
|
||||
out.write(chunk)
|
||||
except Exception:
|
||||
dest.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
return {"ok": True, "path": str(dest.resolve()), "name": original, "kind": kind}
|
||||
|
||||
|
||||
@router.get("/uploads")
|
||||
async def list_uploaded_media() -> list[dict[str, Any]]:
|
||||
"""List previously uploaded media files, newest first."""
|
||||
uploads = _uploads_dir()
|
||||
if not uploads.is_dir():
|
||||
return []
|
||||
entries: list[tuple[float, dict[str, Any]]] = []
|
||||
for f in uploads.iterdir():
|
||||
if not f.is_file():
|
||||
continue
|
||||
kind = _kind_for_ext(f.suffix)
|
||||
if kind is None:
|
||||
continue
|
||||
stat = f.stat()
|
||||
entries.append(
|
||||
(
|
||||
stat.st_mtime,
|
||||
{
|
||||
"name": _upload_display_name(f.name),
|
||||
"path": str(f.resolve()),
|
||||
"kind": kind,
|
||||
"size": stat.st_size,
|
||||
"mtime": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat(),
|
||||
},
|
||||
)
|
||||
)
|
||||
entries.sort(key=lambda e: e[0], reverse=True)
|
||||
return [item for _, item in entries]
|
||||
|
||||
|
||||
@router.post("/generate")
|
||||
async def generate(payload: PlaygroundGenerate) -> dict[str, Any]:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
pid = ensure_playground_project(conn)
|
||||
wf = conn.execute(
|
||||
"SELECT id, kind, is_enabled FROM workflows WHERE id = ?",
|
||||
(payload.workflow_id,),
|
||||
).fetchone()
|
||||
if not wf:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
if not wf["is_enabled"]:
|
||||
raise HTTPException(status_code=400, detail="Workflow is disabled")
|
||||
kind = wf["kind"]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
job = queue_manager.enqueue(
|
||||
project_id=pid,
|
||||
kind=kind,
|
||||
workflow_id=payload.workflow_id,
|
||||
scene_id=None,
|
||||
payload={"input_values": payload.input_values, "source": "playground"},
|
||||
)
|
||||
await event_bus.publish(
|
||||
"job.created",
|
||||
{"job_id": job["id"], "kind": kind, "source": "playground", "project_id": pid},
|
||||
)
|
||||
return {"ok": True, "job": _job_public(job)}
|
||||
|
||||
|
||||
@router.post("/attach")
|
||||
async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
|
||||
path = str(_assert_path_in_assets(payload.path))
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
project = conn.execute(
|
||||
"SELECT id, status FROM projects WHERE id = ?", (payload.project_id,)
|
||||
).fetchone()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
if project["status"] == PLAYGROUND_STATUS:
|
||||
raise HTTPException(status_code=400, detail="Cannot attach to playground scratch")
|
||||
|
||||
if payload.target == "character_sheet":
|
||||
if not payload.character_id:
|
||||
raise HTTPException(status_code=400, detail="character_id required")
|
||||
char = conn.execute(
|
||||
"SELECT id FROM characters WHERE id = ? AND project_id = ?",
|
||||
(payload.character_id, payload.project_id),
|
||||
).fetchone()
|
||||
if not char:
|
||||
raise HTTPException(status_code=404, detail="Character not found")
|
||||
conn.execute(
|
||||
"UPDATE characters SET sheet_path = ? WHERE id = ?",
|
||||
(path, payload.character_id),
|
||||
)
|
||||
elif payload.target == "location":
|
||||
if not payload.location_id:
|
||||
raise HTTPException(status_code=400, detail="location_id required")
|
||||
loc = conn.execute(
|
||||
"SELECT id FROM locations WHERE id = ? AND project_id = ?",
|
||||
(payload.location_id, payload.project_id),
|
||||
).fetchone()
|
||||
if not loc:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
conn.execute(
|
||||
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
|
||||
(path, payload.location_id),
|
||||
)
|
||||
elif payload.target == "scene":
|
||||
if not payload.scene_id:
|
||||
raise HTTPException(status_code=400, detail="scene_id required")
|
||||
scene = conn.execute(
|
||||
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
|
||||
(payload.scene_id, payload.project_id),
|
||||
).fetchone()
|
||||
if not scene:
|
||||
raise HTTPException(status_code=404, detail="Scene not found")
|
||||
conn.execute(
|
||||
"UPDATE scenes SET video_path = ? WHERE id = ?",
|
||||
(path, payload.scene_id),
|
||||
)
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="Invalid target")
|
||||
|
||||
conn.execute(
|
||||
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(payload.project_id,),
|
||||
)
|
||||
conn.commit()
|
||||
await event_bus.publish(
|
||||
"asset.ready",
|
||||
{
|
||||
"path": path,
|
||||
"project_id": payload.project_id,
|
||||
"target": payload.target,
|
||||
"source": "playground_attach",
|
||||
},
|
||||
)
|
||||
return {"ok": True, "path": path, "target": payload.target, "project_id": payload.project_id}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import Project, ProjectCreate, ProjectUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _project_stats(project_id: int, conn) -> dict[str, int]:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM scenes WHERE project_id = :pid) AS scene_count,
|
||||
(SELECT COUNT(*) FROM characters WHERE project_id = :pid) AS character_count,
|
||||
(SELECT COUNT(*) FROM characters WHERE project_id = :pid AND sheet_path IS NOT NULL)
|
||||
+ (SELECT COUNT(*) FROM locations WHERE project_id = :pid AND reference_image_path IS NOT NULL) AS asset_ready_count,
|
||||
(SELECT COUNT(*) FROM characters WHERE project_id = :pid)
|
||||
+ (SELECT COUNT(*) FROM locations WHERE project_id = :pid) AS asset_total_count
|
||||
""",
|
||||
{"pid": project_id},
|
||||
)
|
||||
return dict(cur.fetchone())
|
||||
|
||||
|
||||
@router.post("", response_model=Project)
|
||||
async def create_project(payload: ProjectCreate):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO projects (title, idea, genre, tone, target_duration)
|
||||
VALUES (:title, :idea, :genre, :tone, :target_duration)
|
||||
""",
|
||||
payload.model_dump(),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("", response_model=list[Project])
|
||||
async def list_projects():
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM projects WHERE status != 'system' ORDER BY updated_at DESC"
|
||||
).fetchall()
|
||||
out = []
|
||||
for row in rows:
|
||||
project = row_to_dict(row)
|
||||
project["stats"] = _project_stats(row["id"], conn)
|
||||
out.append(project)
|
||||
return out
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/{project_id}")
|
||||
async def get_project(project_id: int):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
project = row_to_dict(row)
|
||||
project["stats"] = _project_stats(project_id, conn)
|
||||
return project
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}", response_model=Project)
|
||||
async def update_project(project_id: int, payload: ProjectUpdate):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
# exclude_unset keeps explicitly-sent nulls (e.g. clearing cover_path)
|
||||
# while leaving fields the client did not send untouched.
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if not data:
|
||||
return row_to_dict(existing)
|
||||
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data.keys())
|
||||
data["id"] = project_id
|
||||
conn.execute(
|
||||
f"UPDATE projects SET {fields}, updated_at = CURRENT_TIMESTAMP WHERE id = :id",
|
||||
data,
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}")
|
||||
async def delete_project(project_id: int):
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute("DELETE FROM projects WHERE id = ?", (project_id,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,166 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.agent.script_agent import generate_script
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import GenerateScenesRequest, SceneCreate, SceneReorder, SceneUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _scene_with_chars(conn, scene_row) -> dict[str, Any]:
|
||||
scene = row_to_dict(scene_row)
|
||||
chars = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.name, c.role, c.portrait_path, c.sheet_path
|
||||
FROM characters c
|
||||
JOIN scene_characters sc ON sc.character_id = c.id
|
||||
WHERE sc.scene_id = ?
|
||||
""",
|
||||
(scene["id"],),
|
||||
).fetchall()
|
||||
scene["characters"] = [row_to_dict(c) for c in chars]
|
||||
scene["character_ids"] = [c["id"] for c in scene["characters"]]
|
||||
return scene
|
||||
|
||||
|
||||
@router.get("/{project_id}/scenes")
|
||||
async def list_scenes(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone():
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
scenes = [_scene_with_chars(conn, r) for r in rows]
|
||||
total = sum((s.get("duration_sec") or 0) for s in scenes)
|
||||
return {"scenes": scenes, "estimated_duration_sec": total}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/{project_id}/generate-script")
|
||||
async def generate_script_endpoint(project_id: int, payload: GenerateScenesRequest | None = None) -> dict[str, Any]:
|
||||
replace = True if payload is None else payload.replace
|
||||
scene_count = None if payload is None else payload.scene_count
|
||||
try:
|
||||
return await generate_script(project_id, replace=replace, scene_count=scene_count)
|
||||
except ValueError as exc:
|
||||
# Distinguish not-found vs constraint failures
|
||||
detail = str(exc)
|
||||
code = 404 if "not found" in detail.lower() else 422
|
||||
raise HTTPException(status_code=code, detail=detail) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{project_id}/scenes")
|
||||
async def create_scene(project_id: int, payload: SceneCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM projects WHERE id = ?", (project_id,)).fetchone():
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO scenes
|
||||
(project_id, beat_id, order_index, heading, action, dialog, duration_sec,
|
||||
workflow_id, env_image_path, location_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
payload.beat_id,
|
||||
payload.order_index,
|
||||
payload.heading,
|
||||
payload.action,
|
||||
payload.dialog,
|
||||
payload.duration_sec,
|
||||
payload.workflow_id,
|
||||
payload.env_image_path,
|
||||
payload.location_id,
|
||||
),
|
||||
)
|
||||
scene_id = cur.lastrowid
|
||||
for cid in payload.character_ids:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)",
|
||||
(scene_id, cid),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
|
||||
return _scene_with_chars(conn, row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/scenes/{scene_id}")
|
||||
async def update_scene(project_id: int, scene_id: int, payload: SceneUpdate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM scenes WHERE id = ? AND project_id = ?",
|
||||
(scene_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Scene not found")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
char_ids = data.pop("character_ids", None)
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = scene_id
|
||||
conn.execute(f"UPDATE scenes SET {fields} WHERE id = :id", data)
|
||||
if char_ids is not None:
|
||||
conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (scene_id,))
|
||||
for cid in char_ids:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scene_characters (scene_id, character_id) VALUES (?, ?)",
|
||||
(scene_id, cid),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM scenes WHERE id = ?", (scene_id,)).fetchone()
|
||||
return _scene_with_chars(conn, row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/scenes/{scene_id}")
|
||||
async def delete_scene(project_id: int, scene_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
conn.execute("DELETE FROM scene_characters WHERE scene_id = ?", (scene_id,))
|
||||
cur = conn.execute(
|
||||
"DELETE FROM scenes WHERE id = ? AND project_id = ?",
|
||||
(scene_id, project_id),
|
||||
)
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Scene not found")
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/{project_id}/scenes/reorder")
|
||||
async def reorder_scenes(project_id: int, payload: SceneReorder) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
for index, scene_id in enumerate(payload.scene_ids, start=1):
|
||||
conn.execute(
|
||||
"UPDATE scenes SET order_index = ? WHERE id = ? AND project_id = ?",
|
||||
(index, scene_id, project_id),
|
||||
)
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM scenes WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
return {"scenes": [_scene_with_chars(conn, r) for r in rows]}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from calliope.config import normalize_path, settings
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class SettingsUpdate(BaseModel):
|
||||
llm_base_url: str | None = None
|
||||
llm_model: str | None = None
|
||||
llm_api_key: str | None = None
|
||||
comfyui_base_url: str | None = None
|
||||
data_dir: str | None = None
|
||||
assets_dir: str | None = None
|
||||
queue_concurrency: int | None = Field(None, ge=1, le=8)
|
||||
queue_poll_interval_sec: float | None = Field(None, ge=0.5, le=60.0)
|
||||
queue_max_retries: int | None = Field(None, ge=0, le=10)
|
||||
dry_run: bool | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_settings() -> dict[str, Any]:
|
||||
return settings.to_public_dict()
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
for key, value in data.items():
|
||||
if key in {"data_dir", "assets_dir"}:
|
||||
path = normalize_path(value)
|
||||
if path is not None:
|
||||
setattr(settings, key, path)
|
||||
continue
|
||||
if key == "dry_run":
|
||||
setattr(settings, key, bool(value))
|
||||
continue
|
||||
setattr(settings, key, value)
|
||||
|
||||
settings.save_config_file()
|
||||
return settings.to_public_dict()
|
||||
@@ -0,0 +1,460 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.agent.llm import generate_structured
|
||||
from calliope.agent.prompts import (
|
||||
build_story_messages,
|
||||
character_sheet_prompt,
|
||||
location_reference_prompt,
|
||||
recommend_beat_count,
|
||||
story_generation_user_prompt,
|
||||
)
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.models.schemas import (
|
||||
BeatCreate,
|
||||
BeatUpdate,
|
||||
CharacterCreate,
|
||||
CharacterUpdate,
|
||||
LocationCreate,
|
||||
LocationUpdate,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("calliope.story")
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _touch_project(conn, project_id: int) -> None:
|
||||
conn.execute(
|
||||
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(project_id,),
|
||||
)
|
||||
|
||||
|
||||
def _require_project(conn, project_id: int) -> dict[str, Any]:
|
||||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
return row_to_dict(row)
|
||||
|
||||
|
||||
@router.post("/{project_id}/generate-story")
|
||||
async def generate_story(project_id: int, replace: bool = True) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = _require_project(conn, project_id)
|
||||
|
||||
required_beats = recommend_beat_count(project.get("target_duration"))
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": (
|
||||
f"Drafting storyline for \"{project['title']}\" "
|
||||
f"(target {project.get('target_duration') or '?'} -> {required_beats} beats)..."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
messages = build_story_messages(
|
||||
title=project["title"],
|
||||
idea=project["idea"],
|
||||
genre=project["genre"],
|
||||
tone=project["tone"],
|
||||
target_duration=project["target_duration"],
|
||||
)
|
||||
result = await generate_structured(messages, temperature=0.7)
|
||||
beats_out = result.get("beats") or []
|
||||
|
||||
# Models often under-deliver on long runtimes — one corrective retry.
|
||||
if len(beats_out) < required_beats:
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": (
|
||||
f"Model returned {len(beats_out)} beats; "
|
||||
f"required {required_beats}. Retrying..."
|
||||
),
|
||||
},
|
||||
)
|
||||
repair = [
|
||||
{"role": "system", "content": messages[0]["content"]},
|
||||
{
|
||||
"role": "user",
|
||||
"content": story_generation_user_prompt(
|
||||
project["title"],
|
||||
project["idea"],
|
||||
project["genre"],
|
||||
project["tone"],
|
||||
project["target_duration"],
|
||||
)
|
||||
+ (
|
||||
f"\n\nPREVIOUS ATTEMPT FAILED: it only had {len(beats_out)} beats. "
|
||||
f"You MUST return exactly {required_beats} beats this time."
|
||||
),
|
||||
},
|
||||
]
|
||||
result = await generate_structured(repair, temperature=0.4)
|
||||
beats_out = result.get("beats") or []
|
||||
if len(beats_out) < required_beats:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=(
|
||||
f"Story draft returned {len(beats_out)} beats but target "
|
||||
f"'{project.get('target_duration')}' requires {required_beats}. "
|
||||
"Try Draft Storyline again, or check the LLM follows JSON instructions."
|
||||
),
|
||||
)
|
||||
|
||||
title = result.get("title") or project["title"]
|
||||
logline = result.get("logline")
|
||||
conn.execute(
|
||||
"UPDATE projects SET title = ?, idea = COALESCE(?, idea), status = 'in_progress', "
|
||||
"updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(title, logline, project_id),
|
||||
)
|
||||
|
||||
if replace:
|
||||
conn.execute("DELETE FROM story_beats WHERE project_id = ?", (project_id,))
|
||||
conn.execute("DELETE FROM characters WHERE project_id = ?", (project_id,))
|
||||
conn.execute("DELETE FROM locations WHERE project_id = ?", (project_id,))
|
||||
|
||||
for beat in result.get("beats", []):
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO story_beats (project_id, order_index, title, description)
|
||||
VALUES (:project_id, :order_index, :title, :description)
|
||||
""",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"order_index": beat.get("order_index", 0),
|
||||
"title": beat.get("title", ""),
|
||||
"description": beat.get("description", ""),
|
||||
},
|
||||
)
|
||||
|
||||
for character in result.get("characters", []):
|
||||
appearance = character.get("appearance", "") or ""
|
||||
row_seed = {
|
||||
"name": character.get("name", ""),
|
||||
"role": character.get("role", ""),
|
||||
"age": character.get("age", ""),
|
||||
"appearance": appearance,
|
||||
"personality": character.get("personality", ""),
|
||||
}
|
||||
# Seed with the published sheet template so Assets shows a real prompt, not a hidden blob.
|
||||
sheet_prompt = character_sheet_prompt(row_seed)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO characters
|
||||
(project_id, name, role, age, appearance, personality, consistency_prompt)
|
||||
VALUES (:project_id, :name, :role, :age, :appearance, :personality, :consistency_prompt)
|
||||
""",
|
||||
{
|
||||
"project_id": project_id,
|
||||
**row_seed,
|
||||
"consistency_prompt": sheet_prompt,
|
||||
},
|
||||
)
|
||||
|
||||
for location in result.get("locations", []):
|
||||
description = location.get("description", "") or ""
|
||||
loc_seed = {
|
||||
"name": location.get("name", ""),
|
||||
"description": description,
|
||||
}
|
||||
env_prompt = location_reference_prompt(loc_seed)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO locations (project_id, name, description, consistency_prompt)
|
||||
VALUES (:project_id, :name, :description, :consistency_prompt)
|
||||
""",
|
||||
{
|
||||
"project_id": project_id,
|
||||
**loc_seed,
|
||||
"consistency_prompt": env_prompt,
|
||||
},
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
beat_n = len(result.get("beats", []))
|
||||
await event_bus.publish(
|
||||
"story.ready",
|
||||
{
|
||||
"project_id": project_id,
|
||||
"message": f"Story drafted — {beat_n} beats",
|
||||
},
|
||||
)
|
||||
return {"ok": True, "project_id": project_id, "generated": result}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("Story generation failed for project %s", project_id)
|
||||
await event_bus.publish(
|
||||
"agent.thinking",
|
||||
{"project_id": project_id, "message": f"Story draft failed: {exc}"},
|
||||
)
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/{project_id}/story")
|
||||
async def get_story(project_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
project = conn.execute(
|
||||
"SELECT id, title, idea, genre, tone, target_duration, status FROM projects WHERE id = ?",
|
||||
(project_id,),
|
||||
).fetchone()
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
beats = conn.execute(
|
||||
"SELECT id, order_index, title, description FROM story_beats WHERE project_id = ? ORDER BY order_index",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
characters = conn.execute(
|
||||
"""
|
||||
SELECT id, name, role, age, appearance, personality, portrait_path, sheet_path, consistency_prompt
|
||||
FROM characters WHERE project_id = ?
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
locations = conn.execute(
|
||||
"""
|
||||
SELECT id, name, description, reference_image_path, consistency_prompt
|
||||
FROM locations WHERE project_id = ?
|
||||
""",
|
||||
(project_id,),
|
||||
).fetchall()
|
||||
|
||||
return {
|
||||
"project": row_to_dict(project),
|
||||
"beats": [row_to_dict(b) for b in beats],
|
||||
"characters": [row_to_dict(c) for c in characters],
|
||||
"locations": [row_to_dict(l) for l in locations],
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Beats CRUD ---
|
||||
|
||||
|
||||
@router.post("/{project_id}/beats")
|
||||
async def create_beat(project_id: int, payload: BeatCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_require_project(conn, project_id)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO story_beats (project_id, order_index, title, description)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(project_id, payload.order_index, payload.title, payload.description),
|
||||
)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM story_beats WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/beats/{beat_id}")
|
||||
async def update_beat(project_id: int, beat_id: int, payload: BeatUpdate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM story_beats WHERE id = ? AND project_id = ?",
|
||||
(beat_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Beat not found")
|
||||
data = {k: v for k, v in payload.model_dump().items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = beat_id
|
||||
conn.execute(f"UPDATE story_beats SET {fields} WHERE id = :id", data)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM story_beats WHERE id = ?", (beat_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/beats/{beat_id}")
|
||||
async def delete_beat(project_id: int, beat_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM story_beats WHERE id = ? AND project_id = ?",
|
||||
(beat_id, project_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Beat not found")
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Characters CRUD ---
|
||||
|
||||
|
||||
@router.post("/{project_id}/characters")
|
||||
async def create_character(project_id: int, payload: CharacterCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_require_project(conn, project_id)
|
||||
consistency = payload.consistency_prompt or character_sheet_prompt(
|
||||
{
|
||||
"name": payload.name,
|
||||
"role": payload.role,
|
||||
"age": payload.age,
|
||||
"appearance": payload.appearance,
|
||||
"personality": payload.personality,
|
||||
}
|
||||
)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO characters
|
||||
(project_id, name, role, age, appearance, personality, consistency_prompt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
payload.name,
|
||||
payload.role,
|
||||
payload.age,
|
||||
payload.appearance,
|
||||
payload.personality,
|
||||
consistency,
|
||||
),
|
||||
)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM characters WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/characters/{character_id}")
|
||||
async def update_character(
|
||||
project_id: int, character_id: int, payload: CharacterUpdate
|
||||
) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM characters WHERE id = ? AND project_id = ?",
|
||||
(character_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Character not found")
|
||||
data = {k: v for k, v in payload.model_dump().items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = character_id
|
||||
conn.execute(f"UPDATE characters SET {fields} WHERE id = :id", data)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM characters WHERE id = ?", (character_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/characters/{character_id}")
|
||||
async def delete_character(project_id: int, character_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM characters WHERE id = ? AND project_id = ?",
|
||||
(character_id, project_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Character not found")
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Locations CRUD ---
|
||||
|
||||
|
||||
@router.post("/{project_id}/locations")
|
||||
async def create_location(project_id: int, payload: LocationCreate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
_require_project(conn, project_id)
|
||||
consistency = payload.consistency_prompt or location_reference_prompt(
|
||||
{"name": payload.name, "description": payload.description}
|
||||
)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO locations (project_id, name, description, consistency_prompt)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(project_id, payload.name, payload.description, consistency),
|
||||
)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM locations WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{project_id}/locations/{location_id}")
|
||||
async def update_location(
|
||||
project_id: int, location_id: int, payload: LocationUpdate
|
||||
) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM locations WHERE id = ? AND project_id = ?",
|
||||
(location_id, project_id),
|
||||
).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
data = {k: v for k, v in payload.model_dump().items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = location_id
|
||||
conn.execute(f"UPDATE locations SET {fields} WHERE id = :id", data)
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM locations WHERE id = ?", (location_id,)).fetchone()
|
||||
return row_to_dict(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{project_id}/locations/{location_id}")
|
||||
async def delete_location(project_id: int, location_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM locations WHERE id = ? AND project_id = ?",
|
||||
(location_id, project_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
_touch_project(conn, project_id)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from calliope.comfyui.parser import parse_dynamic_inputs, parse_dynamic_outputs
|
||||
from calliope.comfyui.profiles import detect_prompt_profile
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.models.schemas import WorkflowAnalyze, WorkflowCreate, WorkflowUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _serialize_workflow(row: Any) -> dict[str, Any]:
|
||||
data = row_to_dict(row)
|
||||
data["workflow_json"] = json.loads(data["workflow_json"])
|
||||
data["input_schema"] = json.loads(data["input_schema"]) if data.get("input_schema") else []
|
||||
data["output_schema"] = json.loads(data["output_schema"]) if data.get("output_schema") else []
|
||||
data["is_enabled"] = bool(data.get("is_enabled"))
|
||||
return data
|
||||
|
||||
|
||||
@router.post("/analyze")
|
||||
async def analyze_workflow(payload: WorkflowAnalyze) -> dict[str, Any]:
|
||||
inputs = parse_dynamic_inputs(payload.workflow_json)
|
||||
outputs = parse_dynamic_outputs(payload.workflow_json)
|
||||
return {
|
||||
"inputs": inputs,
|
||||
"outputs": outputs,
|
||||
"suggested_profile": detect_prompt_profile(payload.workflow_json),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_workflows() -> list[dict[str, Any]]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
rows = conn.execute("SELECT * FROM workflows ORDER BY id DESC").fetchall()
|
||||
return [_serialize_workflow(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
|
||||
inputs = parse_dynamic_inputs(payload.workflow_json)
|
||||
outputs = parse_dynamic_outputs(payload.workflow_json)
|
||||
profile = payload.prompt_profile or detect_prompt_profile(payload.workflow_json)
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO workflows (name, kind, workflow_json, input_schema,
|
||||
output_schema, description, prompt_profile, is_enabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 1)
|
||||
""",
|
||||
(
|
||||
payload.name,
|
||||
payload.kind,
|
||||
json.dumps(payload.workflow_json),
|
||||
json.dumps(inputs),
|
||||
json.dumps(outputs),
|
||||
payload.description,
|
||||
profile,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (cur.lastrowid,)).fetchone()
|
||||
return _serialize_workflow(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/{workflow_id}")
|
||||
async def get_workflow(workflow_id: int) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
return _serialize_workflow(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/{workflow_id}")
|
||||
async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
existing = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
|
||||
if not existing:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "is_enabled" in data and data["is_enabled"] is not None:
|
||||
data["is_enabled"] = 1 if data["is_enabled"] else 0
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if data:
|
||||
fields = ", ".join(f"{k} = :{k}" for k in data)
|
||||
data["id"] = workflow_id
|
||||
conn.execute(f"UPDATE workflows SET {fields} WHERE id = :id", data)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
|
||||
return _serialize_workflow(row)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/{workflow_id}")
|
||||
async def delete_workflow(workflow_id: int) -> dict[str, bool]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
cur = conn.execute("DELETE FROM workflows WHERE id = ?", (workflow_id,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found")
|
||||
return {"ok": True}
|
||||
finally:
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user