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.
Python agentic-aiai-dramaai-filmmakingai-short-dramaai-video-generationdrama-generatorfastapigenerative-aiimage-to-videokling-aimicro-dramamulti-agentnextjsseedanceseedance2short-dramashort-filmshort-form-videotext-to-videoveo3
Initial commit: Open AI Micro Drama Generator
Anil Matchaed5b449b7eb6
diff --git a/README.md b/README.mdnew file mode 100644index 0000000..4b1f9d4--- /dev/null+++ b/README.md@@ -0,0 +1,167 @@+# ViGen — Agentic AI Video Generation++ViGen is a multi-agent video generation web app. You provide an idea or script; a coordinated pipeline of AI agents writes the story, designs the storyboard, generates frames, and produces a complete cinematic video — automatically, powered entirely by [MuAPI](https://muapi.ai).++---++## Architecture++```+Idea / Script+ │+ ▼+┌─────────────────────────────────────────────────────────┐+│ FastAPI Server │+│ │+│ ┌─────────────────┐ ┌──────────────────────────┐ │+│ │ Screenwriter │ ──► │ Scene scripts (2-4) │ │+│ │ (Claude) │ └──────────────────────────┘ │+│ └─────────────────┘ │ │+│ ▼ │+│ ┌─────────────────┐ ┌──────────────────────────┐ │+│ │ CharacterExtra- │ ──► │ Character descriptions │ │+│ │ ctor (Claude) │ └──────────────────────────┘ │+│ └─────────────────┘ │ │+│ ▼ │+│ ┌─────────────────┐ ┌──────────────────────────┐ │+│ │ Storyboard │ ──► │ Shots (3-5 per scene) │ │+│ │ Artist (Claude) │ └──────────────────────────┘ │+│ └─────────────────┘ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────┐ │+│ │ MuAPI Tools │ │+│ │ • Portrait Generator (flux-dev T2I) │ │+│ │ • Frame Generator (flux-kontext I2I or T2I) │ │+│ │ • Video Generator (kling-v2.1 I2V) │ │+│ └────────────────────────────────────────────────────┘ │+│ │ │+│ ┌─────────────────┐ ▼ │+│ │ Concatenator │ ◄── Clips per shot / scene │+│ │ (moviepy) │ │+│ └─────────────────┘ │ │+│ ▼ │+│ final_video.mp4 │+└─────────────────────────────────────────────────────────┘+```++### Pipeline stages++| Stage | Agent/Tool | What it does |+|-------|-----------|--------------|+| Story | Screenwriter (Claude) | Expands idea into a story outline |+| Characters | Character Extractor (Claude) | Pulls characters + visual descriptions |+| Scene scripts | Screenwriter (Claude) | Writes 2-4 individual scene scripts |+| Portraits | MuAPI flux-dev T2I | Reference portrait image per character |+| Storyboard | Storyboard Artist (Claude) | 3-5 shots per scene with visual/motion/audio |+| Frames | MuAPI flux-kontext I2I / flux-dev T2I | First frame per shot (with character consistency) |+| Video clips | MuAPI kling-v2.1 I2V | 5-second video per shot |+| Concat | moviepy | All clips joined into final video |++---++## Project structure++```+GPT-Actions/+├── server/+│ ├── api.py # FastAPI app (SSE progress, job tracking)+│ ├── requirements.txt+│ ├── .env.example+│ ├── agents/+│ │ ├── screenwriter.py # develop_story, write_script_based_on_story+│ │ ├── character_extractor.py+│ │ └── storyboard_artist.py+│ ├── interfaces/+│ │ ├── character.py # CharacterInScene pydantic model+│ │ └── shot.py # ShotBriefDescription, ShotDescription+│ ├── tools/+│ │ ├── muapi_image_generator.py # T2I + I2I via MuAPI+│ │ ├── muapi_video_generator.py # I2V via MuAPI+│ │ └── muapi_uploader.py # upload_file helper+│ ├── pipelines/+│ │ ├── idea2video.py # Full end-to-end pipeline+│ │ └── script2video.py # Scene-level pipeline+│ └── utils/+│ └── video.py # moviepy concatenation+└── client/+ ├── app/+ │ ├── layout.js+ │ ├── page.js # Landing + form+ │ └── generate/[jobId]/+ │ └── page.js # Progress + result+ └── components/+ ├── IdeaForm.js # Input form+ ├── PipelineProgress.js # SSE-driven progress UI+ └── VideoResult.js # Video player + download+```++---++## Setup++### Environment variables++Copy `.env.example` and fill in your keys:++```bash+cd server+cp .env.example .env+```++Required variables:+- `MUAPI_KEY` — your [MuAPI](https://muapi.ai) API key (used for all LLM, image, and video generation)++### Server++```bash+cd server+python -m venv venv+source venv/bin/activate # Windows: venv\Scripts\activate+pip install -r requirements.txt+uvicorn api:app --reload --port 8000+```++### Client++```bash+cd client+npm install+npm run dev+```++Open [http://localhost:3000](http://localhost:3000).++---++## Usage++1. Open the app in your browser.+2. Enter an idea (e.g. "A time-traveller arrives in Renaissance Florence").+3. Choose visual style (Cinematic, Anime, Fantasy, etc.).+4. Click **Generate Video**.+5. Watch the pipeline progress in real-time via the animated stage timeline.+6. Download or view your final video when it completes.++### Modes++- **Idea to Video** — Full agentic pipeline: the AI develops story, characters, scenes, storyboard, and video from scratch.+- **Script to Video** — Provide your own scene script; the pipeline handles storyboard, frames, and video generation.++---++## API endpoints++| Method | Path | Description |+|--------|------|-------------|+| POST | `/api/generate` | Start a generation job |+| GET | `/api/status/{job_id}` | SSE stream of progress events |+| GET | `/api/result/{job_id}` | Get final job result |+| GET | `/api/health` | Health check |++### SSE event format++```json+{"type": "progress", "stage": "screenwriter", "message": "Developing story...", "progress": 10}+{"type": "complete", "video_url": "/outputs/job_id/final_video.mp4", "progress": 100}+{"type": "error", "message": "...", "progress": -1}+```diff --git a/client/app/generate/[jobId]/page.js b/client/app/generate/[jobId]/page.jsnew file mode 100644index 0000000..d6d6dde--- /dev/null+++ b/client/app/generate/[jobId]/page.js@@ -0,0 +1,197 @@+"use client";++import { useParams } from "next/navigation";+import { useEffect, useState, useRef } from "react";+import PipelineProgress from "../../../components/PipelineProgress";+import VideoResult from "../../../components/VideoResult";+import { ArrowLeft } from "lucide-react";+import Link from "next/link";++export default function GeneratePage() {+ const { jobId } = useParams();+ const [events, setEvents] = useState([]);+ const [status, setStatus] = useState("running"); // running | completed | failed+ const [videoUrl, setVideoUrl] = useState(null);+ const [errorMsg, setErrorMsg] = useState(null);+ const [progress, setProgress] = useState(0);+ const [currentMessage, setCurrentMessage] = useState("Starting pipeline...");+ const [logs, setLogs] = useState([]);+ const esRef = useRef(null);++ useEffect(() => {+ if (!jobId) return;++ const es = new EventSource(`/api/status/${jobId}`);+ esRef.current = es;++ es.onmessage = (e) => {+ try {+ const event = JSON.parse(e.data);+ setEvents((prev) => [...prev, event]);+ setLogs((prev) => [+ ...prev,+ {+ time: new Date().toLocaleTimeString(),+ message: event.message || event.stage || "",+ type: event.type,+ },+ ]);++ if (event.type === "progress") {+ setProgress(event.progress || 0);+ setCurrentMessage(event.message || "");+ } else if (event.type === "complete") {+ setProgress(100);+ setStatus("completed");+ setVideoUrl(event.video_url);+ setCurrentMessage("Video generation complete!");+ es.close();+ } else if (event.type === "error") {+ setStatus("failed");+ setErrorMsg(event.message || "Generation failed");+ setCurrentMessage("Generation failed");+ es.close();+ }+ } catch (err) {+ console.error("Failed to parse SSE event:", err);+ }+ };++ es.onerror = () => {+ // If SSE drops after completion it's fine; otherwise check job result+ if (status !== "completed") {+ fetch(`/api/result/${jobId}`)+ .then((r) => r.json())+ .then((data) => {+ if (data.status === "completed") {+ setStatus("completed");+ setVideoUrl(data.video_url);+ setProgress(100);+ } else if (data.status === "failed") {+ setStatus("failed");+ setErrorMsg(data.error || "Unknown error");+ }+ })+ .catch(() => {});+ }+ es.close();+ };++ return () => {+ es.close();+ };+ }, [jobId]);++ return (+ <main+ className="min-h-screen"+ style={{ backgroundColor: "#0a0a0f" }}+ >+ {/* Top bar */}+ <div+ className="sticky top-0 z-10 px-6 py-4 flex items-center gap-4"+ style={{+ backgroundColor: "rgba(10, 10, 15, 0.9)",+ backdropFilter: "blur(12px)",+ borderBottom: "1px solid #1a1a26",+ }}+ >+ <Link+ href="/"+ className="flex items-center gap-2 text-sm transition-colors"+ style={{ color: "#6b7280" }}+ onMouseEnter={(e) => (e.currentTarget.style.color = "#a78bfa")}+ onMouseLeave={(e) => (e.currentTarget.style.color = "#6b7280")}+ >+ <ArrowLeft size={16} />+ New video+ </Link>+ <div+ className="h-4 w-px"+ style={{ backgroundColor: "#22223a" }}+ />+ <span className="text-sm" style={{ color: "#4b5563" }}>+ Job: <span style={{ color: "#7c3aed", fontFamily: "monospace" }}>{jobId}</span>+ </span>++ {/* Status badge */}+ <div className="ml-auto">+ {status === "running" && (+ <span+ className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium"+ style={{+ backgroundColor: "rgba(234, 179, 8, 0.15)",+ border: "1px solid rgba(234, 179, 8, 0.3)",+ color: "#fde047",+ }}+ >+ <span className="w-1.5 h-1.5 rounded-full bg-yellow-400 animate-pulse" />+ Generating+ </span>+ )}+ {status === "completed" && (+ <span+ className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium"+ style={{+ backgroundColor: "rgba(34, 197, 94, 0.15)",+ border: "1px solid rgba(34, 197, 94, 0.3)",+ color: "#86efac",+ }}+ >+ <span className="w-1.5 h-1.5 rounded-full bg-green-400" />+ Complete+ </span>+ )}+ {status === "failed" && (+ <span+ className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium"+ style={{+ backgroundColor: "rgba(239, 68, 68, 0.15)",+ border: "1px solid rgba(239, 68, 68, 0.3)",+ color: "#fca5a5",+ }}+ >+ <span className="w-1.5 h-1.5 rounded-full bg-red-400" />+ Failed+ </span>+ )}+ </div>+ </div>++ <div className="max-w-5xl mx-auto px-6 py-10">+ {/* Result */}+ {status === "completed" && videoUrl && (+ <div className="mb-10 animate-slide-up">+ <VideoResult videoUrl={videoUrl} jobId={jobId} />+ </div>+ )}++ {/* Error */}+ {status === "failed" && errorMsg && (+ <div+ className="mb-10 p-5 rounded-2xl animate-slide-up"+ style={{+ backgroundColor: "rgba(239, 68, 68, 0.08)",+ border: "1px solid rgba(239, 68, 68, 0.25)",+ }}+ >+ <p className="text-sm font-medium mb-1" style={{ color: "#fca5a5" }}>+ Generation Failed+ </p>+ <p className="text-sm" style={{ color: "#9ca3af" }}>+ {errorMsg}+ </p>+ </div>+ )}++ {/* Pipeline progress */}+ <PipelineProgress+ progress={progress}+ currentMessage={currentMessage}+ status={status}+ logs={logs}+ />+ </div>+ </main>+ );+}diff --git a/client/app/globals.css b/client/app/globals.cssnew file mode 100644index 0000000..9e80084--- /dev/null+++ b/client/app/globals.css@@ -0,0 +1,71 @@+@tailwind base;+@tailwind components;+@tailwind utilities;++:root {+ --background: #0a0a0f;+ --surface: #12121a;+}++* {+ box-sizing: border-box;+ padding: 0;+ margin: 0;+}++html,+body {+ max-width: 100vw;+ overflow-x: hidden;+ background-color: var(--background);+ color: #e2e8f0;+}++/* Custom scrollbar */+::-webkit-scrollbar {+ width: 6px;+}+::-webkit-scrollbar-track {+ background: #12121a;+}+::-webkit-scrollbar-thumb {+ background: #3b3b5c;+ border-radius: 3px;+}+::-webkit-scrollbar-thumb:hover {+ background: #7c3aed;+}++/* Gradient text utility */+.gradient-text {+ background: linear-gradient(135deg, #a78bfa 0%, #7c3aed 50%, #6d28d9 100%);+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ background-clip: text;+}++/* Glass card */+.glass {+ background: rgba(18, 18, 26, 0.8);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ border: 1px solid rgba(124, 58, 237, 0.15);+}++/* Animated border gradient */+.border-glow {+ position: relative;+}+.border-glow::before {+ content: "";+ position: absolute;+ inset: -1px;+ background: linear-gradient(135deg, #7c3aed, #a78bfa, #7c3aed);+ border-radius: inherit;+ z-index: -1;+ opacity: 0;+ transition: opacity 0.3s;+}+.border-glow:focus-within::before {+ opacity: 1;+}diff --git a/client/app/layout.js b/client/app/layout.jsnew file mode 100644index 0000000..4e2c142--- /dev/null+++ b/client/app/layout.js@@ -0,0 +1,17 @@+import "./globals.css";++export const metadata = {+ title: "ViGen — Agentic AI Video Generation",+ description:+ "Transform any idea into a complete cinematic video using a multi-agent AI pipeline powered by MuAPI.",+};++export default function RootLayout({ children }) {+ return (+ <html lang="en">+ <body className="antialiased min-h-screen" style={{ backgroundColor: "#0a0a0f" }}>+ {children}+ </body>+ </html>+ );+}diff --git a/client/app/page.js b/client/app/page.jsnew file mode 100644index 0000000..f39e6b6--- /dev/null+++ b/client/app/page.js@@ -0,0 +1,122 @@+"use client";++import { useState } from "react";+import { useRouter } from "next/navigation";+import IdeaForm from "../components/IdeaForm";+import { Film, Zap, GitBranch, Layers } from "lucide-react";++export default function HomePage() {+ const router = useRouter();+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [error, setError] = useState(null);++ const handleSubmit = async (formData) => {+ setIsSubmitting(true);+ setError(null);+ try {+ const res = await fetch("/api/generate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(formData),+ });+ if (!res.ok) {+ const err = await res.json();+ throw new Error(err.detail || "Failed to start generation");+ }+ const data = await res.json();+ router.push(`/generate/${data.job_id}`);+ } catch (err) {+ setError(err.message);+ setIsSubmitting(false);+ }+ };++ return (+ <main className="min-h-screen" style={{ backgroundColor: "#0a0a0f" }}>+ {/* Hero header */}+ <div className="relative overflow-hidden">+ {/* Background glow effects */}+ <div+ className="absolute inset-0 pointer-events-none"+ aria-hidden="true"+ >+ <div+ className="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[400px] rounded-full opacity-20"+ style={{+ background:+ "radial-gradient(ellipse at center, #7c3aed 0%, transparent 70%)",+ filter: "blur(60px)",+ }}+ />+ </div>++ <div className="relative max-w-5xl mx-auto px-6 pt-20 pb-16 text-center">+ {/* Badge */}+ <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium mb-6"+ style={{ backgroundColor: "rgba(124, 58, 237, 0.15)", border: "1px solid rgba(124, 58, 237, 0.3)", color: "#a78bfa" }}>+ <Zap size={12} />+ Powered by MuAPI & Claude AI+ </div>++ {/* Title */}+ <h1 className="text-6xl md:text-7xl font-black tracking-tight mb-6">+ <span className="gradient-text">ViGen</span>+ </h1>+ <p className="text-xl md:text-2xl font-light mb-3" style={{ color: "#94a3b8" }}>+ Agentic AI Video Generation+ </p>+ <p className="text-base max-w-2xl mx-auto mb-12" style={{ color: "#64748b" }}>+ Type an idea. A multi-agent pipeline writes the script, designs the+ storyboard, generates frames, and produces a complete cinematic+ video — automatically.+ </p>++ {/* Feature pills */}+ <div className="flex flex-wrap justify-center gap-3 mb-16">+ {[+ { icon: <Film size={14} />, label: "Screenwriter Agent" },+ { icon: <GitBranch size={14} />, label: "Storyboard Artist" },+ { icon: <Layers size={14} />, label: "Frame Generator" },+ { icon: <Zap size={14} />, label: "Video Generator" },+ ].map((f) => (+ <div+ key={f.label}+ className="flex items-center gap-2 px-4 py-2 rounded-full text-sm"+ style={{+ backgroundColor: "#12121a",+ border: "1px solid #22223a",+ color: "#94a3b8",+ }}+ >+ <span style={{ color: "#7c3aed" }}>{f.icon}</span>+ {f.label}+ </div>+ ))}+ </div>+ </div>+ </div>++ {/* Form section */}+ <div className="max-w-3xl mx-auto px-6 pb-24">+ {error && (+ <div+ className="mb-6 px-4 py-3 rounded-xl text-sm animate-fade-in"+ style={{+ backgroundColor: "rgba(239, 68, 68, 0.1)",+ border: "1px solid rgba(239, 68, 68, 0.3)",+ color: "#fca5a5",+ }}+ >+ {error}+ </div>+ )}+ <IdeaForm onSubmit={handleSubmit} isSubmitting={isSubmitting} />+ </div>++ {/* Footer */}+ <footer className="text-center pb-8 text-sm" style={{ color: "#374151" }}>+ ViGen — Built on MuAPI generative media infrastructure+ </footer>+ </main>+ );+}diff --git a/client/components/IdeaForm.js b/client/components/IdeaForm.jsnew file mode 100644index 0000000..b6b016e--- /dev/null+++ b/client/components/IdeaForm.js@@ -0,0 +1,223 @@+"use client";++import { useState } from "react";+import { Sparkles, ChevronDown, Loader2 } from "lucide-react";++const STYLES = [+ { value: "Cinematic", label: "Cinematic", desc: "Epic film quality" },+ { value: "Realistic", label: "Realistic", desc: "True-to-life" },+ { value: "Anime", label: "Anime", desc: "Japanese animation" },+ { value: "Fantasy", label: "Fantasy", desc: "Magical & fantastical" },+ { value: "Documentary", label: "Documentary", desc: "Journalistic style" },+];++const MODES = [+ {+ value: "idea2video",+ label: "Idea to Video",+ desc: "Full agentic pipeline: story, scenes, storyboard, video",+ },+ {+ value: "script2video",+ label: "Script to Video",+ desc: "Start from your own scene script",+ },+];++export default function IdeaForm({ onSubmit, isSubmitting }) {+ const [idea, setIdea] = useState("");+ const [userRequirement, setUserRequirement] = useState("");+ const [style, setStyle] = useState("Cinematic");+ const [mode, setMode] = useState("idea2video");+ const [script, setScript] = useState("");++ const handleSubmit = (e) => {+ e.preventDefault();+ if (!idea.trim() && (mode !== "script2video" || !script.trim())) return;+ onSubmit({+ idea: idea.trim(),+ user_requirement: userRequirement.trim(),+ style,+ mode,+ script: script.trim(),+ });+ };++ const inputStyle = {+ backgroundColor: "#12121a",+ border: "1px solid #22223a",+ borderRadius: "12px",+ color: "#e2e8f0",+ padding: "12px 16px",+ width: "100%",+ fontSize: "14px",+ transition: "border-color 0.2s",+ outline: "none",+ resize: "vertical",+ };++ const labelStyle = {+ display: "block",+ fontSize: "13px",+ fontWeight: "500",+ marginBottom: "8px",+ color: "#94a3b8",+ };++ return (+ <form+ onSubmit={handleSubmit}+ className="rounded-2xl p-6 space-y-6"+ style={{+ backgroundColor: "#12121a",+ border: "1px solid #1a1a26",+ }}+ >+ {/* Mode selector */}+ <div>+ <label style={labelStyle}>Generation Mode</label>+ <div className="grid grid-cols-2 gap-3">+ {MODES.map((m) => (+ <button+ key={m.value}+ type="button"+ onClick={() => setMode(m.value)}+ className="text-left p-4 rounded-xl transition-all"+ style={{+ backgroundColor: mode === m.value ? "rgba(124, 58, 237, 0.15)" : "#1a1a26",+ border: mode === m.value+ ? "1px solid rgba(124, 58, 237, 0.5)"+ : "1px solid #22223a",+ cursor: "pointer",+ }}+ >+ <div+ className="text-sm font-semibold mb-1"+ style={{ color: mode === m.value ? "#a78bfa" : "#e2e8f0" }}+ >+ {m.label}+ </div>+ <div className="text-xs" style={{ color: "#6b7280" }}>+ {m.desc}+ </div>+ </button>+ ))}+ </div>+ </div>++ {/* Idea input */}+ <div>+ <label style={labelStyle}>+ {mode === "script2video" ? "Brief idea or title" : "Your Idea *"}+ </label>+ <textarea+ value={idea}+ onChange={(e) => setIdea(e.target.value)}+ placeholder={+ mode === "idea2video"+ ? "e.g. A lone astronaut discovers an ancient alien structure on Mars..."+ : "Brief title or concept for your video"+ }+ rows={3}+ required={mode === "idea2video"}+ style={inputStyle}+ onFocus={(e) => (e.target.style.borderColor = "#7c3aed")}+ onBlur={(e) => (e.target.style.borderColor = "#22223a")}+ />+ </div>++ {/* Script input (script2video only) */}+ {mode === "script2video" && (+ <div>+ <label style={labelStyle}>Scene Script *</label>+ <textarea+ value={script}+ onChange={(e) => setScript(e.target.value)}+ placeholder="Write your scene script here. Be descriptive about setting, characters, actions, and mood..."+ rows={6}+ required+ style={inputStyle}+ onFocus={(e) => (e.target.style.borderColor = "#7c3aed")}+ onBlur={(e) => (e.target.style.borderColor = "#22223a")}+ />+ </div>+ )}++ {/* Style selector */}+ <div>+ <label style={labelStyle}>Visual Style</label>+ <div className="grid grid-cols-5 gap-2">+ {STYLES.map((s) => (+ <button+ key={s.value}+ type="button"+ onClick={() => setStyle(s.value)}+ className="p-3 rounded-xl text-center transition-all"+ style={{+ backgroundColor: style === s.value ? "rgba(124, 58, 237, 0.15)" : "#1a1a26",+ border: style === s.value+ ? "1px solid rgba(124, 58, 237, 0.5)"+ : "1px solid #22223a",+ cursor: "pointer",+ }}+ >+ <div+ className="text-xs font-semibold mb-1"+ style={{ color: style === s.value ? "#a78bfa" : "#e2e8f0" }}+ >+ {s.label}+ </div>+ <div className="text-xs" style={{ color: "#4b5563", fontSize: "10px" }}>+ {s.desc}+ </div>+ </button>+ ))}+ </div>+ </div>++ {/* Additional requirements */}+ <div>+ <label style={labelStyle}>+ Additional Requirements{" "}+ <span style={{ color: "#4b5563", fontWeight: 400 }}>(optional)</span>+ </label>+ <textarea+ value={userRequirement}+ onChange={(e) => setUserRequirement(e.target.value)}+ placeholder="Any specific instructions, mood, pacing, color palette, character details..."+ rows={2}+ style={inputStyle}+ onFocus={(e) => (e.target.style.borderColor = "#7c3aed")}+ onBlur={(e) => (e.target.style.borderColor = "#22223a")}+ />+ </div>++ {/* Submit */}+ <button+ type="submit"+ disabled={isSubmitting || (!idea.trim() && (mode !== "script2video" || !script.trim()))}+ className="w-full py-4 rounded-xl text-sm font-semibold flex items-center justify-center gap-2 transition-all"+ style={{+ background: isSubmitting+ ? "#3b3b5c"+ : "linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)",+ color: isSubmitting ? "#6b7280" : "white",+ cursor: isSubmitting ? "not-allowed" : "pointer",+ boxShadow: isSubmitting ? "none" : "0 4px 20px rgba(124, 58, 237, 0.4)",+ }}+ >+ {isSubmitting ? (+ <>+ <Loader2 size={16} className="animate-spin" />+ Starting pipeline...+ </>+ ) : (+ <>+ <Sparkles size={16} />+ Generate Video+ </>+ )}+ </button>+ </form>+ );+}diff --git a/client/components/PipelineProgress.js b/client/components/PipelineProgress.jsnew file mode 100644index 0000000..094e211--- /dev/null+++ b/client/components/PipelineProgress.js@@ -0,0 +1,242 @@+"use client";++import { useRef, useEffect } from "react";+import {+ FileText,+ Users,+ Layout,+ Image,+ Film,+ Video,+ Scissors,+ CheckCircle,+ Circle,+ Loader2,+} from "lucide-react";++const STAGES = [+ { id: "screenwriter", label: "Story", icon: FileText, progress_range: [5, 25] },+ { id: "characters", label: "Characters", icon: Users, progress_range: [20, 35] },+ { id: "storyboard", label: "Storyboard", icon: Layout, progress_range: [30, 45] },+ { id: "portraits", label: "Portraits", icon: Image, progress_range: [40, 55] },+ { id: "frames", label: "Frames", icon: Film, progress_range: [50, 75] },+ { id: "video", label: "Video", icon: Video, progress_range: [65, 88] },+ { id: "concat", label: "Done", icon: Scissors, progress_range: [88, 100] },+];++function getStageState(stage, progress) {+ const [start, end] = stage.progress_range;+ if (progress >= end) return "done";+ if (progress >= start) return "active";+ return "pending";+}++export default function PipelineProgress({+ progress,+ currentMessage,+ status,+ logs,+}) {+ const logsEndRef = useRef(null);++ useEffect(() => {+ logsEndRef.current?.scrollIntoView({ behavior: "smooth" });+ }, [logs]);++ return (+ <div className="space-y-6">+ {/* Stage timeline */}+ <div+ className="p-6 rounded-2xl"+ style={{+ backgroundColor: "#12121a",+ border: "1px solid #1a1a26",+ }}+ >+ <h2 className="text-sm font-semibold mb-6" style={{ color: "#94a3b8" }}>+ Pipeline Progress+ </h2>++ {/* Stage nodes */}+ <div className="flex items-center gap-0">+ {STAGES.map((stage, i) => {+ const state =+ status === "completed"+ ? "done"+ : status === "failed"+ ? getStageState(stage, progress) === "active"+ ? "failed"+ : getStageState(stage, progress)+ : getStageState(stage, progress);++ const Icon = stage.icon;+ const isLast = i === STAGES.length - 1;++ return (+ <div key={stage.id} className="flex items-center flex-1">+ {/* Node */}+ <div className="flex flex-col items-center" style={{ minWidth: 60 }}>+ <div+ className="w-10 h-10 rounded-full flex items-center justify-center mb-2 transition-all"+ style={{+ backgroundColor:+ state === "done"+ ? "rgba(124, 58, 237, 0.2)"+ : state === "active"+ ? "rgba(124, 58, 237, 0.15)"+ : state === "failed"+ ? "rgba(239, 68, 68, 0.15)"+ : "#1a1a26",+ border:+ state === "done"+ ? "2px solid #7c3aed"+ : state === "active"+ ? "2px solid rgba(124, 58, 237, 0.6)"+ : state === "failed"+ ? "2px solid rgba(239, 68, 68, 0.6)"+ : "2px solid #22223a",+ boxShadow:+ state === "active"+ ? "0 0 12px rgba(124, 58, 237, 0.4)"+ : "none",+ }}+ >+ {state === "done" ? (+ <CheckCircle size={16} style={{ color: "#7c3aed" }} />+ ) : state === "active" ? (+ <Loader2+ size={16}+ className="animate-spin"+ style={{ color: "#a78bfa" }}+ />+ ) : (+ <Icon+ size={15}+ style={{+ color:+ state === "failed" ? "#f87171" : "#4b5563",+ }}+ />+ )}+ </div>+ <span+ className="text-xs font-medium text-center"+ style={{+ color:+ state === "done"+ ? "#a78bfa"+ : state === "active"+ ? "#e2e8f0"+ : state === "failed"+ ? "#f87171"+ : "#4b5563",+ }}+ >+ {stage.label}+ </span>+ </div>++ {/* Connector line */}+ {!isLast && (+ <div+ className="flex-1 h-0.5 mx-1 transition-all"+ style={{+ backgroundColor:+ getStageState(stage, progress) === "done" ||+ status === "completed"+ ? "#7c3aed"+ : "#22223a",+ opacity:+ getStageState(stage, progress) === "done" ||+ status === "completed"+ ? 0.6+ : 1,+ }}+ />+ )}+ </div>+ );+ })}+ </div>++ {/* Progress bar */}+ <div className="mt-8">+ <div className="flex justify-between items-center mb-2">+ <span className="text-xs" style={{ color: "#6b7280" }}>+ {currentMessage}+ </span>+ <span+ className="text-xs font-mono font-bold"+ style={{ color: "#7c3aed" }}+ >+ {progress}%+ </span>+ </div>+ <div+ className="w-full h-1.5 rounded-full overflow-hidden"+ style={{ backgroundColor: "#1a1a26" }}+ >+ <div+ className="h-full rounded-full transition-all duration-700"+ style={{+ width: `${progress}%`,+ background:+ status === "failed"+ ? "#ef4444"+ : "linear-gradient(90deg, #7c3aed 0%, #a78bfa 100%)",+ boxShadow:+ status !== "failed"+ ? "0 0 8px rgba(124, 58, 237, 0.5)"+ : "none",+ }}+ />+ </div>+ </div>+ </div>++ {/* Live logs */}+ {logs.length > 0 && (+ <div+ className="rounded-2xl overflow-hidden"+ style={{+ backgroundColor: "#0d0d14",+ border: "1px solid #1a1a26",+ }}+ >+ <div+ className="px-4 py-3 flex items-center gap-2"+ style={{ borderBottom: "1px solid #1a1a26" }}+ >+ <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />+ <span className="text-xs font-medium" style={{ color: "#6b7280" }}>+ Pipeline Log+ </span>+ </div>+ <div+ className="p-4 max-h-48 overflow-y-auto font-mono text-xs space-y-1"+ style={{ color: "#64748b" }}+ >+ {logs.map((log, i) => (+ <div+ key={i}+ className="flex gap-3"+ style={{+ color:+ log.type === "complete"+ ? "#86efac"+ : log.type === "error"+ ? "#fca5a5"+ : "#94a3b8",+ }}+ >+ <span style={{ color: "#374151", flexShrink: 0 }}>{log.time}</span>+ <span>{log.message}</span>+ </div>+ ))}+ <div ref={logsEndRef} />+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/components/VideoResult.js b/client/components/VideoResult.jsnew file mode 100644index 0000000..92ffcee--- /dev/null+++ b/client/components/VideoResult.js@@ -0,0 +1,118 @@+"use client";++import { useState } from "react";+import { Download, Play, Pause, ExternalLink, CheckCircle } from "lucide-react";++export default function VideoResult({ videoUrl, jobId }) {+ const [isPlaying, setIsPlaying] = useState(false);++ const handleDownload = () => {+ const a = document.createElement("a");+ a.href = videoUrl;+ a.download = `vigen-${jobId}.mp4`;+ a.click();+ };++ return (+ <div+ className="rounded-2xl overflow-hidden"+ style={{+ backgroundColor: "#12121a",+ border: "1px solid rgba(124, 58, 237, 0.3)",+ boxShadow: "0 0 40px rgba(124, 58, 237, 0.1)",+ }}+ >+ {/* Header */}+ <div+ className="px-5 py-4 flex items-center gap-3"+ style={{ borderBottom: "1px solid #1a1a26" }}+ >+ <div+ className="w-8 h-8 rounded-full flex items-center justify-center"+ style={{ backgroundColor: "rgba(124, 58, 237, 0.2)" }}+ >+ <CheckCircle size={16} style={{ color: "#a78bfa" }} />+ </div>+ <div>+ <h2 className="text-sm font-semibold" style={{ color: "#e2e8f0" }}>+ Your Video is Ready+ </h2>+ <p className="text-xs" style={{ color: "#6b7280" }}>+ Generated by ViGen agentic pipeline+ </p>+ </div>+ <div className="ml-auto flex items-center gap-2">+ <a+ href={videoUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs transition-all"+ style={{+ backgroundColor: "#1a1a26",+ border: "1px solid #22223a",+ color: "#94a3b8",+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = "#7c3aed";+ e.currentTarget.style.color = "#a78bfa";+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = "#22223a";+ e.currentTarget.style.color = "#94a3b8";+ }}+ >+ <ExternalLink size={12} />+ Open+ </a>+ <button+ onClick={handleDownload}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all"+ style={{+ background: "linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%)",+ color: "white",+ border: "none",+ cursor: "pointer",+ boxShadow: "0 2px 8px rgba(124, 58, 237, 0.4)",+ }}+ >+ <Download size={12} />+ Download+ </button>+ </div>+ </div>++ {/* Video player */}+ <div+ className="relative"+ style={{ backgroundColor: "#0a0a0f", aspectRatio: "16/9" }}+ >+ <video+ src={videoUrl}+ controls+ autoPlay+ loop+ className="w-full h-full"+ style={{ display: "block" }}+ onPlay={() => setIsPlaying(true)}+ onPause={() => setIsPlaying(false)}+ />+ </div>++ {/* Footer */}+ <div+ className="px-5 py-3 flex items-center justify-between"+ style={{ borderTop: "1px solid #1a1a26" }}+ >+ <span className="text-xs" style={{ color: "#4b5563" }}>+ Job ID:{" "}+ <span style={{ fontFamily: "monospace", color: "#6b7280" }}>+ {jobId}+ </span>+ </span>+ <span className="text-xs" style={{ color: "#4b5563" }}>+ Powered by MuAPI & Claude AI+ </span>+ </div>+ </div>+ );+}diff --git a/client/next.config.js b/client/next.config.jsnew file mode 100644index 0000000..5966629--- /dev/null+++ b/client/next.config.js@@ -0,0 +1,17 @@+/** @type {import('next').NextConfig} */+const nextConfig = {+ async rewrites() {+ return [+ {+ source: "/api/:path*",+ destination: "http://localhost:8000/api/:path*",+ },+ {+ source: "/outputs/:path*",+ destination: "http://localhost:8000/outputs/:path*",+ },+ ];+ },+};++module.exports = nextConfig;diff --git a/client/package.json b/client/package.jsonnew file mode 100644index 0000000..bde2c92--- /dev/null+++ b/client/package.json@@ -0,0 +1,25 @@+{+ "name": "vigen-client",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "dev": "next dev",+ "build": "next build",+ "start": "next start",+ "lint": "next lint"+ },+ "dependencies": {+ "next": "14.2.3",+ "react": "^18",+ "react-dom": "^18",+ "lucide-react": "^0.381.0"+ },+ "devDependencies": {+ "@tailwindcss/typography": "^0.5.13",+ "autoprefixer": "^10.4.19",+ "eslint": "^8",+ "eslint-config-next": "14.2.3",+ "postcss": "^8.4.38",+ "tailwindcss": "^3.4.3"+ }+}diff --git a/client/postcss.config.js b/client/postcss.config.jsnew file mode 100644index 0000000..12a703d--- /dev/null+++ b/client/postcss.config.js@@ -0,0 +1,6 @@+module.exports = {+ plugins: {+ tailwindcss: {},+ autoprefixer: {},+ },+};diff --git a/client/tailwind.config.js b/client/tailwind.config.jsnew file mode 100644index 0000000..0a7bed3--- /dev/null+++ b/client/tailwind.config.js@@ -0,0 +1,44 @@+/** @type {import('tailwindcss').Config} */+module.exports = {+ content: [+ "./pages/**/*.{js,ts,jsx,tsx,mdx}",+ "./components/**/*.{js,ts,jsx,tsx,mdx}",+ "./app/**/*.{js,ts,jsx,tsx,mdx}",+ ],+ theme: {+ extend: {+ colors: {+ background: "#0a0a0f",+ surface: "#12121a",+ "surface-2": "#1a1a26",+ "surface-3": "#22223a",+ accent: "#7c3aed",+ "accent-light": "#a78bfa",+ "accent-glow": "rgba(124, 58, 237, 0.3)",+ muted: "#6b7280",+ "muted-2": "#4b5563",+ },+ animation: {+ "pulse-slow": "pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite",+ "glow": "glow 2s ease-in-out infinite alternate",+ "slide-up": "slideUp 0.4s ease-out",+ "fade-in": "fadeIn 0.3s ease-out",+ },+ keyframes: {+ glow: {+ "0%": { boxShadow: "0 0 5px rgba(124, 58, 237, 0.3)" },+ "100%": { boxShadow: "0 0 20px rgba(124, 58, 237, 0.7), 0 0 40px rgba(124, 58, 237, 0.3)" },+ },+ slideUp: {+ "0%": { transform: "translateY(10px)", opacity: "0" },+ "100%": { transform: "translateY(0)", opacity: "1" },+ },+ fadeIn: {+ "0%": { opacity: "0" },+ "100%": { opacity: "1" },+ },+ },+ },+ },+ plugins: [require("@tailwindcss/typography")],+};diff --git a/server/.env.example b/server/.env.examplenew file mode 100644index 0000000..485fb67--- /dev/null+++ b/server/.env.example@@ -0,0 +1 @@+MUAPI_KEY=your_muapi_key_herediff --git a/server/agents/__init__.py b/server/agents/__init__.pynew file mode 100644index 0000000..2b3622b--- /dev/null+++ b/server/agents/__init__.py@@ -0,0 +1,5 @@+from .screenwriter import Screenwriter+from .character_extractor import CharacterExtractor+from .storyboard_artist import StoryboardArtist++__all__ = ["Screenwriter", "CharacterExtractor", "StoryboardArtist"]diff --git a/server/agents/character_extractor.py b/server/agents/character_extractor.pynew file mode 100644index 0000000..affa055--- /dev/null+++ b/server/agents/character_extractor.py@@ -0,0 +1,58 @@+import json+import os+from typing import List++from interfaces.character import CharacterInScene+from tools.muapi_llm import MuAPILLM+++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. "+ "Focus on characteristics that remain consistent (static) and scene-specific details (dynamic). "+ "Respond ONLY with valid JSON — no markdown, no explanation, just JSON."+ )+ prompt = f"""Extract all characters from this script and provide visual descriptions for AI image generation.++Script:+{script}++Return a JSON object with this exact structure:+{{+ "characters": [+ {{+ "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",+ "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"""++ raw = await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)+ 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 charactersdiff --git a/server/agents/screenwriter.py b/server/agents/screenwriter.pynew file mode 100644index 0000000..424aced--- /dev/null+++ b/server/agents/screenwriter.py@@ -0,0 +1,80 @@+import json+import os+from typing import List++from tools.muapi_llm import MuAPILLM+++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. "+ "Include premise, protagonist, conflict, rising action, climax, and resolution. "+ "Keep it suitable for a short video (1-3 minutes). "+ "Write in clear prose, focusing on visual storytelling."+ )+ prompt = f"""Develop a story based on this idea:++Idea: {idea}++Additional requirements: {user_requirement if user_requirement else "None"}++Write a detailed story outline that can be translated into a short video. Include:+- Setting and atmosphere+- Main character(s) and their goal+- The conflict or journey+- Emotional arc+- Visual climax moment+- Resolution++Write the story outline as flowing prose."""++ return await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)++ 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. "+ "Each scene should be self-contained, visually rich, and suitable for video generation. "+ "Write 2-4 scenes maximum. "+ "Respond ONLY with valid JSON — no markdown, no explanation, just JSON."+ )+ prompt = f"""Based on this story outline, write individual scene scripts for a short video.++Story Outline:+{story}++Additional requirements: {user_requirement if user_requirement else "None"}++Return a JSON object with this exact structure:+{{+ "scenes": [+ {{+ "scene_number": 1,+ "title": "Scene title",+ "script": "Full scene script with action lines, dialogue, and scene description. Should be 100-200 words per scene."+ }},+ ...+ ]+}}++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"""++ raw = await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)+ raw = raw.strip()+ if raw.startswith("```"):+ raw = raw.split("```")[1]+ if raw.startswith("json"):+ raw = raw[4:]+ data = json.loads(raw)+ return [scene["script"] for scene in data.get("scenes", [])]diff --git a/server/agents/storyboard_artist.py b/server/agents/storyboard_artist.pynew file mode 100644index 0000000..2fab9d7--- /dev/null+++ b/server/agents/storyboard_artist.py@@ -0,0 +1,78 @@+import json+import os+from typing import List++from interfaces.character import CharacterInScene+from interfaces.shot import ShotBriefDescription+from tools.muapi_llm import MuAPILLM+++class StoryboardArtist:+ def __init__(self):+ self.llm = MuAPILLM()++ async def design_storyboard(+ self,+ script: str,+ 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. "+ "Each shot should have a clear visual description, camera movement, and audio description. "+ "Keep shots between 3-6 seconds each (they will be 5-second video clips). "+ "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+ ]+ )++ prompt = f"""Design a storyboard for this scene script by breaking it into individual shots.++Scene Script:+{script}++Characters in this scene:+{character_descriptions if character_descriptions else "No named characters"}++Style requirement: {user_requirement if user_requirement else "Cinematic, professional"}++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'"+ }},+ ...+ ]+}}++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"""++ raw = await self.llm.complete(prompt, system_prompt=system_prompt, timeout=120)+ 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 shotsdiff --git a/server/api.py b/server/api.pynew file mode 100644index 0000000..fd09ecf--- /dev/null+++ b/server/api.py@@ -0,0 +1,241 @@+import asyncio+import json+import os+import uuid+from pathlib import Path+from typing import Any, Dict++from dotenv import load_dotenv++load_dotenv()++from fastapi import FastAPI, BackgroundTasks, HTTPException+from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import StreamingResponse, JSONResponse+from fastapi.staticfiles import StaticFiles+from pydantic import BaseModel++from pipelines.idea2video import Idea2VideoPipeline+from pipelines.script2video import Script2VideoPipeline+from agents.character_extractor import CharacterExtractor+++# ---------------------------------------------------------------------------+# App setup+# ---------------------------------------------------------------------------+app = FastAPI(title="ViGen API", version="1.0.0")++app.add_middleware(+ CORSMiddleware,+ allow_origins=["*"],+ allow_credentials=True,+ allow_methods=["*"],+ allow_headers=["*"],+)++# Ensure outputs directory exists on startup+OUTPUTS_DIR = Path("outputs")+OUTPUTS_DIR.mkdir(exist_ok=True)++app.mount("/outputs", StaticFiles(directory="outputs"), name="outputs")+++# ---------------------------------------------------------------------------+# In-memory job store+# ---------------------------------------------------------------------------+# job structure:+# {+# "status": "running" | "completed" | "failed",+# "events": [...], # list of JSON-serialisable dicts+# "video_url": str | None,+# "error": str | None,+# "queue": asyncio.Queue, # fed by pipeline, consumed by SSE+# }+jobs: Dict[str, Dict[str, Any]] = {}+++# ---------------------------------------------------------------------------+# Request / Response schemas+# ---------------------------------------------------------------------------+class GenerateRequest(BaseModel):+ idea: str+ user_requirement: str = ""+ style: str = "Cinematic"+ mode: str = "idea2video" # "idea2video" or "script2video"+ script: str = "" # used when mode == "script2video"+++class GenerateResponse(BaseModel):+ job_id: str+++class JobResult(BaseModel):+ job_id: str+ status: str+ video_url: str | None = None+ error: str | None = None+++# ---------------------------------------------------------------------------+# Background pipeline runner+# ---------------------------------------------------------------------------+async def run_pipeline(job_id: str, req: GenerateRequest) -> None:+ job = jobs[job_id]+ queue: asyncio.Queue = job["queue"]++ async def progress_callback(stage: str, message: str, progress: int) -> None:+ event = {+ "type": "progress",+ "stage": stage,+ "message": message,+ "progress": progress,+ }+ job["events"].append(event)+ await queue.put(event)++ try:+ if req.mode == "script2video":+ # Script2Video: user provides a single scene script+ pipeline = Script2VideoPipeline()+ character_extractor = CharacterExtractor()++ await progress_callback("characters", "Extracting characters...", 10)+ characters = await character_extractor.extract_characters(req.script or req.idea)++ output_dir = str(OUTPUTS_DIR / job_id / "scene_00")+ video_path = await pipeline.run(+ script=req.script or req.idea,+ characters=characters,+ user_requirement=req.user_requirement,+ style=req.style,+ working_dir=output_dir,+ progress_callback=progress_callback,+ scene_idx=0,+ base_progress=15,+ progress_range=80,+ )+ else:+ # Idea2Video: full agentic pipeline+ pipeline = Idea2VideoPipeline()+ video_path = await pipeline.run(+ idea=req.idea,+ user_requirement=req.user_requirement,+ style=req.style,+ job_id=job_id,+ progress_callback=progress_callback,+ )++ # Convert local path to URL+ rel_path = Path(video_path).relative_to(Path("."))+ video_url = f"/{rel_path}"++ job["status"] = "completed"+ job["video_url"] = video_url++ complete_event = {+ "type": "complete",+ "video_url": video_url,+ "progress": 100,+ }+ job["events"].append(complete_event)+ await queue.put(complete_event)++ except Exception as exc:+ error_msg = str(exc)+ job["status"] = "failed"+ job["error"] = error_msg++ error_event = {+ "type": "error",+ "message": error_msg,+ "progress": -1,+ }+ job["events"].append(error_event)+ await queue.put(error_event)++ finally:+ # Signal SSE consumers that the stream is done+ await queue.put(None)+++# ---------------------------------------------------------------------------+# Endpoints+# ---------------------------------------------------------------------------[email protected]("/api/health")+async def health():+ return {"status": "ok", "service": "vigen-api"}++[email protected]("/api/generate", response_model=GenerateResponse)+async def generate(req: GenerateRequest, background_tasks: BackgroundTasks):+ job_id = str(uuid.uuid4())+ jobs[job_id] = {+ "status": "running",+ "events": [],+ "video_url": None,+ "error": None,+ "queue": asyncio.Queue(),+ }+ background_tasks.add_task(run_pipeline, job_id, req)+ return GenerateResponse(job_id=job_id)++[email protected]("/api/status/{job_id}")+async def status_stream(job_id: str):+ """SSE endpoint — streams progress events until job completes or fails."""+ if job_id not in jobs:+ raise HTTPException(status_code=404, detail="Job not found")++ job = jobs[job_id]++ async def event_generator():+ # Replay already-emitted events first (in case client reconnects)+ for event in job["events"]:+ yield f"data: {json.dumps(event)}\n\n"++ # If job is already done, we've replayed everything — finish+ if job["status"] in ("completed", "failed"):+ return++ # Otherwise stream live events from queue+ queue: asyncio.Queue = job["queue"]+ while True:+ event = await queue.get()+ if event is None:+ # Sentinel — pipeline finished+ break+ yield f"data: {json.dumps(event)}\n\n"+ if event.get("type") in ("complete", "error"):+ break++ return StreamingResponse(+ event_generator(),+ media_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ "X-Accel-Buffering": "no",+ },+ )++[email protected]("/api/result/{job_id}", response_model=JobResult)+async def get_result(job_id: str):+ if job_id not in jobs:+ raise HTTPException(status_code=404, detail="Job not found")++ job = jobs[job_id]+ return JobResult(+ job_id=job_id,+ status=job["status"],+ video_url=job.get("video_url"),+ error=job.get("error"),+ )+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+if __name__ == "__main__":+ import uvicorn+ uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True)diff --git a/server/interfaces/__init__.py b/server/interfaces/__init__.pynew file mode 100644index 0000000..00022b4--- /dev/null+++ b/server/interfaces/__init__.py@@ -0,0 +1,4 @@+from .character import CharacterInScene+from .shot import ShotBriefDescription, ShotDescription++__all__ = ["CharacterInScene", "ShotBriefDescription", "ShotDescription"]diff --git a/server/interfaces/character.py b/server/interfaces/character.pynew file mode 100644index 0000000..b7b8864--- /dev/null+++ b/server/interfaces/character.py@@ -0,0 +1,9 @@+from pydantic import BaseModel+++class CharacterInScene(BaseModel):+ idx: int+ name: str # e.g. "Alice"+ static_features: str # hair, build, face — unchanging+ dynamic_features: str # clothing, accessories for this scene+ is_visible: bool = Truediff --git a/server/interfaces/shot.py b/server/interfaces/shot.pynew file mode 100644index 0000000..e596d4a--- /dev/null+++ b/server/interfaces/shot.py@@ -0,0 +1,14 @@+from typing import Optional+from pydantic import BaseModel+++class ShotBriefDescription(BaseModel):+ idx: int+ visual_desc: str # full scene visual description+ motion_desc: str # camera movement and action motion for video prompt+ audio_desc: str # sound effects / dialogue+++class ShotDescription(ShotBriefDescription):+ first_frame_url: Optional[str] = None+ video_url: Optional[str] = Nonediff --git a/server/pipelines/__init__.py b/server/pipelines/__init__.pynew file mode 100644index 0000000..6277fd9--- /dev/null+++ b/server/pipelines/__init__.py@@ -0,0 +1,4 @@+from .idea2video import Idea2VideoPipeline+from .script2video import Script2VideoPipeline++__all__ = ["Idea2VideoPipeline", "Script2VideoPipeline"]diff --git a/server/pipelines/idea2video.py b/server/pipelines/idea2video.pynew file mode 100644index 0000000..9a6dd3b--- /dev/null+++ b/server/pipelines/idea2video.py@@ -0,0 +1,105 @@+import os+from pathlib import Path+from typing import Callable, Awaitable, Optional++from agents.screenwriter import Screenwriter+from agents.character_extractor import CharacterExtractor+from pipelines.script2video import Script2VideoPipeline+from utils.video import concatenate_videos+++ProgressCallback = Callable[[str, str, int], Awaitable[None]]+++class Idea2VideoPipeline:+ def __init__(self, api_key: Optional[str] = None):+ self.api_key = api_key or os.environ["MUAPI_KEY"]+ self.screenwriter = Screenwriter()+ self.character_extractor = CharacterExtractor()+ self.script2video = Script2VideoPipeline(api_key=self.api_key)++ async def run(+ self,+ idea: str,+ user_requirement: str,+ style: str,+ job_id: str,+ progress_callback: ProgressCallback,+ ) -> str:+ """+ Full pipeline: idea → story → scenes → videos → final concatenated video.+ Returns the path to the final video.+ """+ outputs_dir = Path("outputs") / job_id+ outputs_dir.mkdir(parents=True, exist_ok=True)++ # Stage 1: Develop story+ await progress_callback(+ "screenwriter", "Developing story...", 10+ )+ story = await self.screenwriter.develop_story(idea, user_requirement)++ # Stage 2: Extract characters from story+ await progress_callback(+ "characters", "Extracting characters...", 20+ )+ characters = await self.character_extractor.extract_characters(story)++ # Stage 3: Write scene scripts+ await progress_callback(+ "screenwriter", "Writing scene scripts...", 25+ )+ scene_scripts = await self.screenwriter.write_script_based_on_story(+ story, user_requirement+ )++ if not scene_scripts:+ raise RuntimeError("Screenwriter produced no scene scripts")++ # Stage 4: Generate video for each scene+ scene_video_paths = []+ num_scenes = len(scene_scripts)++ # Distribute progress range 30-88 across scenes+ progress_per_scene = int(58 / max(num_scenes, 1))++ for scene_idx, scene_script in enumerate(scene_scripts):+ scene_dir = str(outputs_dir / f"scene_{scene_idx:02d}")+ base_progress = 30 + scene_idx * progress_per_scene++ try:+ scene_video = await self.script2video.run(+ script=scene_script,+ characters=characters,+ user_requirement=user_requirement,+ style=style,+ working_dir=scene_dir,+ progress_callback=progress_callback,+ scene_idx=scene_idx,+ base_progress=base_progress,+ progress_range=progress_per_scene,+ )+ scene_video_paths.append(scene_video)+ except Exception as e:+ # Log but continue with remaining scenes+ print(f"Warning: scene {scene_idx} failed: {e}")+ await progress_callback(+ "video",+ f"Scene {scene_idx + 1} failed, continuing...",+ base_progress + progress_per_scene,+ )++ if not scene_video_paths:+ raise RuntimeError("All scenes failed to generate")++ # Stage 5: Concatenate all scene videos+ await progress_callback(+ "concat", "Combining all scenes into final video...", 90+ )+ final_video_path = str(outputs_dir / "final_video.mp4")+ await concatenate_videos(scene_video_paths, final_video_path)++ await progress_callback(+ "concat", "Video generation complete!", 100+ )+ return final_video_pathdiff --git a/server/pipelines/script2video.py b/server/pipelines/script2video.pynew file mode 100644index 0000000..86ca5f9--- /dev/null+++ b/server/pipelines/script2video.py@@ -0,0 +1,207 @@+import asyncio+import os+from pathlib import Path+from typing import Callable, Awaitable, List, Optional++from agents.storyboard_artist import StoryboardArtist+from interfaces.character import CharacterInScene+from interfaces.shot import ShotDescription+from tools.muapi_image_generator import MuAPIImageGenerator+from tools.muapi_video_generator import MuAPIVideoGenerator+from tools.muapi_uploader import upload_image_from_url+from utils.video import concatenate_videos, download_video+++ProgressCallback = Callable[[str, str, int], Awaitable[None]]+++class Script2VideoPipeline:+ def __init__(self, api_key: Optional[str] = None):+ self.api_key = api_key or os.environ["MUAPI_KEY"]+ self.storyboard_artist = StoryboardArtist()+ self.image_gen = MuAPIImageGenerator(api_key=self.api_key)+ self.video_gen = MuAPIVideoGenerator(api_key=self.api_key)++ async def run(+ self,+ script: str,+ characters: List[CharacterInScene],+ user_requirement: str,+ style: str,+ working_dir: str,+ progress_callback: ProgressCallback,+ scene_idx: int = 0,+ base_progress: int = 30,+ progress_range: int = 60,+ ) -> str:+ """+ Run the script-to-video pipeline for a single scene.+ Returns the path to the final scene video.+ """+ Path(working_dir).mkdir(parents=True, exist_ok=True)++ # Step 1: Generate character portraits in parallel+ await progress_callback(+ "portraits",+ f"Generating character portraits for scene {scene_idx + 1}...",+ base_progress + int(progress_range * 0.05),+ )+ character_portrait_urls: dict[str, str] = {}+ if characters:+ portrait_tasks = {+ c.name: self._generate_portrait(c, style)+ for c in characters+ if c.is_visible+ }+ results = await asyncio.gather(*portrait_tasks.values(), return_exceptions=True)+ for name, result in zip(portrait_tasks.keys(), results):+ if isinstance(result, Exception):+ # Non-fatal: continue without portrait+ print(f"Warning: portrait generation failed for {name}: {result}")+ else:+ character_portrait_urls[name] = result++ # Step 2: Design storyboard+ await progress_callback(+ "storyboard",+ f"Designing storyboard for scene {scene_idx + 1}...",+ base_progress + int(progress_range * 0.15),+ )+ shots_brief = await self.storyboard_artist.design_storyboard(+ script, characters, f"{user_requirement}. Style: {style}"+ )++ shots: List[ShotDescription] = [+ ShotDescription(**s.model_dump()) for s in shots_brief+ ]++ # Step 3: Generate first frames sequentially (to maintain visual order)+ frame_progress_step = int(progress_range * 0.35 / max(len(shots), 1))+ for i, shot in enumerate(shots):+ await progress_callback(+ "frames",+ f"Generating frame for shot {i + 1}/{len(shots)} (scene {scene_idx + 1})...",+ base_progress + int(progress_range * 0.20) + i * frame_progress_step,+ )+ frame_url = await self._generate_first_frame(+ shot, characters, character_portrait_urls, style+ )+ shot.first_frame_url = frame_url++ # Step 4: Generate videos in parallel+ await progress_callback(+ "video",+ f"Generating videos for scene {scene_idx + 1}...",+ base_progress + int(progress_range * 0.60),+ )+ video_tasks = [+ self._generate_shot_video(shot, i, working_dir)+ for i, shot in enumerate(shots)+ if shot.first_frame_url+ ]+ video_results = await asyncio.gather(*video_tasks, return_exceptions=True)++ shot_video_paths = []+ for i, result in enumerate(video_results):+ if isinstance(result, Exception):+ print(f"Warning: video generation failed for shot {i}: {result}")+ else:+ shot_video_paths.append(result)+ shots[i].video_url = result++ if not shot_video_paths:+ raise RuntimeError(f"All video generation failed for scene {scene_idx + 1}")++ # Step 5: Concatenate shot videos+ await progress_callback(+ "concat",+ f"Combining shots for scene {scene_idx + 1}...",+ base_progress + int(progress_range * 0.90),+ )+ scene_video_path = str(Path(working_dir) / "scene_video.mp4")+ await concatenate_videos(shot_video_paths, scene_video_path)++ return scene_video_path++ async def _generate_portrait(self, character: CharacterInScene, style: str) -> str:+ """Generate a character portrait image."""+ prompt = (+ f"Professional portrait photo of {character.name}. "+ f"{character.static_features}. "+ f"Wearing {character.dynamic_features}. "+ f"Style: {style}. "+ "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)++ async def _generate_first_frame(+ self,+ shot: ShotDescription,+ characters: List[CharacterInScene],+ portrait_urls: dict,+ style: str,+ ) -> str:+ """Generate the first frame for a shot, using character references if available."""+ # Find which characters appear in this shot+ mentioned_chars = [+ c for c in characters if c.name.lower() in shot.visual_desc.lower()+ ]++ reference_url = None+ if mentioned_chars and portrait_urls.get(mentioned_chars[0].name):+ reference_url = portrait_urls[mentioned_chars[0].name]++ char_desc = ""+ if mentioned_chars:+ char_desc = " ".join(+ [+ f"{c.name} ({c.dynamic_features})"+ for c in mentioned_chars+ ]+ )++ full_prompt = (+ f"{shot.visual_desc}. "+ f"{char_desc}. "+ f"Style: {style}. "+ "Cinematic composition, 16:9 aspect ratio, high quality, detailed."+ )++ if reference_url:+ try:+ return await self.image_gen.generate_image_with_reference(+ full_prompt, reference_url, aspect_ratio="16:9"+ )+ except Exception as e:+ 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)++ async def _generate_shot_video(+ self, shot: ShotDescription, shot_idx: int, working_dir: str+ ) -> str:+ """Generate a video clip for a shot. Returns local file path."""+ if not shot.first_frame_url:+ raise ValueError(f"Shot {shot_idx} has no first_frame_url")++ # Build video prompt from motion + audio descriptions+ video_prompt = f"{shot.motion_desc}. {shot.audio_desc}"++ # Upload the first frame to get a stable MuAPI URL if needed+ frame_url = shot.first_frame_url+ if not frame_url.startswith("https://api.muapi.ai"):+ try:+ frame_url = await upload_image_from_url(frame_url, self.api_key)+ except Exception as e:+ print(f"Warning: re-upload failed, using original URL: {e}")++ video_url = await self.video_gen.generate_video_from_image(+ video_prompt, frame_url, duration=5, aspect_ratio="16:9"+ )++ # Download the video locally+ local_path = str(Path(working_dir) / f"shot_{shot_idx:03d}.mp4")+ await download_video(video_url, local_path)+ return local_pathdiff --git a/server/requirements.txt b/server/requirements.txtnew file mode 100644index 0000000..15114e0--- /dev/null+++ b/server/requirements.txt@@ -0,0 +1,10 @@+fastapi+uvicorn[standard]+httpx+aiofiles+python-multipart+pydantic+moviepy+pillow+python-dotenv+aiohttpdiff --git a/server/tools/__init__.py b/server/tools/__init__.pynew file mode 100644index 0000000..d301304--- /dev/null+++ b/server/tools/__init__.py@@ -0,0 +1,10 @@+from .muapi_image_generator import MuAPIImageGenerator+from .muapi_video_generator import MuAPIVideoGenerator+from .muapi_uploader import upload_image_from_url, upload_image_from_path++__all__ = [+ "MuAPIImageGenerator",+ "MuAPIVideoGenerator",+ "upload_image_from_url",+ "upload_image_from_path",+]diff --git a/server/tools/muapi_image_generator.py b/server/tools/muapi_image_generator.pynew file mode 100644index 0000000..8e68588--- /dev/null+++ b/server/tools/muapi_image_generator.py@@ -0,0 +1,106 @@+import asyncio+import os+from typing import Optional++import httpx+++MUAPI_BASE = "https://api.muapi.ai/api/v1"+POLL_INTERVAL = 3 # seconds+++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 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()+ 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}")++ 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)++ async def generate_image_with_reference(+ self,+ prompt: str,+ reference_url: str,+ aspect_ratio: str = "16:9",+ ) -> str:+ """Generate an image using a reference image for character consistency. Returns URL."""+ 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()+ 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}")++ 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)++ 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:+ await asyncio.sleep(POLL_INTERVAL)+ elapsed += POLL_INTERVAL++ resp = await client.get(+ f"{MUAPI_BASE}/predictions/{request_id}/result",+ headers=self.headers,+ )+ resp.raise_for_status()+ data = resp.json()++ status = data.get("status", "")+ if status == "completed":+ return data+ elif status == "failed":+ raise RuntimeError(+ f"MuAPI image job {request_id} failed: {data.get('error', 'unknown error')}"+ )+ 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.pynew file mode 100644index 0000000..6c4219d--- /dev/null+++ b/server/tools/muapi_llm.py@@ -0,0 +1,65 @@+import asyncio+import os+from typing import Optional++import httpx+++MUAPI_BASE = "https://api.muapi.ai/api/v1"+POLL_INTERVAL = 3+++class MuAPILLM:+ """Calls MuAPI's claude-sonnet-4-6 LLM endpoint and polls for the text result."""++ 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 complete(self, prompt: str, system_prompt: Optional[str] = None, timeout: int = 120) -> str:+ """Submit an LLM completion request and return the response text."""+ payload: dict = {"prompt": prompt}+ if system_prompt:+ payload["system_prompt"] = system_prompt++ async with httpx.AsyncClient(timeout=60) as client:+ resp = await client.post(+ f"{MUAPI_BASE}/claude-sonnet-4-6",+ headers=self.headers,+ json=payload,+ )+ resp.raise_for_status()+ data = resp.json()++ request_id = data.get("request_id") or data.get("id")+ if not request_id:+ raise ValueError(f"No request_id in LLM response: {data}")++ return await self._poll_until_done(request_id, timeout=timeout)++ async def _poll_until_done(self, request_id: str, timeout: int = 120) -> str:+ elapsed = 0+ async with httpx.AsyncClient(timeout=30) as client:+ while elapsed < timeout:+ await asyncio.sleep(POLL_INTERVAL)+ elapsed += POLL_INTERVAL++ resp = await client.get(+ f"{MUAPI_BASE}/predictions/{request_id}/result",+ headers=self.headers,+ )+ resp.raise_for_status()+ data = resp.json()++ status = data.get("status", "")+ if status == "completed":+ outputs = data.get("outputs", [])+ if not outputs:+ raise ValueError(f"No outputs in LLM result: {data}")+ return str(outputs[0])+ elif status == "failed":+ raise RuntimeError(f"MuAPI LLM job {request_id} failed: {data.get('error', 'unknown')}")+ elif status == "cancelled":+ raise RuntimeError(f"MuAPI LLM job {request_id} was cancelled")++ raise TimeoutError(f"MuAPI LLM job {request_id} did not complete within {timeout}s")diff --git a/server/tools/muapi_uploader.py b/server/tools/muapi_uploader.pynew file mode 100644index 0000000..1c1cd83--- /dev/null+++ b/server/tools/muapi_uploader.py@@ -0,0 +1,80 @@+import os+import tempfile+from pathlib import Path+from typing import Optional++import httpx+++MUAPI_BASE = "https://api.muapi.ai/api/v1"+++async def upload_image_from_url(url: str, api_key: Optional[str] = None) -> str:+ """Download an image from a URL and re-upload it to MuAPI. Returns MuAPI-hosted URL."""+ key = api_key or os.environ["MUAPI_KEY"]++ # Download the image+ async with httpx.AsyncClient(timeout=60, follow_redirects=True) as client:+ resp = await client.get(url)+ resp.raise_for_status()+ content = resp.content+ content_type = resp.headers.get("content-type", "image/jpeg")++ # Determine extension from content type+ ext_map = {+ "image/jpeg": ".jpg",+ "image/jpg": ".jpg",+ "image/png": ".png",+ "image/webp": ".webp",+ "image/gif": ".gif",+ }+ ext = ext_map.get(content_type.split(";")[0].strip(), ".jpg")++ # Write to temp file and upload+ with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:+ tmp.write(content)+ tmp_path = tmp.name++ try:+ result = await upload_image_from_path(tmp_path, key)+ return result+ finally:+ Path(tmp_path).unlink(missing_ok=True)+++async def upload_image_from_path(path: str, api_key: Optional[str] = None) -> str:+ """Upload a local image file to MuAPI. Returns MuAPI-hosted URL."""+ key = api_key or os.environ["MUAPI_KEY"]+ headers = {"x-api-key": key}++ with open(path, "rb") as f:+ file_content = f.read()++ filename = Path(path).name+ 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()+ data = resp.json()++ url = data.get("url") or data.get("file_url") or data.get("data", {}).get("url")+ if not url:+ raise ValueError(f"No URL in upload response: {data}")+ return url+++def _guess_content_type(filename: str) -> str:+ ext = Path(filename).suffix.lower()+ types = {+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".png": "image/png",+ ".webp": "image/webp",+ ".gif": "image/gif",+ }+ return types.get(ext, "image/jpeg")diff --git a/server/tools/muapi_video_generator.py b/server/tools/muapi_video_generator.pynew file mode 100644index 0000000..df5696d--- /dev/null+++ b/server/tools/muapi_video_generator.py@@ -0,0 +1,81 @@+import asyncio+import os+from typing import Optional++import httpx+++MUAPI_BASE = "https://api.muapi.ai/api/v1"+POLL_INTERVAL = 3 # seconds+++class MuAPIVideoGenerator:+ 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_video_from_image(+ self,+ prompt: str,+ image_url: str,+ duration: int = 5,+ aspect_ratio: str = "16:9",+ ) -> str:+ """Generate a video clip from an image + motion prompt. Returns URL of generated video."""+ 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()+ 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}")++ result = await self._poll_until_done(request_id, timeout=600)+ 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:+ await asyncio.sleep(POLL_INTERVAL)+ elapsed += POLL_INTERVAL++ resp = await client.get(+ f"{MUAPI_BASE}/predictions/{request_id}/result",+ headers=self.headers,+ )+ resp.raise_for_status()+ data = resp.json()++ status = data.get("status", "")+ if status == "completed":+ return data+ elif status == "failed":+ raise RuntimeError(+ f"MuAPI video job {request_id} failed: {data.get('error', 'unknown error')}"+ )+ 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"+ )diff --git a/server/utils/__init__.py b/server/utils/__init__.pynew file mode 100644index 0000000..fa3c133--- /dev/null+++ b/server/utils/__init__.py@@ -0,0 +1,3 @@+from .video import concatenate_videos++__all__ = ["concatenate_videos"]diff --git a/server/utils/video.py b/server/utils/video.pynew file mode 100644index 0000000..1d48029--- /dev/null+++ b/server/utils/video.py@@ -0,0 +1,87 @@+import asyncio+import os+import tempfile+from pathlib import Path+from typing import List++import httpx+++async def download_video(url: str, dest_path: str) -> str:+ """Download a video from a URL to a local path. Returns the path."""+ async with httpx.AsyncClient(timeout=120, follow_redirects=True) as client:+ resp = await client.get(url)+ resp.raise_for_status()+ with open(dest_path, "wb") as f:+ f.write(resp.content)+ return dest_path+++async def concatenate_videos(video_paths: List[str], output_path: str) -> str:+ """+ Concatenate multiple video files into one using moviepy.+ video_paths: list of local file paths or URLs+ output_path: local path for the output video+ Returns the output_path.+ """+ # Resolve URLs to local paths+ local_paths = []+ temp_files = []++ for i, vp in enumerate(video_paths):+ if vp.startswith("http://") or vp.startswith("https://"):+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)+ tmp.close()+ await download_video(vp, tmp.name)+ local_paths.append(tmp.name)+ temp_files.append(tmp.name)+ else:+ local_paths.append(vp)++ # Run moviepy concatenation in a thread executor to avoid blocking+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _concat_sync, local_paths, output_path)++ # Clean up temp files+ for tf in temp_files:+ Path(tf).unlink(missing_ok=True)++ return output_path+++def _concat_sync(video_paths: List[str], output_path: str) -> None:+ """Synchronous moviepy concatenation (runs in thread executor)."""+ try:+ from moviepy.editor import VideoFileClip, concatenate_videoclips+ except ImportError:+ from moviepy import VideoFileClip, concatenate_videoclips++ clips = []+ try:+ for path in video_paths:+ clip = VideoFileClip(path)+ clips.append(clip)++ if not clips:+ raise ValueError("No video clips to concatenate")++ if len(clips) == 1:+ # Just copy+ clips[0].write_videofile(+ output_path,+ codec="libx264",+ audio_codec="aac",+ logger=None,+ )+ else:+ final = concatenate_videoclips(clips, method="compose")+ final.write_videofile(+ output_path,+ codec="libx264",+ audio_codec="aac",+ logger=None,+ )+ final.close()+ finally:+ for clip in clips:+ clip.close()