Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,7 +5,7 @@ import tempfile
|
|
| 5 |
import base64
|
| 6 |
import json
|
| 7 |
from io import BytesIO
|
| 8 |
-
from typing import List, Tuple, Optional
|
| 9 |
import requests
|
| 10 |
from PIL import Image, ImageFile, UnidentifiedImageError
|
| 11 |
import gradio as gr
|
|
@@ -85,18 +85,20 @@ Image.MAX_IMAGE_PIXELS = 10000 * 10000
|
|
| 85 |
|
| 86 |
DEFAULT_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
|
| 87 |
|
| 88 |
-
# --- Temporary File Cleanup ---
|
| 89 |
-
_temp_files_to_delete
|
| 90 |
|
| 91 |
def _cleanup_all_temp_files():
|
| 92 |
"""Removes all temporary files created upon application exit."""
|
| 93 |
-
|
|
|
|
| 94 |
if os.path.exists(f_path):
|
| 95 |
try:
|
| 96 |
os.remove(f_path)
|
|
|
|
| 97 |
except Exception as e:
|
| 98 |
print(f"Error during final cleanup of {f_path}: {e}")
|
| 99 |
-
_temp_files_to_delete.clear()
|
| 100 |
|
| 101 |
atexit.register(_cleanup_all_temp_files)
|
| 102 |
|
|
@@ -156,7 +158,7 @@ def _temp_file(data: bytes, suffix: str) -> str:
|
|
| 156 |
os.close(fd)
|
| 157 |
with open(path, "wb") as f:
|
| 158 |
f.write(data)
|
| 159 |
-
_temp_files_to_delete.
|
| 160 |
return path
|
| 161 |
|
| 162 |
def fetch_bytes(src: str, stream_threshold: int = STREAM_THRESHOLD_BYTES, timeout: int = 60, progress=None) -> bytes:
|
|
@@ -176,10 +178,15 @@ def fetch_bytes(src: str, stream_threshold: int = STREAM_THRESHOLD_BYTES, timeou
|
|
| 176 |
try:
|
| 177 |
with requests.get(src, timeout=timeout, stream=True, headers=DEFAULT_HEADERS) as r:
|
| 178 |
r.raise_for_status()
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
with open(p, "rb") as fh:
|
| 184 |
return fh.read()
|
| 185 |
finally:
|
|
@@ -236,11 +243,13 @@ def _ffprobe_streams(path: str) -> Optional[dict]:
|
|
| 236 |
"""Uses ffprobe to get stream information for a media file."""
|
| 237 |
if not FFMPEG_BIN:
|
| 238 |
return None
|
| 239 |
-
|
|
|
|
| 240 |
if not shutil.which(ffprobe_path):
|
| 241 |
-
|
|
|
|
| 242 |
if not shutil.which(ffprobe_path):
|
| 243 |
-
return None
|
| 244 |
|
| 245 |
cmd = [
|
| 246 |
ffprobe_path, "-v", "error", "-print_format", "json", "-show_streams", "-show_format", path
|
|
@@ -248,7 +257,8 @@ def _ffprobe_streams(path: str) -> Optional[dict]:
|
|
| 248 |
try:
|
| 249 |
out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
|
| 250 |
return json.loads(out)
|
| 251 |
-
except Exception:
|
|
|
|
| 252 |
return None
|
| 253 |
|
| 254 |
def _get_video_info_and_timestamps(media_path: str, sample_count: int) -> Tuple[Optional[dict], List[float]]:
|
|
@@ -269,7 +279,7 @@ def _get_video_info_and_timestamps(media_path: str, sample_count: int) -> Tuple[
|
|
| 269 |
timestamps = [step * (i + 1) for i in range(actual_sample_count)]
|
| 270 |
|
| 271 |
if not timestamps: # Fallback for very short videos or if duration couldn't be determined
|
| 272 |
-
timestamps = [0.5, 1.0, 2.0, 3.0, 4.0][:sample_count]
|
| 273 |
|
| 274 |
return info, timestamps
|
| 275 |
|
|
@@ -281,9 +291,13 @@ def extract_frames_for_model_and_gallery(media_path: str, sample_count: int = 5,
|
|
| 281 |
frames_for_model: List[bytes] = []
|
| 282 |
frame_paths_for_gallery: List[str] = []
|
| 283 |
|
| 284 |
-
if not FFMPEG_BIN
|
| 285 |
-
print(f"Warning: FFMPEG not found
|
| 286 |
return frames_for_model, frame_paths_for_gallery
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
if progress is not None:
|
| 289 |
progress(0.05, desc="Preparing frame extraction...")
|
|
@@ -473,6 +487,10 @@ def analyze_video_cohesive(client, video_path: str, prompt: str, progress=None)
|
|
| 473 |
Returns: (analysis result text, list of paths to gallery frames)
|
| 474 |
"""
|
| 475 |
gallery_frame_paths: List[str] = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
try:
|
| 477 |
if progress is not None:
|
| 478 |
progress(0.3, desc="Uploading video for full analysis...")
|
|
@@ -558,8 +576,7 @@ def _convert_video_for_preview_if_needed(path: str) -> str:
|
|
| 558 |
except Exception as e:
|
| 559 |
print(f"Error converting video for preview: {e}")
|
| 560 |
# If conversion fails, remove the failed temp file and return original path
|
| 561 |
-
|
| 562 |
-
_temp_files_to_delete.remove(out_path)
|
| 563 |
try: os.remove(out_path)
|
| 564 |
except Exception: pass
|
| 565 |
return path
|
|
@@ -613,7 +630,23 @@ def _get_button_label_for_status(status: str) -> str:
|
|
| 613 |
|
| 614 |
def create_demo():
|
| 615 |
"""Creates the Gradio interface for Flux Multimodal analysis."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 616 |
with gr.Blocks(title="Flux Multimodal", css=GRADIO_CSS) as demo:
|
|
|
|
|
|
|
|
|
|
| 617 |
with gr.Row():
|
| 618 |
with gr.Column(scale=1):
|
| 619 |
preview_image = gr.Image(label="Preview Image", type="filepath", elem_classes="preview_media", visible=False)
|
|
@@ -641,13 +674,15 @@ def create_demo():
|
|
| 641 |
"""
|
| 642 |
Cleans up all tracked temporary files and resets all relevant UI components and states.
|
| 643 |
"""
|
| 644 |
-
|
|
|
|
| 645 |
if os.path.exists(f_path):
|
| 646 |
try:
|
| 647 |
os.remove(f_path)
|
|
|
|
| 648 |
except Exception as e:
|
| 649 |
print(f"Error during proactive cleanup of {f_path}: {e}")
|
| 650 |
-
_temp_files_to_delete.clear()
|
| 651 |
|
| 652 |
return "", \
|
| 653 |
gr.update(value=None, visible=False), \
|
|
@@ -692,20 +727,19 @@ def create_demo():
|
|
| 692 |
Also handles cleanup of previously loaded media.
|
| 693 |
"""
|
| 694 |
# --- Proactive cleanup of old files related to previous load ---
|
| 695 |
-
files_to_clean_up_now = []
|
| 696 |
if current_main_preview_path and os.path.exists(current_main_preview_path):
|
| 697 |
-
|
|
|
|
|
|
|
| 698 |
if current_raw_media_path and os.path.exists(current_raw_media_path):
|
| 699 |
-
|
|
|
|
|
|
|
| 700 |
for path in current_screenshot_paths:
|
| 701 |
if path and os.path.exists(path):
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
if f_path in _temp_files_to_delete:
|
| 706 |
-
_temp_files_to_delete.remove(f_path)
|
| 707 |
-
try: os.remove(f_path)
|
| 708 |
-
except Exception as e: print(f"Error cleaning up old temp file {f_path}: {e}")
|
| 709 |
|
| 710 |
# Default cleared states for UI and backend values to be returned on empty URL or error
|
| 711 |
img_update_clear = gr.update(value=None, visible=False)
|
|
@@ -723,7 +757,7 @@ def create_demo():
|
|
| 723 |
temp_raw_path_for_analysis = ""
|
| 724 |
try:
|
| 725 |
progress(0.01, desc="Downloading media for preview and analysis...")
|
| 726 |
-
raw_bytes_for_analysis = fetch_bytes(url, timeout=60, progress=progress)
|
| 727 |
if not raw_bytes_for_analysis:
|
| 728 |
return img_update_clear, video_update_clear, gallery_update_clear, \
|
| 729 |
gr.update(value="Preview load failed: No media bytes fetched.", visible=True), \
|
|
@@ -736,14 +770,13 @@ def create_demo():
|
|
| 736 |
gr.update(value="Preview load failed: Could not save raw media to temp file.", visible=True), \
|
| 737 |
main_path_clear, raw_media_path_clear, screenshot_paths_clear
|
| 738 |
|
| 739 |
-
progress(0.
|
| 740 |
is_img_initial, is_vid_initial = determine_media_type(url)
|
| 741 |
local_playable_path = _get_playable_preview_path_from_raw(url, raw_bytes_for_analysis, is_img_initial, is_vid_initial)
|
| 742 |
|
| 743 |
if not local_playable_path:
|
| 744 |
# If preview failed, cleanup the temp_raw_path_for_analysis as well
|
| 745 |
-
|
| 746 |
-
_temp_files_to_delete.remove(temp_raw_path_for_analysis)
|
| 747 |
try: os.remove(temp_raw_path_for_analysis)
|
| 748 |
except Exception as e: print(f"Error during cleanup of raw temp file {temp_raw_path_for_analysis}: {e}")
|
| 749 |
|
|
@@ -765,13 +798,11 @@ def create_demo():
|
|
| 765 |
local_playable_path, temp_raw_path_for_analysis, screenshot_paths_clear
|
| 766 |
else:
|
| 767 |
# If local_playable_path exists but is not image/video, clean it up
|
| 768 |
-
|
| 769 |
-
_temp_files_to_delete.remove(local_playable_path)
|
| 770 |
try: os.remove(local_playable_path)
|
| 771 |
except Exception as e: print(f"Error during cleanup of unplayable temp file {local_playable_path}: {e}")
|
| 772 |
# Also clean up raw_media_path if the playable path was not generated successfully
|
| 773 |
-
|
| 774 |
-
_temp_files_to_delete.remove(temp_raw_path_for_analysis)
|
| 775 |
try: os.remove(temp_raw_path_for_analysis)
|
| 776 |
except Exception as e: print(f"Error during cleanup of raw temp file {temp_raw_path_for_analysis}: {e}")
|
| 777 |
|
|
@@ -782,8 +813,7 @@ def create_demo():
|
|
| 782 |
except Exception as e:
|
| 783 |
# If an error occurred during loading, clear all relevant paths.
|
| 784 |
if os.path.exists(temp_raw_path_for_analysis):
|
| 785 |
-
|
| 786 |
-
_temp_files_to_delete.remove(temp_raw_path_for_analysis)
|
| 787 |
try: os.remove(temp_raw_path_for_analysis)
|
| 788 |
except Exception as ex: print(f"Error during cleanup of raw temp file {temp_raw_path_for_analysis} on error: {ex}")
|
| 789 |
|
|
@@ -808,6 +838,14 @@ def create_demo():
|
|
| 808 |
if not raw_media_path or not os.path.exists(raw_media_path):
|
| 809 |
return "error", "**Error:** No raw media file available for analysis. Please load a URL first.", current_main_preview_path, []
|
| 810 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 811 |
with open(raw_media_path, "rb") as f:
|
| 812 |
raw_bytes_for_analysis = f.read()
|
| 813 |
|
|
|
|
| 5 |
import base64
|
| 6 |
import json
|
| 7 |
from io import BytesIO
|
| 8 |
+
from typing import List, Tuple, Optional, Set # Import Set
|
| 9 |
import requests
|
| 10 |
from PIL import Image, ImageFile, UnidentifiedImageError
|
| 11 |
import gradio as gr
|
|
|
|
| 85 |
|
| 86 |
DEFAULT_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
|
| 87 |
|
| 88 |
+
# --- Temporary File Cleanup (Changed to use a set) ---
|
| 89 |
+
_temp_files_to_delete: Set[str] = set() # Use a set for better management
|
| 90 |
|
| 91 |
def _cleanup_all_temp_files():
|
| 92 |
"""Removes all temporary files created upon application exit."""
|
| 93 |
+
# Create a copy to iterate while modifying the original set
|
| 94 |
+
for f_path in _temp_files_to_delete.copy():
|
| 95 |
if os.path.exists(f_path):
|
| 96 |
try:
|
| 97 |
os.remove(f_path)
|
| 98 |
+
_temp_files_to_delete.discard(f_path) # Remove from set after deletion
|
| 99 |
except Exception as e:
|
| 100 |
print(f"Error during final cleanup of {f_path}: {e}")
|
| 101 |
+
_temp_files_to_delete.clear() # Ensure the set is empty
|
| 102 |
|
| 103 |
atexit.register(_cleanup_all_temp_files)
|
| 104 |
|
|
|
|
| 158 |
os.close(fd)
|
| 159 |
with open(path, "wb") as f:
|
| 160 |
f.write(data)
|
| 161 |
+
_temp_files_to_delete.add(path) # Add to set
|
| 162 |
return path
|
| 163 |
|
| 164 |
def fetch_bytes(src: str, stream_threshold: int = STREAM_THRESHOLD_BYTES, timeout: int = 60, progress=None) -> bytes:
|
|
|
|
| 178 |
try:
|
| 179 |
with requests.get(src, timeout=timeout, stream=True, headers=DEFAULT_HEADERS) as r:
|
| 180 |
r.raise_for_status()
|
| 181 |
+
total_size = int(r.headers.get("content-length", 0))
|
| 182 |
+
downloaded_size = 0
|
| 183 |
+
for chunk in r.iter_content(8192):
|
| 184 |
+
if chunk:
|
| 185 |
+
fh.write(chunk)
|
| 186 |
+
downloaded_size += len(chunk)
|
| 187 |
+
if progress is not None and total_size > 0:
|
| 188 |
+
# Scale progress from 0.1 to 0.25 for streaming phase
|
| 189 |
+
progress(0.1 + (downloaded_size / total_size) * 0.15)
|
| 190 |
with open(p, "rb") as fh:
|
| 191 |
return fh.read()
|
| 192 |
finally:
|
|
|
|
| 243 |
"""Uses ffprobe to get stream information for a media file."""
|
| 244 |
if not FFMPEG_BIN:
|
| 245 |
return None
|
| 246 |
+
# Use FFMPEG_BIN for ffprobe if it's explicitly provided and ends with ffmpeg
|
| 247 |
+
ffprobe_path = FFMPEG_BIN.replace("ffmpeg", "ffprobe") if "ffmpeg" in os.path.basename(FFMPEG_BIN) else "ffprobe"
|
| 248 |
if not shutil.which(ffprobe_path):
|
| 249 |
+
# Fallback to just 'ffprobe' if the path replacement didn't find it
|
| 250 |
+
ffprobe_path = "ffprobe"
|
| 251 |
if not shutil.which(ffprobe_path):
|
| 252 |
+
return None # ffprobe is not available
|
| 253 |
|
| 254 |
cmd = [
|
| 255 |
ffprobe_path, "-v", "error", "-print_format", "json", "-show_streams", "-show_format", path
|
|
|
|
| 257 |
try:
|
| 258 |
out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
|
| 259 |
return json.loads(out)
|
| 260 |
+
except Exception as e:
|
| 261 |
+
print(f"Error running ffprobe on {path}: {e}")
|
| 262 |
return None
|
| 263 |
|
| 264 |
def _get_video_info_and_timestamps(media_path: str, sample_count: int) -> Tuple[Optional[dict], List[float]]:
|
|
|
|
| 279 |
timestamps = [step * (i + 1) for i in range(actual_sample_count)]
|
| 280 |
|
| 281 |
if not timestamps: # Fallback for very short videos or if duration couldn't be determined
|
| 282 |
+
timestamps = [0.5, 1.0, 2.0, 3.0, 4.0][:sample_count] # Try fixed early timestamps
|
| 283 |
|
| 284 |
return info, timestamps
|
| 285 |
|
|
|
|
| 291 |
frames_for_model: List[bytes] = []
|
| 292 |
frame_paths_for_gallery: List[str] = []
|
| 293 |
|
| 294 |
+
if not FFMPEG_BIN: # Check FFMPEG_BIN here
|
| 295 |
+
print(f"Warning: FFMPEG not found. Cannot extract frames for {media_path}.")
|
| 296 |
return frames_for_model, frame_paths_for_gallery
|
| 297 |
+
if not os.path.exists(media_path):
|
| 298 |
+
print(f"Warning: Media path does not exist: {media_path}. Cannot extract frames.")
|
| 299 |
+
return frames_for_model, frame_paths_for_gallery
|
| 300 |
+
|
| 301 |
|
| 302 |
if progress is not None:
|
| 303 |
progress(0.05, desc="Preparing frame extraction...")
|
|
|
|
| 487 |
Returns: (analysis result text, list of paths to gallery frames)
|
| 488 |
"""
|
| 489 |
gallery_frame_paths: List[str] = []
|
| 490 |
+
# If FFmpeg is not available, we can't do video analysis at all
|
| 491 |
+
if not FFMPEG_BIN:
|
| 492 |
+
return "Error: FFmpeg is not found in your system PATH. Video analysis and preview are unavailable.", []
|
| 493 |
+
|
| 494 |
try:
|
| 495 |
if progress is not None:
|
| 496 |
progress(0.3, desc="Uploading video for full analysis...")
|
|
|
|
| 576 |
except Exception as e:
|
| 577 |
print(f"Error converting video for preview: {e}")
|
| 578 |
# If conversion fails, remove the failed temp file and return original path
|
| 579 |
+
_temp_files_to_delete.discard(out_path) # Remove from set
|
|
|
|
| 580 |
try: os.remove(out_path)
|
| 581 |
except Exception: pass
|
| 582 |
return path
|
|
|
|
| 630 |
|
| 631 |
def create_demo():
|
| 632 |
"""Creates the Gradio interface for Flux Multimodal analysis."""
|
| 633 |
+
# Determine FFMPEG status once for UI message
|
| 634 |
+
ffmpeg_status_message = ""
|
| 635 |
+
if not FFMPEG_BIN:
|
| 636 |
+
ffmpeg_status_message = "🔴 FFmpeg not found! Video analysis and preview will be limited/unavailable."
|
| 637 |
+
else:
|
| 638 |
+
ffmpeg_status_message = "🟢 FFmpeg found. Video features enabled."
|
| 639 |
+
|
| 640 |
+
mistral_client_status_message = ""
|
| 641 |
+
if not _MISTRAL_CLIENT_INSTALLED:
|
| 642 |
+
mistral_client_status_message = "🔴 Mistral AI client ('mistralai') not installed. AI analysis features will fail. Run `pip install mistralai`."
|
| 643 |
+
else:
|
| 644 |
+
mistral_client_status_message = "🟢 Mistral AI client found."
|
| 645 |
+
|
| 646 |
with gr.Blocks(title="Flux Multimodal", css=GRADIO_CSS) as demo:
|
| 647 |
+
gr.Markdown("# Flux Multimodal AI Assistant")
|
| 648 |
+
gr.Markdown(f"{mistral_client_status_message}<br>{ffmpeg_status_message}") # Display dependency status
|
| 649 |
+
|
| 650 |
with gr.Row():
|
| 651 |
with gr.Column(scale=1):
|
| 652 |
preview_image = gr.Image(label="Preview Image", type="filepath", elem_classes="preview_media", visible=False)
|
|
|
|
| 674 |
"""
|
| 675 |
Cleans up all tracked temporary files and resets all relevant UI components and states.
|
| 676 |
"""
|
| 677 |
+
# Iterate a copy of the set while potentially modifying the original
|
| 678 |
+
for f_path in _temp_files_to_delete.copy():
|
| 679 |
if os.path.exists(f_path):
|
| 680 |
try:
|
| 681 |
os.remove(f_path)
|
| 682 |
+
_temp_files_to_delete.discard(f_path) # Remove from set
|
| 683 |
except Exception as e:
|
| 684 |
print(f"Error during proactive cleanup of {f_path}: {e}")
|
| 685 |
+
_temp_files_to_delete.clear() # Ensure set is empty
|
| 686 |
|
| 687 |
return "", \
|
| 688 |
gr.update(value=None, visible=False), \
|
|
|
|
| 727 |
Also handles cleanup of previously loaded media.
|
| 728 |
"""
|
| 729 |
# --- Proactive cleanup of old files related to previous load ---
|
|
|
|
| 730 |
if current_main_preview_path and os.path.exists(current_main_preview_path):
|
| 731 |
+
_temp_files_to_delete.discard(current_main_preview_path) # Remove from set
|
| 732 |
+
try: os.remove(current_main_preview_path)
|
| 733 |
+
except Exception as e: print(f"Error cleaning up old temp file {current_main_preview_path}: {e}")
|
| 734 |
if current_raw_media_path and os.path.exists(current_raw_media_path):
|
| 735 |
+
_temp_files_to_delete.discard(current_raw_media_path) # Remove from set
|
| 736 |
+
try: os.remove(current_raw_media_path)
|
| 737 |
+
except Exception as e: print(f"Error cleaning up old temp file {current_raw_media_path}: {e}")
|
| 738 |
for path in current_screenshot_paths:
|
| 739 |
if path and os.path.exists(path):
|
| 740 |
+
_temp_files_to_delete.discard(path) # Remove from set
|
| 741 |
+
try: os.remove(path)
|
| 742 |
+
except Exception as e: print(f"Error cleaning up old temp file {path}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 743 |
|
| 744 |
# Default cleared states for UI and backend values to be returned on empty URL or error
|
| 745 |
img_update_clear = gr.update(value=None, visible=False)
|
|
|
|
| 757 |
temp_raw_path_for_analysis = ""
|
| 758 |
try:
|
| 759 |
progress(0.01, desc="Downloading media for preview and analysis...")
|
| 760 |
+
raw_bytes_for_analysis = fetch_bytes(url, timeout=60, progress=progress) # Pass progress here
|
| 761 |
if not raw_bytes_for_analysis:
|
| 762 |
return img_update_clear, video_update_clear, gallery_update_clear, \
|
| 763 |
gr.update(value="Preview load failed: No media bytes fetched.", visible=True), \
|
|
|
|
| 770 |
gr.update(value="Preview load failed: Could not save raw media to temp file.", visible=True), \
|
| 771 |
main_path_clear, raw_media_path_clear, screenshot_paths_clear
|
| 772 |
|
| 773 |
+
progress(0.25, desc="Generating playable preview...") # Adjusted progress start
|
| 774 |
is_img_initial, is_vid_initial = determine_media_type(url)
|
| 775 |
local_playable_path = _get_playable_preview_path_from_raw(url, raw_bytes_for_analysis, is_img_initial, is_vid_initial)
|
| 776 |
|
| 777 |
if not local_playable_path:
|
| 778 |
# If preview failed, cleanup the temp_raw_path_for_analysis as well
|
| 779 |
+
_temp_files_to_delete.discard(temp_raw_path_for_analysis) # Remove from set
|
|
|
|
| 780 |
try: os.remove(temp_raw_path_for_analysis)
|
| 781 |
except Exception as e: print(f"Error during cleanup of raw temp file {temp_raw_path_for_analysis}: {e}")
|
| 782 |
|
|
|
|
| 798 |
local_playable_path, temp_raw_path_for_analysis, screenshot_paths_clear
|
| 799 |
else:
|
| 800 |
# If local_playable_path exists but is not image/video, clean it up
|
| 801 |
+
_temp_files_to_delete.discard(local_playable_path) # Remove from set
|
|
|
|
| 802 |
try: os.remove(local_playable_path)
|
| 803 |
except Exception as e: print(f"Error during cleanup of unplayable temp file {local_playable_path}: {e}")
|
| 804 |
# Also clean up raw_media_path if the playable path was not generated successfully
|
| 805 |
+
_temp_files_to_delete.discard(temp_raw_path_for_analysis) # Remove from set
|
|
|
|
| 806 |
try: os.remove(temp_raw_path_for_analysis)
|
| 807 |
except Exception as e: print(f"Error during cleanup of raw temp file {temp_raw_path_for_analysis}: {e}")
|
| 808 |
|
|
|
|
| 813 |
except Exception as e:
|
| 814 |
# If an error occurred during loading, clear all relevant paths.
|
| 815 |
if os.path.exists(temp_raw_path_for_analysis):
|
| 816 |
+
_temp_files_to_delete.discard(temp_raw_path_for_analysis) # Remove from set
|
|
|
|
| 817 |
try: os.remove(temp_raw_path_for_analysis)
|
| 818 |
except Exception as ex: print(f"Error during cleanup of raw temp file {temp_raw_path_for_analysis} on error: {ex}")
|
| 819 |
|
|
|
|
| 838 |
if not raw_media_path or not os.path.exists(raw_media_path):
|
| 839 |
return "error", "**Error:** No raw media file available for analysis. Please load a URL first.", current_main_preview_path, []
|
| 840 |
|
| 841 |
+
# Initial check for FFmpeg for video processing
|
| 842 |
+
if not FFMPEG_BIN:
|
| 843 |
+
# If this is a video, and ffmpeg is missing, return early.
|
| 844 |
+
# Otherwise, proceed for image analysis.
|
| 845 |
+
is_image_check, is_video_check = determine_media_type(url)
|
| 846 |
+
if is_video_check:
|
| 847 |
+
return "error", "**Error:** FFmpeg is not found in your system PATH. Video analysis is unavailable. Please install FFmpeg.", current_main_preview_path, []
|
| 848 |
+
|
| 849 |
with open(raw_media_path, "rb") as f:
|
| 850 |
raw_bytes_for_analysis = f.read()
|
| 851 |
|