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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
import gradio as gr
import torch
from PIL import Image
import numpy as np
from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline, DPMSolverMultistepScheduler
from diffusers.utils import load_image
import cv2
import os
from typing import Optional, Tuple
import warnings
import random
from huggingface_hub import hf_hub_download
warnings.filterwarnings("ignore")

# Try to import IPAdapter, fallback to manual implementation
try:
    from ip_adapter import IPAdapter
    HAS_IP_ADAPTER = True
except ImportError:
    HAS_IP_ADAPTER = False
    print("IPAdapter not found, using fallback implementation")

# Global variables for models
pipe = None
ip_adapter = None
device = "cuda" if torch.cuda.is_available() else "cpu"
current_model = None

# Available models
MODELS = {
    "Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5",
    "Stable Diffusion XL": "stabilityai/stable-diffusion-xl-base-1.0"
}

RESOLUTIONS = [
    "512x512",
    "768x768", 
    "1024x1024",
    "512x768",
    "768x512"
]

class FallbackIPAdapter:
    """Fallback IPAdapter implementation using CLIP image encoder"""
    def __init__(self, pipe, device):
        self.pipe = pipe
        self.device = device
        self.scale = 1.0
        
    def set_scale(self, scale):
        self.scale = scale
        
    def generate(self, pil_image, prompt, negative_prompt="", **kwargs):
        # Simple fallback: use the pipeline directly with image conditioning
        # This is a simplified version - real IPAdapter is more sophisticated
        try:
            # Convert image to tensor for conditioning (simplified approach)
            width = kwargs.get('width', 512)
            height = kwargs.get('height', 512)
            
            # Resize reference image to match output dimensions
            ref_image = pil_image.resize((width, height), Image.Resampling.LANCZOS)
            
            # Generate with standard pipeline
            result = self.pipe(
                prompt=prompt,
                negative_prompt=negative_prompt,
                num_inference_steps=kwargs.get('num_inference_steps', 20),
                guidance_scale=kwargs.get('guidance_scale', 7.5),
                width=width,
                height=height,
                generator=torch.Generator(device=self.device).manual_seed(kwargs.get('seed', random.randint(0, 2**32-1)))
            )
            
            return result.images
            
        except Exception as e:
            print(f"Fallback generation error: {e}")
            # Return a blank image as last resort
            return [Image.new('RGB', (width, height), (128, 128, 128))]

def parse_resolution(resolution_str: str) -> Tuple[int, int]:
    """Parse resolution string to width, height tuple"""
    width, height = map(int, resolution_str.split('x'))
    return width, height

def load_model(model_name: str):
    """Load the selected model with IPAdapter"""
    global pipe, ip_adapter, current_model
    
    if current_model == model_name and pipe is not None:
        return "Model already loaded"
    
    try:
        # Clear previous models
        if pipe is not None:
            del pipe
        if ip_adapter is not None:
            del ip_adapter
        torch.cuda.empty_cache() if torch.cuda.is_available() else None
        
        model_id = MODELS[model_name]
        
        # Load pipeline based on model type
        if "xl" in model_id.lower():
            pipe = StableDiffusionXLPipeline.from_pretrained(
                model_id,
                torch_dtype=torch.float16 if device == "cuda" else torch.float32,
                use_safetensors=True,
                variant="fp16" if device == "cuda" else None
            )
        else:
            pipe = StableDiffusionPipeline.from_pretrained(
                model_id,
                torch_dtype=torch.float16 if device == "cuda" else torch.float32,
                use_safetensors=True
            )
        
        # Optimize for memory
        pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
        pipe = pipe.to(device)
        
        if device == "cuda":
            try:
                pipe.enable_memory_efficient_attention()
            except:
                pass
            try:
                pipe.enable_xformers_memory_efficient_attention()
            except:
                pass
        
        # Load IPAdapter
        if HAS_IP_ADAPTER:
            try:
                if "xl" in model_id.lower():
                    ip_adapter = IPAdapter(pipe, "h94/IP-Adapter", "ip-adapter_sdxl.bin", device)
                else:
                    ip_adapter = IPAdapter(pipe, "h94/IP-Adapter", "ip-adapter_sd15.bin", device)
            except Exception as e:
                print(f"IPAdapter loading failed, using fallback: {e}")
                ip_adapter = FallbackIPAdapter(pipe, device)
        else:
            ip_adapter = FallbackIPAdapter(pipe, device)
        
        current_model = model_name
        return f"βœ… {model_name} loaded successfully"
        
    except Exception as e:
        return f"❌ Error loading model: {str(e)}"

