#!/usr/bin/env python3 """ Enhanced UI Components - BackgroundFX Pro Streamlined interface with better error handling and user experience """ import gradio as gr import os import json import time import traceback from typing import Optional, Dict, Any, Tuple from pathlib import Path # Remove redundant Gradio schema patching - handled in app.py print("UI Components: Initializing interface...") # Import core functions with comprehensive error handling try: from app import ( VideoProcessor, processor, load_models_with_validation, process_video_fixed, get_model_status, get_cache_status ) CORE_FUNCTIONS_AVAILABLE = True print("UI Components: Core functions imported successfully") except Exception as e: print(f"UI Components: Core functions import failed: {e}") CORE_FUNCTIONS_AVAILABLE = False # Import utilities with error handling try: from utilities import PROFESSIONAL_BACKGROUNDS UTILITIES_AVAILABLE = True print("UI Components: Utilities imported successfully") except Exception as e: print(f"UI Components: Utilities import failed: {e}") UTILITIES_AVAILABLE = False PROFESSIONAL_BACKGROUNDS = { "office_modern": {"name": "Modern Office", "description": "Clean office environment"}, "studio_blue": {"name": "Professional Blue", "description": "Blue studio background"}, "minimalist": {"name": "Minimalist White", "description": "Clean white background"} } # Import two-stage processor with error handling try: from two_stage_processor import CHROMA_PRESETS TWO_STAGE_AVAILABLE = True print("UI Components: Two-stage processor available") except ImportError: TWO_STAGE_AVAILABLE = False CHROMA_PRESETS = { 'standard': {'name': 'Standard Quality'}, 'balanced': {'name': 'Balanced'}, 'high': {'name': 'High Quality'} } print("UI Components: Two-stage processor not available") class UIStateManager: """Manage UI state and provide user feedback""" def __init__(self): self.processing_active = False self.models_loaded = False self.last_processing_time = None self.processing_history = [] def update_processing_state(self, active: bool): self.processing_active = active if not active and self.last_processing_time: duration = time.time() - self.last_processing_time self.processing_history.append({ 'timestamp': time.time(), 'duration': duration }) elif active: self.last_processing_time = time.time() def get_average_processing_time(self) -> float: if not self.processing_history: return 0 recent_history = self.processing_history[-5:] # Last 5 processing sessions return sum(h['duration'] for h in recent_history) / len(recent_history) # Global UI state ui_state = UIStateManager() def create_interface(): """Create the enhanced Gradio interface with better UX""" # Enhanced processing function with better error handling def enhanced_process_video( video_path, bg_method, custom_img, prof_choice, use_two_stage, chroma_preset, quality_preset, progress: Optional[gr.Progress] = None ): """Enhanced video processing with comprehensive error handling and user feedback""" if not CORE_FUNCTIONS_AVAILABLE: return None, "Error: Core processing functions not available", "System Error: Please check installation" if not processor.models_loaded: return None, "Error: Models not loaded", "Please load models first using the 'Load Models' button" if not video_path: return None, "Error: No video uploaded", "Please upload a video file first" # Validate inputs if bg_method == "professional" and not prof_choice: return None, "Error: No background selected", "Please select a professional background" if bg_method == "upload" and not custom_img: return None, "Error: No custom background", "Please upload a custom background image" try: ui_state.update_processing_state(True) # Set quality preset in processor config if quality_preset and hasattr(processor, 'config'): processor.config.quality_preset = quality_preset def progress_callback(pct, desc): if progress: progress(pct, desc) return desc # Determine background choice if bg_method == "professional": background_choice = prof_choice custom_background_path = None else: background_choice = "custom" custom_background_path = custom_img # Process video result_path, result_message = process_video_fixed( video_path=video_path, background_choice=background_choice, custom_background_path=custom_background_path, progress_callback=progress_callback, use_two_stage=bool(use_two_stage), chroma_preset=chroma_preset or "standard", preview_mask=False, preview_greenscreen=False ) ui_state.update_processing_state(False) if result_path: # Enhanced success message avg_time = ui_state.get_average_processing_time() success_info = f""" â Processing Complete! đ Results: {result_message} âąī¸ Performance: - Average processing time: {avg_time:.1f}s - Two-stage mode: {'Enabled' if use_two_stage else 'Disabled'} - Quality preset: {quality_preset or 'Default'} đĄ Tips: - Try two-stage mode for better quality - Use 'fast' preset for quicker processing - Shorter videos process faster """ return result_path, success_info, "Processing completed successfully!" else: return None, f"Processing failed: {result_message}", f"Error: {result_message}" except Exception as e: ui_state.update_processing_state(False) error_msg = f"Processing error: {str(e)}" print(f"UI Error: {error_msg}\n{traceback.format_exc()}") return None, error_msg, f"System Error: {error_msg}" # Enhanced model loading with better feedback def enhanced_load_models(progress: Optional[gr.Progress] = None): """Enhanced model loading with detailed feedback""" if not CORE_FUNCTIONS_AVAILABLE: return "Error: Core functions not available", "System Error: Installation incomplete" try: def progress_callback(pct, desc): if progress: progress(pct, desc) return desc result = load_models_with_validation(progress_callback) if "SUCCESS" in result or "successful" in result.lower(): ui_state.models_loaded = True enhanced_result = f""" â Models Loaded Successfully! đ Status: {result} đ¯ Ready for Processing: - High-quality segmentation (SAM2) - Professional mask refinement (MatAnyone) - {'Two-stage green screen mode available' if TWO_STAGE_AVAILABLE else 'Single-stage processing only'} đĄ Next Steps: 1. Upload your video 2. Choose background method 3. Click 'Process Video' """ return enhanced_result, "Models loaded successfully! Ready to process videos." else: return result, f"Model loading failed: {result}" except Exception as e: error_msg = f"Model loading error: {str(e)}" print(f"UI Model Loading Error: {error_msg}\n{traceback.format_exc()}") return error_msg, error_msg # Enhanced status functions def get_enhanced_model_status(): """Get enhanced model status with user-friendly formatting""" try: status = get_model_status() if isinstance(status, dict): formatted_status = { "SAM2 Segmentation": "â Ready" if status.get('sam2_available') else "â Not Loaded", "MatAnyone Refinement": "â Ready" if status.get('matanyone_available') else "â Not Loaded", "Two-Stage Mode": "â Available" if status.get('two_stage_available') else "â Not Available", "Device": status.get('device', 'Unknown'), "Models Validated": "â Yes" if status.get('models_loaded') else "â No" } if 'memory_usage' in status and status['memory_usage']: memory = status['memory_usage'] if 'gpu_percent' in memory: formatted_status["GPU Memory"] = f"{memory['gpu_percent']:.1f}% used" return formatted_status else: return {"Status": str(status)} except Exception as e: return {"Error": f"Failed to get status: {e}"} def get_enhanced_cache_status(): """Get enhanced cache status with detailed information""" try: status = get_cache_status() if isinstance(status, dict): return { "Cache Status": "â Active" if status.get('models_loaded') else "â Inactive", "Processing Mode": "Two-Stage" if status.get('two_stage_available') else "Single-Stage", "Configuration": status.get('config', {}), "System Device": status.get('device', 'Unknown') } else: return {"Cache": str(status)} except Exception as e: return {"Error": f"Failed to get cache info: {e}"} # Create the main interface with gr.Blocks( title="BackgroundFX Pro - Professional Video Background Replacement", theme=gr.themes.Soft( primary_hue="blue", secondary_hue="gray", neutral_hue="slate" ), css=""" .main-header { text-align: center; margin-bottom: 20px; } .status-box { background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 10px 0; } .error-box { background: #fee; border-left: 4px solid #dc3545; padding: 15px; } .success-box { background: #efe; border-left: 4px solid #28a745; padding: 15px; } .feature-list { columns: 2; column-gap: 20px; } """ ) as demo: # Header with gr.Row(): gr.Markdown(""" # đŦ BackgroundFX Pro - Video Background Replacement Professional-quality video background replacement using AI segmentation and advanced compositing techniques. """, elem_classes=["main-header"]) # System status indicator with gr.Row(): with gr.Column(scale=1): system_status = gr.HTML(f"""