Shalmoni commited on
Commit
62998c3
·
verified ·
1 Parent(s): d1795bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -263
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 List, Optional
12
 
13
- import gradio as gr
14
- from PIL import Image
 
 
 
15
 
16
- # ================================
17
- # Config
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
- # If ffmpeg is not on PATH for any reason, set absolute path here
26
- FFMPEG_BIN = "ffmpeg"
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
- Extract the very last frame as PNG using ffmpeg.
50
- Uses -sseof -1 to seek to the last second.
51
- """
52
- out_path = os.path.join(TMP_DIR, _safe_filename("lastframe", "png"))
53
- # Seek to last second and output a single frame
54
- _run_ffmpeg([
55
- "-sseof", "-1",
56
- "-i", video_path,
57
- "-update", "1",
58
- "-frames:v", "1",
59
- "-q:v", "2",
60
- out_path
61
- ])
62
- return out_path
63
-
64
- def concat_videos_ffmpeg(video_paths: List[str]) -> str:
65
- """
66
- Concatenate MP4s using ffmpeg concat demuxer.
67
- """
68
- if len(video_paths) == 1:
69
- # copy the single file to a new name to keep UX consistent
70
- dst = os.path.join(OUT_DIR, _safe_filename("continuous", "mp4"))
71
- shutil.copy(video_paths[0], dst)
72
- return dst
73
-
74
- list_file = os.path.join(TMP_DIR, f"concat_{uuid.uuid4().hex}.txt")
75
- with open(list_file, "w") as f:
76
- for p in video_paths:
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
- # Backend call
129
- # ================================
130
- def call_generator(prompt: str, seed_frame_path: Optional[str]) -> str:
131
- """
132
- Calls your Modal endpoint. Supports two response modes:
133
- 1) Direct video bytes (Content-Type like video/mp4)
134
- 2) JSON with {"video_url": "..."} which we then download.
135
-
136
- We send:
137
- - form field: prompt
138
- - optional file: seed_frame (PNG/JPG)
139
- """
140
- files = {}
141
- data = {"prompt": prompt}
142
-
143
- if seed_frame_path and os.path.exists(seed_frame_path):
144
- files["seed_frame"] = (os.path.basename(seed_frame_path), open(seed_frame_path, "rb"), "image/png")
145
-
146
- # Make the request
147
- resp = requests.post(ENDPOINT_URL, data=data, files=files, timeout=600)
148
- if files:
149
- # close file handles
150
- for _, f in files.items():
151
- # f is a tuple (name, fileobj, mimetype)
152
- try:
153
- f[1].close()
154
- except Exception:
155
- pass
156
 
157
- if resp.status_code != 200:
158
- raise RuntimeError(f"Generator returned {resp.status_code}: {resp.text[:500]}")
159
 
160
- ctype = resp.headers.get("Content-Type", "")
161
- if ctype.startswith("video/"):
162
- # Direct bytes
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
- # Assume JSON with URL
170
  try:
171
- payload = resp.json()
 
 
 
 
 
 
 
 
 
172
  except Exception:
173
- # fallback: treat body as raw mp4
174
- return save_bytes_to_file(resp.content, "mp4")
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
- # Download the video
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 (Prompt UseChain Download)")
198
 
199
- state_used = gr.State([]) # list[str] of used clip paths
200
- state_seed = gr.State(None) # path to last-frame image
201
- state_current = gr.State(None) # most recent generated video path
 
202
 
203
  with gr.Row():
204
- prompt = gr.Textbox(
205
- label="Prompt",
206
- placeholder="Describe your next shot…",
207
- lines=2,
208
- autofocus=True
209
  )
210
  with gr.Row():
211
- video_out = gr.Video(label="Video Output", interactive=False)
212
-
213
  with gr.Row():
214
- btn_generate = gr.Button("Generate", variant="primary")
215
- btn_use = gr.Button("Chain")
216
- btn_download = gr.Button("Download All")
217
- btn_reset = gr.Button("Reset Session", variant="stop")
218
-
219
- files_out = gr.Files(label="Downloads", height=100)
220
-
221
- # ---------- Handlers ----------
222
 
223
- def on_generate(prompt_text, seed_frame):
224
- if not prompt_text or not prompt_text.strip():
225
- return gr.update(value=None), None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  try:
227
- vid_path = call_generator(prompt_text.strip(), seed_frame)
 
 
 
 
 
 
 
 
228
  except Exception as e:
229
- # Surface the error in the UI
230
- err_mp4 = os.path.join(OUT_DIR, _safe_filename("error", "txt"))
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
- btn_generate.click(
237
  on_generate,
238
- inputs=[prompt, state_seed],
239
- outputs=[video_out, state_current],
240
  )
241
 
242
- def on_use(current_path, used_paths):
243
- if not current_path or not os.path.exists(current_path):
244
- return used_paths, None
245
- new_used = list(used_paths)
246
- if current_path not in new_used:
247
- new_used.append(current_path)
248
- # Extract last frame -> seed for next gen
249
- try:
250
- seed_img = extract_last_frame(current_path)
251
- except Exception as e:
252
- # If extraction fails, keep chaining logic but without seed
253
- seed_img = None
254
- return new_used, seed_img
 
 
 
 
 
 
 
 
 
 
 
255
 
256
- btn_use.click(
257
- on_use,
258
- inputs=[state_current, state_used],
259
- outputs=[state_used, state_seed],
260
  )
261
 
262
- def on_download(used_paths):
263
- if not used_paths:
264
- return []
265
  try:
266
- concat_path = concat_videos_ffmpeg(used_paths)
267
  except Exception as e:
268
- # If concat fails, skip it but still offer the ZIP
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
- for f in os.listdir(TMP_DIR):
286
- fp = os.path.join(TMP_DIR, f)
287
- if os.path.isfile(fp):
288
- os.remove(fp)
289
- except Exception:
290
- pass
291
- return None, [], None, gr.update(value=None), gr.update(value=None), gr.update(value=[])
292
 
293
- btn_reset.click(
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()