File size: 15,716 Bytes
3407e44
 
865391b
 
 
 
3407e44
865391b
 
 
 
 
 
 
 
40290c7
d8e6a5c
40290c7
d8e6a5c
 
 
865391b
40290c7
d8e6a5c
40290c7
 
 
d8e6a5c
40290c7
d8e6a5c
40290c7
 
 
 
 
 
 
 
d8e6a5c
40290c7
 
 
 
 
 
 
d8e6a5c
40290c7
 
 
 
 
 
 
 
d8e6a5c
40290c7
 
 
 
 
 
 
 
 
d8e6a5c
865391b
40290c7
865391b
40290c7
d8e6a5c
40290c7
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40290c7
d8e6a5c
40290c7
 
 
d8e6a5c
40290c7
d8e6a5c
40290c7
 
 
 
 
865391b
40290c7
d8e6a5c
40290c7
d8e6a5c
40290c7
d8e6a5c
865391b
d8e6a5c
40290c7
 
 
 
 
 
865391b
d8e6a5c
 
 
865391b
d8e6a5c
40290c7
 
d8e6a5c
 
40290c7
d8e6a5c
 
 
40290c7
d8e6a5c
40290c7
d8e6a5c
40290c7
 
d8e6a5c
40290c7
 
d8e6a5c
 
 
40290c7
 
 
 
d8e6a5c
40290c7
 
 
d8e6a5c
40290c7
 
 
d8e6a5c
40290c7
 
 
d8e6a5c
 
40290c7
 
 
 
 
 
 
 
 
 
d8e6a5c
40290c7
 
 
d8e6a5c
865391b
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40290c7
865391b
d8e6a5c
 
 
 
40290c7
 
 
d8e6a5c
 
 
40290c7
 
d8e6a5c
 
40290c7
d8e6a5c
40290c7
 
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
40290c7
d8e6a5c
 
40290c7
d8e6a5c
40290c7
d8e6a5c
865391b
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
865391b
d8e6a5c
 
40290c7
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40290c7
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40290c7
d8e6a5c
40290c7
 
865391b
d8e6a5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40290c7
d8e6a5c
 
 
 
 
 
40290c7
d8e6a5c
 
 
40290c7
d8e6a5c
 
 
 
40290c7
 
 
 
 
 
d8e6a5c
 
40290c7
d8e6a5c
40290c7
865391b
40290c7
d8e6a5c
40290c7
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
import gradio as gr
import torch
import os
import glob
import spaces
import numpy as np

from datetime import datetime
from PIL import Image
from diffusers.utils import load_image
from diffusers import EulerDiscreteScheduler
from pipline_StableDiffusionXL_ConsistentID import ConsistentIDStableDiffusionXLPipeline
from huggingface_hub import hf_hub_download
from models.BiSeNet.model import BiSeNet

# ====================================================================================
# Global model management for ZeroGPU compatibility
# ====================================================================================
DEVICE = "cuda"
pipe = None
bise_net = None

def load_models():
    """Load all models on CPU to avoid ZeroGPU initialization issues"""
    global pipe, bise_net
    
    if pipe is not None:
        return
    
    print("โณ Loading models on CPU...")
    
    base_model_path = "SG161222/RealVisXL_V3.0"
    consistentID_path = hf_hub_download(
        repo_id="JackAILab/ConsistentID", 
        filename="ConsistentID_SDXL-v1.bin", 
        repo_type="model"
    )
    
    # Load pipeline on CPU
    pipe = ConsistentIDStableDiffusionXLPipeline.from_pretrained(
        base_model_path, 
        torch_dtype=torch.float16,
        safety_checker=None,
        variant="fp16"
    )
    
    # Load BiSeNet
    bise_net_cp_path = hf_hub_download(
        repo_id="JackAILab/ConsistentID", 
        filename="face_parsing.pth", 
        local_dir="./checkpoints"
    )
    bise_net = BiSeNet(n_classes=19)
    bise_net.load_state_dict(torch.load(bise_net_cp_path, map_location="cpu"))
    
    # Load ConsistentID components
    pipe.load_ConsistentID_model(
        os.path.dirname(consistentID_path),
        bise_net,
        subfolder="",
        weight_name=os.path.basename(consistentID_path),
        trigger_word="img",
    )
    pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
    
    print("โœ… Models loaded successfully")

