Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ import os, shutil, subprocess, tempfile, base64, json
|
|
| 6 |
from io import BytesIO
|
| 7 |
from typing import List, Tuple
|
| 8 |
import requests
|
| 9 |
-
from PIL import Image, ImageFile, UnidentifiedImageError
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
# --- Config
|
|
@@ -164,7 +164,7 @@ def ffmpeg_make_browser_mp4(input_path: str, output_path: str, max_width: int =
|
|
| 164 |
"-c:a", "aac", "-b:a", "128k",
|
| 165 |
"-movflags", "+faststart",
|
| 166 |
output_path
|
| 167 |
-
|
| 168 |
try:
|
| 169 |
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout, check=True)
|
| 170 |
return os.path.exists(output_path) and os.path.getsize(output_path) > 0
|
|
@@ -184,13 +184,11 @@ def analyze_video_cohesive(client, video_path: str, prompt: str) -> str:
|
|
| 184 |
except Exception:
|
| 185 |
pass
|
| 186 |
|
| 187 |
-
# If upload failed or not available, try to make a browser-friendly MP4 for Gradio to play and for ffmpeg frame extraction.
|
| 188 |
tmp_fixed = None
|
| 189 |
try:
|
| 190 |
tmp_fd, tmp_fixed = tempfile.mkstemp(suffix=".mp4"); os.close(tmp_fd)
|
| 191 |
ok = ffmpeg_make_browser_mp4(video_path, tmp_fixed, max_width=1280, crf=28, preset="fast", timeout=120)
|
| 192 |
if ok:
|
| 193 |
-
# Use frame extraction on the fixed file for analysis if upload isn't possible
|
| 194 |
frames = extract_best_frames_bytes(tmp_fixed, sample_count=6)
|
| 195 |
else:
|
| 196 |
frames = extract_best_frames_bytes(video_path, sample_count=6)
|
|
@@ -225,6 +223,30 @@ def determine_media_type(src: str) -> Tuple[bool, bool]:
|
|
| 225 |
elif ctype.startswith("video/"): is_video, is_image = True, False
|
| 226 |
return is_image, is_video
|
| 227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
def process_media(src: str, custom_prompt: str, api_key: str, progress=gr.Progress()) -> str:
|
| 229 |
client = get_client(api_key)
|
| 230 |
prompt = (custom_prompt or "").strip() or "Please provide a detailed visual review."
|
|
@@ -286,58 +308,3 @@ def create_demo():
|
|
| 286 |
clear_btn = gr.Button("Clear")
|
| 287 |
output_md = gr.Markdown("")
|
| 288 |
status_state = gr.State("idle")
|
| 289 |
-
|
| 290 |
-
def load_preview(url: str):
|
| 291 |
-
empty_img = gr.update(value=None, visible=False)
|
| 292 |
-
empty_vid = gr.update(value=None, visible=False)
|
| 293 |
-
if not url: return empty_img, empty_vid
|
| 294 |
-
if not is_remote(url) and os.path.exists(url):
|
| 295 |
-
ext = ext_from_src(url)
|
| 296 |
-
if ext in VIDEO_EXTS: return empty_img, gr.update(value=os.path.abspath(url), visible=True)
|
| 297 |
-
if ext in IMAGE_EXTS:
|
| 298 |
-
try:
|
| 299 |
-
img = Image.open(url)
|
| 300 |
-
if getattr(img, "is_animated", False): img.seek(0)
|
| 301 |
-
return gr.update(value=img.convert("RGB"), visible=True), empty_vid
|
| 302 |
-
except Exception: return empty_img, empty_vid
|
| 303 |
-
head = safe_head(url)
|
| 304 |
-
if head:
|
| 305 |
-
ctype = (head.headers.get("content-type") or "").lower()
|
| 306 |
-
if ctype.startswith("video/") or any(url.lower().endswith(ext) for ext in VIDEO_EXTS):
|
| 307 |
-
return empty_img, gr.update(value=url, visible=True)
|
| 308 |
-
try:
|
| 309 |
-
r = safe_get(url, timeout=15)
|
| 310 |
-
img = Image.open(BytesIO(r.content))
|
| 311 |
-
if getattr(img, "is_animated", False): img.seek(0)
|
| 312 |
-
return gr.update(value=img.convert("RGB"), visible=True), empty_vid
|
| 313 |
-
except Exception:
|
| 314 |
-
return empty_img, empty_vid
|
| 315 |
-
|
| 316 |
-
url_input.change(fn=load_preview, inputs=[url_input], outputs=[preview_image, preview_video])
|
| 317 |
-
|
| 318 |
-
def clear_all():
|
| 319 |
-
return "", gr.update(value=None, visible=False), gr.update(value=None, visible=False), "idle", gr.update(value=_btn_label_for_status("idle"))
|
| 320 |
-
clear_btn.click(fn=clear_all, inputs=[], outputs=[url_input, preview_image, preview_video, status_state, submit_btn])
|
| 321 |
-
|
| 322 |
-
def start_busy():
|
| 323 |
-
s = "busy"
|
| 324 |
-
return s, gr.update(value=_btn_label_for_status(s))
|
| 325 |
-
submit_btn.click(fn=start_busy, inputs=[], outputs=[status_state, submit_btn])
|
| 326 |
-
|
| 327 |
-
def worker(url: str, prompt: str, key: str, progress=gr.Progress()):
|
| 328 |
-
return process_media(url or "", prompt or "", key or "", progress=progress)
|
| 329 |
-
submit_btn.click(fn=worker, inputs=[url_input, custom_prompt, api_key], outputs=[output_md], queue=True).then(
|
| 330 |
-
fn=lambda res: ("error", "**Error:** no result returned.") if not res else
|
| 331 |
-
("error", f"**Error:** {res}") if isinstance(res, str) and res.lower().startswith("error") else ("done", res),
|
| 332 |
-
inputs=[output_md],
|
| 333 |
-
outputs=[status_state, output_md],
|
| 334 |
-
)
|
| 335 |
-
|
| 336 |
-
def btn_label_for_state(s: str):
|
| 337 |
-
return _btn_label_for_status(s)
|
| 338 |
-
status_state.change(fn=btn_label_for_state, inputs=[status_state], outputs=[submit_btn])
|
| 339 |
-
|
| 340 |
-
return demo
|
| 341 |
-
|
| 342 |
-
if __name__ == "__main__":
|
| 343 |
-
create_demo().launch()
|
|
|
|
| 6 |
from io import BytesIO
|
| 7 |
from typing import List, Tuple
|
| 8 |
import requests
|
| 9 |
+
from PIL import Image, ImageFile, UnidentifiedImageError, ImageSequence
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
# --- Config
|
|
|
|
| 164 |
"-c:a", "aac", "-b:a", "128k",
|
| 165 |
"-movflags", "+faststart",
|
| 166 |
output_path
|
| 167 |
+
]
|
| 168 |
try:
|
| 169 |
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout, check=True)
|
| 170 |
return os.path.exists(output_path) and os.path.getsize(output_path) > 0
|
|
|
|
| 184 |
except Exception:
|
| 185 |
pass
|
| 186 |
|
|
|
|
| 187 |
tmp_fixed = None
|
| 188 |
try:
|
| 189 |
tmp_fd, tmp_fixed = tempfile.mkstemp(suffix=".mp4"); os.close(tmp_fd)
|
| 190 |
ok = ffmpeg_make_browser_mp4(video_path, tmp_fixed, max_width=1280, crf=28, preset="fast", timeout=120)
|
| 191 |
if ok:
|
|
|
|
| 192 |
frames = extract_best_frames_bytes(tmp_fixed, sample_count=6)
|
| 193 |
else:
|
| 194 |
frames = extract_best_frames_bytes(video_path, sample_count=6)
|
|
|
|
| 223 |
elif ctype.startswith("video/"): is_video, is_image = True, False
|
| 224 |
return is_image, is_video
|
| 225 |
|
| 226 |
+
def save_bytes_to_temp(data: bytes, suffix: str = ".dat") -> str:
|
| 227 |
+
fd, path = tempfile.mkstemp(suffix=suffix)
|
| 228 |
+
os.close(fd)
|
| 229 |
+
with open(path, "wb") as fh:
|
| 230 |
+
fh.write(data)
|
| 231 |
+
return path
|
| 232 |
+
|
| 233 |
+
def convert_to_jpeg_bytes(data: bytes, base_h: int = 1024) -> bytes:
|
| 234 |
+
buf = BytesIO(data)
|
| 235 |
+
img = Image.open(buf)
|
| 236 |
+
if getattr(img, "is_animated", False):
|
| 237 |
+
img = next(ImageSequence.Iterator(img))
|
| 238 |
+
img = img.convert("RGB")
|
| 239 |
+
w, h = img.size
|
| 240 |
+
if h > base_h:
|
| 241 |
+
new_w = int(w * (base_h / h))
|
| 242 |
+
img = img.resize((new_w, base_h), Image.LANCZOS)
|
| 243 |
+
out = BytesIO()
|
| 244 |
+
img.save(out, format="JPEG", quality=90, optimize=True)
|
| 245 |
+
return out.getvalue()
|
| 246 |
+
|
| 247 |
+
def b64_bytes(data: bytes, mime: str = "image/jpeg") -> str:
|
| 248 |
+
return "data:" + mime + ";base64," + base64.b64encode(data).decode("ascii")
|
| 249 |
+
|
| 250 |
def process_media(src: str, custom_prompt: str, api_key: str, progress=gr.Progress()) -> str:
|
| 251 |
client = get_client(api_key)
|
| 252 |
prompt = (custom_prompt or "").strip() or "Please provide a detailed visual review."
|
|
|
|
| 308 |
clear_btn = gr.Button("Clear")
|
| 309 |
output_md = gr.Markdown("")
|
| 310 |
status_state = gr.State("idle")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|