Shalmoni commited on
Commit
1addcdc
·
verified ·
1 Parent(s): c576104

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -25
app.py CHANGED
@@ -1,8 +1,8 @@
1
- import os, uuid, time, json, 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"
@@ -83,7 +83,7 @@ def call_backend(
83
  if ctype.startswith("video/"): # raw video bytes
84
  return save_video_bytes(r.content, ctype)
85
 
86
- # expect JSON with { "video_url": ... } or direct mp4 URL
87
  try:
88
  payload = r.json()
89
  url = payload.get("video_url")
@@ -96,37 +96,43 @@ def call_backend(
96
  if chunk: f.write(chunk)
97
  return path
98
  except Exception:
99
- # if backend returns direct bytes but mislabeled JSON, fallback
100
  return save_video_bytes(r.content, ctype or "video/mp4")
101
 
 
102
  with gr.Blocks() as demo:
103
  gr.Markdown("## Continuous Video — chain last frame → next first frame")
104
 
105
  # state
106
  used_videos = gr.State([]) # list[str]
107
- last_seed_img = gr.State(None) # str path (PNG) to send as image_bytes
108
- current_video = gr.State(None) # str path
109
 
110
  with gr.Row():
111
  prompt = gr.Textbox(label="Prompt", placeholder="Describe your shot…", lines=2)
112
  with gr.Row():
113
- start_file = gr.File(label="Initial start image or video (only needed for the very first clip)", file_types=["image","video"])
 
 
 
114
  with gr.Row():
115
  negative = gr.Textbox(label="Negative prompt (optional)", placeholder="What to avoid…")
116
  with gr.Row():
117
  fps = gr.Slider(1,60, value=24, step=1, label="Frames per second")
118
  vlen = gr.Slider(1,12, value=4, step=1, label="Video length (seconds)")
119
- steps = gr.Slider(1,100, value=30, step=1, label="Num inference steps (optional)", interactive=True)
120
- seed = gr.Number(label="Seed (optional)", precision=0, value=None)
121
 
122
  video_out = gr.Video(label="Output")
 
123
  with gr.Row():
124
  gen_btn = gr.Button("Generate", variant="primary")
125
- use_btn = gr.Button("Chain")
126
  dl_btn = gr.Button("Download")
127
 
128
  files_out = gr.Files(label="Downloads")
129
 
 
130
  def on_generate(prompt_txt, start_file_obj, neg, fps_val, vlen_val, steps_val, seed_val, seed_img):
131
  if not prompt_txt or not prompt_txt.strip():
132
  raise gr.Error("Prompt is required.")
@@ -147,37 +153,51 @@ with gr.Blocks() as demo:
147
  )
148
  except Exception as e:
149
  raise gr.Error(str(e))
150
- return out, out # preview path, current_video state
151
 
152
  gen_btn.click(
153
  on_generate,
154
  inputs=[prompt, start_file, negative, fps, vlen, steps, seed, last_seed_img],
155
- outputs=[video_out, current_video]
156
  )
157
 
158
- def on_use(curr, used):
 
 
 
 
 
159
  if not curr or not os.path.exists(curr):
160
  raise gr.Error("Generate a video first.")
161
- if curr not in used: used = used + [curr]
162
- try:
163
- seed_img = extract_last_frame(curr)
164
- except Exception as e:
165
- raise gr.Error(f"Could not extract last frame: {e}")
166
- return used, seed_img
167
-
168
- use_btn.click(
169
- on_use,
 
 
 
 
 
 
 
 
 
 
170
  inputs=[current_video, used_videos],
171
- outputs=[used_videos, last_seed_img]
172
  )
173
 
174
  def on_download(used):
175
- if not used: raise gr.Error("Nothing to download. Click Use after generating clips.")
176
  files = []
177
  try:
178
  merged = concat_videos(used); files.append(merged)
179
  except Exception as e:
180
- # still allow ZIP even if concat fails
181
  print("concat error:", e)
182
  try:
183
  zipped = zip_used(used); files.append(zipped)
 
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"
 
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")
 
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")
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.")
 
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)