diff --git a/calliope-backend/src/calliope/agent/video_agent.py b/calliope-backend/src/calliope/agent/video_agent.py index 5bad59df..0d07ba47 100644 --- a/calliope-backend/src/calliope/agent/video_agent.py +++ b/calliope-backend/src/calliope/agent/video_agent.py @@ -3,6 +3,8 @@ from __future__ import annotations import json import logging +import sqlite3 +from pathlib import Path from typing import Any from calliope.agent.llm import LLMClient @@ -12,6 +14,7 @@ from calliope.agent.prompts import ( scene_video_prompt, ) from calliope.comfyui.parser import parse_dynamic_inputs +from calliope.comfyui.roles import input_has_role from calliope.comfyui.smart_fill import ref_image_slots, smart_fill_inputs from calliope.config import settings from calliope.db import get_db, row_to_dict @@ -77,6 +80,42 @@ async def _h3_rewrite(scene: dict[str, Any], subjects: list[dict[str, Any]]) -> await client.close() +def _video_input(inputs: list[dict[str, Any]]) -> dict[str, Any] | None: + """First workflow input whose canonical role is ``video``.""" + for inp in inputs: + if input_has_role(inp, "video"): + return inp + return None + + +def _previous_clip( + conn: sqlite3.Connection, + project_id: int, + order_index: int, +) -> tuple[str | None, bool]: + """Nearest earlier scene's clip path + whether any earlier scene exists. + + Returns ``(path, has_earlier_scene)``; path is None when the clip file does + not exist on disk (not yet generated) or there is no earlier scene. + """ + row = conn.execute( + """ + SELECT video_path FROM scenes + WHERE project_id = ? AND order_index < ? AND video_path IS NOT NULL + ORDER BY order_index DESC LIMIT 1 + """, + (project_id, order_index), + ).fetchone() + has_earlier = conn.execute( + "SELECT 1 FROM scenes WHERE project_id = ? AND order_index < ? LIMIT 1", + (project_id, order_index), + ).fetchone() is not None + path = row["video_path"] if row else None + if path and Path(path).exists(): + return path, has_earlier + return None, has_earlier + + def _workflow_json(workflow: dict[str, Any] | None) -> dict[str, Any]: if not workflow: return {} @@ -211,13 +250,37 @@ async def enqueue_video_jobs( ) payload: dict[str, Any] = {"input_values": values, "prompt": prompt} if scene.get("chain_from_prev"): - # Resolved at RUN time by the worker (the previous scene's clip may not - # exist yet at enqueue time — e.g. a batch queues all scenes up front). - payload["chain_from_prev"] = True - payload["scene_order_index"] = scene.get("order_index") - # The value the location/first-image ref slot holds right now, so the - # worker can find and replace that exact slot whatever the layout. - payload["chain_replace_value"] = loc_image + video_input = _video_input(inputs) + if not video_input: + raise ValueError( + f"Scene {scene.get('order_index')} is marked continue-from-previous " + f"but workflow '{(workflow or {}).get('name') or workflow_id}' has no " + "video input — pick a workflow with a (Input:video) node." + ) + video_node_id = str(video_input["nodeId"]) + if not values.get(video_node_id): + # Explicit clip from the form / input_values_override wins. + prev_clip, has_earlier = _previous_clip( + conn, project_id, scene.get("order_index") or 0 + ) + if prev_clip: + # Local path: the worker's prepare_media_inputs uploads it + # to ComfyUI before queuing (same shape as char/loc refs). + values[video_node_id] = prev_clip + elif has_earlier: + # Previous clip not generated yet (typical when a batch is + # queued in one go). The worker resolves it at RUN time — + # the queue is concurrency-1, so the earlier scene's clip + # will exist by then. + payload["continue_source"] = { + "scene_order_index": scene.get("order_index"), + } + else: + raise ValueError( + f"Scene {scene.get('order_index')} is marked continue-from-previous " + "but no previous clip exists yet — generate an earlier clip first " + "or upload a video in the Video stage." + ) job = queue_manager.enqueue( project_id=project_id, kind="video", diff --git a/calliope-backend/tests/test_video_continue.py b/calliope-backend/tests/test_video_continue.py new file mode 100644 index 00000000..0be8597b --- /dev/null +++ b/calliope-backend/tests/test_video_continue.py @@ -0,0 +1,217 @@ +"""Continue-from-previous scenes: enqueue-time video validation + source resolution.""" +from __future__ import annotations + +import asyncio +import json +from pathlib import Path + +from calliope.agent.video_agent import enqueue_video_jobs +from calliope.config import settings +from calliope.db import get_db + +# One prompt node, one video input slot — the minimum viable "continue" workflow. +VIDEO_WORKFLOW = { + "10": { + "class_type": "CLIPTextEncode", + "inputs": {"text": ""}, + "_meta": {"title": "Main Prompt (Input:prompt)"}, + }, + "20": { + "class_type": "LoadVideo", + "inputs": {"file": ""}, + "_meta": {"title": "Previous Clip (Input:video)"}, + }, +} + +# Same but the video slot is missing entirely — must be rejected at enqueue. +NO_VIDEO_WORKFLOW = { + "10": { + "class_type": "CLIPTextEncode", + "inputs": {"text": ""}, + "_meta": {"title": "Main Prompt (Input:prompt)"}, + }, +} + + +def _mk_project(client, title: str) -> int: + return client.post("/api/projects", json={"title": title}).json()["id"] + + +def _add_scene(client, pid: int, order: int, **extra) -> dict: + payload = {"order_index": order, "heading": f"S{order}", **extra} + return client.post(f"/api/projects/{pid}/scenes", json=payload).json() + + +def _set_chain(client, pid: int, scene_id: int, on: bool) -> None: + r = client.patch( + f"/api/projects/{pid}/scenes/{scene_id}", json={"chain_from_prev": on} + ) + assert r.status_code == 200 + + +def _insert_workflow(conn, name: str, wf_json: dict) -> int: + cur = conn.execute( + """ + INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, is_enabled) + VALUES (?, 'video', ?, '[]', '[]', 1) + """, + (name, json.dumps(wf_json)), + ) + conn.commit() + return int(cur.lastrowid) + + +def _job_payloads(pid: int) -> list[dict]: + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT payload_json FROM jobs WHERE project_id = ? AND kind = 'video' " + "ORDER BY id", + (pid,), + ).fetchall() + return [json.loads(r["payload_json"]) for r in rows] + finally: + conn.close() + + +def _touch_clip(name: str) -> str: + root = Path(settings.assets_dir) + root.mkdir(parents=True, exist_ok=True) + path = root / name + path.write_bytes(b"mp4-placeholder") + return str(path) + + +def test_continue_scene_requires_video_input_role(client): + pid = _mk_project(client, "No Video WF") + _add_scene(client, pid, 1) + scene2 = _add_scene(client, pid, 2) + _set_chain(client, pid, scene2["id"], True) + conn = get_db(settings.db_path) + try: + _insert_workflow(conn, "no-video", NO_VIDEO_WORKFLOW) + finally: + conn.close() + + try: + asyncio.run(enqueue_video_jobs(pid)) + except ValueError as exc: + assert "no video input" in str(exc) + assert "(Input:video)" in str(exc) + else: + raise AssertionError("expected ValueError for workflow without video role") + + # Supersede + video_path clear happened for scene 1 before the failure on + # scene 2; the failing scene must not have produced a job. + assert len(_job_payloads(pid)) == 1 + + +def test_continue_scene_uses_previous_clip_path(client): + pid = _mk_project(client, "Prev Clip") + _add_scene(client, pid, 1) + scene2 = _add_scene(client, pid, 2) + _set_chain(client, pid, scene2["id"], True) + clip = _touch_clip("prev-clip.mp4") + conn = get_db(settings.db_path) + try: + wid = _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + conn.execute( + "UPDATE scenes SET video_path = ? WHERE order_index = 1 AND project_id = ?", + (clip, pid), + ) + conn.commit() + finally: + conn.close() + + # Re-generate only the continue scene: scene 1 is not in the batch, so its + # clip stays on disk and is injected directly (no worker deferral needed). + jobs = asyncio.run(enqueue_video_jobs(pid, scene_ids=[scene2["id"]])) + payloads = _job_payloads(pid) + assert len(payloads) == 1 + + video_values = payloads[0]["input_values"] + # Node 20 (Input:video) holds the previous scene's local clip path. + assert video_values["20"] == clip + assert "continue_source" not in payloads[0] + assert jobs[0]["workflow_id"] == wid + + +def test_continue_scene_defers_to_worker_without_clip(client): + pid = _mk_project(client, "Deferred Clip") + _add_scene(client, pid, 1) + scene2 = _add_scene(client, pid, 2) + _set_chain(client, pid, scene2["id"], True) + conn = get_db(settings.db_path) + try: + _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + finally: + conn.close() + + jobs = asyncio.run(enqueue_video_jobs(pid)) + payloads = _job_payloads(pid) + assert len(payloads) == 2 + assert payloads[1]["continue_source"] == {"scene_order_index": 2} + assert "20" not in payloads[1]["input_values"] + assert jobs[1]["scene_id"] == scene2["id"] + + +def test_continue_scene_on_first_scene_raises(client): + pid = _mk_project(client, "First Scene") + scene1 = _add_scene(client, pid, 1) + _set_chain(client, pid, scene1["id"], True) + conn = get_db(settings.db_path) + try: + _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + finally: + conn.close() + + try: + asyncio.run(enqueue_video_jobs(pid)) + except ValueError as exc: + assert "no previous clip exists yet" in str(exc) + else: + raise AssertionError("expected ValueError for continue on first scene") + + # Nothing was enqueued for the failing scene. + assert _job_payloads(pid) == [] + + +def test_continue_scene_explicit_value_wins_over_previous(client): + pid = _mk_project(client, "Explicit Clip") + _add_scene(client, pid, 1) + scene2 = _add_scene(client, pid, 2) + _set_chain(client, pid, scene2["id"], True) + conn = get_db(settings.db_path) + try: + wid = _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + finally: + conn.close() + explicit_clip = _touch_clip("user-upload.mp4") + + jobs = asyncio.run(enqueue_video_jobs(pid, input_values_override={"20": explicit_clip})) + payloads = _job_payloads(pid) + assert len(payloads) == 2 + assert payloads[1]["input_values"]["20"] == explicit_clip + assert "continue_source" not in payloads[1] + assert jobs[1]["workflow_id"] == wid + + +def test_non_continue_scene_untouched(client): + pid = _mk_project(client, "Plain Scenes") + _add_scene(client, pid, 1) + _add_scene(client, pid, 2) + conn = get_db(settings.db_path) + try: + _insert_workflow(conn, "video-wf", VIDEO_WORKFLOW) + finally: + conn.close() + + asyncio.run(enqueue_video_jobs(pid)) + payloads = _job_payloads(pid) + assert len(payloads) == 2 + for payload in payloads: + assert "continue_source" not in payload + assert "chain_from_prev" not in payload + assert "scene_order_index" not in payload + assert "chain_replace_value" not in payload + assert "20" not in payload["input_values"]