Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ import shutil
|
|
| 6 |
from io import BytesIO
|
| 7 |
import base64
|
| 8 |
import requests
|
| 9 |
-
from PIL import Image, UnidentifiedImageError
|
| 10 |
import gradio as gr
|
| 11 |
from mistralai import Mistral
|
| 12 |
|
|
@@ -14,6 +14,7 @@ DEFAULT_KEY = os.getenv("MISTRAL_API_KEY", "")
|
|
| 14 |
DEFAULT_IMAGE_MODEL = "pixtral-12b-2409"
|
| 15 |
DEFAULT_VIDEO_MODEL = "voxtral-mini-latest"
|
| 16 |
STREAM_THRESHOLD = 20 * 1024 * 1024
|
|
|
|
| 17 |
|
| 18 |
SYSTEM_INSTRUCTION = (
|
| 19 |
"You are a clinical visual analyst. Only analyze media actually provided (image data or extracted frames). "
|
|
@@ -25,6 +26,9 @@ SYSTEM_INSTRUCTION = (
|
|
| 25 |
IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp", ".gif")
|
| 26 |
VIDEO_EXTS = (".mp4", ".mov", ".webm", ".mkv", ".avi", ".flv")
|
| 27 |
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def get_client(key: str = None):
|
| 30 |
api_key = (key or "").strip() or DEFAULT_KEY
|
|
@@ -48,16 +52,18 @@ def fetch_bytes(src: str, stream_threshold=STREAM_THRESHOLD, timeout=60) -> byte
|
|
| 48 |
if cl and int(cl) > stream_threshold:
|
| 49 |
fd, path = tempfile.mkstemp()
|
| 50 |
os.close(fd)
|
| 51 |
-
with open(path, "wb") as f:
|
| 52 |
-
for chunk in r.iter_content(8192):
|
| 53 |
-
if chunk:
|
| 54 |
-
f.write(chunk)
|
| 55 |
-
with open(path, "rb") as f:
|
| 56 |
-
data = f.read()
|
| 57 |
try:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return data
|
| 62 |
return r.content
|
| 63 |
with open(src, "rb") as f:
|
|
@@ -93,46 +99,19 @@ def save_bytes_to_temp(b: bytes, suffix: str):
|
|
| 93 |
return path
|
| 94 |
|
| 95 |
|
| 96 |
-
def
|
| 97 |
-
if not
|
| 98 |
-
return
|
| 99 |
-
data = getattr(chunk, "data", None) or getattr(chunk, "response", None) or getattr(chunk, "delta", None)
|
| 100 |
-
if not data:
|
| 101 |
-
return None
|
| 102 |
-
try:
|
| 103 |
-
content = data.choices[0].delta.content
|
| 104 |
-
if content is None:
|
| 105 |
-
return None
|
| 106 |
-
return str(content)
|
| 107 |
-
except Exception:
|
| 108 |
-
pass
|
| 109 |
-
try:
|
| 110 |
-
msg = data.choices[0].message
|
| 111 |
-
if isinstance(msg, dict):
|
| 112 |
-
content = msg.get("content")
|
| 113 |
-
else:
|
| 114 |
-
content = getattr(msg, "content", None)
|
| 115 |
-
if content is None:
|
| 116 |
-
return None
|
| 117 |
-
return str(content)
|
| 118 |
-
except Exception:
|
| 119 |
-
pass
|
| 120 |
-
try:
|
| 121 |
-
return str(data)
|
| 122 |
-
except Exception:
|
| 123 |
-
return None
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
def extract_best_frame_bytes(media_path: str, sample_count: int = 5, timeout_probe: int = 10, timeout_extract: int = 15):
|
| 127 |
-
ffmpeg = shutil.which("ffmpeg")
|
| 128 |
-
if not ffmpeg or not os.path.exists(media_path):
|
| 129 |
-
return None
|
| 130 |
tmp_frames = []
|
| 131 |
try:
|
| 132 |
-
probe_cmd = [
|
| 133 |
"-of", "default=noprint_wrappers=1:nokey=1", media_path]
|
| 134 |
proc = subprocess.Popen(probe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
duration = None
|
| 137 |
try:
|
| 138 |
duration = float(out.strip().split(b"\n")[0]) if out else None
|
|
@@ -148,7 +127,7 @@ def extract_best_frame_bytes(media_path: str, sample_count: int = 5, timeout_pro
|
|
| 148 |
fd, tmp_frame = tempfile.mkstemp(suffix=f"_{i}.jpg")
|
| 149 |
os.close(fd)
|
| 150 |
cmd = [
|
| 151 |
-
|
| 152 |
"-ss", str(t),
|
| 153 |
"-frames:v", "1",
|
| 154 |
"-q:v", "2",
|
|
@@ -164,29 +143,18 @@ def extract_best_frame_bytes(media_path: str, sample_count: int = 5, timeout_pro
|
|
| 164 |
pass
|
| 165 |
proc.communicate()
|
| 166 |
if proc.returncode == 0 and os.path.exists(tmp_frame) and os.path.getsize(tmp_frame) > 0:
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
try:
|
| 170 |
-
if os.path.exists(tmp_frame):
|
| 171 |
-
os.remove(tmp_frame)
|
| 172 |
-
except Exception:
|
| 173 |
-
pass
|
| 174 |
-
|
| 175 |
-
if not tmp_frames:
|
| 176 |
-
return None
|
| 177 |
-
|
| 178 |
-
chosen = max(tmp_frames, key=lambda p: os.path.getsize(p) if os.path.exists(p) else 0)
|
| 179 |
-
with open(chosen, "rb") as f:
|
| 180 |
-
data = f.read()
|
| 181 |
-
return data
|
| 182 |
-
finally:
|
| 183 |
-
for fpath in tmp_frames:
|
| 184 |
try:
|
| 185 |
-
if os.path.exists(
|
| 186 |
-
os.remove(
|
| 187 |
except Exception:
|
| 188 |
pass
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
def upload_file_to_mistral(client, path, filename=None, purpose="batch"):
|
| 192 |
fname = filename or os.path.basename(path)
|
|
@@ -219,11 +187,9 @@ def upload_file_to_mistral(client, path, filename=None, purpose="batch"):
|
|
| 219 |
|
| 220 |
|
| 221 |
def build_messages_for_image(prompt: str, b64_jpg: str = None, image_url: str = None):
|
| 222 |
-
# Keep user-visible prompt and include a single string content containing a data URL or image URL.
|
| 223 |
if image_url:
|
| 224 |
content = f"{prompt}\n\nImage: {image_url}"
|
| 225 |
elif b64_jpg:
|
| 226 |
-
# Use explicit data URL so Mistral chat content is a single string (fixes Pydantic validation)
|
| 227 |
content = f"{prompt}\n\nImage (base64): data:image/jpeg;base64,{b64_jpg}"
|
| 228 |
else:
|
| 229 |
raise ValueError("Either image_url or b64_jpg required")
|
|
@@ -234,6 +200,36 @@ def build_messages_for_text(prompt: str, extra_text: str):
|
|
| 234 |
return [{"role": "system", "content": SYSTEM_INSTRUCTION}, {"role": "user", "content": f"{prompt}\n\n{extra_text}"}]
|
| 235 |
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def extract_text_from_response(res, parts: list):
|
| 238 |
try:
|
| 239 |
choices = getattr(res, "choices", None) or res.get("choices", [])
|
|
@@ -265,60 +261,87 @@ def extract_text_from_response(res, parts: list):
|
|
| 265 |
|
| 266 |
|
| 267 |
def stream_and_collect(client, model, messages, parts: list):
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
|
|
|
| 291 |
nm = m.copy()
|
| 292 |
-
nm["content"] =
|
| 293 |
norm_msgs.append(nm)
|
| 294 |
else:
|
| 295 |
-
|
| 296 |
-
nm = m.copy()
|
| 297 |
-
nm["content"] = str(c or "")
|
| 298 |
-
norm_msgs.append(nm)
|
| 299 |
-
else:
|
| 300 |
-
norm_msgs.append(m)
|
| 301 |
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
| 303 |
stream_gen = None
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
|
| 324 |
def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
@@ -328,31 +351,25 @@ def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
| 328 |
is_image = ext in IMAGE_EXTS or (not is_remote(src) and os.path.isfile(src) and ext in IMAGE_EXTS)
|
| 329 |
parts = []
|
| 330 |
|
| 331 |
-
# IMAGE path: keep exactly the previous behavior but send content as a single string data URL
|
| 332 |
if is_image:
|
| 333 |
try:
|
| 334 |
if is_remote(src):
|
| 335 |
-
|
|
|
|
| 336 |
else:
|
| 337 |
raw = fetch_bytes(src)
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
except Exception as e:
|
| 342 |
return f"Error processing image: {e}"
|
| 343 |
-
stream_and_collect(client, DEFAULT_IMAGE_MODEL, msgs, parts)
|
| 344 |
-
return "".join(parts).strip()
|
| 345 |
|
| 346 |
-
# REMOTE VIDEO path
|
| 347 |
if is_remote(src):
|
|
|
|
| 348 |
try:
|
| 349 |
media_bytes = fetch_bytes(src, timeout=120)
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
ext = ext_from_src(src) or ".mp4"
|
| 353 |
-
tmp_media = save_bytes_to_temp(media_bytes, suffix=ext)
|
| 354 |
-
try:
|
| 355 |
-
# Try uploading full video to Mistral files first
|
| 356 |
try:
|
| 357 |
file_id = upload_file_to_mistral(client, tmp_media, filename=os.path.basename(src.split("?")[0]))
|
| 358 |
extra = (
|
|
@@ -362,19 +379,11 @@ def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
| 362 |
msgs = build_messages_for_text(prompt, extra)
|
| 363 |
stream_and_collect(client, DEFAULT_VIDEO_MODEL, msgs, parts)
|
| 364 |
return "".join(parts).strip()
|
| 365 |
-
except Exception
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
try:
|
| 371 |
-
jpg = convert_to_jpeg_bytes(frame_bytes, base_h=480)
|
| 372 |
-
except UnidentifiedImageError:
|
| 373 |
-
jpg = frame_bytes
|
| 374 |
-
b64 = b64_jpeg(jpg)
|
| 375 |
-
msgs = build_messages_for_image(prompt, b64_jpg=b64)
|
| 376 |
-
stream_and_collect(client, DEFAULT_VIDEO_MODEL, msgs, parts)
|
| 377 |
-
return "".join(parts).strip()
|
| 378 |
finally:
|
| 379 |
try:
|
| 380 |
if tmp_media and os.path.exists(tmp_media):
|
|
@@ -382,7 +391,6 @@ def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
| 382 |
except Exception:
|
| 383 |
pass
|
| 384 |
|
| 385 |
-
# LOCAL VIDEO path
|
| 386 |
tmp_media = None
|
| 387 |
try:
|
| 388 |
media_bytes = fetch_bytes(src)
|
|
@@ -390,7 +398,6 @@ def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
| 390 |
ext = ext or ".mp4"
|
| 391 |
tmp_media = save_bytes_to_temp(media_bytes, suffix=ext)
|
| 392 |
try:
|
| 393 |
-
# Upload local video file to Mistral files and analyze by file id
|
| 394 |
file_id = upload_file_to_mistral(client, tmp_media, filename=os.path.basename(src))
|
| 395 |
extra = (
|
| 396 |
f"Local video uploaded to Mistral Files with id: {file_id}\n\n"
|
|
@@ -400,15 +407,10 @@ def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
| 400 |
stream_and_collect(client, DEFAULT_VIDEO_MODEL, msgs, parts)
|
| 401 |
return "".join(parts).strip()
|
| 402 |
except Exception:
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
if not frame_bytes:
|
| 406 |
return "Unable to process the provided file. Provide a direct image/frame URL or a remote video URL."
|
| 407 |
-
|
| 408 |
-
b64 = b64_jpeg(jpg)
|
| 409 |
-
msgs = build_messages_for_image(prompt, b64_jpg=b64)
|
| 410 |
-
stream_and_collect(client, DEFAULT_VIDEO_MODEL, msgs, parts)
|
| 411 |
-
return "".join(parts).strip()
|
| 412 |
finally:
|
| 413 |
try:
|
| 414 |
if tmp_media and os.path.exists(tmp_media):
|
|
@@ -419,16 +421,13 @@ def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
| 419 |
|
| 420 |
css = ".preview_media img, .preview_media video { max-width: 100%; height: auto; }"
|
| 421 |
|
| 422 |
-
|
| 423 |
def load_preview(url: str):
|
| 424 |
-
# Return (image_or_None, video_or_None, status_text)
|
| 425 |
if not url:
|
| 426 |
return None, None, ""
|
| 427 |
try:
|
| 428 |
r = requests.get(url, timeout=30, stream=True)
|
| 429 |
r.raise_for_status()
|
| 430 |
ctype = (r.headers.get("content-type") or "").lower()
|
| 431 |
-
# If content-type indicates video or URL ends with a video ext, return video preview
|
| 432 |
if (ctype and ctype.startswith("video/")) or any(url.lower().split("?")[0].endswith(ext) for ext in VIDEO_EXTS):
|
| 433 |
return None, url, "Video"
|
| 434 |
data = r.content
|
|
@@ -451,17 +450,16 @@ with gr.Blocks(title="Flux", css=css) as demo:
|
|
| 451 |
with gr.Accordion("Mistral API Key (optional)", open=False):
|
| 452 |
api_key = gr.Textbox(label="API Key", type="password", max_lines=1)
|
| 453 |
submit = gr.Button("Submit")
|
| 454 |
-
preview_image = gr.Image(label="Preview", type="pil", elem_classes="preview_media")
|
| 455 |
-
preview_video = gr.Video(label="Preview", elem_classes="preview_media")
|
| 456 |
|
| 457 |
with gr.Column(scale=2):
|
| 458 |
final_text = gr.Markdown(value="")
|
| 459 |
|
| 460 |
-
# Ensure preview outputs get None when not applicable so Gradio hides them
|
| 461 |
url_input.change(fn=load_preview, inputs=[url_input], outputs=[preview_image, preview_video, gr.Textbox(visible=False)])
|
| 462 |
submit.click(fn=generate_final_text, inputs=[url_input, custom_prompt, api_key], outputs=[final_text])
|
| 463 |
demo.queue()
|
| 464 |
|
| 465 |
if __name__ == "__main__":
|
| 466 |
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
|
| 467 |
-
|
|
|
|
| 6 |
from io import BytesIO
|
| 7 |
import base64
|
| 8 |
import requests
|
| 9 |
+
from PIL import Image, UnidentifiedImageError, ImageFile
|
| 10 |
import gradio as gr
|
| 11 |
from mistralai import Mistral
|
| 12 |
|
|
|
|
| 14 |
DEFAULT_IMAGE_MODEL = "pixtral-12b-2409"
|
| 15 |
DEFAULT_VIDEO_MODEL = "voxtral-mini-latest"
|
| 16 |
STREAM_THRESHOLD = 20 * 1024 * 1024
|
| 17 |
+
FFMPEG_BIN = shutil.which("ffmpeg")
|
| 18 |
|
| 19 |
SYSTEM_INSTRUCTION = (
|
| 20 |
"You are a clinical visual analyst. Only analyze media actually provided (image data or extracted frames). "
|
|
|
|
| 26 |
IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp", ".gif")
|
| 27 |
VIDEO_EXTS = (".mp4", ".mov", ".webm", ".mkv", ".avi", ".flv")
|
| 28 |
|
| 29 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 30 |
+
Image.MAX_IMAGE_PIXELS = 10000 * 10000
|
| 31 |
+
|
| 32 |
|
| 33 |
def get_client(key: str = None):
|
| 34 |
api_key = (key or "").strip() or DEFAULT_KEY
|
|
|
|
| 52 |
if cl and int(cl) > stream_threshold:
|
| 53 |
fd, path = tempfile.mkstemp()
|
| 54 |
os.close(fd)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
+
with open(path, "wb") as f:
|
| 57 |
+
for chunk in r.iter_content(8192):
|
| 58 |
+
if chunk:
|
| 59 |
+
f.write(chunk)
|
| 60 |
+
with open(path, "rb") as f:
|
| 61 |
+
data = f.read()
|
| 62 |
+
finally:
|
| 63 |
+
try:
|
| 64 |
+
os.remove(path)
|
| 65 |
+
except Exception:
|
| 66 |
+
pass
|
| 67 |
return data
|
| 68 |
return r.content
|
| 69 |
with open(src, "rb") as f:
|
|
|
|
| 99 |
return path
|
| 100 |
|
| 101 |
|
| 102 |
+
def extract_best_frames_bytes(media_path: str, sample_count: int = 5, timeout_probe: int = 10, timeout_extract: int = 15):
|
| 103 |
+
if not FFMPEG_BIN or not os.path.exists(media_path):
|
| 104 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
tmp_frames = []
|
| 106 |
try:
|
| 107 |
+
probe_cmd = [FFMPEG_BIN, "-v", "error", "-show_entries", "format=duration",
|
| 108 |
"-of", "default=noprint_wrappers=1:nokey=1", media_path]
|
| 109 |
proc = subprocess.Popen(probe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 110 |
+
try:
|
| 111 |
+
out, _ = proc.communicate(timeout=timeout_probe)
|
| 112 |
+
except subprocess.TimeoutExpired:
|
| 113 |
+
proc.kill()
|
| 114 |
+
out, _ = proc.communicate()
|
| 115 |
duration = None
|
| 116 |
try:
|
| 117 |
duration = float(out.strip().split(b"\n")[0]) if out else None
|
|
|
|
| 127 |
fd, tmp_frame = tempfile.mkstemp(suffix=f"_{i}.jpg")
|
| 128 |
os.close(fd)
|
| 129 |
cmd = [
|
| 130 |
+
FFMPEG_BIN, "-nostdin", "-y", "-i", media_path,
|
| 131 |
"-ss", str(t),
|
| 132 |
"-frames:v", "1",
|
| 133 |
"-q:v", "2",
|
|
|
|
| 143 |
pass
|
| 144 |
proc.communicate()
|
| 145 |
if proc.returncode == 0 and os.path.exists(tmp_frame) and os.path.getsize(tmp_frame) > 0:
|
| 146 |
+
with open(tmp_frame, "rb") as f:
|
| 147 |
+
tmp_frames.append(f.read())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
try:
|
| 149 |
+
if os.path.exists(tmp_frame):
|
| 150 |
+
os.remove(tmp_frame)
|
| 151 |
except Exception:
|
| 152 |
pass
|
| 153 |
|
| 154 |
+
return tmp_frames
|
| 155 |
+
finally:
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
|
| 159 |
def upload_file_to_mistral(client, path, filename=None, purpose="batch"):
|
| 160 |
fname = filename or os.path.basename(path)
|
|
|
|
| 187 |
|
| 188 |
|
| 189 |
def build_messages_for_image(prompt: str, b64_jpg: str = None, image_url: str = None):
|
|
|
|
| 190 |
if image_url:
|
| 191 |
content = f"{prompt}\n\nImage: {image_url}"
|
| 192 |
elif b64_jpg:
|
|
|
|
| 193 |
content = f"{prompt}\n\nImage (base64): data:image/jpeg;base64,{b64_jpg}"
|
| 194 |
else:
|
| 195 |
raise ValueError("Either image_url or b64_jpg required")
|
|
|
|
| 200 |
return [{"role": "system", "content": SYSTEM_INSTRUCTION}, {"role": "user", "content": f"{prompt}\n\n{extra_text}"}]
|
| 201 |
|
| 202 |
|
| 203 |
+
def extract_delta(chunk):
|
| 204 |
+
if not chunk:
|
| 205 |
+
return None
|
| 206 |
+
data = getattr(chunk, "data", None) or getattr(chunk, "response", None) or getattr(chunk, "delta", None)
|
| 207 |
+
if not data:
|
| 208 |
+
return None
|
| 209 |
+
try:
|
| 210 |
+
content = data.choices[0].delta.content
|
| 211 |
+
if content is None:
|
| 212 |
+
return None
|
| 213 |
+
return str(content)
|
| 214 |
+
except Exception:
|
| 215 |
+
pass
|
| 216 |
+
try:
|
| 217 |
+
msg = data.choices[0].message
|
| 218 |
+
if isinstance(msg, dict):
|
| 219 |
+
content = msg.get("content")
|
| 220 |
+
else:
|
| 221 |
+
content = getattr(msg, "content", None)
|
| 222 |
+
if content is None:
|
| 223 |
+
return None
|
| 224 |
+
return str(content)
|
| 225 |
+
except Exception:
|
| 226 |
+
pass
|
| 227 |
+
try:
|
| 228 |
+
return str(data)
|
| 229 |
+
except Exception:
|
| 230 |
+
return None
|
| 231 |
+
|
| 232 |
+
|
| 233 |
def extract_text_from_response(res, parts: list):
|
| 234 |
try:
|
| 235 |
choices = getattr(res, "choices", None) or res.get("choices", [])
|
|
|
|
| 261 |
|
| 262 |
|
| 263 |
def stream_and_collect(client, model, messages, parts: list):
|
| 264 |
+
norm_msgs = []
|
| 265 |
+
for m in messages:
|
| 266 |
+
if not isinstance(m, dict):
|
| 267 |
+
norm_msgs.append(m)
|
| 268 |
+
continue
|
| 269 |
+
c = m.get("content")
|
| 270 |
+
if isinstance(c, list):
|
| 271 |
+
picked = []
|
| 272 |
+
for item in c:
|
| 273 |
+
if isinstance(item, dict):
|
| 274 |
+
if item.get("type") == "image_url" and item.get("image_url"):
|
| 275 |
+
picked.append(item["image_url"])
|
| 276 |
+
elif item.get("type") == "image_base64" and item.get("image_base64"):
|
| 277 |
+
picked.append("data:image/jpeg;base64," + item["image_base64"])
|
| 278 |
+
elif item.get("type") == "text" and item.get("text"):
|
| 279 |
+
picked.append(item["text"])
|
| 280 |
+
elif isinstance(item, str):
|
| 281 |
+
picked.append(item)
|
| 282 |
+
newc = "\n\n".join(p for p in picked if p).strip()
|
| 283 |
+
nm = m.copy()
|
| 284 |
+
nm["content"] = newc
|
| 285 |
+
norm_msgs.append(nm)
|
| 286 |
+
else:
|
| 287 |
+
if not isinstance(c, str):
|
| 288 |
nm = m.copy()
|
| 289 |
+
nm["content"] = str(c or "")
|
| 290 |
norm_msgs.append(nm)
|
| 291 |
else:
|
| 292 |
+
norm_msgs.append(m)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
+
stream_gen = None
|
| 295 |
+
try:
|
| 296 |
+
stream_gen = client.chat.stream(model=model, messages=norm_msgs)
|
| 297 |
+
except Exception:
|
| 298 |
stream_gen = None
|
| 299 |
+
if stream_gen:
|
| 300 |
+
for chunk in stream_gen:
|
| 301 |
+
d = extract_delta(chunk)
|
| 302 |
+
if d is None:
|
| 303 |
+
continue
|
| 304 |
+
if d.strip() == "" and parts:
|
| 305 |
+
continue
|
| 306 |
+
parts.append(d)
|
| 307 |
+
return
|
| 308 |
+
|
| 309 |
+
res = client.chat.complete(model=model, messages=norm_msgs, stream=False)
|
| 310 |
+
extract_text_from_response(res, parts)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def analyze_image_bytes(client, img_bytes: bytes, prompt: str, model=DEFAULT_IMAGE_MODEL):
|
| 314 |
+
jpg = convert_to_jpeg_bytes(img_bytes, base_h=480)
|
| 315 |
+
b64 = b64_jpeg(jpg)
|
| 316 |
+
msgs = build_messages_for_image(prompt, b64_jpg=b64)
|
| 317 |
+
parts = []
|
| 318 |
+
stream_and_collect(client, model, msgs, parts)
|
| 319 |
+
return "".join(parts).strip()
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def analyze_multiple_frames(client, frames_bytes_list, prompt: str, model=DEFAULT_IMAGE_MODEL):
|
| 323 |
+
results = []
|
| 324 |
+
for i, fb in enumerate(frames_bytes_list):
|
| 325 |
+
res = analyze_image_bytes(client, fb, f"{prompt}\n\nFrame index: {i+1}", model=model)
|
| 326 |
+
results.append((i, res))
|
| 327 |
+
|
| 328 |
+
merged = []
|
| 329 |
+
for i, text in results:
|
| 330 |
+
merged.append(f"Frame {i+1} analysis:\n{text}")
|
| 331 |
+
|
| 332 |
+
consolidation_prompt = (
|
| 333 |
+
prompt
|
| 334 |
+
+ "\n\nConsolidate the key consistent observations across the provided frame analyses below. "
|
| 335 |
+
"List consistent findings first, then note any differences between frames."
|
| 336 |
+
+ "\n\n" + "\n\n".join(f"Frame {i+1}:\n{text}" for i, text in results)
|
| 337 |
+
)
|
| 338 |
+
parts = []
|
| 339 |
+
msgs = build_messages_for_text(consolidation_prompt, "")
|
| 340 |
+
stream_and_collect(client, DEFAULT_IMAGE_MODEL, msgs, parts)
|
| 341 |
+
consolidated = "".join(parts).strip()
|
| 342 |
+
if consolidated:
|
| 343 |
+
merged.append("Consolidated summary:\n" + consolidated)
|
| 344 |
+
return "\n\n".join(merged)
|
| 345 |
|
| 346 |
|
| 347 |
def generate_final_text(src: str, custom_prompt: str, api_key: str):
|
|
|
|
| 351 |
is_image = ext in IMAGE_EXTS or (not is_remote(src) and os.path.isfile(src) and ext in IMAGE_EXTS)
|
| 352 |
parts = []
|
| 353 |
|
|
|
|
| 354 |
if is_image:
|
| 355 |
try:
|
| 356 |
if is_remote(src):
|
| 357 |
+
raw = fetch_bytes(src)
|
| 358 |
+
return analyze_image_bytes(client, raw, prompt, model=DEFAULT_IMAGE_MODEL)
|
| 359 |
else:
|
| 360 |
raw = fetch_bytes(src)
|
| 361 |
+
return analyze_image_bytes(client, raw, prompt, model=DEFAULT_IMAGE_MODEL)
|
| 362 |
+
except UnidentifiedImageError:
|
| 363 |
+
return "Error: provided file is not a valid image."
|
| 364 |
except Exception as e:
|
| 365 |
return f"Error processing image: {e}"
|
|
|
|
|
|
|
| 366 |
|
|
|
|
| 367 |
if is_remote(src):
|
| 368 |
+
tmp_media = None
|
| 369 |
try:
|
| 370 |
media_bytes = fetch_bytes(src, timeout=120)
|
| 371 |
+
ext = ext_from_src(src) or ".mp4"
|
| 372 |
+
tmp_media = save_bytes_to_temp(media_bytes, suffix=ext)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
try:
|
| 374 |
file_id = upload_file_to_mistral(client, tmp_media, filename=os.path.basename(src.split("?")[0]))
|
| 375 |
extra = (
|
|
|
|
| 379 |
msgs = build_messages_for_text(prompt, extra)
|
| 380 |
stream_and_collect(client, DEFAULT_VIDEO_MODEL, msgs, parts)
|
| 381 |
return "".join(parts).strip()
|
| 382 |
+
except Exception:
|
| 383 |
+
frames = extract_best_frames_bytes(tmp_media, sample_count=5)
|
| 384 |
+
if not frames:
|
| 385 |
+
return "Error: could not upload remote video and no frames extracted."
|
| 386 |
+
return analyze_multiple_frames(client, frames, prompt, model=DEFAULT_IMAGE_MODEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
finally:
|
| 388 |
try:
|
| 389 |
if tmp_media and os.path.exists(tmp_media):
|
|
|
|
| 391 |
except Exception:
|
| 392 |
pass
|
| 393 |
|
|
|
|
| 394 |
tmp_media = None
|
| 395 |
try:
|
| 396 |
media_bytes = fetch_bytes(src)
|
|
|
|
| 398 |
ext = ext or ".mp4"
|
| 399 |
tmp_media = save_bytes_to_temp(media_bytes, suffix=ext)
|
| 400 |
try:
|
|
|
|
| 401 |
file_id = upload_file_to_mistral(client, tmp_media, filename=os.path.basename(src))
|
| 402 |
extra = (
|
| 403 |
f"Local video uploaded to Mistral Files with id: {file_id}\n\n"
|
|
|
|
| 407 |
stream_and_collect(client, DEFAULT_VIDEO_MODEL, msgs, parts)
|
| 408 |
return "".join(parts).strip()
|
| 409 |
except Exception:
|
| 410 |
+
frames = extract_best_frames_bytes(tmp_media, sample_count=5)
|
| 411 |
+
if not frames:
|
|
|
|
| 412 |
return "Unable to process the provided file. Provide a direct image/frame URL or a remote video URL."
|
| 413 |
+
return analyze_multiple_frames(client, frames, prompt, model=DEFAULT_IMAGE_MODEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
finally:
|
| 415 |
try:
|
| 416 |
if tmp_media and os.path.exists(tmp_media):
|
|
|
|
| 421 |
|
| 422 |
css = ".preview_media img, .preview_media video { max-width: 100%; height: auto; }"
|
| 423 |
|
|
|
|
| 424 |
def load_preview(url: str):
|
|
|
|
| 425 |
if not url:
|
| 426 |
return None, None, ""
|
| 427 |
try:
|
| 428 |
r = requests.get(url, timeout=30, stream=True)
|
| 429 |
r.raise_for_status()
|
| 430 |
ctype = (r.headers.get("content-type") or "").lower()
|
|
|
|
| 431 |
if (ctype and ctype.startswith("video/")) or any(url.lower().split("?")[0].endswith(ext) for ext in VIDEO_EXTS):
|
| 432 |
return None, url, "Video"
|
| 433 |
data = r.content
|
|
|
|
| 450 |
with gr.Accordion("Mistral API Key (optional)", open=False):
|
| 451 |
api_key = gr.Textbox(label="API Key", type="password", max_lines=1)
|
| 452 |
submit = gr.Button("Submit")
|
| 453 |
+
preview_image = gr.Image(label="Preview", type="pil", elem_classes="preview_media", visible=False)
|
| 454 |
+
preview_video = gr.Video(label="Preview", elem_classes="preview_media", visible=False)
|
| 455 |
|
| 456 |
with gr.Column(scale=2):
|
| 457 |
final_text = gr.Markdown(value="")
|
| 458 |
|
|
|
|
| 459 |
url_input.change(fn=load_preview, inputs=[url_input], outputs=[preview_image, preview_video, gr.Textbox(visible=False)])
|
| 460 |
submit.click(fn=generate_final_text, inputs=[url_input, custom_prompt, api_key], outputs=[final_text])
|
| 461 |
demo.queue()
|
| 462 |
|
| 463 |
if __name__ == "__main__":
|
| 464 |
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
|
| 465 |
+
|