def enhance_face(image: Image.Image, use_codeformer: bool = False) -> Image.Image:
    """Apply face enhancement using CodeFormer or GFPGAN"""
    try:
        if use_codeformer:
            # Placeholder for CodeFormer - would need actual implementation
            # For now, return original image
            return image
        else:
            # Placeholder for GFPGAN - would need actual implementation
            # For now, return original image
            return image
    except Exception as e:
        print(f"Face enhancement failed: {e}")
        return image

def apply_lora(pipe, lora_path: str, lora_scale: float = 1.0):
    """Apply LoRA weights to the pipeline"""
    try:
        if lora_path and os.path.exists(lora_path):
            pipe.load_lora_weights(lora_path)
            pipe.fuse_lora(lora_scale)
            return True
    except Exception as e:
        print(f"LoRA application failed: {e}")
    return False

def generate_image(
    prompt: str,
    reference_image: Image.Image,
    model_name: str,
    guidance_scale: float,
    resolution: str,
    num_steps: int,
    ip_adapter_scale: float,
    seed: int,
    enable_face_enhancement: bool,
    use_codeformer: bool,
    lora_path: str,
    lora_scale: float
) -> Tuple[Image.Image, str]:
    """Generate image using IPAdapter"""
    
    if not prompt.strip():
        return None, "❌ Please enter a text prompt"
    
    if reference_image is None:
        return None, "❌ Please upload a reference image"
    
    try:
        # Load model if needed
        load_status = load_model(model_name)
        if "Error" in load_status:
            return None, load_status
        
        # Parse resolution
        width, height = parse_resolution(resolution)
        
        # Set seed for reproducibility
        if seed <= 0:
            seed = random.randint(0, 2**32-1)
        
        torch.manual_seed(seed)
        if torch.cuda.is_available():
            torch.cuda.manual_seed(seed)
        
        # Apply LoRA if specified
        lora_applied = False
        if lora_path and lora_path.strip():
            lora_applied = apply_lora(pipe, lora_path.strip(), lora_scale)
        
        # Prepare reference image
        ref_image = reference_image.convert("RGB")
        ref_image = ref_image.resize((width, height), Image.Resampling.LANCZOS)
        
        # Generate image with IPAdapter
        with torch.autocast(device):
            # Set IPAdapter scale
            ip_adapter.set_scale(ip_adapter_scale)
            
            # Generate
            generated_images = ip_adapter.generate(
                pil_image=ref_image,
                prompt=prompt,
                negative_prompt="blurry, low quality, distorted, deformed, ugly, bad anatomy",
                num_inference_steps=num_steps,
                guidance_scale=guidance_scale,
                width=width,
                height=height,
                seed=seed
            )
            
            generated_image = generated_images[0]
        
        # Apply face enhancement if enabled
        if enable_face_enhancement:
            generated_image = enhance_face(generated_image, use_codeformer)
        
        # Create side-by-side comparison
        comparison = create_comparison(ref_image, generated_image)
        
        status = f"βœ… Image generated successfully (seed: {seed})"
        if lora_applied:
            status += f" (LoRA applied: {lora_scale:.2f})"
        
        return comparison, status
        
    except Exception as e:
        error_msg = f"❌ Generation failed: {str(e)}"
        print(error_msg)
        return None, error_msg

def create_comparison(reference: Image.Image, generated: Image.Image) -> Image.Image:
    """Create side-by-side comparison of reference and generated images"""
    # Ensure both images have the same height
    ref_width, ref_height = reference.size
    gen_width, gen_height = generated.size
    
    # Resize to match heights
    target_height = min(ref_height, gen_height, 512)  # Limit height for display
    
    ref_aspect = ref_width / ref_height
    gen_aspect = gen_width / gen_height
    
    ref_resized = reference.resize((int(target_height * ref_aspect), target_height), Image.Resampling.LANCZOS)
    gen_resized = generated.resize((int(target_height * gen_aspect), target_height), Image.Resampling.LANCZOS)
    
    # Create comparison image
    total_width = ref_resized.width + gen_resized.width + 10  # 10px gap
    comparison = Image.new('RGB', (total_width, target_height), (255, 255, 255))
    
    comparison.paste(ref_resized, (0, 0))
    comparison.paste(gen_resized, (ref_resized.width + 10, 0))
    
    return comparison