load_models()

# ====================================================================================
# Inference function with GPU management
# ====================================================================================
@spaces.GPU(duration=180)  # Extended duration for SDXL
def generate_image(
    selected_template_images,
    custom_image,
    prompt,
    negative_prompt,
    prompt_selected,
    model_selected_tab,
    prompt_selected_tab,
    width,
    height,
    merge_steps,
    seed,
    num_steps
):
    """
    Generate image using ConsistentID-SDXL
    """
    global pipe, bise_net
    
    print("๐Ÿš€ Moving models to GPU...")
    
    # Move to GPU
    pipe.to(DEVICE)
    pipe.image_encoder.to(DEVICE)
    pipe.image_proj_model.to(DEVICE)
    pipe.FacialEncoder.to(DEVICE)
    bise_net.to(DEVICE)
    
    try:
        # Select input image
        if model_selected_tab == 0:
            input_image = load_image(Image.open(selected_template_images))
        else:
            input_image = load_image(Image.fromarray(custom_image))

        # Select prompt
        if prompt_selected_tab == 0:
            prompt = prompt_selected
            negative_prompt = ""
            need_safetycheck = False
        else:
            need_safetycheck = True

        # Default prompts
        if not prompt or prompt.strip() == "":
            prompt = "A person, professional portrait"

        if not negative_prompt or negative_prompt.strip() == "":
            negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality, blurry"

        # Enhance prompt
        enhanced_prompt = f"cinematic photo, {prompt}, 50mm photograph, half-length portrait, film, bokeh, professional, 4k, highly detailed"

        # Negative prompt enhancement
        negative_enhancement = "((cross-eye)), ((cross-eyed)), (((NSFW))), (nipple), ((((ugly)))), (((duplicate))), ((morbid)), ((mutilated)), [out of frame], extra fingers, mutated hands, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), (((deformed))), ((ugly)), blurry, ((bad anatomy)), (((bad proportions))), ((extra limbs)), cloned face, (((disfigured))), out of frame, ugly, extra limbs, (bad anatomy), gross proportions, (malformed limbs), ((missing arms)), ((missing legs)), (((extra arms))), (((extra legs))), mutated hands, (fused fingers), (too many fingers), (((long neck)))"
        final_negative_prompt = negative_prompt + ", " + negative_enhancement

        generator = torch.Generator(device=DEVICE).manual_seed(seed)

        print(f"๐ŸŽจ Generating with prompt: {enhanced_prompt[:100]}...")
        
        images = pipe(
            prompt=enhanced_prompt,
            width=width,    
            height=height,
            input_id_images=input_image,
            input_image_path=selected_template_images if model_selected_tab == 0 else None,
            negative_prompt=final_negative_prompt,
            num_images_per_prompt=1,
            num_inference_steps=num_steps,
            start_merge_step=merge_steps,
            generator=generator,
            retouching=False,
            need_safetycheck=need_safetycheck,
        ).images[0]

        print("โœ… Generation completed")
        return np.array(images)
        
    except Exception as e:
        print(f"โŒ Error: {str(e)}")
        raise
        
    finally:
        # Clean up GPU
        print("๐Ÿงน Releasing GPU memory...")
        pipe.to("cpu")
        pipe.image_encoder.to("cpu")
        pipe.image_proj_model.to("cpu")
        pipe.FacialEncoder.to("cpu")
        bise_net.to("cpu")
        
        if torch.cuda.is_available():
            torch.cuda.empty_cache()

# ====================================================================================
# Beautiful Gradio Interface
# ====================================================================================

# Get template images
preset_templates = glob.glob("./images/templates/*.png") + glob.glob("./images/templates/*.jpg")

