File size: 31,207 Bytes
5b9724f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
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

        """)