# Create Gradio interface
def create_interface():
    with gr.Blocks(title="ComfyUI-Style IPAdapter Generator", theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # 🎨 ComfyUI-Style IPAdapter Generator
        Generate images using text prompts and reference images with IPAdapter technology.
        Upload a reference image (face or style guide) and describe what you want to create!
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### πŸ“ Input Controls")
                
                # Model selection
                model_dropdown = gr.Dropdown(
                    choices=list(MODELS.keys()),
                    value="Stable Diffusion 1.5",
                    label="Model"
                )
                
                # Text prompt
                prompt_input = gr.Textbox(
                    label="Text Prompt",
                    placeholder="Describe the image you want to generate...",
                    lines=3
                )
                
                # Reference image
                gr.Markdown("**Reference Image** - Upload a face or style reference image")
                reference_input = gr.Image(
                    label="Reference Image",
                    type="pil"
                )
                
                with gr.Row():
                    guidance_scale = gr.Slider(
                        minimum=1.0,
                        maximum=20.0,
                        value=7.5,
                        step=0.5,
                        label="Guidance Scale"
                    )
                    
                    ip_adapter_scale = gr.Slider(
                        minimum=0.0,
                        maximum=2.0,
                        value=1.0,
                        step=0.1,
                        label="IPAdapter Scale"
                    )
                
                with gr.Row():
                    resolution_dropdown = gr.Dropdown(
                        choices=RESOLUTIONS,
                        value="512x512",
                        label="Resolution"
                    )
                    
                    num_steps = gr.Slider(
                        minimum=10,
                        maximum=50,
                        value=20,
                        step=1,
                        label="Inference Steps"
                    )
                
                seed_input = gr.Number(
                    label="Seed (0 for random)",
                    value=0,
                    precision=0
                )
                
                # Enhancement options
                gr.Markdown("### πŸ”§ Enhancement Options")
                
                enable_face_enhancement = gr.Checkbox(
                    label="Enable Face Enhancement",
                    value=False
                )
                
                use_codeformer = gr.Checkbox(
                    label="Use CodeFormer (vs GFPGAN)",
                    value=False
                )
                
                # LoRA options
                gr.Markdown("### 🎭 LoRA Style Options")
                
                lora_path = gr.Textbox(
                    label="LoRA Model Path (optional)",
                    placeholder="/path/to/lora/model.safetensors"
                )
                
                lora_scale = gr.Slider(
                    minimum=0.0,
                    maximum=2.0,
                    value=1.0,
                    step=0.1,
                    label="LoRA Scale"
                )
                
                generate_btn = gr.Button("πŸš€ Generate Image", variant="primary", size="lg")
            
            with gr.Column(scale=1):
                gr.Markdown("### πŸ–ΌοΈ Results")
                
                status_output = gr.Textbox(
                    label="Status",
                    interactive=False,
                    value="Ready to generate..."
                )
                
                output_image = gr.Image(
                    label="Reference | Generated",
                    type="pil"
                )
        
        # Event handlers
        generate_btn.click(
            fn=generate_image,
            inputs=[
                prompt_input,
                reference_input,
                model_dropdown,
                guidance_scale,
                resolution_dropdown,
                num_steps,
                ip_adapter_scale,
                seed_input,
                enable_face_enhancement,
                use_codeformer,
                lora_path,
                lora_scale
            ],
            outputs=[output_image, status_output]
        )
        
        # Examples
        gr.Markdown("### πŸ“š Example Prompts")
        gr.Examples(
            examples=[
                ["A professional headshot photo, studio lighting, high quality", None],
                ["An oil painting portrait in the style of Renaissance masters", None],
                ["A cyberpunk character with neon lighting and futuristic elements", None],
                ["A fantasy warrior in medieval armor, dramatic lighting", None],
                ["An anime-style character with vibrant colors", None]
            ],
            inputs=[prompt_input, reference_input]
        )
    
    return demo

if __name__ == "__main__":
    # Initialize with default model
    print("πŸš€ Starting ComfyUI-Style IPAdapter Generator...")
    print(f"Device: {device}")
    
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True
    )