Update app.py
Browse files
app.py
CHANGED
|
@@ -5,40 +5,13 @@
|
|
| 5 |
No inline JavaScript, CSP-compliant Gradio, safe environment vars, fallback AI models
|
| 6 |
"""
|
| 7 |
|
|
|
|
|
|
|
| 8 |
import os
|
| 9 |
import logging
|
| 10 |
from pathlib import Path
|
| 11 |
from typing import Optional, Tuple, Dict, Any, Callable
|
| 12 |
|
| 13 |
-
# 0️⃣ Early threading/OMP sanitization (prevents libgomp + interop warnings)
|
| 14 |
-
def _clean_int_env(name: str, default: str | None = None):
|
| 15 |
-
val = os.environ.get(name)
|
| 16 |
-
if val is None:
|
| 17 |
-
if default is not None:
|
| 18 |
-
os.environ[name] = str(default)
|
| 19 |
-
return
|
| 20 |
-
try:
|
| 21 |
-
int(str(val).strip())
|
| 22 |
-
except ValueError:
|
| 23 |
-
if default is None:
|
| 24 |
-
os.environ.pop(name, None)
|
| 25 |
-
else:
|
| 26 |
-
os.environ[name] = str(default)
|
| 27 |
-
|
| 28 |
-
_clean_int_env("OMP_NUM_THREADS", "2")
|
| 29 |
-
_clean_int_env("MKL_NUM_THREADS", "2")
|
| 30 |
-
_clean_int_env("OPENBLAS_NUM_THREADS", "2")
|
| 31 |
-
_clean_int_env("NUMEXPR_NUM_THREADS", "2")
|
| 32 |
-
|
| 33 |
-
try:
|
| 34 |
-
import torch # call thread setters BEFORE heavy parallel work starts
|
| 35 |
-
if hasattr(torch, "set_num_interop_threads"):
|
| 36 |
-
torch.set_num_interop_threads(2)
|
| 37 |
-
if hasattr(torch, "set_num_threads"):
|
| 38 |
-
torch.set_num_threads(2)
|
| 39 |
-
except Exception:
|
| 40 |
-
pass
|
| 41 |
-
|
| 42 |
# 1️⃣ Set CSP-safe environment variables BEFORE any imports (Gradio will see these)
|
| 43 |
os.environ['GRADIO_ALLOW_FLAGGING'] = 'never'
|
| 44 |
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
|
|
@@ -119,10 +92,8 @@ def load_models(self, progress_callback: Optional[Callable]=None) -> str:
|
|
| 119 |
except Exception as e:
|
| 120 |
logger.warning(f"Model loading failed ({e}) - Using CSP-safe fallbacks")
|
| 121 |
sam2, matanyone = None, None
|
| 122 |
-
# Unwrap LoadedModel if needed
|
| 123 |
sam2_model = getattr(sam2, "model", sam2) if sam2 else CSPSafeSAM2()
|
| 124 |
matanyone_model = getattr(matanyone, "model", matanyone) if matanyone else CSPSafeMatAnyone()
|
| 125 |
-
# Set up Core Processor (replace models if None)
|
| 126 |
self.core_processor = CoreVideoProcessor(config=ProcessorConfig(), models=None)
|
| 127 |
self.core_processor.models = type('FakeModelManager', (), {
|
| 128 |
'get_sam2': lambda self: sam2_model,
|
|
@@ -134,14 +105,11 @@ def load_models(self, progress_callback: Optional[Callable]=None) -> str:
|
|
| 134 |
def process_video(self, video, bg_style, custom_bg_file):
|
| 135 |
if not self.models_loaded:
|
| 136 |
return None, "Models not loaded yet"
|
| 137 |
-
# Prepare output path
|
| 138 |
import time
|
| 139 |
output_path = f"/tmp/output_{int(time.time())}.mp4"
|
| 140 |
-
# Build background config
|
| 141 |
cfg = PROFESSIONAL_BACKGROUNDS.get(bg_style, PROFESSIONAL_BACKGROUNDS["minimalist"])
|
| 142 |
if custom_bg_file:
|
| 143 |
cfg = {"custom_path": custom_bg_file.name}
|
| 144 |
-
# Validate and process
|
| 145 |
ok, msg = validate_video_file(video)
|
| 146 |
if not ok:
|
| 147 |
return None, f"Invalid video: {msg}"
|
|
@@ -151,7 +119,6 @@ def process_video(self, video, bg_style, custom_bg_file):
|
|
| 151 |
output_path=output_path,
|
| 152 |
bg_config=cfg
|
| 153 |
)
|
| 154 |
-
# Add audio back (optional, comment out if not needed)
|
| 155 |
output_with_audio = self.audio_proc.add_audio_to_video(video, output_path)
|
| 156 |
return output_with_audio, f"Processing complete ({result.get('frames', 'n/a')} frames, {bg_style})"
|
| 157 |
except Exception as e:
|
|
@@ -187,7 +154,6 @@ def create_csp_safe_gradio():
|
|
| 187 |
status = gr.Textbox(label="Status", lines=4)
|
| 188 |
out_video = gr.Video(label="Processed Video")
|
| 189 |
|
| 190 |
-
# CSP-safe event bindings (no JS eval)
|
| 191 |
def safe_load():
|
| 192 |
return app.load_models()
|
| 193 |
def safe_process(vid, style, custom_bg_file):
|
|
@@ -206,5 +172,5 @@ def safe_process(vid, style, custom_bg_file):
|
|
| 206 |
server_port=7860,
|
| 207 |
show_error=True,
|
| 208 |
debug=False,
|
| 209 |
-
inbrowser=False
|
| 210 |
)
|
|
|
|
| 5 |
No inline JavaScript, CSP-compliant Gradio, safe environment vars, fallback AI models
|
| 6 |
"""
|
| 7 |
|
| 8 |
+
import early_env # <<< must be FIRST to sanitize threading/env before anything else
|
| 9 |
+
|
| 10 |
import os
|
| 11 |
import logging
|
| 12 |
from pathlib import Path
|
| 13 |
from typing import Optional, Tuple, Dict, Any, Callable
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
# 1️⃣ Set CSP-safe environment variables BEFORE any imports (Gradio will see these)
|
| 16 |
os.environ['GRADIO_ALLOW_FLAGGING'] = 'never'
|
| 17 |
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
|
|
|
|
| 92 |
except Exception as e:
|
| 93 |
logger.warning(f"Model loading failed ({e}) - Using CSP-safe fallbacks")
|
| 94 |
sam2, matanyone = None, None
|
|
|
|
| 95 |
sam2_model = getattr(sam2, "model", sam2) if sam2 else CSPSafeSAM2()
|
| 96 |
matanyone_model = getattr(matanyone, "model", matanyone) if matanyone else CSPSafeMatAnyone()
|
|
|
|
| 97 |
self.core_processor = CoreVideoProcessor(config=ProcessorConfig(), models=None)
|
| 98 |
self.core_processor.models = type('FakeModelManager', (), {
|
| 99 |
'get_sam2': lambda self: sam2_model,
|
|
|
|
| 105 |
def process_video(self, video, bg_style, custom_bg_file):
|
| 106 |
if not self.models_loaded:
|
| 107 |
return None, "Models not loaded yet"
|
|
|
|
| 108 |
import time
|
| 109 |
output_path = f"/tmp/output_{int(time.time())}.mp4"
|
|
|
|
| 110 |
cfg = PROFESSIONAL_BACKGROUNDS.get(bg_style, PROFESSIONAL_BACKGROUNDS["minimalist"])
|
| 111 |
if custom_bg_file:
|
| 112 |
cfg = {"custom_path": custom_bg_file.name}
|
|
|
|
| 113 |
ok, msg = validate_video_file(video)
|
| 114 |
if not ok:
|
| 115 |
return None, f"Invalid video: {msg}"
|
|
|
|
| 119 |
output_path=output_path,
|
| 120 |
bg_config=cfg
|
| 121 |
)
|
|
|
|
| 122 |
output_with_audio = self.audio_proc.add_audio_to_video(video, output_path)
|
| 123 |
return output_with_audio, f"Processing complete ({result.get('frames', 'n/a')} frames, {bg_style})"
|
| 124 |
except Exception as e:
|
|
|
|
| 154 |
status = gr.Textbox(label="Status", lines=4)
|
| 155 |
out_video = gr.Video(label="Processed Video")
|
| 156 |
|
|
|
|
| 157 |
def safe_load():
|
| 158 |
return app.load_models()
|
| 159 |
def safe_process(vid, style, custom_bg_file):
|
|
|
|
| 172 |
server_port=7860,
|
| 173 |
show_error=True,
|
| 174 |
debug=False,
|
| 175 |
+
inbrowser=False
|
| 176 |
)
|