Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,301 +1,211 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
import json
|
| 4 |
-
import uuid
|
| 5 |
-
import time
|
| 6 |
-
import shutil
|
| 7 |
-
import mimetypes
|
| 8 |
-
import requests
|
| 9 |
-
import subprocess
|
| 10 |
from datetime import datetime
|
| 11 |
-
from typing import
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
ENDPOINT_URL = "https://moonmath-ai-dev--moonmath-i2v-backend-moonmathinference-run.modal.run" # your backend
|
| 20 |
-
OUT_DIR = "outputs"
|
| 21 |
-
TMP_DIR = "tmp"
|
| 22 |
-
os.makedirs(OUT_DIR, exist_ok=True)
|
| 23 |
-
os.makedirs(TMP_DIR, exist_ok=True)
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
# Helpers
|
| 30 |
-
# ================================
|
| 31 |
-
|
| 32 |
-
def _ts() -> str:
|
| 33 |
-
return datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
| 34 |
-
|
| 35 |
-
def _safe_filename(prefix: str, ext: str) -> str:
|
| 36 |
-
return f"{prefix}_{_ts()}_{uuid.uuid4().hex[:8]}.{ext}"
|
| 37 |
-
|
| 38 |
-
def _run_ffmpeg(args: List[str]) -> None:
|
| 39 |
-
"""Run ffmpeg with given args; raise on failure with readable message."""
|
| 40 |
-
cmd = [FFMPEG_BIN] + args
|
| 41 |
-
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 42 |
-
if proc.returncode != 0:
|
| 43 |
-
raise RuntimeError(
|
| 44 |
-
f"ffmpeg failed ({proc.returncode}).\nSTDOUT:\n{proc.stdout.decode(errors='ignore')}\n\nSTDERR:\n{proc.stderr.decode(errors='ignore')}"
|
| 45 |
-
)
|
| 46 |
|
| 47 |
def extract_last_frame(video_path: str) -> str:
|
| 48 |
-
"""
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
"
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
return
|
| 63 |
-
|
| 64 |
-
def
|
| 65 |
-
""
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# paths must be quoted if they may contain spaces
|
| 78 |
-
f.write(f"file '{os.path.abspath(p)}'\n")
|
| 79 |
-
|
| 80 |
-
out_path = os.path.join(OUT_DIR, _safe_filename("continuous", "mp4"))
|
| 81 |
-
_run_ffmpeg([
|
| 82 |
-
"-f", "concat",
|
| 83 |
-
"-safe", "0",
|
| 84 |
-
"-i", list_file,
|
| 85 |
-
"-c", "copy",
|
| 86 |
-
out_path
|
| 87 |
-
])
|
| 88 |
-
try:
|
| 89 |
-
os.remove(list_file)
|
| 90 |
-
except Exception:
|
| 91 |
-
pass
|
| 92 |
-
return out_path
|
| 93 |
-
|
| 94 |
-
def zip_files(file_paths: List[str]) -> str:
|
| 95 |
-
base = os.path.join(OUT_DIR, f"used_{_ts()}")
|
| 96 |
-
shutil.make_archive(base, "zip", root_dir=os.path.dirname(file_paths[0]) if file_paths else ".", base_dir=".")
|
| 97 |
-
# The above zips the entire directory — better: copy into temp pack dir first
|
| 98 |
-
# For precision, we’ll do that instead:
|
| 99 |
-
stamp = _ts()
|
| 100 |
-
pack_dir = os.path.join(TMP_DIR, f"pack_{stamp}_{uuid.uuid4().hex[:6]}")
|
| 101 |
-
os.makedirs(pack_dir, exist_ok=True)
|
| 102 |
-
for p in file_paths:
|
| 103 |
-
shutil.copy(p, pack_dir)
|
| 104 |
-
zip_base = os.path.join(OUT_DIR, f"used_{stamp}")
|
| 105 |
-
shutil.make_archive(zip_base, "zip", pack_dir)
|
| 106 |
-
shutil.rmtree(pack_dir, ignore_errors=True)
|
| 107 |
-
return f"{zip_base}.zip"
|
| 108 |
-
|
| 109 |
-
def _guess_filename_from_response(resp: requests.Response, default_ext: str = "mp4") -> str:
|
| 110 |
-
# Try Content-Disposition
|
| 111 |
-
cd = resp.headers.get("Content-Disposition", "")
|
| 112 |
-
if "filename=" in cd:
|
| 113 |
-
name = cd.split("filename=")[-1].strip('"; ')
|
| 114 |
-
if name:
|
| 115 |
-
return name
|
| 116 |
-
# Otherwise, attempt from content-type
|
| 117 |
-
ctype = resp.headers.get("Content-Type", "")
|
| 118 |
-
ext = mimetypes.guess_extension(ctype) or f".{default_ext}"
|
| 119 |
-
return _safe_filename("gen", ext.lstrip("."))
|
| 120 |
-
|
| 121 |
-
def save_bytes_to_file(content: bytes, ext: str = "mp4") -> str:
|
| 122 |
-
path = os.path.join(OUT_DIR, _safe_filename("gen", ext))
|
| 123 |
-
with open(path, "wb") as f:
|
| 124 |
-
f.write(content)
|
| 125 |
return path
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
if
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
f[1].close()
|
| 154 |
-
except Exception:
|
| 155 |
-
pass
|
| 156 |
|
| 157 |
-
if
|
| 158 |
-
raise RuntimeError(f"
|
| 159 |
|
| 160 |
-
ctype =
|
| 161 |
-
if ctype.startswith("video/"):
|
| 162 |
-
|
| 163 |
-
ext = mimetypes.guess_extension(ctype) or ".mp4"
|
| 164 |
-
out_path = os.path.join(OUT_DIR, _safe_filename("gen", ext.lstrip(".")))
|
| 165 |
-
with open(out_path, "wb") as f:
|
| 166 |
-
f.write(resp.content)
|
| 167 |
-
return out_path
|
| 168 |
|
| 169 |
-
#
|
| 170 |
try:
|
| 171 |
-
payload =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
except Exception:
|
| 173 |
-
# fallback
|
| 174 |
-
return
|
| 175 |
-
|
| 176 |
-
video_url = payload.get("video_url")
|
| 177 |
-
if not video_url:
|
| 178 |
-
# Maybe it returned base64? If so, add handling here if needed.
|
| 179 |
-
raise RuntimeError(f"Unexpected response: {json.dumps(payload)[:500]}")
|
| 180 |
|
| 181 |
-
|
| 182 |
-
r2 = requests.get(video_url, stream=True, timeout=600)
|
| 183 |
-
if r2.status_code != 200:
|
| 184 |
-
raise RuntimeError(f"Failed to fetch video from URL: {r2.status_code}")
|
| 185 |
-
ext = mimetypes.guess_extension(r2.headers.get("Content-Type", "")) or ".mp4"
|
| 186 |
-
out_path = os.path.join(OUT_DIR, _safe_filename("gen", ext.lstrip(".")))
|
| 187 |
-
with open(out_path, "wb") as f:
|
| 188 |
-
for chunk in r2.iter_content(chunk_size=1024 * 1024):
|
| 189 |
-
if chunk:
|
| 190 |
-
f.write(chunk)
|
| 191 |
-
return out_path
|
| 192 |
-
|
| 193 |
-
# ================================
|
| 194 |
-
# Gradio UI
|
| 195 |
-
# ================================
|
| 196 |
with gr.Blocks() as demo:
|
| 197 |
-
gr.Markdown("## Continuous Video
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
| 202 |
|
| 203 |
with gr.Row():
|
| 204 |
-
prompt = gr.Textbox(
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
)
|
| 210 |
with gr.Row():
|
| 211 |
-
|
| 212 |
-
|
| 213 |
with gr.Row():
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
files_out = gr.Files(label="Downloads", height=100)
|
| 220 |
-
|
| 221 |
-
# ---------- Handlers ----------
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
try:
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
except Exception as e:
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
with open(err_mp4, "w") as f:
|
| 232 |
-
f.write(str(e))
|
| 233 |
-
return gr.update(value=None), None
|
| 234 |
-
return vid_path, vid_path
|
| 235 |
|
| 236 |
-
|
| 237 |
on_generate,
|
| 238 |
-
inputs=[prompt,
|
| 239 |
-
outputs=[video_out,
|
| 240 |
)
|
| 241 |
|
| 242 |
-
def
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
inputs=[
|
| 259 |
-
outputs=[
|
| 260 |
)
|
| 261 |
|
| 262 |
-
def on_download(
|
| 263 |
-
if not
|
| 264 |
-
|
| 265 |
try:
|
| 266 |
-
|
| 267 |
except Exception as e:
|
| 268 |
-
|
| 269 |
-
concat_path = None
|
| 270 |
-
zip_path = zip_files(used_paths)
|
| 271 |
-
files = [zip_path]
|
| 272 |
-
if concat_path:
|
| 273 |
-
files.insert(0, concat_path)
|
| 274 |
-
return files
|
| 275 |
-
|
| 276 |
-
btn_download.click(
|
| 277 |
-
on_download,
|
| 278 |
-
inputs=[state_used],
|
| 279 |
-
outputs=[files_out],
|
| 280 |
-
)
|
| 281 |
-
|
| 282 |
-
def on_reset():
|
| 283 |
-
# Clear temp files and state
|
| 284 |
try:
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
except Exception:
|
| 290 |
-
pass
|
| 291 |
-
return None, [], None, gr.update(value=None), gr.update(value=None), gr.update(value=[])
|
| 292 |
|
| 293 |
-
|
| 294 |
-
on_reset,
|
| 295 |
-
inputs=None,
|
| 296 |
-
outputs=[state_seed, state_used, state_current, prompt, video_out, files_out],
|
| 297 |
-
)
|
| 298 |
|
| 299 |
if __name__ == "__main__":
|
| 300 |
demo.launch()
|
| 301 |
-
|
|
|
|
| 1 |
+
import os, uuid, time, shutil, mimetypes, subprocess, requests, gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from datetime import datetime
|
| 3 |
+
from typing import Optional, List
|
| 4 |
|
| 5 |
+
# --- config ---
|
| 6 |
+
ENDPOINT = "https://moonmath-ai-dev--moonmath-i2v-backend-moonmathinference-run.modal.run"
|
| 7 |
+
FFMPEG = "ffmpeg"
|
| 8 |
+
OUT, TMP = "outputs", "tmp"
|
| 9 |
+
os.makedirs(OUT, exist_ok=True); os.makedirs(TMP, exist_ok=True)
|
| 10 |
|
| 11 |
+
ts = lambda: datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
| 12 |
+
fname = lambda p,e: f"{p}_{ts()}_{uuid.uuid4().hex[:6]}.{e}"
|
| 13 |
+
abspath= lambda p: os.path.abspath(p)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
def run_ffmpeg(args: List[str]):
|
| 16 |
+
p = subprocess.run([FFMPEG]+args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 17 |
+
if p.returncode:
|
| 18 |
+
raise RuntimeError(p.stderr.decode(errors="ignore"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
def extract_last_frame(video_path: str) -> str:
|
| 21 |
+
out = os.path.join(TMP, fname("last", "png"))
|
| 22 |
+
run_ffmpeg(["-sseof","-1","-i",video_path,"-frames:v","1","-q:v","2",out])
|
| 23 |
+
return out
|
| 24 |
+
|
| 25 |
+
def concat_videos(paths: List[str]) -> str:
|
| 26 |
+
if not paths: raise ValueError("No videos selected.")
|
| 27 |
+
if len(paths)==1:
|
| 28 |
+
dst = os.path.join(OUT, fname("continuous","mp4")); shutil.copy(paths[0], dst); return dst
|
| 29 |
+
listfile = os.path.join(TMP, f"concat_{uuid.uuid4().hex}.txt")
|
| 30 |
+
with open(listfile,"w") as f:
|
| 31 |
+
for p in paths: f.write(f"file '{abspath(p)}'\n")
|
| 32 |
+
out = os.path.join(OUT, fname("continuous","mp4"))
|
| 33 |
+
run_ffmpeg(["-f","concat","-safe","0","-i",listfile,"-c","copy",out])
|
| 34 |
+
os.remove(listfile)
|
| 35 |
+
return out
|
| 36 |
+
|
| 37 |
+
def zip_used(paths: List[str]) -> str:
|
| 38 |
+
pack = os.path.join(TMP, f"pack_{uuid.uuid4().hex[:6]}")
|
| 39 |
+
os.makedirs(pack, exist_ok=True)
|
| 40 |
+
for p in paths: shutil.copy(p, pack)
|
| 41 |
+
base = os.path.join(OUT, f"used_{ts()}")
|
| 42 |
+
shutil.make_archive(base, "zip", pack)
|
| 43 |
+
shutil.rmtree(pack, ignore_errors=True)
|
| 44 |
+
return base + ".zip"
|
| 45 |
+
|
| 46 |
+
def save_video_bytes(content: bytes, content_type: str) -> str:
|
| 47 |
+
ext = (mimetypes.guess_extension(content_type) or ".mp4").lstrip(".")
|
| 48 |
+
path = os.path.join(OUT, fname("gen", ext))
|
| 49 |
+
with open(path,"wb") as f: f.write(content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return path
|
| 51 |
|
| 52 |
+
def call_backend(
|
| 53 |
+
prompt: str,
|
| 54 |
+
image_bytes_path: str,
|
| 55 |
+
negative_prompt: Optional[str],
|
| 56 |
+
fps: int,
|
| 57 |
+
vlen: int,
|
| 58 |
+
steps: Optional[int],
|
| 59 |
+
seed: Optional[int]
|
| 60 |
+
) -> str:
|
| 61 |
+
params = {
|
| 62 |
+
"prompt": prompt,
|
| 63 |
+
"frames_per_second": str(fps),
|
| 64 |
+
"video_length": str(vlen),
|
| 65 |
+
}
|
| 66 |
+
if negative_prompt: params["negative_prompt"] = negative_prompt
|
| 67 |
+
if steps is not None: params["num_inference_steps"] = str(steps)
|
| 68 |
+
if seed is None: seed = int(time.time())
|
| 69 |
+
params["seed"] = str(seed)
|
| 70 |
+
|
| 71 |
+
files = {"image_bytes": (os.path.basename(image_bytes_path), open(image_bytes_path,"rb"),
|
| 72 |
+
"application/octet-stream")}
|
| 73 |
+
try:
|
| 74 |
+
r = requests.post(ENDPOINT, params=params, files=files, headers={"accept":"application/json"}, timeout=600)
|
| 75 |
+
finally:
|
| 76 |
+
try: files["image_bytes"][1].close()
|
| 77 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
if r.status_code != 200:
|
| 80 |
+
raise RuntimeError(f"Backend {r.status_code}: {r.text[:500]}")
|
| 81 |
|
| 82 |
+
ctype = r.headers.get("Content-Type","")
|
| 83 |
+
if ctype.startswith("video/"): # raw video bytes
|
| 84 |
+
return save_video_bytes(r.content, ctype)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
# expect JSON with { "video_url": ... }
|
| 87 |
try:
|
| 88 |
+
payload = r.json()
|
| 89 |
+
url = payload.get("video_url")
|
| 90 |
+
if not url: raise ValueError("no video_url in response")
|
| 91 |
+
r2 = requests.get(url, stream=True, timeout=600)
|
| 92 |
+
if r2.status_code != 200: raise RuntimeError(f"fetch video {r2.status_code}")
|
| 93 |
+
path = os.path.join(OUT, fname("gen","mp4"))
|
| 94 |
+
with open(path,"wb") as f:
|
| 95 |
+
for chunk in r2.iter_content(1<<20):
|
| 96 |
+
if chunk: f.write(chunk)
|
| 97 |
+
return path
|
| 98 |
except Exception:
|
| 99 |
+
# fallback if backend mislabels content
|
| 100 |
+
return save_video_bytes(r.content, ctype or "video/mp4")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# ================= UI =================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
with gr.Blocks() as demo:
|
| 104 |
+
gr.Markdown("## Continuous Video — chain last frame → next first frame")
|
| 105 |
|
| 106 |
+
# state
|
| 107 |
+
used_videos = gr.State([]) # list[str]
|
| 108 |
+
last_seed_img = gr.State(None) # PNG path (becomes image_bytes)
|
| 109 |
+
current_video = gr.State(None) # latest generated video
|
| 110 |
|
| 111 |
with gr.Row():
|
| 112 |
+
prompt = gr.Textbox(label="Prompt", placeholder="Describe your shot…", lines=2)
|
| 113 |
+
with gr.Row():
|
| 114 |
+
start_file = gr.File(
|
| 115 |
+
label="Initial start image or video (only for the very first clip)",
|
| 116 |
+
file_types=["image","video"]
|
| 117 |
)
|
| 118 |
with gr.Row():
|
| 119 |
+
negative = gr.Textbox(label="Negative prompt (optional)", placeholder="What to avoid…")
|
|
|
|
| 120 |
with gr.Row():
|
| 121 |
+
fps = gr.Slider(1,60, value=24, step=1, label="Frames per second")
|
| 122 |
+
vlen = gr.Slider(1,12, value=4, step=1, label="Video length (seconds)")
|
| 123 |
+
steps = gr.Slider(1,100, value=30, step=1, label="Num inference steps (optional)")
|
| 124 |
+
seed = gr.Number(label="Seed (optional)", precision=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
video_out = gr.Video(label="Output")
|
| 127 |
+
status_md = gr.Markdown("") # shows ✅ Saved… after Chain
|
| 128 |
+
with gr.Row():
|
| 129 |
+
gen_btn = gr.Button("Generate", variant="primary")
|
| 130 |
+
chain_btn= gr.Button("Chain (save & clear)")
|
| 131 |
+
dl_btn = gr.Button("Download (concatenate & ZIP)")
|
| 132 |
+
|
| 133 |
+
files_out = gr.Files(label="Downloads")
|
| 134 |
+
|
| 135 |
+
# ---- handlers ----
|
| 136 |
+
def on_generate(prompt_txt, start_file_obj, neg, fps_val, vlen_val, steps_val, seed_val, seed_img):
|
| 137 |
+
if not prompt_txt or not prompt_txt.strip():
|
| 138 |
+
raise gr.Error("Prompt is required.")
|
| 139 |
+
# choose image_bytes source: last stolen frame > uploaded start file
|
| 140 |
+
image_path = seed_img
|
| 141 |
+
if not image_path:
|
| 142 |
+
if not start_file_obj: raise gr.Error("First generation requires an initial image OR video.")
|
| 143 |
+
image_path = start_file_obj.name
|
| 144 |
try:
|
| 145 |
+
out = call_backend(
|
| 146 |
+
prompt=prompt_txt.strip(),
|
| 147 |
+
image_bytes_path=image_path,
|
| 148 |
+
negative_prompt=(neg.strip() if (neg and neg.strip()) else None),
|
| 149 |
+
fps=int(fps_val),
|
| 150 |
+
vlen=int(vlen_val),
|
| 151 |
+
steps=int(steps_val) if steps_val else None,
|
| 152 |
+
seed=int(seed_val) if (seed_val not in [None,""]) else None
|
| 153 |
+
)
|
| 154 |
except Exception as e:
|
| 155 |
+
raise gr.Error(str(e))
|
| 156 |
+
return out, out, gr.update(value="") # show video, set state, clear status
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
+
gen_btn.click(
|
| 159 |
on_generate,
|
| 160 |
+
inputs=[prompt, start_file, negative, fps, vlen, steps, seed, last_seed_img],
|
| 161 |
+
outputs=[video_out, current_video, status_md]
|
| 162 |
)
|
| 163 |
|
| 164 |
+
def on_chain(curr, used):
|
| 165 |
+
"""
|
| 166 |
+
Save current video, steal last frame for next seed,
|
| 167 |
+
and CLEAR: preview, prompt, negative, start_file.
|
| 168 |
+
Also show a visible 'saved' banner.
|
| 169 |
+
"""
|
| 170 |
+
if not curr or not os.path.exists(curr):
|
| 171 |
+
raise gr.Error("Generate a video first.")
|
| 172 |
+
new_used = used[:] if used else []
|
| 173 |
+
if curr not in new_used: new_used.append(curr)
|
| 174 |
+
# last frame for next seed
|
| 175 |
+
seed_img = extract_last_frame(curr)
|
| 176 |
+
saved_idx = len(new_used)
|
| 177 |
+
saved_msg = f"✅ **Saved clip #{saved_idx}** — last frame captured. Ready for your next prompt."
|
| 178 |
+
|
| 179 |
+
return (
|
| 180 |
+
new_used, # used_videos
|
| 181 |
+
seed_img, # last_seed_img (image_bytes for next gen)
|
| 182 |
+
gr.update(value=None), # CLEAR prompt
|
| 183 |
+
gr.update(value=None), # CLEAR negative prompt
|
| 184 |
+
gr.update(value=None), # CLEAR start_file
|
| 185 |
+
gr.update(value=None), # CLEAR video preview
|
| 186 |
+
gr.update(value=saved_msg) # status banner
|
| 187 |
+
)
|
| 188 |
|
| 189 |
+
chain_btn.click(
|
| 190 |
+
on_chain,
|
| 191 |
+
inputs=[current_video, used_videos],
|
| 192 |
+
outputs=[used_videos, last_seed_img, prompt, negative, start_file, video_out, status_md]
|
| 193 |
)
|
| 194 |
|
| 195 |
+
def on_download(used):
|
| 196 |
+
if not used: raise gr.Error("Nothing to download. Click Chain after generating clips.")
|
| 197 |
+
files = []
|
| 198 |
try:
|
| 199 |
+
merged = concat_videos(used); files.append(merged)
|
| 200 |
except Exception as e:
|
| 201 |
+
print("concat error:", e)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
try:
|
| 203 |
+
zipped = zip_used(used); files.append(zipped)
|
| 204 |
+
except Exception as e:
|
| 205 |
+
print("zip error:", e)
|
| 206 |
+
return files
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
+
dl_btn.click(on_download, inputs=[used_videos], outputs=[files_out])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
if __name__ == "__main__":
|
| 211 |
demo.launch()
|
|
|