# Custom CSS for beautiful interface
custom_css = """
.gradio-container {
    font-family: 'IBM Plex Sans', sans-serif;
}

.main-title {
    text-align: center;
    font-size: 2.5em;
    font-weight: 700;
    background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 1em;
}

.subtitle {
    text-align: center;
    font-size: 1.1em;
    color: #666;
    margin-bottom: 2em;
}

.section-header {
    font-size: 1.3em;
    font-weight: 600;
    margin: 1em 0 0.5em 0;
    color: #333;
}

.info-box {
    background: #f8f9fa;
    border-left: 4px solid #667eea;
    padding: 1em;
    margin: 1em 0;
    border-radius: 4px;
}

.generate-btn {
    background: linear-gradient(45deg, #667eea 0%, #764ba2 100%) !important;
    border: none !important;
    color: white !important;
    font-size: 1.1em !important;
    font-weight: 600 !important;
    padding: 0.8em 2em !important;
    border-radius: 8px !important;
}

.gallery-item {
    border-radius: 8px;
    overflow: hidden;
}
"""

# Template prompts with better organization
template_prompts = [
    ("๐Ÿ‘ฐ Wedding", "A woman in an elegant wedding dress, professional photography"),
    ("๐Ÿ‘‘ Royalty", "A person as royalty, sitting on throne in gorgeous palace, regal attire"),
    ("๐Ÿ–๏ธ Beach", "A person sitting at the beach with beautiful sunset, relaxed atmosphere"),
    ("๐Ÿ‘ฎ Officer", "A person as police officer, professional uniform, half body shot"),
    ("โ›ต Sailor", "A person as sailor, on boat deck above ocean, nautical uniform"),
    ("๐ŸŽง Music", "A person wearing headphones, listening to music, modern setting"),
    ("๐Ÿš’ Firefighter", "A person as firefighter, professional gear, half body shot"),
    ("๐Ÿ’ผ Business", "A person in business attire, professional corporate environment"),
    ("๐ŸŽจ Artist", "A person as artist in studio, creative atmosphere, artistic clothing"),
    ("๐Ÿ”ฌ Scientist", "A person as scientist in laboratory, lab coat, professional setting"),
]

