Update ui_components.py
Browse files- ui_components.py +150 -107
ui_components.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
| 3 |
FIXED UI Components for Video Background Replacement
|
| 4 |
Updated to use the fixed core processing functions with working SAM2 + MatAnyone
|
| 5 |
Now includes TWO-STAGE processing option
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import gradio as gr
|
|
@@ -11,6 +12,7 @@
|
|
| 11 |
import os
|
| 12 |
import time
|
| 13 |
import logging
|
|
|
|
| 14 |
from typing import Optional
|
| 15 |
|
| 16 |
# Import FIXED core processing functions
|
|
@@ -27,6 +29,10 @@
|
|
| 27 |
|
| 28 |
logger = logging.getLogger(__name__)
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
# ============================================================================ #
|
| 31 |
# GRADIO MONKEY PATCH (BUG FIX for gradio>=4.44.0)
|
| 32 |
# ============================================================================ #
|
|
@@ -44,26 +50,54 @@ def patched_get_type(schema):
|
|
| 44 |
except (ImportError, AttributeError) as e:
|
| 45 |
logger.warning(f"Could not apply Gradio monkey patch: {e}")
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# ============================================================================ #
|
| 48 |
# UI HELPER FUNCTIONS
|
| 49 |
# ============================================================================ #
|
| 50 |
def generate_ai_background(prompt, style):
|
| 51 |
"""Generate AI background from prompt"""
|
| 52 |
if not prompt or not prompt.strip():
|
| 53 |
-
return None, "Please enter a prompt"
|
| 54 |
try:
|
|
|
|
| 55 |
bg_image = create_procedural_background(prompt, style, 1920, 1080)
|
| 56 |
if bg_image is not None:
|
| 57 |
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
|
| 58 |
cv2.imwrite(tmp.name, bg_image)
|
| 59 |
-
|
| 60 |
-
|
|
|
|
| 61 |
except Exception as e:
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
def switch_background_method(method):
|
| 66 |
"""Switch between background method UI groups"""
|
|
|
|
| 67 |
return (
|
| 68 |
gr.update(visible=(method == "upload")),
|
| 69 |
gr.update(visible=(method == "professional")),
|
|
@@ -72,20 +106,11 @@ def switch_background_method(method):
|
|
| 72 |
)
|
| 73 |
|
| 74 |
def update_cache_status():
|
| 75 |
-
"""Update cache status display
|
| 76 |
try:
|
| 77 |
-
status = get_model_status()
|
| 78 |
cache = get_cache_status()
|
| 79 |
-
|
| 80 |
-
sam2_status = f"✅ Loaded & Validated" if status['sam2'] == 'Ready' else "❌ Not loaded"
|
| 81 |
-
matanyone_status = f"✅ Loaded & Validated" if status['matanyone'] == 'Ready' else "❌ Not loaded"
|
| 82 |
-
models_status = "✅ Models Validated" if status['validated'] else "❌ Not validated"
|
| 83 |
two_stage_status = "✅ Available" if cache.get('two_stage_available', False) else "❌ Not available"
|
| 84 |
-
|
| 85 |
-
return (f"SAM2: {sam2_status}\n"
|
| 86 |
-
f"MatAnyone: {matanyone_status}\n"
|
| 87 |
-
f"Two-Stage: {two_stage_status}\n"
|
| 88 |
-
f"Status: {models_status}")
|
| 89 |
except Exception as e:
|
| 90 |
return f"Status check error: {str(e)}"
|
| 91 |
|
|
@@ -97,49 +122,62 @@ def gradio_progress_wrapper(progress_obj, pct, desc):
|
|
| 97 |
try:
|
| 98 |
if progress_obj is not None:
|
| 99 |
progress_obj(pct, desc=desc)
|
|
|
|
| 100 |
except Exception:
|
| 101 |
pass
|
| 102 |
|
| 103 |
# ============================================================================ #
|
| 104 |
-
# MAIN PROCESSING FUNCTION
|
| 105 |
# ============================================================================ #
|
| 106 |
def process_video_enhanced_fixed(
|
| 107 |
video_path, bg_method, custom_img, prof_choice, grad_type,
|
| 108 |
color1, color2, color3, use_third, ai_prompt, ai_style, ai_img,
|
| 109 |
-
use_two_stage, chroma_preset,
|
| 110 |
progress: Optional[gr.Progress] = None
|
| 111 |
):
|
| 112 |
-
"""
|
| 113 |
if not video_path:
|
| 114 |
-
|
|
|
|
| 115 |
|
| 116 |
def progress_callback(pct, desc):
|
| 117 |
gradio_progress_wrapper(progress, pct, desc)
|
| 118 |
|
| 119 |
try:
|
| 120 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
mode_msg = "TWO-STAGE Green Screen" if use_two_stage else "Single-Stage"
|
| 122 |
-
|
| 123 |
|
| 124 |
if bg_method == "upload":
|
| 125 |
if custom_img and os.path.exists(custom_img):
|
| 126 |
-
|
|
|
|
| 127 |
progress_callback, use_two_stage=use_two_stage,
|
| 128 |
chroma_preset=chroma_preset)
|
| 129 |
-
|
|
|
|
| 130 |
|
| 131 |
elif bg_method == "professional":
|
| 132 |
if prof_choice and prof_choice in PROFESSIONAL_BACKGROUNDS:
|
| 133 |
-
|
|
|
|
| 134 |
progress_callback, use_two_stage=use_two_stage,
|
| 135 |
chroma_preset=chroma_preset)
|
| 136 |
-
|
|
|
|
| 137 |
|
| 138 |
elif bg_method == "colors":
|
| 139 |
try:
|
| 140 |
colors = [color1 or "#3498db", color2 or "#2ecc71"]
|
| 141 |
if use_third and color3:
|
| 142 |
colors.append(color3)
|
|
|
|
| 143 |
|
| 144 |
from utilities import create_professional_background
|
| 145 |
bg_config = {
|
|
@@ -150,38 +188,49 @@ def progress_callback(pct, desc):
|
|
| 150 |
gradient_bg = create_professional_background(bg_config, 1920, 1080)
|
| 151 |
temp_path = f"/tmp/gradient_{int(time.time())}.png"
|
| 152 |
cv2.imwrite(temp_path, gradient_bg)
|
| 153 |
-
|
|
|
|
|
|
|
| 154 |
progress_callback, use_two_stage=use_two_stage,
|
| 155 |
chroma_preset=chroma_preset)
|
|
|
|
| 156 |
except Exception as e:
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
|
| 159 |
elif bg_method == "ai":
|
| 160 |
if ai_img and os.path.exists(ai_img):
|
| 161 |
-
|
|
|
|
| 162 |
progress_callback, use_two_stage=use_two_stage,
|
| 163 |
chroma_preset=chroma_preset)
|
| 164 |
-
|
|
|
|
| 165 |
|
| 166 |
else:
|
| 167 |
-
return None, f"Unknown background method: {bg_method}"
|
| 168 |
|
| 169 |
except Exception as e:
|
| 170 |
-
|
| 171 |
-
|
|
|
|
| 172 |
|
| 173 |
def load_models_with_progress_fixed(progress: Optional[gr.Progress] = None):
|
| 174 |
-
"""
|
| 175 |
def progress_callback(pct, desc):
|
| 176 |
gradio_progress_wrapper(progress, pct, desc)
|
| 177 |
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
# ============================================================================ #
|
| 181 |
-
# MAIN INTERFACE CREATION
|
| 182 |
# ============================================================================ #
|
| 183 |
def create_interface():
|
| 184 |
-
"""Create the complete Gradio interface with
|
| 185 |
|
| 186 |
with gr.Blocks(
|
| 187 |
title="FIXED High-Quality Video Background Replacement",
|
|
@@ -190,6 +239,14 @@ def create_interface():
|
|
| 190 |
.gradio-container { max-width: 1200px !important; }
|
| 191 |
.progress-bar { background: linear-gradient(90deg, #3498db, #2ecc71) !important; }
|
| 192 |
.status-box { background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 6px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
.two-stage-box {
|
| 194 |
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 195 |
color: white;
|
|
@@ -201,7 +258,6 @@ def create_interface():
|
|
| 201 |
) as demo:
|
| 202 |
gr.Markdown("# FIXED Cinema-Quality Video Background Replacement")
|
| 203 |
gr.Markdown("**Upload a video → Choose a background → Get professional results with VALIDATED AI**")
|
| 204 |
-
gr.Markdown("*Powered by PROPERLY INTEGRATED SAM2 + MatAnyone with comprehensive validation*")
|
| 205 |
|
| 206 |
# Two-stage mode banner if available
|
| 207 |
if TWO_STAGE_AVAILABLE:
|
|
@@ -227,12 +283,6 @@ def create_interface():
|
|
| 227 |
value="professional",
|
| 228 |
label="Background Method"
|
| 229 |
)
|
| 230 |
-
gr.Markdown(
|
| 231 |
-
"- **upload** = Upload Image \n"
|
| 232 |
-
"- **professional** = Professional Presets \n"
|
| 233 |
-
"- **colors** = Colors/Gradients \n"
|
| 234 |
-
"- **ai** = AI Generated"
|
| 235 |
-
)
|
| 236 |
|
| 237 |
with gr.Group(visible=False) as upload_group:
|
| 238 |
gr.Markdown("**Upload Your Background Image**")
|
|
@@ -264,7 +314,7 @@ def create_interface():
|
|
| 264 |
gr.Markdown("**AI Generated Background**")
|
| 265 |
ai_prompt = gr.Textbox(
|
| 266 |
label="Describe your background",
|
| 267 |
-
placeholder="e.g., 'modern office with plants', 'sunset over mountains'
|
| 268 |
lines=2
|
| 269 |
)
|
| 270 |
ai_style = gr.Dropdown(
|
|
@@ -300,7 +350,6 @@ def create_interface():
|
|
| 300 |
visible=False
|
| 301 |
)
|
| 302 |
|
| 303 |
-
# Show/hide chroma preset based on two-stage checkbox
|
| 304 |
use_two_stage.change(
|
| 305 |
fn=lambda x: gr.update(visible=x),
|
| 306 |
inputs=use_two_stage,
|
|
@@ -308,82 +357,93 @@ def create_interface():
|
|
| 308 |
)
|
| 309 |
|
| 310 |
gr.Markdown("### Processing Controls")
|
| 311 |
-
gr.Markdown("*First load and validate the AI models, then process your video*")
|
| 312 |
with gr.Row():
|
| 313 |
-
load_models_btn = gr.Button("Step 1: Load
|
| 314 |
process_btn = gr.Button("Step 2: Process Video", variant="primary")
|
|
|
|
| 315 |
|
| 316 |
status_text = gr.Textbox(
|
| 317 |
label="System Status",
|
| 318 |
-
value="Ready - click 'Load
|
| 319 |
interactive=False,
|
| 320 |
-
lines=
|
| 321 |
elem_classes=["status-box"]
|
| 322 |
)
|
| 323 |
|
| 324 |
-
# Enhanced cache/validation status indicator
|
| 325 |
validation_status = gr.Textbox(
|
| 326 |
-
label="
|
| 327 |
value=update_cache_status(),
|
| 328 |
interactive=False,
|
| 329 |
-
lines=
|
| 330 |
elem_classes=["status-box"]
|
| 331 |
)
|
| 332 |
|
| 333 |
with gr.Column(scale=1):
|
| 334 |
gr.Markdown("### Your Results")
|
| 335 |
-
gr.Markdown("*Processed video with validated SAM2 + MatAnyone will appear here*")
|
| 336 |
video_output = gr.Video(label="Your Processed Video", height=400)
|
| 337 |
result_text = gr.Textbox(
|
| 338 |
label="Processing Results",
|
| 339 |
interactive=False,
|
| 340 |
-
lines=
|
| 341 |
-
placeholder="Processing status
|
| 342 |
elem_classes=["status-box"]
|
| 343 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
<div style='display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; padding: 10px; max-height: 400px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px;'>
|
| 348 |
-
"""
|
| 349 |
-
for key, config in PROFESSIONAL_BACKGROUNDS.items():
|
| 350 |
-
colors = config["colors"]
|
| 351 |
-
gradient = f"linear-gradient(45deg, {colors[0]}, {colors[-1]})" if len(colors) >= 2 else colors[0]
|
| 352 |
-
bg_preview_html += f"""
|
| 353 |
-
<div style='padding: 12px 8px; border: 1px solid #ddd; border-radius: 6px; text-align: center; background: {gradient};
|
| 354 |
-
min-height: 60px; display: flex; align-items: center; justify-content: center;'>
|
| 355 |
-
<div>
|
| 356 |
-
<strong style='color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.8); font-size: 12px; display: block;'>{config["name"]}</strong>
|
| 357 |
-
<small style='color: rgba(255,255,255,0.9); text-shadow: 1px 1px 1px rgba(0,0,0,0.6); font-size: 10px;'>{config.get("description", "")[:30]}...</small>
|
| 358 |
-
</div>
|
| 359 |
-
</div>
|
| 360 |
-
"""
|
| 361 |
-
bg_preview_html += "</div>"
|
| 362 |
-
gr.HTML(bg_preview_html)
|
| 363 |
-
|
| 364 |
-
# Event handlers with FIXED functions
|
| 365 |
-
load_models_btn.click(
|
| 366 |
fn=load_models_with_progress_fixed,
|
| 367 |
-
outputs=[status_text]
|
| 368 |
)
|
| 369 |
|
| 370 |
generate_ai_btn.click(
|
| 371 |
fn=generate_ai_background,
|
| 372 |
inputs=[ai_prompt, ai_style],
|
| 373 |
-
outputs=[ai_generated_image, status_text]
|
| 374 |
)
|
| 375 |
|
| 376 |
-
#
|
| 377 |
-
process_btn.click(
|
| 378 |
fn=process_video_enhanced_fixed,
|
| 379 |
inputs=[video_input, background_method, custom_background, professional_choice,
|
| 380 |
gradient_type, color1, color2, color3, use_third_color,
|
| 381 |
ai_prompt, ai_style, ai_generated_image,
|
| 382 |
-
use_two_stage, chroma_preset],
|
| 383 |
-
outputs=[video_output, result_text]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
)
|
| 385 |
|
| 386 |
-
# Auto-update validation status
|
| 387 |
load_models_btn.click(
|
| 388 |
fn=update_cache_status,
|
| 389 |
outputs=[validation_status]
|
|
@@ -391,29 +451,12 @@ def create_interface():
|
|
| 391 |
|
| 392 |
with gr.Accordion("Quality & Features", open=False):
|
| 393 |
gr.Markdown("""
|
| 394 |
-
###
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
-
|
| 398 |
-
-
|
| 399 |
-
-
|
| 400 |
-
- Morphological edge cleaning
|
| 401 |
-
|
| 402 |
-
**Two-Stage Mode (Professional):**
|
| 403 |
-
- Stage 1: Original → Green Screen
|
| 404 |
-
- Stage 2: Green Screen → Final (Chroma Key)
|
| 405 |
-
- Perfect edges with spill suppression
|
| 406 |
-
- Adjustable tolerance and softness
|
| 407 |
-
- Cinema-grade quality
|
| 408 |
-
|
| 409 |
-
**Core Technology:**
|
| 410 |
-
- SAM2 with multi-point strategy
|
| 411 |
-
- MatAnyone refinement every 3 frames
|
| 412 |
-
- Enhanced OpenCV fallbacks
|
| 413 |
-
- H.264 CRF 18, AAC 192kbps audio
|
| 414 |
""")
|
| 415 |
|
| 416 |
-
gr.Markdown("---")
|
| 417 |
-
gr.Markdown("*Cinema-Quality Video Background Replacement — Validated SAM2 + MatAnyone pipeline*")
|
| 418 |
-
|
| 419 |
return demo
|
|
|
|
| 3 |
FIXED UI Components for Video Background Replacement
|
| 4 |
Updated to use the fixed core processing functions with working SAM2 + MatAnyone
|
| 5 |
Now includes TWO-STAGE processing option
|
| 6 |
+
ENHANCED: Added debug logging and cancel functionality
|
| 7 |
"""
|
| 8 |
|
| 9 |
import gradio as gr
|
|
|
|
| 12 |
import os
|
| 13 |
import time
|
| 14 |
import logging
|
| 15 |
+
import traceback
|
| 16 |
from typing import Optional
|
| 17 |
|
| 18 |
# Import FIXED core processing functions
|
|
|
|
| 29 |
|
| 30 |
logger = logging.getLogger(__name__)
|
| 31 |
|
| 32 |
+
# Global debug log storage
|
| 33 |
+
DEBUG_LOG = []
|
| 34 |
+
MAX_DEBUG_LINES = 100
|
| 35 |
+
|
| 36 |
# ============================================================================ #
|
| 37 |
# GRADIO MONKEY PATCH (BUG FIX for gradio>=4.44.0)
|
| 38 |
# ============================================================================ #
|
|
|
|
| 50 |
except (ImportError, AttributeError) as e:
|
| 51 |
logger.warning(f"Could not apply Gradio monkey patch: {e}")
|
| 52 |
|
| 53 |
+
# ============================================================================ #
|
| 54 |
+
# DEBUG LOGGING FUNCTIONS
|
| 55 |
+
# ============================================================================ #
|
| 56 |
+
def add_debug_log(message):
|
| 57 |
+
"""Add message to debug log"""
|
| 58 |
+
global DEBUG_LOG
|
| 59 |
+
timestamp = time.strftime("%H:%M:%S")
|
| 60 |
+
log_entry = f"[{timestamp}] {message}"
|
| 61 |
+
DEBUG_LOG.append(log_entry)
|
| 62 |
+
if len(DEBUG_LOG) > MAX_DEBUG_LINES:
|
| 63 |
+
DEBUG_LOG = DEBUG_LOG[-MAX_DEBUG_LINES:]
|
| 64 |
+
logger.info(message)
|
| 65 |
+
return "\n".join(DEBUG_LOG)
|
| 66 |
+
|
| 67 |
+
def clear_debug_log():
|
| 68 |
+
"""Clear the debug log"""
|
| 69 |
+
global DEBUG_LOG
|
| 70 |
+
DEBUG_LOG = []
|
| 71 |
+
return "Debug log cleared"
|
| 72 |
+
|
| 73 |
+
def get_debug_log():
|
| 74 |
+
"""Get current debug log as string"""
|
| 75 |
+
return "\n".join(DEBUG_LOG)
|
| 76 |
+
|
| 77 |
# ============================================================================ #
|
| 78 |
# UI HELPER FUNCTIONS
|
| 79 |
# ============================================================================ #
|
| 80 |
def generate_ai_background(prompt, style):
|
| 81 |
"""Generate AI background from prompt"""
|
| 82 |
if not prompt or not prompt.strip():
|
| 83 |
+
return None, "Please enter a prompt", get_debug_log()
|
| 84 |
try:
|
| 85 |
+
add_debug_log(f"Generating AI background: {prompt[:50]}...")
|
| 86 |
bg_image = create_procedural_background(prompt, style, 1920, 1080)
|
| 87 |
if bg_image is not None:
|
| 88 |
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
|
| 89 |
cv2.imwrite(tmp.name, bg_image)
|
| 90 |
+
add_debug_log(f"AI background saved to: {tmp.name}")
|
| 91 |
+
return tmp.name, f"Background generated: {prompt[:50]}...", get_debug_log()
|
| 92 |
+
return None, "Generation failed, try different prompt", get_debug_log()
|
| 93 |
except Exception as e:
|
| 94 |
+
error_msg = f"AI generation error: {str(e)}"
|
| 95 |
+
add_debug_log(error_msg)
|
| 96 |
+
return None, error_msg, get_debug_log()
|
| 97 |
|
| 98 |
def switch_background_method(method):
|
| 99 |
"""Switch between background method UI groups"""
|
| 100 |
+
add_debug_log(f"Switched to background method: {method}")
|
| 101 |
return (
|
| 102 |
gr.update(visible=(method == "upload")),
|
| 103 |
gr.update(visible=(method == "professional")),
|
|
|
|
| 106 |
)
|
| 107 |
|
| 108 |
def update_cache_status():
|
| 109 |
+
"""Update cache status display - Simplified to remove misleading info"""
|
| 110 |
try:
|
|
|
|
| 111 |
cache = get_cache_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
two_stage_status = "✅ Available" if cache.get('two_stage_available', False) else "❌ Not available"
|
| 113 |
+
return f"Two-Stage Mode: {two_stage_status}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
except Exception as e:
|
| 115 |
return f"Status check error: {str(e)}"
|
| 116 |
|
|
|
|
| 122 |
try:
|
| 123 |
if progress_obj is not None:
|
| 124 |
progress_obj(pct, desc=desc)
|
| 125 |
+
add_debug_log(f"Progress: {pct:.1%} - {desc}")
|
| 126 |
except Exception:
|
| 127 |
pass
|
| 128 |
|
| 129 |
# ============================================================================ #
|
| 130 |
+
# MAIN PROCESSING FUNCTION WITH ENHANCED ERROR HANDLING
|
| 131 |
# ============================================================================ #
|
| 132 |
def process_video_enhanced_fixed(
|
| 133 |
video_path, bg_method, custom_img, prof_choice, grad_type,
|
| 134 |
color1, color2, color3, use_third, ai_prompt, ai_style, ai_img,
|
| 135 |
+
use_two_stage, chroma_preset,
|
| 136 |
progress: Optional[gr.Progress] = None
|
| 137 |
):
|
| 138 |
+
"""Enhanced video processing with comprehensive error logging"""
|
| 139 |
if not video_path:
|
| 140 |
+
add_debug_log("ERROR: No video file provided")
|
| 141 |
+
return None, "No video file provided.", get_debug_log()
|
| 142 |
|
| 143 |
def progress_callback(pct, desc):
|
| 144 |
gradio_progress_wrapper(progress, pct, desc)
|
| 145 |
|
| 146 |
try:
|
| 147 |
+
# Clear old logs for new processing
|
| 148 |
+
add_debug_log("="*50)
|
| 149 |
+
add_debug_log("Starting new video processing...")
|
| 150 |
+
add_debug_log(f"Video: {video_path}")
|
| 151 |
+
add_debug_log(f"Background method: {bg_method}")
|
| 152 |
+
add_debug_log(f"Two-stage mode: {use_two_stage}")
|
| 153 |
+
|
| 154 |
mode_msg = "TWO-STAGE Green Screen" if use_two_stage else "Single-Stage"
|
| 155 |
+
add_debug_log(f"Processing mode: {mode_msg}")
|
| 156 |
|
| 157 |
if bg_method == "upload":
|
| 158 |
if custom_img and os.path.exists(custom_img):
|
| 159 |
+
add_debug_log(f"Using uploaded image: {custom_img}")
|
| 160 |
+
result = process_video_fixed(video_path, "custom", custom_img,
|
| 161 |
progress_callback, use_two_stage=use_two_stage,
|
| 162 |
chroma_preset=chroma_preset)
|
| 163 |
+
return result[0], result[1], get_debug_log()
|
| 164 |
+
return None, "No image uploaded. Please upload a background image.", get_debug_log()
|
| 165 |
|
| 166 |
elif bg_method == "professional":
|
| 167 |
if prof_choice and prof_choice in PROFESSIONAL_BACKGROUNDS:
|
| 168 |
+
add_debug_log(f"Using professional background: {prof_choice}")
|
| 169 |
+
result = process_video_fixed(video_path, prof_choice, None,
|
| 170 |
progress_callback, use_two_stage=use_two_stage,
|
| 171 |
chroma_preset=chroma_preset)
|
| 172 |
+
return result[0], result[1], get_debug_log()
|
| 173 |
+
return None, f"Invalid professional background: {prof_choice}", get_debug_log()
|
| 174 |
|
| 175 |
elif bg_method == "colors":
|
| 176 |
try:
|
| 177 |
colors = [color1 or "#3498db", color2 or "#2ecc71"]
|
| 178 |
if use_third and color3:
|
| 179 |
colors.append(color3)
|
| 180 |
+
add_debug_log(f"Creating gradient with colors: {colors}")
|
| 181 |
|
| 182 |
from utilities import create_professional_background
|
| 183 |
bg_config = {
|
|
|
|
| 188 |
gradient_bg = create_professional_background(bg_config, 1920, 1080)
|
| 189 |
temp_path = f"/tmp/gradient_{int(time.time())}.png"
|
| 190 |
cv2.imwrite(temp_path, gradient_bg)
|
| 191 |
+
add_debug_log(f"Gradient saved to: {temp_path}")
|
| 192 |
+
|
| 193 |
+
result = process_video_fixed(video_path, "custom", temp_path,
|
| 194 |
progress_callback, use_two_stage=use_two_stage,
|
| 195 |
chroma_preset=chroma_preset)
|
| 196 |
+
return result[0], result[1], get_debug_log()
|
| 197 |
except Exception as e:
|
| 198 |
+
error_msg = f"Error creating gradient: {str(e)}"
|
| 199 |
+
add_debug_log(f"ERROR: {error_msg}")
|
| 200 |
+
return None, error_msg, get_debug_log()
|
| 201 |
|
| 202 |
elif bg_method == "ai":
|
| 203 |
if ai_img and os.path.exists(ai_img):
|
| 204 |
+
add_debug_log(f"Using AI generated image: {ai_img}")
|
| 205 |
+
result = process_video_fixed(video_path, "custom", ai_img,
|
| 206 |
progress_callback, use_two_stage=use_two_stage,
|
| 207 |
chroma_preset=chroma_preset)
|
| 208 |
+
return result[0], result[1], get_debug_log()
|
| 209 |
+
return None, "No AI background generated. Click 'Generate Background' first.", get_debug_log()
|
| 210 |
|
| 211 |
else:
|
| 212 |
+
return None, f"Unknown background method: {bg_method}", get_debug_log()
|
| 213 |
|
| 214 |
except Exception as e:
|
| 215 |
+
error_msg = f"Processing error: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 216 |
+
add_debug_log(f"CRITICAL ERROR: {error_msg}")
|
| 217 |
+
return None, error_msg, get_debug_log()
|
| 218 |
|
| 219 |
def load_models_with_progress_fixed(progress: Optional[gr.Progress] = None):
|
| 220 |
+
"""Model loading with debug logging"""
|
| 221 |
def progress_callback(pct, desc):
|
| 222 |
gradio_progress_wrapper(progress, pct, desc)
|
| 223 |
|
| 224 |
+
add_debug_log("Starting model loading...")
|
| 225 |
+
result = load_models_with_validation(progress_callback)
|
| 226 |
+
add_debug_log(f"Model loading result: {result}")
|
| 227 |
+
return result, get_debug_log()
|
| 228 |
|
| 229 |
# ============================================================================ #
|
| 230 |
+
# MAIN INTERFACE CREATION WITH DEBUG PANEL
|
| 231 |
# ============================================================================ #
|
| 232 |
def create_interface():
|
| 233 |
+
"""Create the complete Gradio interface with debug capabilities"""
|
| 234 |
|
| 235 |
with gr.Blocks(
|
| 236 |
title="FIXED High-Quality Video Background Replacement",
|
|
|
|
| 239 |
.gradio-container { max-width: 1200px !important; }
|
| 240 |
.progress-bar { background: linear-gradient(90deg, #3498db, #2ecc71) !important; }
|
| 241 |
.status-box { background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 6px; }
|
| 242 |
+
.debug-box {
|
| 243 |
+
background-color: #1e1e1e;
|
| 244 |
+
color: #00ff00;
|
| 245 |
+
font-family: monospace;
|
| 246 |
+
font-size: 12px;
|
| 247 |
+
padding: 10px;
|
| 248 |
+
border-radius: 4px;
|
| 249 |
+
}
|
| 250 |
.two-stage-box {
|
| 251 |
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 252 |
color: white;
|
|
|
|
| 258 |
) as demo:
|
| 259 |
gr.Markdown("# FIXED Cinema-Quality Video Background Replacement")
|
| 260 |
gr.Markdown("**Upload a video → Choose a background → Get professional results with VALIDATED AI**")
|
|
|
|
| 261 |
|
| 262 |
# Two-stage mode banner if available
|
| 263 |
if TWO_STAGE_AVAILABLE:
|
|
|
|
| 283 |
value="professional",
|
| 284 |
label="Background Method"
|
| 285 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
with gr.Group(visible=False) as upload_group:
|
| 288 |
gr.Markdown("**Upload Your Background Image**")
|
|
|
|
| 314 |
gr.Markdown("**AI Generated Background**")
|
| 315 |
ai_prompt = gr.Textbox(
|
| 316 |
label="Describe your background",
|
| 317 |
+
placeholder="e.g., 'modern office with plants', 'sunset over mountains'",
|
| 318 |
lines=2
|
| 319 |
)
|
| 320 |
ai_style = gr.Dropdown(
|
|
|
|
| 350 |
visible=False
|
| 351 |
)
|
| 352 |
|
|
|
|
| 353 |
use_two_stage.change(
|
| 354 |
fn=lambda x: gr.update(visible=x),
|
| 355 |
inputs=use_two_stage,
|
|
|
|
| 357 |
)
|
| 358 |
|
| 359 |
gr.Markdown("### Processing Controls")
|
|
|
|
| 360 |
with gr.Row():
|
| 361 |
+
load_models_btn = gr.Button("Step 1: Load Models", variant="secondary")
|
| 362 |
process_btn = gr.Button("Step 2: Process Video", variant="primary")
|
| 363 |
+
cancel_btn = gr.Button("Cancel", variant="stop")
|
| 364 |
|
| 365 |
status_text = gr.Textbox(
|
| 366 |
label="System Status",
|
| 367 |
+
value="Ready - click 'Load Models' to start",
|
| 368 |
interactive=False,
|
| 369 |
+
lines=3,
|
| 370 |
elem_classes=["status-box"]
|
| 371 |
)
|
| 372 |
|
|
|
|
| 373 |
validation_status = gr.Textbox(
|
| 374 |
+
label="Processing Mode",
|
| 375 |
value=update_cache_status(),
|
| 376 |
interactive=False,
|
| 377 |
+
lines=1,
|
| 378 |
elem_classes=["status-box"]
|
| 379 |
)
|
| 380 |
|
| 381 |
with gr.Column(scale=1):
|
| 382 |
gr.Markdown("### Your Results")
|
|
|
|
| 383 |
video_output = gr.Video(label="Your Processed Video", height=400)
|
| 384 |
result_text = gr.Textbox(
|
| 385 |
label="Processing Results",
|
| 386 |
interactive=False,
|
| 387 |
+
lines=8,
|
| 388 |
+
placeholder="Processing status will appear here...",
|
| 389 |
elem_classes=["status-box"]
|
| 390 |
)
|
| 391 |
+
|
| 392 |
+
# Debug panel
|
| 393 |
+
with gr.Accordion("🔧 Debug Log", open=False):
|
| 394 |
+
debug_output = gr.Textbox(
|
| 395 |
+
label="Debug Output",
|
| 396 |
+
value=get_debug_log(),
|
| 397 |
+
lines=15,
|
| 398 |
+
max_lines=20,
|
| 399 |
+
interactive=False,
|
| 400 |
+
elem_classes=["debug-box"]
|
| 401 |
+
)
|
| 402 |
+
with gr.Row():
|
| 403 |
+
refresh_debug_btn = gr.Button("Refresh Log", size="sm")
|
| 404 |
+
clear_debug_btn = gr.Button("Clear Log", size="sm")
|
| 405 |
|
| 406 |
+
# Event handlers
|
| 407 |
+
load_event = load_models_btn.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
fn=load_models_with_progress_fixed,
|
| 409 |
+
outputs=[status_text, debug_output]
|
| 410 |
)
|
| 411 |
|
| 412 |
generate_ai_btn.click(
|
| 413 |
fn=generate_ai_background,
|
| 414 |
inputs=[ai_prompt, ai_style],
|
| 415 |
+
outputs=[ai_generated_image, status_text, debug_output]
|
| 416 |
)
|
| 417 |
|
| 418 |
+
# Process with cancel capability
|
| 419 |
+
process_event = process_btn.click(
|
| 420 |
fn=process_video_enhanced_fixed,
|
| 421 |
inputs=[video_input, background_method, custom_background, professional_choice,
|
| 422 |
gradient_type, color1, color2, color3, use_third_color,
|
| 423 |
ai_prompt, ai_style, ai_generated_image,
|
| 424 |
+
use_two_stage, chroma_preset],
|
| 425 |
+
outputs=[video_output, result_text, debug_output]
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
# Cancel button
|
| 429 |
+
cancel_btn.click(
|
| 430 |
+
fn=lambda: (add_debug_log("Processing cancelled by user"), "Processing cancelled")[1],
|
| 431 |
+
outputs=[status_text],
|
| 432 |
+
cancels=[process_event, load_event]
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Debug controls
|
| 436 |
+
refresh_debug_btn.click(
|
| 437 |
+
fn=get_debug_log,
|
| 438 |
+
outputs=[debug_output]
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
clear_debug_btn.click(
|
| 442 |
+
fn=clear_debug_log,
|
| 443 |
+
outputs=[debug_output]
|
| 444 |
)
|
| 445 |
|
| 446 |
+
# Auto-update validation status
|
| 447 |
load_models_btn.click(
|
| 448 |
fn=update_cache_status,
|
| 449 |
outputs=[validation_status]
|
|
|
|
| 451 |
|
| 452 |
with gr.Accordion("Quality & Features", open=False):
|
| 453 |
gr.Markdown("""
|
| 454 |
+
### Features:
|
| 455 |
+
- Single-Stage: Fast processing with good quality
|
| 456 |
+
- Two-Stage: Cinema-grade green screen processing
|
| 457 |
+
- Debug logging for troubleshooting
|
| 458 |
+
- Cancel button to stop long processes
|
| 459 |
+
- SAM2 + MatAnyone AI models
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
""")
|
| 461 |
|
|
|
|
|
|
|
|
|
|
| 462 |
return demo
|