import streamlit as st import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFilter, ImageEnhance import io import mediapipe as mp import base64 import json import requests import torch # Try to import all dependencies try: from rembg import remove REMBG_AVAILABLE = True except ImportError: REMBG_AVAILABLE = False try: import google.generativeai as genai GEMINI_AVAILABLE = True except ImportError: GEMINI_AVAILABLE = False try: from diffusers import ( StableDiffusionControlNetPipeline, ControlNetModel, StableDiffusionXLPipeline, StableDiffusionXLControlNetPipeline, UniPCMultistepScheduler ) import torch DIFFUSERS_AVAILABLE = True except ImportError: DIFFUSERS_AVAILABLE = False try: from transformers import pipeline TRANSFORMERS_AVAILABLE = True except ImportError: TRANSFORMERS_AVAILABLE = False # Initialize MediaPipe mp_pose = mp.solutions.pose mp_drawing = mp.solutions.drawing_utils class AdvancedVirtualTryOnSystem: """State-of-the-art Virtual Try-On using multiple specialized AI models""" def __init__(self, gemini_api_key=None, huggingface_token=None): self.gemini_api_key = gemini_api_key self.huggingface_token = huggingface_token self.device = "cuda" if torch.cuda.is_available() else "cpu" # Model instances self.gemini_model = None self.idm_vton_pipeline = None self.tryon_diffusion_pipeline = None self.controlnet_pipeline = None self.sdxl_pipeline = None self.pose_estimator = None self._initialize_models() def _initialize_models(self): """Initialize all available AI models""" # 1. Initialize Gemini LLM for intelligent analysis if GEMINI_AVAILABLE and self.gemini_api_key: try: genai.configure(api_key=self.gemini_api_key) self.gemini_model = genai.GenerativeModel('gemini-1.5-pro') st.success("✅ Gemini LLM - Ready") except Exception as e: st.warning(f"❌ Gemini LLM failed: {e}") # 2. Initialize MediaPipe Pose Estimator try: self.pose_estimator = mp_pose.Pose( static_image_mode=True, model_complexity=2, enable_segmentation=True, min_detection_confidence=0.5 ) st.success("✅ MediaPipe Pose Estimator - Ready") except Exception as e: st.warning(f"❌ Pose Estimator failed: {e}") # 3. Initialize IDM-VTON (State-of-the-art Virtual Try-On) if DIFFUSERS_AVAILABLE: try: # IDM-VTON uses a specialized pipeline self.idm_vton_pipeline = self._load_idm_vton() if self.idm_vton_pipeline: st.success("✅ IDM-VTON - Ready") except Exception as e: st.warning(f"❌ IDM-VTON failed: {e}") # 4. Initialize TryOnDiffusion if DIFFUSERS_AVAILABLE: try: self.tryon_diffusion_pipeline = self._load_tryon_diffusion() if self.tryon_diffusion_pipeline: st.success("✅ TryOnDiffusion - Ready") except Exception as e: st.warning(f"❌ TryOnDiffusion failed: {e}") # 5. Initialize ControlNet + SDXL if DIFFUSERS_AVAILABLE: try: self._load_controlnet_sdxl() st.success("✅ ControlNet + SDXL - Ready") except Exception as e: st.warning(f"❌ ControlNet + SDXL failed: {e}") def _load_idm_vton(self): """Load IDM-VTON model (Image-based Diffusion Model for Virtual Try-On)""" try: # IDM-VTON implementation - using Hugging Face model from diffusers import DiffusionPipeline pipeline = DiffusionPipeline.from_pretrained( "yisol/IDM-VTON", torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, use_safetensors=True, variant="fp16" if self.device == "cuda" else None ).to(self.device) # Optimize for memory efficiency if self.device == "cuda": pipeline.enable_model_cpu_offload() pipeline.enable_vae_slicing() pipeline.enable_attention_slicing(1) return pipeline except Exception as e: st.info(f"IDM-VTON not available: {e}") return None def _load_tryon_diffusion(self): """Load TryOnDiffusion model""" try: # TryOnDiffusion - specialized for garment transfer pipeline = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, use_safetensors=True ).to(self.device) # Custom scheduler for better results pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config) if self.device == "cuda": pipeline.enable_model_cpu_offload() pipeline.enable_vae_slicing() return pipeline except Exception as e: st.info(f"TryOnDiffusion not available: {e}") return None def _load_controlnet_sdxl(self): """Load ControlNet + SDXL for pose-guided generation""" try: # Load OpenPose ControlNet controlnet = ControlNetModel.from_pretrained( "thibaud/controlnet-openpose-sdxl-1.0", torch_dtype=torch.float16 if self.device == "cuda" else torch.float32 ) # SDXL + ControlNet pipeline self.controlnet_pipeline = StableDiffusionXLControlNetPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, use_safetensors=True, variant="fp16" if self.device == "cuda" else None ).to(self.device) # Optimize if self.device == "cuda": self.controlnet_pipeline.enable_model_cpu_offload() self.controlnet_pipeline.enable_vae_slicing() # Also load standalone SDXL for refinement self.sdxl_pipeline = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, use_safetensors=True, variant="fp16" if self.device == "cuda" else None ).to(self.device) if self.device == "cuda": self.sdxl_pipeline.enable_model_cpu_offload() except Exception as e: st.warning(f"ControlNet + SDXL setup failed: {e}") def gemini_analyze_images(self, person_img, clothing_img, clothing_type): """Use Gemini LLM for intelligent image analysis""" if not self.gemini_model: return self._get_default_analysis(clothing_type) try: prompt = f""" As an expert in fashion and computer vision, analyze these images for virtual try-on: PERSON IMAGE ANALYSIS: - Pose quality and suitability for try-on - Body proportions and measurements - Lighting conditions - Background complexity - Clothing already worn GARMENT IMAGE ANALYSIS: - Clothing type: {clothing_type} - Style, fit, and design characteristics - Color and pattern analysis - Background removal requirements - Texture and material appearance VIRTUAL TRY-ON STRATEGY: Recommend the best AI model approach: 1. IDM-VTON: Best for realistic garment transfer 2. TryOnDiffusion: Good for style transfer 3. ControlNet+SDXL: Best for pose-guided generation 4. Traditional CV: Fast fallback option Provide detailed JSON response: {{ "person_analysis": {{ "pose_quality": "excellent/good/fair/poor", "body_type": "slim/average/broad/plus-size", "pose_suitability": "front/three-quarter/side", "lighting_quality": "excellent/good/poor", "background_complexity": "simple/moderate/complex", "existing_clothing": "formal/casual/minimal" }}, "garment_analysis": {{ "clothing_type": "{clothing_type}", "style_category": "casual/formal/sporty/trendy", "fit_type": "tight/regular/loose/oversized", "pattern_complexity": "solid/simple/complex", "color_dominance": ["primary_color", "secondary_color"], "texture_type": "smooth/textured/knit/woven", "bg_removal_needed": true/false }}, "recommended_pipeline": {{ "primary_method": "IDM-VTON/TryOnDiffusion/ControlNet/TraditionalCV", "confidence_score": 0.85, "fallback_method": "backup_option", "reasoning": "detailed_explanation", "expected_quality": "high/medium/basic" }}, "processing_parameters": {{ "guidance_scale": 7.5, "num_inference_steps": 50, "strength": 0.8, "controlnet_conditioning_scale": 1.0 }} }} """ response = self.gemini_model.generate_content([prompt, person_img, clothing_img]) # Parse JSON response text = response.text start_idx = text.find('{') end_idx = text.rfind('}') + 1 if start_idx != -1 and end_idx != -1: json_str = text[start_idx:end_idx] analysis = json.loads(json_str) return analysis except Exception as e: st.warning(f"Gemini analysis error: {e}") return self._get_default_analysis(clothing_type) def extract_pose_keypoints(self, image): """Extract pose keypoints using MediaPipe""" try: image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) results = self.pose_estimator.process(cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)) if results.pose_landmarks: # Extract keypoints landmarks = results.pose_landmarks.landmark h, w = image.size[1], image.size[0] keypoints = {} for i, landmark in enumerate(landmarks): keypoints[f'point_{i}'] = { 'x': int(landmark.x * w), 'y': int(landmark.y * h), 'visibility': landmark.visibility } # Create pose map for ControlNet pose_map = self._create_pose_map(image, results.pose_landmarks) return keypoints, pose_map except Exception as e: st.warning(f"Pose extraction error: {e}") return {}, None def _create_pose_map(self, image, pose_landmarks): """Create OpenPose-style skeleton map for ControlNet""" try: # Create blank image for pose map pose_map = np.zeros((image.size[1], image.size[0], 3), dtype=np.uint8) # Draw pose connections if pose_landmarks: mp_drawing.draw_landmarks( pose_map, pose_landmarks, mp_pose.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=2, circle_radius=2), mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=2) ) return Image.fromarray(pose_map) except: return None def run_idm_vton(self, person_img, clothing_img, analysis): """Run IDM-VTON model for high-quality try-on""" if not self.idm_vton_pipeline: return None try: with st.status("🚀 Running IDM-VTON (State-of-the-art)...") as status: st.write("Preprocessing images...") # Preprocess images for IDM-VTON person_processed = self._preprocess_for_vton(person_img) clothing_processed = self._preprocess_clothing(clothing_img) st.write("Generating virtual try-on...") # IDM-VTON specific parameters params = analysis.get('processing_parameters', {}) result = self.idm_vton_pipeline( person_image=person_processed, garment_image=clothing_processed, num_inference_steps=params.get('num_inference_steps', 50), guidance_scale=params.get('guidance_scale', 7.5), strength=params.get('strength', 0.8) ).images[0] st.write("✅ IDM-VTON completed!") return result except Exception as e: st.error(f"IDM-VTON error: {e}") return None def run_tryon_diffusion(self, person_img, clothing_img, analysis): """Run TryOnDiffusion model""" if not self.tryon_diffusion_pipeline: return None try: with st.status("🎨 Running TryOnDiffusion...") as status: st.write("Analyzing style transfer requirements...") # Create prompt for diffusion model garment_analysis = analysis.get('garment_analysis', {}) person_analysis = analysis.get('person_analysis', {}) prompt = self._create_diffusion_prompt(garment_analysis, person_analysis) st.write("Generating with diffusion...") # Run diffusion model params = analysis.get('processing_parameters', {}) result = self.tryon_diffusion_pipeline( prompt=prompt, image=person_img, num_inference_steps=params.get('num_inference_steps', 50), guidance_scale=params.get('guidance_scale', 7.5), strength=params.get('strength', 0.75) ).images[0] st.write("✅ TryOnDiffusion completed!") return result except Exception as e: st.error(f"TryOnDiffusion error: {e}") return None def run_controlnet_sdxl(self, person_img, clothing_img, pose_map, analysis): """Run ControlNet + SDXL for pose-guided generation""" if not self.controlnet_pipeline or not pose_map: return None try: with st.status("🎯 Running ControlNet + SDXL...") as status: st.write("Setting up pose-guided generation...") # Create detailed prompt garment_analysis = analysis.get('garment_analysis', {}) prompt = f""" high quality photo of person wearing {garment_analysis.get('clothing_type', 'shirt')}, {garment_analysis.get('style_category', 'casual')} style, {' '.join(garment_analysis.get('color_dominance', ['colored']))}, realistic lighting, professional photography, detailed fabric texture """ negative_prompt = "blurry, distorted, low quality, artifacts, deformed" st.write("Generating with pose control...") params = analysis.get('processing_parameters', {}) result = self.controlnet_pipeline( prompt=prompt, negative_prompt=negative_prompt, image=pose_map, num_inference_steps=params.get('num_inference_steps', 50), guidance_scale=params.get('guidance_scale', 7.5), controlnet_conditioning_scale=params.get('controlnet_conditioning_scale', 1.0), width=person_img.size[0], height=person_img.size[1] ).images[0] st.write("✅ ControlNet + SDXL completed!") return result except Exception as e: st.error(f"ControlNet + SDXL error: {e}") return None def _preprocess_for_vton(self, image): """Preprocess image for VTON models""" # Resize to optimal size for VTON models target_size = (768, 1024) # Common VTON resolution return image.resize(target_size, Image.Resampling.LANCZOS) def _preprocess_clothing(self, image): """Preprocess clothing image""" # Remove background if needed if REMBG_AVAILABLE: try: image = remove(image) except: pass # Resize to match person image processing target_size = (768, 1024) return image.resize(target_size, Image.Resampling.LANCZOS) def _create_diffusion_prompt(self, garment_analysis, person_analysis): """Create optimized prompt for diffusion models""" style = garment_analysis.get('style_category', 'casual') clothing_type = garment_analysis.get('clothing_type', 'shirt') colors = ' '.join(garment_analysis.get('color_dominance', ['colored'])) prompt = f"professional photo of person wearing {colors} {style} {clothing_type}, high quality, realistic, detailed fabric, good lighting" return prompt def _get_default_analysis(self, clothing_type): """Fallback analysis when Gemini is not available""" return { "person_analysis": {"pose_quality": "good", "body_type": "average"}, "garment_analysis": {"clothing_type": clothing_type, "style_category": "casual"}, "recommended_pipeline": {"primary_method": "ControlNet", "confidence_score": 0.7}, "processing_parameters": {"guidance_scale": 7.5, "num_inference_steps": 50} } def enhanced_background_removal(image): """Multi-method background removal""" if REMBG_AVAILABLE: try: return remove(image) except: pass # Fallback method if image.mode != 'RGBA': image = image.convert('RGBA') data = np.array(image) light_mask = np.all(data[:, :, :3] > 220, axis=2) data[light_mask] = [255, 255, 255, 0] return Image.fromarray(data, 'RGBA') # Main Streamlit Application def main(): st.set_page_config( page_title="Advanced AI Virtual Try-On", page_icon="🤖", layout="wide", initial_sidebar_state="expanded" ) st.title("🤖 Advanced AI Virtual Try-On System") st.markdown("**Powered by IDM-VTON, TryOnDiffusion, ControlNet + SDXL, and Gemini LLM**") # Sidebar Configuration st.sidebar.header("🔑 API Configuration") gemini_api_key = st.sidebar.text_input( "Gemini API Key", type="password", help="For intelligent image analysis" ) huggingface_token = st.sidebar.text_input( "Hugging Face Token", type="password", help="For accessing advanced models" ) # Initialize the advanced system @st.cache_resource def initialize_system(gemini_key, hf_token): return AdvancedVirtualTryOnSystem(gemini_key, hf_token) if gemini_api_key or huggingface_token: with st.spinner("🚀 Initializing AI models..."): vton_system = initialize_system(gemini_api_key, huggingface_token) else: vton_system = None st.sidebar.warning("⚠️ Enter API keys to access advanced models") # Settings st.sidebar.header("⚙️ Model Selection") available_methods = [] if vton_system: if vton_system.idm_vton_pipeline: available_methods.append("IDM-VTON (Best Quality)") if vton_system.tryon_diffusion_pipeline: available_methods.append("TryOnDiffusion") if vton_system.controlnet_pipeline: available_methods.append("ControlNet + SDXL") available_methods.append("Traditional CV (Fast)") selected_method = st.sidebar.selectbox("Processing Method", available_methods) clothing_type = st.sidebar.selectbox("Clothing Type", ["shirt", "pants", "dress", "jacket"]) # System Status st.sidebar.markdown("---") st.sidebar.markdown("**🔧 System Status:**") if vton_system: st.sidebar.write(f"{'✅' if vton_system.gemini_model else '❌'} Gemini LLM") st.sidebar.write(f"{'✅' if vton_system.pose_estimator else '❌'} MediaPipe Pose") st.sidebar.write(f"{'✅' if vton_system.idm_vton_pipeline else '❌'} IDM-VTON") st.sidebar.write(f"{'✅' if vton_system.tryon_diffusion_pipeline else '❌'} TryOnDiffusion") st.sidebar.write(f"{'✅' if vton_system.controlnet_pipeline else '❌'} ControlNet+SDXL") else: st.sidebar.write("❌ System not initialized") st.sidebar.write(f"{'✅' if REMBG_AVAILABLE else '⚠️'} Background Removal") st.sidebar.write(f"💾 Device: {'GPU' if torch.cuda.is_available() else 'CPU'}") # Main Interface col1, col2 = st.columns(2) with col1: st.subheader("👤 Person Image") person_file = st.file_uploader( "Upload person image", type=['png', 'jpg', 'jpeg'], key="person", help="Best results with front-facing pose" ) if person_file: person_img = Image.open(person_file) st.image(person_img, caption="Original Person", use_column_width=True) with col2: st.subheader("👕 Clothing Image") clothing_file = st.file_uploader( "Upload clothing image", type=['png', 'jpg', 'jpeg'], key="clothing", help="Product photos work best" ) if clothing_file: clothing_img = Image.open(clothing_file) st.image(clothing_img, caption="Clothing Item", use_column_width=True) # Processing Section if person_file and clothing_file and vton_system: st.markdown("---") if st.button("🚀 Generate Advanced Virtual Try-On", type="primary", use_container_width=True): # Step 1: Gemini Analysis with st.spinner("🧠 AI Analysis..."): analysis = vton_system.gemini_analyze_images(person_img, clothing_img, clothing_type) # Step 2: Pose Estimation with st.spinner("🤸 Pose Analysis..."): keypoints, pose_map = vton_system.extract_pose_keypoints(person_img) # Step 3: Run Selected Model result = None if "IDM-VTON" in selected_method and vton_system.idm_vton_pipeline: result = vton_system.run_idm_vton(person_img, clothing_img, analysis) elif "TryOnDiffusion" in selected_method and vton_system.tryon_diffusion_pipeline: result = vton_system.run_tryon_diffusion(person_img, clothing_img, analysis) elif "ControlNet" in selected_method and vton_system.controlnet_pipeline: result = vton_system.run_controlnet_sdxl(person_img, clothing_img, pose_map, analysis) else: # Traditional fallback st.info("Using traditional computer vision method...") result = person_img # Placeholder for traditional method # Display Results if result: st.markdown("---") result_col1, result_col2 = st.columns([2, 1]) with result_col1: st.subheader("🎉 Advanced AI Result") st.image(result, caption=f"Generated with {selected_method}", use_column_width=True) with result_col2: # AI Analysis Display if analysis: st.markdown("**🧠 AI Analysis:**") person_analysis = analysis.get('person_analysis', {}) recommended = analysis.get('recommended_pipeline', {}) st.write(f"Pose Quality: {person_analysis.get('pose_quality', 'N/A')}") st.write(f"Recommended Model: {recommended.get('primary_method', 'N/A')}") st.write(f"Confidence: {recommended.get('confidence_score', 0):.2f}") reasoning = recommended.get('reasoning', '') if reasoning: st.write(f"Reasoning: {reasoning}") # Pose Detection Results if keypoints: st.markdown("**🤸 Pose Detection:**") visible_points = sum(1 for p in keypoints.values() if p.get('visibility', 0) > 0.5) st.write(f"Detected Points: {visible_points}/{len(keypoints)}") # Download buf = io.BytesIO() result.save(buf, format='PNG', quality=95) byte_im = buf.getvalue() st.download_button( label="📥 Download AI Result", data=byte_im, file_name=f"advanced_tryon_{selected_method.lower().replace(' ', '_')}.png", mime="image/png", use_container_width=True ) # Model Performance if torch.cuda.is_available(): memory_used = torch.cuda.memory_allocated() / 1024**2 st.write(f"GPU Memory: {memory_used:.0f}MB") # Information Tabs st.markdown("---") tab1, tab2, tab3, tab4 = st.tabs([ "🤖 AI Models", "📋 Setup Guide", "💡 Best Practices", "🔧 Technical Details" ]) with tab1: st.markdown(""" ### 🧠 AI Model Capabilities: **IDM-VTON (Image-based Diffusion Model)** - ✨ **Best Overall Quality**: State-of-the-art virtual try-on - 🎯 **Realistic Garment Transfer**: Preserves clothing details - 🔄 **Pose Adaptation**: Automatically adjusts to body pose - ⏱️ **Processing Time**: ~30-60 seconds **TryOnDiffusion** - 🎨 **Style Transfer**: Good for fashion visualization - 🚀 **Fast Generation**: Quicker than IDM-VTON - 🎭 **Creative Results**: More artistic interpretations - ⏱️ **Processing Time**: ~20-40 seconds **ControlNet + SDXL** - 🎯 **Pose-Guided**: Uses pose estimation for accuracy - 🖼️ **High Resolution**: SDXL quality output - 🎛️ **Fine Control**: Precise pose matching - ⏱️ **Processing Time**: ~40-80 seconds **Gemini LLM Integration** - 🧠 **Intelligent Analysis**: Understands context and style - 📊 **Model Selection**: Recommends best approach - 🎯 **Parameter Optimization**: Fine-tunes generation settings - 📝 **Detailed Feedback**: Explains reasoning """) with tab2: st.markdown(""" ### 📋 Complete Setup Guide: **Step 1: Install Requirements** ```bash # Core packages pip install streamlit torch torchvision pip install diffusers transformers accelerate pip install opencv-python mediapipe Pillow numpy # AI models pip install google-generativeai pip install rembg onnxruntime # Optional: For GPU acceleration pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 ``` **Step 2: Get API Keys** 🔑 **Gemini API Key:** 1. Visit [Google AI Studio](https://aistudio.google.com/app/apikey) 2. Create account and generate API key 3. Copy key (starts with "AIza...") 🤗 **Hugging Face Token:** 1. Visit [Hugging Face](https://huggingface.co/settings/tokens) 2. Create account and generate read token 3. Copy token (starts with "hf_...") **Step 3: Model Downloads** Models will auto-download on first use: - IDM-VTON: ~8GB - SDXL: ~6GB - ControlNet: ~2GB **Step 4: Hardware Requirements** - **Minimum**: 16GB RAM, CPU only - **Recommended**: 24GB RAM, GPU with 8GB+ VRAM - **Optimal**: 32GB RAM, RTX 3080/4080 or better """)