with gr.Blocks(css=custom_css, theme=gr.themes.Soft(), title="ConsistentID-SDXL") as demo:
    
    # Header
    gr.HTML("""
        <div class="main-title">โœจ ConsistentID-SDXL Demo โœจ</div>
        <div class="subtitle">
            High-fidelity portrait generation with consistent identity preservation
        </div>
    """)
    
    gr.Markdown("""
        <div style='text-align: center; margin-bottom: 2em;'>
            <a href='https://github.com/JackAILab/ConsistentID' target='_blank' style='text-decoration: none;'>
                โญ Star us on GitHub
            </a> | 
            <a href='https://arxiv.org/abs/2404.16771' target='_blank' style='text-decoration: none;'>
                ๐Ÿ“„ Read the Paper
            </a>
        </div>
    """)
    
    with gr.Row():
        # Left column - Inputs
        with gr.Column(scale=1):
            gr.HTML("<div class='section-header'>๐Ÿ“ธ Input Image</div>")
            
            model_selected_tab = gr.Number(value=0, visible=False)
            
            with gr.Tabs() as image_tabs:
                with gr.Tab("๐Ÿ–ผ๏ธ Templates") as template_tab:
                    template_gallery = gr.Gallery(
                        value=[(img, img) for img in preset_templates],
                        columns=4,
                        rows=2,
                        height=300,
                        object_fit="cover",
                        show_label=False,
                        elem_classes="gallery-item"
                    )
                    
                    selected_template = gr.Textbox(visible=False)
                    
                    def select_template(evt: gr.SelectData):
                        return preset_templates[evt.index]
                    
                    template_gallery.select(select_template, None, selected_template)
                    
                with gr.Tab("๐Ÿ“ค Upload") as upload_tab:
                    custom_image = gr.Image(
                        label="Upload your image",
                        type="numpy",
                        height=300
                    )
            
            template_tab.select(fn=lambda: 0, inputs=[], outputs=[model_selected_tab])
            upload_tab.select(fn=lambda: 1, inputs=[], outputs=[model_selected_tab])
            
            gr.HTML("<div class='section-header'>โœ๏ธ Prompt</div>")
            
            prompt_selected_tab = gr.Number(value=0, visible=False)
            
            with gr.Tabs() as prompt_tabs:
                with gr.Tab("๐Ÿ“‹ Templates") as template_prompt_tab:
                    prompt_dropdown = gr.Dropdown(
                        choices=[f"{icon} {name}" for icon, name in template_prompts],
                        value="๐Ÿ‘ฎ Officer",
                        label="Choose a style",
                        scale=1
                    )
                    
                    # Hidden textbox to store actual prompt
                    prompt_mapping = {f"{icon} {name}": prompt for (icon, name), (_, prompt) in zip([(icon, name) for icon, name in template_prompts], template_prompts)}
                    prompt_selected = gr.Textbox(value=template_prompts[3][1], visible=False)
                    
                    def update_prompt(choice):
                        for (icon, name), (_, prompt) in zip([(icon, name) for icon, name in template_prompts], template_prompts):
                            if f"{icon} {name}" == choice:
                                return prompt
                        return template_prompts[0][1]
                    
                    prompt_dropdown.change(update_prompt, inputs=[prompt_dropdown], outputs=[prompt_selected])
                    
                with gr.Tab("โœ๏ธ Custom") as custom_prompt_tab:
                    custom_prompt = gr.Textbox(
                        label="Your prompt",
                        placeholder="A person wearing a santa hat, festive atmosphere...",
                        lines=3
                    )
                    custom_negative = gr.Textbox(
                        label="Negative prompt (optional)",
                        placeholder="blurry, low quality...",
                        lines=2
                    )
            
            template_prompt_tab.select(fn=lambda: 0, inputs=[], outputs=[prompt_selected_tab])
            custom_prompt_tab.select(fn=lambda: 1, inputs=[], outputs=[prompt_selected_tab])
            
            gr.HTML("<div class='section-header'>โš™๏ธ Generation Settings</div>")
            
            with gr.Row():
                width = gr.Slider(
                    label="Width",
                    minimum=512,
                    maximum=1280,
                    value=896,
                    step=64
                )
                height = gr.Slider(
                    label="Height",
                    minimum=512,
                    maximum=1280,
                    value=1152,
                    step=64
                )
            
            with gr.Row():
                num_steps = gr.Slider(
                    label="Steps",
                    minimum=20,
                    maximum=50,
                    value=30,
                    step=1
                )
                merge_steps = gr.Slider(
                    label="Merge Step",
                    minimum=10,
                    maximum=40,
                    value=20,
                    step=1
                )
            
            seed = gr.Slider(
                label="๐ŸŽฒ Seed",
                minimum=0,
                maximum=2147483647,
                value=42,
                step=1
            )
            
            generate_btn = gr.Button(
                "๐ŸŽจ Generate Image",
                variant="primary",
                size="lg",
                elem_classes="generate-btn"
            )
        
        # Right column - Output
        with gr.Column(scale=1):
            gr.HTML("<div class='section-header'>๐Ÿ–ผ๏ธ Generated Result</div>")
            
            output_image = gr.Image(
                label="Output",
                height=600,
                show_label=False
            )
            
            gr.HTML("""
                <div class='info-box'>
                    <h4>๐Ÿ’ก Tips for Best Results:</h4>
                    <ul>
                        <li>โœ… Use clear face images with good lighting</li>
                        <li>โœ… Faces should be clearly visible and not too small</li>
                        <li>โœ… Use "man" or "woman" instead of "person" in prompts</li>
                        <li>โฑ๏ธ Generation takes 1-3 minutes with ZeroGPU</li>
                    </ul>
                </div>
            """)
            
            gr.Markdown("""
                <div style='text-align: center; margin-top: 2em; color: #666; font-size: 0.9em;'>
                    Powered by ConsistentID-SDXL | 
                    <a href='https://huggingface.co/JackAILab/ConsistentID' target='_blank'>Model Card</a>
                </div>
            """)
    
    # Connect the button
    generate_btn.click(
        fn=generate_image,
        inputs=[
            selected_template,
            custom_image,
            custom_prompt,
            custom_negative,
            prompt_selected,
            model_selected_tab,
            prompt_selected_tab,
            width,
            height,
            merge_steps,
            seed,
            num_steps
        ],
        outputs=output_image
    )

if __name__ == "__main__":
    demo.queue(max_size=20)
    demo.launch()