import os import logging import gradio as gr from dotenv import load_dotenv import google.generativeai as genai from auto_diffusers import AutoDiffusersGenerator from simple_memory_calculator import SimpleMemoryCalculator load_dotenv() # Configure logging for Gradio app logger = logging.getLogger(__name__) class GradioAutodiffusers: def __init__(self): logger.info("Initializing GradioAutodiffusers") self.api_key = os.getenv('GOOGLE_API_KEY') if not self.api_key: logger.error("GOOGLE_API_KEY not found in environment variables") raise ValueError("GOOGLE_API_KEY not found in .env file") logger.debug(f"API key found, length: {len(self.api_key)}") try: self.generator = AutoDiffusersGenerator(self.api_key) logger.info("AutoDiffusersGenerator initialized successfully") except Exception as e: logger.error(f"Failed to initialize AutoDiffusersGenerator: {e}") raise try: self.memory_calculator = SimpleMemoryCalculator() logger.info("SimpleMemoryCalculator initialized successfully") except Exception as e: logger.error(f"Failed to initialize SimpleMemoryCalculator: {e}") raise # Default settings self.current_model = 'gemini-2.5-flash-preview-05-20' self.temperature = 0.7 self.max_output_tokens = 8192 self.top_p = 0.9 self.top_k = 40 logger.debug(f"Default model settings: {self.current_model}, temp={self.temperature}") def update_model_settings(self, model_name, temperature, max_output_tokens, top_p, top_k): """Update Gemini model settings.""" logger.info(f"Updating model settings: {model_name}") logger.debug(f"New settings: temp={temperature}, max_tokens={max_output_tokens}, top_p={top_p}, top_k={top_k}") try: self.current_model = model_name self.temperature = temperature self.max_output_tokens = max_output_tokens self.top_p = top_p self.top_k = top_k # Update the generator's model with new settings genai.configure(api_key=self.api_key) generation_config = genai.types.GenerationConfig( temperature=temperature, max_output_tokens=max_output_tokens, top_p=top_p, top_k=top_k ) self.generator.model = genai.GenerativeModel(model_name, generation_config=generation_config) logger.info("Model settings updated successfully") return f"✅ Model updated to {model_name} with new settings" except Exception as e: logger.error(f"Failed to update model settings: {e}") return f"❌ Failed to update model: {str(e)}" def get_generation_prompt(self, model_name, prompt_text, image_size, num_inference_steps, hardware_specs, optimization_profile): """Get the actual prompt that will be sent to Gemini API.""" return self.generator._create_generation_prompt( model_name, prompt_text, image_size, num_inference_steps, hardware_specs, optimization_profile ) def analyze_model_memory(self, model_name, vram_gb): """Analyze model memory requirements and provide recommendations.""" try: if not vram_gb: vram_gb = 8 # Default memory_info = self.memory_calculator.get_model_memory_requirements(model_name) recommendations = self.memory_calculator.get_memory_recommendation(model_name, float(vram_gb)) formatted_info = self.memory_calculator.format_memory_info(model_name) return memory_info, recommendations, formatted_info except Exception as e: error_msg = f"Error analyzing model memory: {str(e)}" return {'error': error_msg}, {'error': error_msg}, error_msg def generate_code_with_manual_specs(self, gpu_name, vram_gb, ram_gb, platform, model_name, prompt_text, dtype_selection, width, height, inference_steps, memory_analysis=None): """Generate optimized code with manual hardware specifications.""" try: # Create manual hardware specs # Parse dtype selection if dtype_selection == "Auto (Let AI decide)": user_dtype = None else: user_dtype = dtype_selection manual_specs = { 'platform': platform, 'architecture': 'manual_input', 'cpu_count': 8, # Default 'python_version': '3.11', 'cuda_available': 'nvidia' in gpu_name.lower() if gpu_name else False, 'mps_available': platform == 'Darwin' and 'apple' in gpu_name.lower() if gpu_name else False, 'torch_version': '2.0+', 'manual_input': True, 'ram_gb': int(ram_gb) if ram_gb else 16, 'user_dtype': user_dtype } # Add GPU info if provided if gpu_name and vram_gb: manual_specs['gpu_info'] = [{ 'name': gpu_name, 'memory_mb': int(vram_gb) * 1024 }] if 'nvidia' in gpu_name.lower(): manual_specs['cuda_available'] = True manual_specs['cuda_device_count'] = 1 manual_specs['cuda_device_name'] = gpu_name manual_specs['cuda_memory'] = int(vram_gb) else: manual_specs['gpu_info'] = None # Generate optimized code with manual specs and memory analysis optimized_code = self.generator.generate_optimized_code( model_name=model_name, prompt_text=prompt_text, image_size=(int(height), int(width)), num_inference_steps=int(inference_steps), use_manual_specs=True, manual_specs=manual_specs, memory_analysis=memory_analysis ) # Clean up any markdown formatting if optimized_code.startswith('```python'): optimized_code = optimized_code[9:] if optimized_code.endswith('```'): optimized_code = optimized_code[:-3] return optimized_code.strip() except Exception as e: return f"Error generating code: {str(e)}" def create_gradio_interface(): """Create and configure the Gradio interface.""" app = GradioAutodiffusers() with gr.Blocks( title="Auto-Diffusers Code Generator", theme=gr.themes.Soft( primary_hue="violet", secondary_hue="blue", neutral_hue="slate", radius_size=gr.themes.sizes.radius_lg, font=[gr.themes.GoogleFont("Poppins"), gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"] ).set( background_fill_primary="*neutral_25", background_fill_secondary="*neutral_50", block_background_fill="rgba(255, 255, 255, 0.95)", block_border_width="0px", block_shadow="0 8px 32px rgba(0, 0, 0, 0.08)", panel_background_fill="rgba(255, 255, 255, 0.9)", button_primary_background_fill="*primary_500", button_primary_background_fill_hover="*primary_600", button_secondary_background_fill="rgba(255, 255, 255, 0.8)", button_secondary_background_fill_hover="rgba(255, 255, 255, 0.95)" ), css=""" /* Global Styles */ .gradio-container { background: linear-gradient(135deg, #667eea 0%, #764ba2 25%, #f093fb 50%, #f5576c 75%, #4facfe 100%) !important; min-height: 100vh; } .main-container { max-width: 1400px; margin: 0 auto; padding: 2rem; /* Removed position: relative that can interfere with dropdown positioning */ } /* Floating Background Elements */ .main-container::before { content: ''; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%), radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%), radial-gradient(circle at 40% 70%, rgba(124, 58, 237, 0.1) 0%, transparent 50%); pointer-events: none; z-index: -1; } /* Glass Morphism Effects - Fixed for Dropdown Compatibility */ .glass-card { background: rgba(255, 255, 255, 0.25) !important; border: 1px solid rgba(255, 255, 255, 0.2) !important; border-radius: 20px !important; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important; /* Removed backdrop-filter and transforms that break dropdown positioning */ } .ultra-glass { background: rgba(255, 255, 255, 0.15) !important; border: 1px solid rgba(255, 255, 255, 0.3) !important; border-radius: 24px !important; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.3) !important; /* Removed backdrop-filter that interferes with dropdown positioning */ } /* Premium Header */ .hero-header { background: linear-gradient(135deg, rgba(124, 58, 237, 0.9) 0%, rgba(236, 72, 153, 0.9) 50%, rgba(59, 130, 246, 0.9) 100%) !important; backdrop-filter: blur(20px) !important; border: 1px solid rgba(255, 255, 255, 0.2) !important; border-radius: 24px !important; box-shadow: 0 20px 60px rgba(124, 58, 237, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important; position: relative; overflow: hidden; } .hero-header::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent); animation: shimmer 3s infinite; } @keyframes shimmer { 0% { left: -100%; } 50% { left: 100%; } 100% { left: 100%; } } /* Premium Buttons */ .generate-btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%) !important; border: none !important; color: white !important; font-weight: 700 !important; font-size: 1.1rem !important; padding: 1rem 3rem !important; border-radius: 16px !important; box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) !important; position: relative; overflow: hidden; } .generate-btn::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent); transition: left 0.5s; } .generate-btn:hover::before { left: 100%; } .generate-btn:hover { transform: translateY(-4px) scale(1.02) !important; box-shadow: 0 16px 48px rgba(102, 126, 234, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.3) !important; } .generate-btn:active { transform: translateY(-2px) scale(1.01) !important; } /* Section Headers */ .section-header { background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.9) 100%) !important; backdrop-filter: blur(10px) !important; border: 1px solid rgba(255, 255, 255, 0.4) !important; border-radius: 16px !important; padding: 1.5rem !important; margin-bottom: 1.5rem !important; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.4) !important; } /* Premium Inputs - Simplified for Dropdown Compatibility */ input[type="text"], input[type="number"], textarea { background: rgba(255, 255, 255, 0.9) !important; border: 1px solid rgba(255, 255, 255, 0.3) !important; border-radius: 12px !important; padding: 0.75rem 1rem !important; font-weight: 500 !important; transition: all 0.3s ease !important; } input[type="text"]:focus, input[type="number"]:focus, textarea:focus { background: rgba(255, 255, 255, 0.95) !important; border-color: rgba(124, 58, 237, 0.5) !important; box-shadow: 0 0 0 4px rgba(124, 58, 237, 0.1), 0 4px 20px rgba(124, 58, 237, 0.2) !important; } /* CRITICAL: Reset all problematic CSS for dropdowns */ label:has(+ [data-testid="dropdown"]), div:has([data-testid="dropdown"]), [data-testid="dropdown"], [data-testid="dropdown"] *, .gradio-dropdown, .gradio-dropdown * { position: static !important; transform: none !important; backdrop-filter: none !important; filter: none !important; } /* AGGRESSIVE FIX: Override ALL possible transparency sources */ * { --dropdown-bg: #ffffff !important; --dropdown-opacity: 1 !important; } /* Target every possible dropdown element with maximum specificity */ .gradio-container [data-testid="dropdown"] div[role="listbox"], .gradio-container .gradio-dropdown .dropdown-content, .gradio-container .dropdown-menu, .gradio-container div[role="listbox"], .gradio-container .svelte-1gfkn6j, body [data-testid="dropdown"] div[role="listbox"], body .dropdown-menu, body div[role="listbox"], html [data-testid="dropdown"] div[role="listbox"] { background: #ffffff !important; background-color: #ffffff !important; opacity: 1 !important; position: absolute !important; z-index: 99999 !important; border: 2px solid #d1d5db !important; border-radius: 8px !important; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25) !important; max-height: 200px !important; overflow-y: auto !important; backdrop-filter: none !important; filter: none !important; background-image: none !important; background-blend-mode: normal !important; /* Force solid with CSS variables */ background: var(--dropdown-bg, #ffffff) !important; opacity: var(--dropdown-opacity, 1) !important; } /* Aggressive option styling */ .gradio-container [data-testid="dropdown"] div[role="listbox"] > *, .gradio-container .dropdown-menu > *, .gradio-container div[role="listbox"] > *, body [data-testid="dropdown"] div[role="listbox"] > *, body .dropdown-menu > *, body div[role="listbox"] > * { background: #ffffff !important; background-color: #ffffff !important; padding: 0.75rem 1rem !important; color: #1f2937 !important; cursor: pointer !important; opacity: 1 !important; border: none !important; margin: 0 !important; display: block !important; width: 100% !important; text-align: left !important; } /* Ensure dropdown menus appear correctly with SOLID background */ [data-testid="dropdown"] div[role="listbox"], .gradio-dropdown .dropdown-content, .dropdown-menu, div[role="listbox"], .svelte-1gfkn6j, .gradio-container div[role="listbox"] { position: absolute !important; z-index: 9999 !important; background: #ffffff !important; background-color: #ffffff !important; opacity: 1 !important; border: 1px solid #d1d5db !important; border-radius: 8px !important; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15) !important; max-height: 200px !important; overflow-y: auto !important; backdrop-filter: none !important; /* Force solid background */ background-image: none !important; background-blend-mode: normal !important; } /* Dropdown option styling - SOLID background for each option */ [data-testid="dropdown"] div[role="listbox"] > *, .dropdown-menu > *, div[role="listbox"] > *, .svelte-1gfkn6j > * { background: #ffffff !important; background-color: #ffffff !important; padding: 0.5rem 0.75rem !important; color: #374151 !important; cursor: pointer !important; transition: background-color 0.2s ease !important; opacity: 1 !important; } /* Dropdown option hover effect */ [data-testid="dropdown"] div[role="listbox"] > *:hover, .dropdown-menu > *:hover, div[role="listbox"] > *:hover { background: #f3f4f6 !important; color: #1f2937 !important; } /* Dropdown option selected state */ [data-testid="dropdown"] div[role="listbox"] > *[aria-selected="true"], .dropdown-menu > *.selected, div[role="listbox"] > *[aria-selected="true"] { background: #e0e7ff !important; color: #3730a3 !important; } /* Code Areas - Ultra Premium Styling */ .code-container { background: linear-gradient(145deg, rgba(15, 23, 42, 0.98) 0%, rgba(30, 41, 59, 0.95) 50%, rgba(15, 23, 42, 0.98) 100%) !important; backdrop-filter: blur(30px) !important; border: 2px solid transparent !important; background-clip: padding-box !important; border-radius: 20px !important; position: relative !important; overflow: hidden !important; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4), 0 8px 32px rgba(15, 23, 42, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1), inset 0 -1px 0 rgba(71, 85, 105, 0.2) !important; } .code-container::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient(45deg, rgba(99, 102, 241, 0.1) 0%, rgba(139, 92, 246, 0.1) 25%, rgba(59, 130, 246, 0.1) 50%, rgba(139, 92, 246, 0.1) 75%, rgba(99, 102, 241, 0.1) 100%) !important; border-radius: 20px !important; z-index: -1 !important; animation: code-shimmer 3s ease-in-out infinite !important; } @keyframes code-shimmer { 0%, 100% { opacity: 0.3; } 50% { opacity: 0.6; } } /* Code editor styling */ .code-container .cm-editor { background: transparent !important; border-radius: 16px !important; font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', 'Fira Code', monospace !important; font-size: 13px !important; line-height: 1.6 !important; } .code-container .cm-focused { outline: none !important; box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.4) !important; } .code-container .cm-content { padding: 1.5rem !important; color: #e2e8f0 !important; } .code-container .cm-line { padding-left: 0.5rem !important; } /* Syntax highlighting for Python */ .code-container .cm-keyword { color: #f472b6 !important; } .code-container .cm-string { color: #34d399 !important; } .code-container .cm-comment { color: #94a3b8 !important; font-style: italic !important; } .code-container .cm-number { color: #fbbf24 !important; } .code-container .cm-variable { color: #60a5fa !important; } .code-container .cm-function { color: #a78bfa !important; } .code-container .cm-operator { color: #fb7185 !important; } /* Code header styling */ .code-container label { background: linear-gradient(90deg, rgba(99, 102, 241, 0.9) 0%, rgba(139, 92, 246, 0.9) 50%, rgba(59, 130, 246, 0.9) 100%) !important; color: white !important; padding: 1rem 1.5rem !important; border-radius: 16px 16px 0 0 !important; font-weight: 600 !important; font-size: 1rem !important; letter-spacing: 0.025em !important; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important; margin: 0 !important; border: none !important; box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2) !important; } /* Custom scrollbar for code area */ .code-container .cm-scroller::-webkit-scrollbar { width: 8px !important; height: 8px !important; } .code-container .cm-scroller::-webkit-scrollbar-track { background: rgba(15, 23, 42, 0.3) !important; border-radius: 4px !important; } .code-container .cm-scroller::-webkit-scrollbar-thumb { background: linear-gradient(135deg, rgba(99, 102, 241, 0.6) 0%, rgba(139, 92, 246, 0.6) 100%) !important; border-radius: 4px !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; } .code-container .cm-scroller::-webkit-scrollbar-thumb:hover { background: linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.8) 100%) !important; } /* Line numbers styling */ .code-container .cm-lineNumbers { background: rgba(15, 23, 42, 0.3) !important; color: rgba(148, 163, 184, 0.6) !important; border-right: 1px solid rgba(71, 85, 105, 0.3) !important; padding-right: 0.5rem !important; } .code-container .cm-lineNumbers .cm-gutterElement { color: rgba(148, 163, 184, 0.5) !important; font-weight: 500 !important; } /* Memory Analysis Cards */ .memory-card { background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(245, 158, 11, 0.1) 100%) !important; backdrop-filter: blur(15px) !important; border: 1px solid rgba(251, 191, 36, 0.2) !important; border-radius: 16px !important; padding: 1.5rem !important; box-shadow: 0 8px 32px rgba(245, 158, 11, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important; } /* Labels with icons */ label { font-weight: 600 !important; color: rgba(30, 41, 59, 0.9) !important; font-size: 0.95rem !important; } /* Floating Animation */ @keyframes float { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-10px); } } .floating { animation: float 6s ease-in-out infinite; } /* Pulse Effect */ @keyframes pulse-glow { 0%, 100% { box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2); } 50% { box-shadow: 0 12px 48px rgba(102, 126, 234, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.3); } } .pulse-glow { animation: pulse-glow 3s ease-in-out infinite; } /* FINAL OVERRIDE: Nuclear option for dropdown transparency */ [role="listbox"] { background: white !important; opacity: 1 !important; } [role="listbox"] > * { background: white !important; opacity: 1 !important; } /* Gradio-specific nuclear option */ .gradio-app [role="listbox"], .gradio-app [role="listbox"] > * { background: #ffffff !important; background-color: #ffffff !important; opacity: 1 !important; } /* Last resort: override all possible transparent backgrounds */ div[style*="background"] { background: unset !important; } [role="listbox"][style*="background"] { background: #ffffff !important; } /* Mobile Responsive Styles */ @media (max-width: 768px) { .main-container { margin: 0 1px !important; padding: 1rem !important; max-width: calc(100% - 2px) !important; } .gradio-container { margin: 0 1px !important; padding: 0 !important; } /* Set left/right margins to 1px for mobile */ .gradio-container > * { margin-left: 1px !important; margin-right: 1px !important; } /* Adjust hero header for mobile */ .hero-header { padding: 2rem 1rem !important; margin-bottom: 2rem !important; } .hero-header h1 { font-size: 2.5rem !important; } .hero-header h2 { font-size: 1.4rem !important; } /* Mobile-friendly glass panels */ .glass-panel { margin: 0.5rem 0 !important; padding: 1rem !important; border-radius: 12px !important; } /* Responsive button sizing */ .primary-button { padding: 0.8rem 2rem !important; font-size: 1rem !important; } /* Mobile code container */ .code-container { margin: 0 !important; border-radius: 8px !important; } /* Stack columns on mobile */ .gradio-row { flex-direction: column !important; } } /* Small mobile devices */ @media (max-width: 480px) { .main-container { margin: 0 1px !important; padding: 0.5rem !important; } .hero-header { padding: 1.5rem 0.5rem !important; } .hero-header h1 { font-size: 2rem !important; } .hero-header h2 { font-size: 1.2rem !important; } .glass-panel { padding: 0.8rem !important; margin: 0.25rem 0 !important; } } """ ) as interface: with gr.Column(elem_classes="main-container"): # Ultra Premium Header with gr.Row(): with gr.Column(scale=1): gr.HTML("""
Generate stunning, optimized diffusers code tailored perfectly for your hardware using advanced AI
Configure your system hardware for optimal code generation
Configure the AI model and generation parameters
Real-time analysis of model memory requirements and optimization strategies