File size: 12,452 Bytes
d5f497d
 
 
6c91ee7
66fd925
6c91ee7
 
011d756
2432eb0
a0ed24e
 
66fd925
d5f497d
 
66fd925
6c91ee7
 
 
66fd925
 
6c91ee7
2432eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ed24e
 
 
 
 
 
 
d5f497d
a0ed24e
 
 
d5f497d
2432eb0
 
 
a0ed24e
 
2432eb0
a0ed24e
 
 
2432eb0
 
a0ed24e
2432eb0
 
a0ed24e
 
 
2432eb0
 
a0ed24e
 
 
 
 
2432eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ed24e
2432eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ed24e
2432eb0
 
a0ed24e
2432eb0
a0ed24e
 
2432eb0
 
 
a0ed24e
2432eb0
 
 
 
a0ed24e
 
 
 
2432eb0
 
a0ed24e
66fd925
2432eb0
 
 
 
66fd925
a0ed24e
 
 
 
 
 
 
 
6c91ee7
d5f497d
2432eb0
 
66fd925
a0ed24e
 
 
 
d5f497d
66fd925
a0ed24e
 
 
66fd925
6c91ee7
66fd925
a0ed24e
66fd925
a0ed24e
 
66fd925
6c91ee7
66fd925
 
a0ed24e
66fd925
 
 
 
 
 
 
 
 
 
 
d5f497d
 
8004741
98c6239
d5f497d
2432eb0
66fd925
a0ed24e
 
 
 
 
 
6c91ee7
a0ed24e
2432eb0
a0ed24e
 
d5f497d
 
a0ed24e
 
 
2502de8
66fd925
a0ed24e
 
 
 
 
 
 
 
2432eb0
66fd925
a0ed24e
66fd925
a0ed24e
 
 
2432eb0
 
 
 
 
 
 
 
 
 
 
78ad020
a0ed24e
 
2432eb0
 
 
 
 
 
 
 
 
 
 
 
 
a0ed24e
 
 
d5f497d
a0ed24e
66fd925
a04b247
 
 
20c2217
a0ed24e
 
 
 
 
d5f497d
 
a0ed24e
3f2277e
6429b4b
 
 
 
 
 
 
 
 
 
 
a0ed24e
 
 
6429b4b
 
d5f497d
 
 
 
 
a0ed24e
 
 
d5f497d
6c91ee7
a0ed24e
 
 
 
 
d5f497d
 
 
a0ed24e
 
d5f497d
 
 
 
 
 
 
a0ed24e
d5f497d
 
 
 
 
 
 
 
66fd925
d5f497d
 
 
 
 
 
66fd925
d5f497d
78ad020
a0ed24e
d5f497d
 
a0ed24e
 
d5f497d
66fd925
a0ed24e
 
 
78ad020
 
a0ed24e
 
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
import spaces
import random
import torch
import cv2
import insightface
import gradio as gr
import numpy as np
import os
import shutil
from huggingface_hub import snapshot_download, login
from transformers import CLIPVisionModelWithProjection, CLIPImageProcessor
from kolors.pipelines.pipeline_stable_diffusion_xl_chatglm_256_ipadapter_FaceID import StableDiffusionXLPipeline
from kolors.models.modeling_chatglm import ChatGLMModel
from kolors.models.tokenization_chatglm import ChatGLMTokenizer
from diffusers import AutoencoderKL
from kolors.models.unet_2d_condition import UNet2DConditionModel
from diffusers import EulerDiscreteScheduler
from PIL import Image
from insightface.app import FaceAnalysis
from insightface.data import get_image as ins_get_image

# ์บ์‹œ ํด๋ฆฌ์–ด (์„ ํƒ์ )
def clear_cache():
    cache_dir = "/home/user/.cache/huggingface/hub"
    if os.path.exists(cache_dir):
        try:
            # CLIP ๋ชจ๋ธ ์บ์‹œ๋งŒ ์‚ญ์ œ
            clip_cache = os.path.join(cache_dir, "models--openai--clip-vit-large-patch14-336")
            if os.path.exists(clip_cache):
                shutil.rmtree(clip_cache)
                print("Cleared CLIP cache")
        except Exception as e:
            print(f"Could not clear cache: {e}")

# ์บ์‹œ ํด๋ฆฌ์–ด (ํ•„์š”์‹œ)
# clear_cache()

# Hugging Face ํ† ํฐ์œผ๋กœ ๋กœ๊ทธ์ธ
HF_TOKEN = os.getenv("HF_TOKEN")
if HF_TOKEN:
    login(token=HF_TOKEN)
    print("Successfully logged in to Hugging Face Hub")
else:
    print("Warning: HF_TOKEN not found. Using public access only.")

# GPU ์‚ฌ์šฉ ๊ฐ€๋Šฅ ์—ฌ๋ถ€ ํ™•์ธ
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if device == "cuda" else torch.float32

print(f"Using device: {device}")
print(f"Using dtype: {dtype}")

# ๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ (ํ† ํฐ ์‚ฌ์šฉ)
try:
    print("Downloading Kolors models...")
    ckpt_dir = snapshot_download(
        repo_id="Kwai-Kolors/Kolors",
        token=HF_TOKEN,
        local_dir_use_symlinks=False,
        resume_download=True
    )
    
    print("Downloading FaceID models...")
    ckpt_dir_faceid = snapshot_download(
        repo_id="Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus",
        token=HF_TOKEN,
        local_dir_use_symlinks=False,
        resume_download=True
    )
except Exception as e:
    print(f"Error downloading models: {e}")
    raise

# ๋ชจ๋ธ ๋กœ๋”ฉ
print("Loading text encoder...")
text_encoder = ChatGLMModel.from_pretrained(
    f'{ckpt_dir}/text_encoder',
    torch_dtype=dtype,
    token=HF_TOKEN,
    trust_remote_code=True
)
if device == "cuda":
    text_encoder = text_encoder.half().to(device)

print("Loading tokenizer...")
tokenizer = ChatGLMTokenizer.from_pretrained(
    f'{ckpt_dir}/text_encoder',
    token=HF_TOKEN,
    trust_remote_code=True
)

print("Loading VAE...")
vae = AutoencoderKL.from_pretrained(
    f"{ckpt_dir}/vae",
    revision=None,
    torch_dtype=dtype,
    token=HF_TOKEN
)
if device == "cuda":
    vae = vae.half().to(device)

print("Loading scheduler...")
scheduler = EulerDiscreteScheduler.from_pretrained(
    f"{ckpt_dir}/scheduler",
    token=HF_TOKEN
)

print("Loading UNet...")
unet = UNet2DConditionModel.from_pretrained(
    f"{ckpt_dir}/unet",
    revision=None,
    torch_dtype=dtype,
    token=HF_TOKEN
)
if device == "cuda":
    unet = unet.half().to(device)

# CLIP ๋ชจ๋ธ ๋กœ๋”ฉ - safetensors ์šฐ์„  ์‚ฌ์šฉ
print("Loading CLIP model...")
try:
    # ๋จผ์ € ๋กœ์ปฌ FaceID ๋””๋ ‰ํ† ๋ฆฌ์—์„œ ์‹œ๋„
    local_clip_path = f'{ckpt_dir_faceid}/clip-vit-large-patch14-336'
    if os.path.exists(local_clip_path):
        print(f"Trying to load CLIP from local: {local_clip_path}")
        clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(
            local_clip_path,
            torch_dtype=dtype,
            ignore_mismatched_sizes=True,
            token=HF_TOKEN,
            use_safetensors=True,  # safetensors ์šฐ์„  ์‚ฌ์šฉ
            local_files_only=True
        )
    else:
        raise FileNotFoundError("Local CLIP not found")
except Exception as e:
    print(f"Local loading failed: {e}")
    try:
        # OpenAI์—์„œ ์ง์ ‘ ๋‹ค์šด๋กœ๋“œ (safetensors ๋ฒ„์ „)
        print("Downloading CLIP from OpenAI...")
        clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(
            'openai/clip-vit-large-patch14-336',
            torch_dtype=dtype,
            ignore_mismatched_sizes=True,
            token=HF_TOKEN,
            use_safetensors=True,  # safetensors ์šฐ์„  ์‚ฌ์šฉ
            revision="main"
        )
    except Exception as e2:
        print(f"SafeTensors loading failed: {e2}")
        # ์ตœํ›„์˜ ์ˆ˜๋‹จ: pytorch_model.bin ์‚ฌ์šฉ
        print("Trying with pytorch format...")
        clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(
            'openai/clip-vit-large-patch14-336',
            torch_dtype=dtype,
            ignore_mismatched_sizes=True,
            token=HF_TOKEN,
            use_safetensors=False
        )

clip_image_encoder.to(device)
clip_image_processor = CLIPImageProcessor(size=336, crop_size=336)

print("Creating pipeline...")
pipe = StableDiffusionXLPipeline(
    vae=vae,
    text_encoder=text_encoder,
    tokenizer=tokenizer,
    unet=unet,
    scheduler=scheduler,
    face_clip_encoder=clip_image_encoder,
    face_clip_processor=clip_image_processor,
    force_zeros_for_empty_prompt=False,
)

print("Models loaded successfully!")

class FaceInfoGenerator():
    def __init__(self, root_dir="./.insightface/"):
        providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if device == "cuda" else ['CPUExecutionProvider']
        self.app = FaceAnalysis(name='antelopev2', root=root_dir, providers=providers)
        self.app.prepare(ctx_id=0, det_size=(640, 640))

    def get_faceinfo_one_img(self, face_image):
        if face_image is None:
            return None
            
        face_info = self.app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))

        if len(face_info) == 0:
            return None
        else:
            # only use the maximum face
            face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1]
        return face_info

def face_bbox_to_square(bbox):
    ## l, t, r, b to square l, t, r, b
    l, t, r, b = bbox
    cent_x = (l + r) / 2
    cent_y = (t + b) / 2
    w, h = r - l, b - t
    r = max(w, h) / 2

    l0 = cent_x - r
    r0 = cent_x + r
    t0 = cent_y - r
    b0 = cent_y + r

    return [l0, t0, r0, b0]

MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
face_info_generator = FaceInfoGenerator()

@spaces.GPU(duration=60)
def infer(prompt, 
          image=None, 
          negative_prompt="low quality, blurry, distorted", 
          seed=66, 
          randomize_seed=False,
          guidance_scale=5.0, 
          num_inference_steps=50
        ):
    if image is None:
        gr.Warning("Please upload an image with a face.")
        return None, 0
    
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    
    generator = torch.Generator(device=device).manual_seed(seed)
    
    global pipe
    pipe = pipe.to(device)
    
    # IP Adapter ๋กœ๋”ฉ
    try:
        pipe.load_ip_adapter_faceid_plus(f'{ckpt_dir_faceid}/ipa-faceid-plus.bin', device=device)
        scale = 0.8
        pipe.set_face_fidelity_scale(scale)
    except Exception as e:
        print(f"Error loading IP adapter: {e}")
        raise gr.Error(f"Failed to load face adapter: {str(e)}")

    # Face ์ •๋ณด ์ถ”์ถœ
    face_info = face_info_generator.get_faceinfo_one_img(image)
    if face_info is None:
        raise gr.Error("No face detected in the image. Please provide an image with a clear face.")
    
    try:
        face_bbox_square = face_bbox_to_square(face_info["bbox"])
        crop_image = image.crop(face_bbox_square)
        crop_image = crop_image.resize((336, 336))
        crop_image = [crop_image]
        
        face_embeds = torch.from_numpy(np.array([face_info["embedding"]]))
        face_embeds = face_embeds.to(device, dtype=dtype)
    except Exception as e:
        print(f"Error processing face: {e}")
        raise gr.Error(f"Failed to process face: {str(e)}")

    # ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    try:
        with torch.no_grad():
            image = pipe(
                prompt=prompt,
                negative_prompt=negative_prompt,
                height=1024,
                width=1024,
                num_inference_steps=num_inference_steps,
                guidance_scale=guidance_scale,
                num_images_per_prompt=1,
                generator=generator,
                face_crop_image=crop_image,
                face_insightface_embeds=face_embeds
            ).images[0]
    except Exception as e:
        print(f"Error during inference: {e}")
        raise gr.Error(f"Failed to generate image: {str(e)}")

    return image, seed

css = """
footer {
    visibility: hidden;
}
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}
"""

# Gradio Interface
with gr.Blocks(theme="soft", css=css) as Kolors:
    gr.HTML(
        """
        <div class='container' style='display:flex; justify-content:center; gap:12px;'>
            <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
                <img src="https://img.shields.io/static/v1?label=OpenFree&message=BEST%20AI%20Services&color=%230000ff&labelColor=%23000080&logo=huggingface&logoColor=%23ffa500&style=for-the-badge" alt="OpenFree badge">
            </a>
    
            <a href="https://discord.gg/openfreeai" target="_blank">
                <img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="Discord badge">
            </a>
        </div>
        <h1 style="text-align: center;">Kolors Face ID - AI Portrait Generator</h1>
        <p style="text-align: center;">Upload a face photo and create stunning AI portraits with text prompts!</p>
        """
    )
    
    with gr.Row():
        with gr.Column(elem_id="col-left"):
            with gr.Row():
                prompt = gr.Textbox(
                    label="Prompt",
                    placeholder="e.g., A professional portrait in business attire, studio lighting",
                    lines=3,
                    value="A professional portrait photo, high quality, detailed face"
                )
            with gr.Row():
                image = gr.Image(
                    label="Upload Face Image",
                    type="pil",
                    height=400
                )
            with gr.Accordion("Advanced Settings", open=False):
                negative_prompt = gr.Textbox(
                    label="Negative prompt",
                    placeholder="Things to avoid in the image",
                    value="low quality, blurry, distorted, disfigured",
                    visible=True,
                )
                seed = gr.Slider(
                    label="Seed",
                    minimum=0,
                    maximum=MAX_SEED,
                    step=1,
                    value=66,
                )
                randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
                with gr.Row():
                    guidance_scale = gr.Slider(
                        label="Guidance scale",
                        minimum=0.0,
                        maximum=10.0,
                        step=0.1,
                        value=5.0,
                    )
                    num_inference_steps = gr.Slider(
                        label="Number of inference steps",
                        minimum=10,
                        maximum=50,
                        step=1,
                        value=25,
                    )
            with gr.Row():
                button = gr.Button("๐ŸŽจ Generate Portrait", elem_id="button", variant="primary", scale=1)
            
        with gr.Column(elem_id="col-right"):
            result = gr.Image(label="Generated Portrait", show_label=True)
            seed_used = gr.Number(label="Seed Used", precision=0)

    button.click(
        fn=infer,
        inputs=[prompt, image, negative_prompt, seed, randomize_seed, guidance_scale, num_inference_steps],
        outputs=[result, seed_used]
    )

if __name__ == "__main__":
    Kolors.queue(max_size=10).launch(debug=True, share=False)