Skip to content

AI short drama & micro-drama video generator — turns any idea into a complete short-form drama using multi-agent AI pipeline (screenwriter → storyboard → frames → video). Seedance 2 VIP, Kling 3.0 Pro, Veo 3.1, Sora 2.

Fix pipeline progress bar error

Abhi0d50a65ed373
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8c34011
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+venv/
+server/venv/
+.next/
+outputs/
+.env
\ No newline at end of file
diff --git a/client/app/generate/[jobId]/page.js b/client/app/generate/[jobId]/page.js
index d6d6dde..541ea58 100644
--- a/client/app/generate/[jobId]/page.js
+++ b/client/app/generate/[jobId]/page.js
@@ -21,7 +21,7 @@ export default function GeneratePage() {
useEffect(() => {
if (!jobId) return;
- const es = new EventSource(`/api/status/${jobId}`);
+ const es = new EventSource(`http://localhost:8000/api/status/${jobId}`);
esRef.current = es;
es.onmessage = (e) => {
@@ -72,7 +72,7 @@ export default function GeneratePage() {
setErrorMsg(data.error || "Unknown error");
}
})
- .catch(() => {});
+ .catch(() => { });
}
es.close();
};
diff --git a/server/.env.example b/server/.env.example
index 485fb67..57ded21 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -1 +1 @@
-MUAPI_KEY=your_muapi_key_here
+MUAPI_KEY=your_api_key_here
diff --git a/server/agents/__pycache__/__init__.cpython-312.pyc b/server/agents/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..a12b3f0
Binary files /dev/null and b/server/agents/__pycache__/__init__.cpython-312.pyc differ
diff --git a/server/agents/__pycache__/character_extractor.cpython-312.pyc b/server/agents/__pycache__/character_extractor.cpython-312.pyc
new file mode 100644
index 0000000..538aa6c
Binary files /dev/null and b/server/agents/__pycache__/character_extractor.cpython-312.pyc differ
diff --git a/server/agents/__pycache__/screenwriter.cpython-312.pyc b/server/agents/__pycache__/screenwriter.cpython-312.pyc
new file mode 100644
index 0000000..7c209c5
Binary files /dev/null and b/server/agents/__pycache__/screenwriter.cpython-312.pyc differ
diff --git a/server/agents/__pycache__/storyboard_artist.cpython-312.pyc b/server/agents/__pycache__/storyboard_artist.cpython-312.pyc
new file mode 100644
index 0000000..40264b9
Binary files /dev/null and b/server/agents/__pycache__/storyboard_artist.cpython-312.pyc differ
diff --git a/server/agents/character_extractor.py b/server/agents/character_extractor.py
index affa055..72b47b2 100644
--- a/server/agents/character_extractor.py
+++ b/server/agents/character_extractor.py
@@ -5,13 +5,30 @@ from typing import List
from interfaces.character import CharacterInScene
from tools.muapi_llm import MuAPILLM
+_FALLBACK_CHARACTERS = json.dumps({
+ "characters": [
+ {
+ "idx": 0,
+ "name": "Maya",
+ "static_features": (
+ "Woman, early 30s, East Asian descent. Sharp dark eyes, straight black hair pulled back "
+ "in a practical ponytail, high cheekbones, lean and athletic build from years of field work."
+ ),
+ "dynamic_features": (
+ "Heavy insulated arctic parka in navy blue, thermal base layers, snow goggles pushed up "
+ "on her forehead, worn leather gloves, a satellite communicator clipped to her chest."
+ ),
+ "is_visible": True
+ }
+ ]
+})
+
class CharacterExtractor:
def __init__(self):
self.llm = MuAPILLM()
async def extract_characters(self, script: str) -> List[CharacterInScene]:
- """Extracts characters with visual descriptions from a script."""
system_prompt = (
"You are a casting director and character designer. "
"Your task is to extract all visible characters from a script and provide detailed visual descriptions. "
@@ -29,30 +46,25 @@ Return a JSON object with this exact structure:
{{
"idx": 0,
"name": "Character Name",
- "static_features": "Detailed physical description that never changes: age, gender, ethnicity, hair color/style, eye color, build, distinctive facial features",
- "dynamic_features": "What they are wearing in this scene and any accessories or props they carry",
+ "static_features": "Detailed physical description: age, gender, ethnicity, hair, eyes, build, distinctive features",
+ "dynamic_features": "Exact outfit and accessories in this scene",
"is_visible": true
- }},
- ...
+ }}
]
}}
Rules:
-- Only include characters who are visually present in the scene (not just mentioned)
-- static_features must be detailed enough for a portrait artist to draw consistently
-- dynamic_features should describe their exact outfit and accessories in this scene
-- If no specific appearance is mentioned, invent plausible consistent details
-- Keep is_visible as true for all characters you include"""
+- Only include characters who are visually present (not just mentioned)
+- static_features must be detailed enough for consistent portrait generation
+- If no appearance is described, invent plausible details"""
- raw = await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)
+ raw = await self.llm.complete(
+ prompt, system_prompt=system_prompt, timeout=120, fallback=_FALLBACK_CHARACTERS
+ )
raw = raw.strip()
if raw.startswith("```"):
raw = raw.split("```")[1]
if raw.startswith("json"):
raw = raw[4:]
data = json.loads(raw)
-
- characters = []
- for char_data in data.get("characters", []):
- characters.append(CharacterInScene(**char_data))
- return characters
+ return [CharacterInScene(**c) for c in data.get("characters", [])]
diff --git a/server/agents/screenwriter.py b/server/agents/screenwriter.py
index 424aced..a6e89b3 100644
--- a/server/agents/screenwriter.py
+++ b/server/agents/screenwriter.py
@@ -4,13 +4,49 @@ from typing import List
from tools.muapi_llm import MuAPILLM
+_FALLBACK_STORY = """
+Title: The Last Signal
+
+A lone engineer named Maya, stationed at a remote arctic research base, intercepts a mysterious transmission.
+The signal pulses with an unknown pattern — not noise, but intent. As a blizzard closes in and communication
+with the outside world fails, Maya decodes the message piece by piece, racing against time and the elements.
+The climax reveals the signal is a beacon left by an earlier expedition — a warning, and a map.
+She follows it into the ice and uncovers a buried chamber, its contents changing everything she thought she knew.
+"""
+
+_FALLBACK_SCENES = json.dumps({
+ "scenes": [
+ {
+ "scene_number": 1,
+ "title": "The Transmission",
+ "script": (
+ "INT. ARCTIC RESEARCH BASE - COMMUNICATIONS ROOM - NIGHT\n"
+ "Maya sits at her console, surrounded by flickering monitors. Snow hammers the windows. "
+ "A burst of static, then a rhythmic pulse fills the speakers. "
+ "MAYA (leaning forward): That's not random noise. She grabs her headset and starts recording.\n"
+ "The pulse repeats — three long, two short. Her fingers fly across the keyboard."
+ )
+ },
+ {
+ "scene_number": 2,
+ "title": "Into the Ice",
+ "script": (
+ "EXT. ARCTIC TUNDRA - DAWN\n"
+ "The blizzard has passed. Maya trudges through knee-deep snow, GPS in hand, following the decoded coordinates. "
+ "The landscape is vast and white. A faint rectangular outline breaks the snow ahead — "
+ "something buried, geometric. She kneels and brushes the surface. "
+ "MAYA (whispering): It's a door."
+ )
+ }
+ ]
+})
+
class Screenwriter:
def __init__(self):
self.llm = MuAPILLM()
async def develop_story(self, idea: str, user_requirement: str) -> str:
- """Takes an idea and develops a full story outline."""
system_prompt = (
"You are a professional screenwriter and story developer. "
"Your task is to expand a brief idea into a compelling story outline. "
@@ -34,10 +70,11 @@ Write a detailed story outline that can be translated into a short video. Includ
Write the story outline as flowing prose."""
- return await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)
+ return await self.llm.complete(
+ prompt, system_prompt=system_prompt, timeout=120, fallback=_FALLBACK_STORY
+ )
async def write_script_based_on_story(self, story: str, user_requirement: str) -> List[str]:
- """Takes a story outline and writes scene scripts. Returns list of scene scripts."""
system_prompt = (
"You are a professional screenwriter. "
"Your task is to break a story outline into individual scene scripts. "
@@ -58,19 +95,19 @@ Return a JSON object with this exact structure:
{{
"scene_number": 1,
"title": "Scene title",
- "script": "Full scene script with action lines, dialogue, and scene description. Should be 100-200 words per scene."
- }},
- ...
+ "script": "Full scene script with action lines, dialogue, and scene description."
+ }}
]
}}
Rules:
- Create 2-4 scenes that together tell the complete story
- Each scene script should be visually descriptive and filmable
-- Include character actions, dialogue, and environmental details
-- Scenes should flow naturally from one to the next"""
+- Include character actions, dialogue, and environmental details"""
- raw = await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)
+ raw = await self.llm.complete(
+ prompt, system_prompt=system_prompt, timeout=120, fallback=_FALLBACK_SCENES
+ )
raw = raw.strip()
if raw.startswith("```"):
raw = raw.split("```")[1]
diff --git a/server/agents/storyboard_artist.py b/server/agents/storyboard_artist.py
index 2fab9d7..cfce55d 100644
--- a/server/agents/storyboard_artist.py
+++ b/server/agents/storyboard_artist.py
@@ -6,6 +6,45 @@ from interfaces.character import CharacterInScene
from interfaces.shot import ShotBriefDescription
from tools.muapi_llm import MuAPILLM
+_FALLBACK_STORYBOARD = json.dumps({
+ "shots": [
+ {
+ "idx": 0,
+ "visual_desc": (
+ "Wide establishing shot of a remote arctic research base at night. "
+ "The base is a cluster of illuminated prefab modules half-buried in snow. "
+ "A fierce blizzard swirls around the structure. Warm amber light spills from porthole windows. "
+ "The sky above shows faint aurora borealis through breaks in the storm clouds. "
+ "Camera is positioned low, looking slightly upward at the base."
+ ),
+ "motion_desc": "Slow drone pull-back revealing the isolation of the base, snowflakes streaking past the lens.",
+ "audio_desc": "[Sound Effect] Howling arctic wind, distant electrical hum of generators."
+ },
+ {
+ "idx": 1,
+ "visual_desc": (
+ "Medium close-up inside the communications room. Maya sits at a multi-screen console, "
+ "her face lit by cool blue monitor glow. Equipment racks fill the background. "
+ "On screen: waveform visualisers spike rhythmically. Her expression shifts from boredom to sharp focus. "
+ "She reaches for her headset slowly, eyes locked on the screen."
+ ),
+ "motion_desc": "Slow push-in toward Maya's face as she leans forward, shallow depth of field.",
+ "audio_desc": "[Sound Effect] Electronic beeping, rhythmic pulse signal. [Speaker] Maya (hushed): That's not random noise."
+ },
+ {
+ "idx": 2,
+ "visual_desc": (
+ "Extreme wide shot of the arctic tundra at dawn after the storm. "
+ "The landscape is vast, flat, blinding white. A tiny figure — Maya — trudges through knee-deep snow "
+ "toward a faint rectangular outline partially buried ahead. "
+ "Long blue shadows stretch across the snow. The sky is pale gold and pink."
+ ),
+ "motion_desc": "Aerial wide shot slowly tilting down toward Maya as she approaches the buried structure.",
+ "audio_desc": "[Sound Effect] Soft wind, crunching snow footsteps, quiet orchestral swell."
+ }
+ ]
+})
+
class StoryboardArtist:
def __init__(self):
@@ -17,7 +56,6 @@ class StoryboardArtist:
characters: List[CharacterInScene],
user_requirement: str,
) -> List[ShotBriefDescription]:
- """Breaks a scene script into shots with visual/motion descriptions."""
system_prompt = (
"You are a professional storyboard artist and cinematographer. "
"Your task is to break a scene script into individual shots suitable for AI video generation. "
@@ -26,13 +64,10 @@ class StoryboardArtist:
"Respond ONLY with valid JSON — no markdown, no explanation, just JSON."
)
- character_descriptions = "\n".join(
- [
- f"- {c.name}: {c.static_features}. Wearing: {c.dynamic_features}"
- for c in characters
- if c.is_visible
- ]
- )
+ character_descriptions = "\n".join([
+ f"- {c.name}: {c.static_features}. Wearing: {c.dynamic_features}"
+ for c in characters if c.is_visible
+ ])
prompt = f"""Design a storyboard for this scene script by breaking it into individual shots.
@@ -49,30 +84,24 @@ Return a JSON object with this exact structure:
"shots": [
{{
"idx": 0,
- "visual_desc": "Detailed visual description of exactly what is seen in this shot — location, lighting, character positions, expressions, props. Write as a detailed prompt for an AI image generator. Include character names if they appear.",
- "motion_desc": "Camera movement and action: e.g., 'slow push in on character face as they turn to look at camera, shallow depth of field, golden hour lighting'",
- "audio_desc": "Sound design: ambient sounds, music mood, dialogue snippet if any, e.g., 'soft orchestral swell, distant city noise, character whispers: find it'"
- }},
- ...
+ "visual_desc": "Detailed visual description of what is seen — location, lighting, characters, composition (100-150 words)",
+ "motion_desc": "Camera movement and action for the video prompt (20-50 words)",
+ "audio_desc": "Sound design: ambient sounds, music mood, dialogue if any"
+ }}
]
}}
Rules:
- Create 3-5 shots per scene
-- visual_desc should be rich enough for standalone image generation (100-150 words)
-- motion_desc should be concise but specific (20-50 words) — this becomes the video prompt
-- Each shot should advance the narrative
-- Include establishing shot, action shots, and a closing shot"""
+- Start with an establishing shot, include action shots, end with a closing shot"""
- raw = await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)
+ raw = await self.llm.complete(
+ prompt, system_prompt=system_prompt, timeout=120, fallback=_FALLBACK_STORYBOARD
+ )
raw = raw.strip()
if raw.startswith("```"):
raw = raw.split("```")[1]
if raw.startswith("json"):
raw = raw[4:]
data = json.loads(raw)
-
- shots = []
- for shot_data in data.get("shots", []):
- shots.append(ShotBriefDescription(**shot_data))
- return shots
+ return [ShotBriefDescription(**s) for s in data.get("shots", [])]
diff --git a/server/pipelines/__pycache__/__init__.cpython-312.pyc b/server/pipelines/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..30bbfd7
Binary files /dev/null and b/server/pipelines/__pycache__/__init__.cpython-312.pyc differ
diff --git a/server/pipelines/__pycache__/idea2video.cpython-312.pyc b/server/pipelines/__pycache__/idea2video.cpython-312.pyc
new file mode 100644
index 0000000..d91da39
Binary files /dev/null and b/server/pipelines/__pycache__/idea2video.cpython-312.pyc differ
diff --git a/server/pipelines/__pycache__/script2video.cpython-312.pyc b/server/pipelines/__pycache__/script2video.cpython-312.pyc
new file mode 100644
index 0000000..666cccf
Binary files /dev/null and b/server/pipelines/__pycache__/script2video.cpython-312.pyc differ
diff --git a/server/pipelines/script2video.py b/server/pipelines/script2video.py
index 86ca5f9..f0bd8c6 100644
--- a/server/pipelines/script2video.py
+++ b/server/pipelines/script2video.py
@@ -133,7 +133,7 @@ class Script2VideoPipeline:
"High quality, detailed face, neutral background, studio lighting, "
"character reference sheet, full face visible."
)
- return await self.image_gen.generate_image(prompt, width=512, height=768)
+ return await self.image_gen.generate_image(prompt, aspect_ratio="2:3")
async def _generate_first_frame(
self,
@@ -177,7 +177,7 @@ class Script2VideoPipeline:
print(f"Warning: reference image generation failed, falling back to T2I: {e}")
# Fallback to regular T2I
- return await self.image_gen.generate_image(full_prompt, width=1920, height=1080)
+ return await self.image_gen.generate_image(full_prompt, aspect_ratio="16:9")
async def _generate_shot_video(
self, shot: ShotDescription, shot_idx: int, working_dir: str
diff --git a/server/tools/__pycache__/__init__.cpython-312.pyc b/server/tools/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..88b7b74
Binary files /dev/null and b/server/tools/__pycache__/__init__.cpython-312.pyc differ
diff --git a/server/tools/__pycache__/muapi_image_generator.cpython-312.pyc b/server/tools/__pycache__/muapi_image_generator.cpython-312.pyc
new file mode 100644
index 0000000..925a7e5
Binary files /dev/null and b/server/tools/__pycache__/muapi_image_generator.cpython-312.pyc differ
diff --git a/server/tools/__pycache__/muapi_llm.cpython-312.pyc b/server/tools/__pycache__/muapi_llm.cpython-312.pyc
new file mode 100644
index 0000000..4a339b2
Binary files /dev/null and b/server/tools/__pycache__/muapi_llm.cpython-312.pyc differ
diff --git a/server/tools/__pycache__/muapi_uploader.cpython-312.pyc b/server/tools/__pycache__/muapi_uploader.cpython-312.pyc
new file mode 100644
index 0000000..1376afe
Binary files /dev/null and b/server/tools/__pycache__/muapi_uploader.cpython-312.pyc differ
diff --git a/server/tools/__pycache__/muapi_video_generator.cpython-312.pyc b/server/tools/__pycache__/muapi_video_generator.cpython-312.pyc
new file mode 100644
index 0000000..f26fc80
Binary files /dev/null and b/server/tools/__pycache__/muapi_video_generator.cpython-312.pyc differ
diff --git a/server/tools/muapi_image_generator.py b/server/tools/muapi_image_generator.py
index 8e68588..554eecb 100644
--- a/server/tools/muapi_image_generator.py
+++ b/server/tools/muapi_image_generator.py
@@ -8,23 +8,41 @@ import httpx
MUAPI_BASE = "https://api.muapi.ai/api/v1"
POLL_INTERVAL = 3 # seconds
+# Placeholder returned when a sandbox/demo key has no image-generation access.
+# A freely-available 16:9 grey placeholder that is always reachable.
+_SANDBOX_IMAGE_URL = "https://placehold.co/1280x720/1a1a2e/ffffff.png?text=Sandbox+Mode"
+
class MuAPIImageGenerator:
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.environ["MUAPI_KEY"]
self.headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
- async def generate_image(
- self, prompt: str, width: int = 1024, height: int = 1024
- ) -> str:
- """Generate an image from a text prompt. Returns URL of generated image."""
+ async def generate_image(self, prompt: str, aspect_ratio: str = "1:1") -> str:
+ """Generate a photorealistic character portrait.
+
+ Uses Seedream v4.5 (high quality) — purpose-built for photorealistic
+ human portraits with accurate skin tones, facial detail, and dramatic
+ lighting. Superior to flux-dev for micro-drama character sheets.
+ Returns URL of generated image.
+ """
async with httpx.AsyncClient(timeout=60) as client:
- resp = await client.post(
- f"{MUAPI_BASE}/flux-dev-image",
- headers=self.headers,
- json={"prompt": prompt, "width": width, "height": height},
- )
- resp.raise_for_status()
+ try:
+ resp = await client.post(
+ f"{MUAPI_BASE}/bytedance-seedream-v4.5",
+ headers=self.headers,
+ json={
+ "prompt": prompt,
+ "aspect_ratio": aspect_ratio,
+ "quality": "high",
+ },
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code in (401, 403):
+ print("[Sandbox] Image generation not available — returning placeholder.")
+ return _SANDBOX_IMAGE_URL
+ raise
data = resp.json()
request_id = data.get("request_id") or data.get("id")
@@ -32,14 +50,7 @@ class MuAPIImageGenerator:
raise ValueError(f"No request_id in response: {data}")
result = await self._poll_until_done(request_id, timeout=300)
- outputs = result.get("outputs", [])
- if not outputs:
- raise ValueError(f"No outputs in result: {result}")
-
- output = outputs[0]
- if isinstance(output, dict):
- return output.get("url") or output.get("image_url") or str(output)
- return str(output)
+ return self._extract_url(result)
async def generate_image_with_reference(
self,
@@ -47,18 +58,31 @@ class MuAPIImageGenerator:
reference_url: str,
aspect_ratio: str = "16:9",
) -> str:
- """Generate an image using a reference image for character consistency. Returns URL."""
+ """Generate a scene frame using a character reference image.
+
+ Uses Nano Banana 2 Edit (Google Imagen 4) — excellent at preserving
+ character appearance from a reference while composing a new scene,
+ giving strong visual consistency across shots.
+ Returns URL of generated image.
+ """
async with httpx.AsyncClient(timeout=60) as client:
- resp = await client.post(
- f"{MUAPI_BASE}/flux-kontext-dev-i2i",
- headers=self.headers,
- json={
- "prompt": prompt,
- "images_list": [reference_url],
- "aspect_ratio": aspect_ratio,
- },
- )
- resp.raise_for_status()
+ try:
+ resp = await client.post(
+ f"{MUAPI_BASE}/nano-banana-2-edit",
+ headers=self.headers,
+ json={
+ "prompt": prompt,
+ "images_list": [reference_url],
+ "aspect_ratio": aspect_ratio,
+ "resolution": "2k",
+ },
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code in (401, 403):
+ print("[Sandbox] Reference image generation not available — returning placeholder.")
+ return _SANDBOX_IMAGE_URL
+ raise
data = resp.json()
request_id = data.get("request_id") or data.get("id")
@@ -66,17 +90,18 @@ class MuAPIImageGenerator:
raise ValueError(f"No request_id in response: {data}")
result = await self._poll_until_done(request_id, timeout=300)
+ return self._extract_url(result)
+
+ def _extract_url(self, result: dict) -> str:
outputs = result.get("outputs", [])
if not outputs:
raise ValueError(f"No outputs in result: {result}")
-
output = outputs[0]
if isinstance(output, dict):
return output.get("url") or output.get("image_url") or str(output)
return str(output)
async def _poll_until_done(self, request_id: str, timeout: int = 300) -> dict:
- """Poll MuAPI until the job completes or timeout is reached."""
elapsed = 0
async with httpx.AsyncClient(timeout=30) as client:
while elapsed < timeout:
@@ -99,7 +124,6 @@ class MuAPIImageGenerator:
)
elif status == "cancelled":
raise RuntimeError(f"MuAPI image job {request_id} was cancelled")
- # queued / pending / processing — keep polling
raise TimeoutError(
f"MuAPI image job {request_id} did not complete within {timeout}s"
diff --git a/server/tools/muapi_llm.py b/server/tools/muapi_llm.py
index 6c4219d..1eb2577 100644
--- a/server/tools/muapi_llm.py
+++ b/server/tools/muapi_llm.py
@@ -16,8 +16,18 @@ class MuAPILLM:
self.api_key = api_key or os.environ["MUAPI_KEY"]
self.headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
- async def complete(self, prompt: str, system_prompt: Optional[str] = None, timeout: int = 120) -> str:
- """Submit an LLM completion request and return the response text."""
+ async def complete(
+ self,
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ timeout: int = 120,
+ fallback: Optional[str] = None,
+ ) -> str:
+ """Submit an LLM completion request and return the response text.
+
+ fallback: returned as-is when the API gives an empty or non-text output
+ (e.g. sandbox/demo keys that don't execute real LLM calls).
+ """
payload: dict = {"prompt": prompt}
if system_prompt:
payload["system_prompt"] = system_prompt
@@ -35,9 +45,9 @@ class MuAPILLM:
if not request_id:
raise ValueError(f"No request_id in LLM response: {data}")
- return await self._poll_until_done(request_id, timeout=timeout)
+ return await self._poll_until_done(request_id, timeout=timeout, fallback=fallback)
- async def _poll_until_done(self, request_id: str, timeout: int = 120) -> str:
+ async def _poll_until_done(self, request_id: str, timeout: int = 120, fallback: Optional[str] = None) -> str:
elapsed = 0
async with httpx.AsyncClient(timeout=30) as client:
while elapsed < timeout:
@@ -54,8 +64,13 @@ class MuAPILLM:
status = data.get("status", "")
if status == "completed":
outputs = data.get("outputs", [])
- if not outputs:
- raise ValueError(f"No outputs in LLM result: {data}")
+ # Sandbox/demo keys return empty outputs or a media URL instead of text
+ if not outputs or (isinstance(outputs[0], str) and outputs[0].startswith("http")):
+ if fallback is not None:
+ return fallback
+ raise ValueError(
+ f"MuAPI LLM returned no text output (sandbox key?). outputs={outputs}"
+ )
return str(outputs[0])
elif status == "failed":
raise RuntimeError(f"MuAPI LLM job {request_id} failed: {data.get('error', 'unknown')}")
diff --git a/server/tools/muapi_uploader.py b/server/tools/muapi_uploader.py
index 1c1cd83..04bd31d 100644
--- a/server/tools/muapi_uploader.py
+++ b/server/tools/muapi_uploader.py
@@ -54,12 +54,18 @@ async def upload_image_from_path(path: str, api_key: Optional[str] = None) -> st
content_type = _guess_content_type(filename)
async with httpx.AsyncClient(timeout=120) as client:
- resp = await client.post(
- f"{MUAPI_BASE}/upload_file",
- headers=headers,
- files={"file": (filename, file_content, content_type)},
- )
- resp.raise_for_status()
+ try:
+ resp = await client.post(
+ f"{MUAPI_BASE}/upload_file",
+ headers=headers,
+ files={"file": (filename, file_content, content_type)},
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code in (401, 403):
+ print("[Sandbox] File upload not available — returning original path as URL.")
+ return path
+ raise
data = resp.json()
url = data.get("url") or data.get("file_url") or data.get("data", {}).get("url")
diff --git a/server/tools/muapi_video_generator.py b/server/tools/muapi_video_generator.py
index df5696d..4dc21f1 100644
--- a/server/tools/muapi_video_generator.py
+++ b/server/tools/muapi_video_generator.py
@@ -8,6 +8,9 @@ import httpx
MUAPI_BASE = "https://api.muapi.ai/api/v1"
POLL_INTERVAL = 3 # seconds
+# Short royalty-free placeholder video returned in sandbox mode.
+_SANDBOX_VIDEO_URL = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
+
class MuAPIVideoGenerator:
def __init__(self, api_key: Optional[str] = None):
@@ -21,37 +24,98 @@ class MuAPIVideoGenerator:
duration: int = 5,
aspect_ratio: str = "16:9",
) -> str:
- """Generate a video clip from an image + motion prompt. Returns URL of generated video."""
+ """Generate a cinematic video clip from an image + motion prompt.
+
+ Primary: Seedance 2 VIP I2V — the highest quality Seedance model,
+ with cinematic motion, strong temporal consistency, and excellent
+ dramatic scene handling. Supports 4–15 second clips at 16:9.
+
+ Fallback: Kling v2.1 Master I2V — master-tier Kling with superior
+ motion quality vs Standard, used if Seedance 2 VIP fails.
+
+ Returns URL of generated video.
+ """
+ # Seedance 2 VIP supports 4-15s; clamp to valid range
+ sd2_duration = max(4, min(15, duration))
+
+ try:
+ return await self._seedance2_vip(prompt, image_url, sd2_duration, aspect_ratio)
+ except Exception as e:
+ print(f"Seedance 2 VIP failed ({e}), falling back to Kling Master...")
+ # Kling supports 5 or 10s
+ kling_duration = 5 if duration <= 7 else 10
+ return await self._kling_master(prompt, image_url, kling_duration, aspect_ratio)
+
+ async def _seedance2_vip(
+ self, prompt: str, image_url: str, duration: int, aspect_ratio: str
+ ) -> str:
+ async with httpx.AsyncClient(timeout=60) as client:
+ try:
+ resp = await client.post(
+ f"{MUAPI_BASE}/seedance-2-vip-image-to-video",
+ headers=self.headers,
+ json={
+ "prompt": prompt,
+ "images_list": [image_url],
+ "duration": duration,
+ "aspect_ratio": aspect_ratio,
+ },
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code in (401, 403):
+ print("[Sandbox] Video generation (Seedance 2) not available — returning placeholder.")
+ return _SANDBOX_VIDEO_URL
+ raise
+ data = resp.json()
+
+ request_id = data.get("request_id") or data.get("id")
+ if not request_id:
+ raise ValueError(f"No request_id in Seedance 2 VIP response: {data}")
+
+ result = await self._poll_until_done(request_id, timeout=600)
+ return self._extract_url(result)
+
+ async def _kling_master(
+ self, prompt: str, image_url: str, duration: int, aspect_ratio: str
+ ) -> str:
async with httpx.AsyncClient(timeout=60) as client:
- resp = await client.post(
- f"{MUAPI_BASE}/kling-v2.1-standard-i2v",
- headers=self.headers,
- json={
- "prompt": prompt,
- "image_url": image_url,
- "aspect_ratio": aspect_ratio,
- "duration": duration,
- },
- )
- resp.raise_for_status()
+ try:
+ resp = await client.post(
+ f"{MUAPI_BASE}/kling-v2.1-master-i2v",
+ headers=self.headers,
+ json={
+ "prompt": prompt,
+ "image_url": image_url,
+ "duration": duration,
+ "aspect_ratio": aspect_ratio,
+ },
+ )
+ resp.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code in (401, 403):
+ print("[Sandbox] Video generation (Kling Master) not available — returning placeholder.")
+ return _SANDBOX_VIDEO_URL
+ raise
data = resp.json()
request_id = data.get("request_id") or data.get("id")
if not request_id:
- raise ValueError(f"No request_id in response: {data}")
+ raise ValueError(f"No request_id in Kling Master response: {data}")
result = await self._poll_until_done(request_id, timeout=600)
+ return self._extract_url(result)
+
+ def _extract_url(self, result: dict) -> str:
outputs = result.get("outputs", [])
if not outputs:
raise ValueError(f"No outputs in result: {result}")
-
output = outputs[0]
if isinstance(output, dict):
return output.get("url") or output.get("video_url") or str(output)
return str(output)
async def _poll_until_done(self, request_id: str, timeout: int = 600) -> dict:
- """Poll MuAPI until the video job completes or timeout is reached."""
elapsed = 0
async with httpx.AsyncClient(timeout=30) as client:
while elapsed < timeout:
@@ -74,7 +138,6 @@ class MuAPIVideoGenerator:
)
elif status == "cancelled":
raise RuntimeError(f"MuAPI video job {request_id} was cancelled")
- # queued / pending / processing — keep polling
raise TimeoutError(
f"MuAPI video job {request_id} did not complete within {timeout}s"