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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import random
|
| 3 |
+
import torch
|
| 4 |
+
import cv2
|
| 5 |
+
import insightface
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import numpy as np
|
| 8 |
+
import os
|
| 9 |
+
from huggingface_hub import snapshot_download
|
| 10 |
+
from transformers import CLIPVisionModelWithProjection,CLIPImageProcessor
|
| 11 |
+
from SAK.pipelines.pipeline_stable_diffusion_xl_chatglm_256_ipadapter_FaceID import StableDiffusionXLPipeline
|
| 12 |
+
from SAK.models.modeling_chatglm import ChatGLMModel
|
| 13 |
+
from SAK.models.tokenization_chatglm import ChatGLMTokenizer
|
| 14 |
+
from diffusers import AutoencoderKL
|
| 15 |
+
from SAK.models.unet_2d_condition import UNet2DConditionModel
|
| 16 |
+
from diffusers import EulerDiscreteScheduler
|
| 17 |
+
from PIL import Image
|
| 18 |
+
from insightface.app import FaceAnalysis
|
| 19 |
+
from insightface.data import get_image as ins_get_image
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
device = "cuda"
|
| 23 |
+
# ckpt_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors")
|
| 24 |
+
# ckpt_dir_faceid = snapshot_download(repo_id="Kwai-Kolors/Kolors-IP-Adapter-FaceID-Plus")
|
| 25 |
+
|
| 26 |
+
text_encoder = ChatGLMModel.from_pretrained(f'{ckpt_dir}/text_encoder', torch_dtype=torch.float16).half().to(device)
|
| 27 |
+
tokenizer = ChatGLMTokenizer.from_pretrained(f'{ckpt_dir}/text_encoder')
|
| 28 |
+
vae = AutoencoderKL.from_pretrained(f"{ckpt_dir}/vae", revision=None).half().to(device)
|
| 29 |
+
scheduler = EulerDiscreteScheduler.from_pretrained(f"{ckpt_dir}/scheduler")
|
| 30 |
+
unet = UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
| 31 |
+
clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(f'{ckpt_dir_faceid}/clip-vit-large-patch14-336', ignore_mismatched_sizes=True)
|
| 32 |
+
clip_image_encoder.to(device)
|
| 33 |
+
clip_image_processor = CLIPImageProcessor(size = 336, crop_size = 336)
|
| 34 |
+
|
| 35 |
+
pipe = StableDiffusionXLPipeline(
|
| 36 |
+
vae = vae,
|
| 37 |
+
text_encoder = text_encoder,
|
| 38 |
+
tokenizer = tokenizer,
|
| 39 |
+
unet = unet,
|
| 40 |
+
scheduler = scheduler,
|
| 41 |
+
face_clip_encoder = clip_image_encoder,
|
| 42 |
+
face_clip_processor = clip_image_processor,
|
| 43 |
+
force_zeros_for_empty_prompt = False,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
class FaceInfoGenerator():
|
| 47 |
+
def __init__(self, root_dir = "./.insightface/"):
|
| 48 |
+
self.app = FaceAnalysis(name = 'antelopev2', root = root_dir, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
| 49 |
+
self.app.prepare(ctx_id = 0, det_size = (640, 640))
|
| 50 |
+
|
| 51 |
+
def get_faceinfo_one_img(self, face_image):
|
| 52 |
+
face_info = self.app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))
|
| 53 |
+
|
| 54 |
+
if len(face_info) == 0:
|
| 55 |
+
face_info = None
|
| 56 |
+
else:
|
| 57 |
+
face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
|
| 58 |
+
return face_info
|
| 59 |
+
|
| 60 |
+
def face_bbox_to_square(bbox):
|
| 61 |
+
## l, t, r, b to square l, t, r, b
|
| 62 |
+
l,t,r,b = bbox
|
| 63 |
+
cent_x = (l + r) / 2
|
| 64 |
+
cent_y = (t + b) / 2
|
| 65 |
+
w, h = r - l, b - t
|
| 66 |
+
r = max(w, h) / 2
|
| 67 |
+
|
| 68 |
+
l0 = cent_x - r
|
| 69 |
+
r0 = cent_x + r
|
| 70 |
+
t0 = cent_y - r
|
| 71 |
+
b0 = cent_y + r
|
| 72 |
+
|
| 73 |
+
return [l0, t0, r0, b0]
|
| 74 |
+
|
| 75 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 76 |
+
MAX_IMAGE_SIZE = 1024
|
| 77 |
+
face_info_generator = FaceInfoGenerator()
|
| 78 |
+
|
| 79 |
+
@spaces.GPU
|
| 80 |
+
def infer(prompt,
|
| 81 |
+
image = None,
|
| 82 |
+
negative_prompt = "nsfw,Face shadows,Low resolution,JPEG artifacts、Vague、bad,Neon lights",
|
| 83 |
+
seed = 66,
|
| 84 |
+
randomize_seed = False,
|
| 85 |
+
guidance_scale = 5.0,
|
| 86 |
+
num_inference_steps = 50
|
| 87 |
+
):
|
| 88 |
+
if randomize_seed:
|
| 89 |
+
seed = random.randint(0, MAX_SEED)
|
| 90 |
+
generator = torch.Generator().manual_seed(seed)
|
| 91 |
+
global pipe
|
| 92 |
+
pipe = pipe.to(device)
|
| 93 |
+
pipe.load_ip_adapter_faceid_plus(f'{ckpt_dir_faceid}/ipa-faceid-plus.bin', device = device)
|
| 94 |
+
scale = 0.8
|
| 95 |
+
pipe.set_face_fidelity_scale(scale)
|
| 96 |
+
|
| 97 |
+
face_info = face_info_generator.get_faceinfo_one_img(image)
|
| 98 |
+
face_bbox_square = face_bbox_to_square(face_info["bbox"])
|
| 99 |
+
crop_image = image.crop(face_bbox_square)
|
| 100 |
+
crop_image = crop_image.resize((336, 336))
|
| 101 |
+
crop_image = [crop_image]
|
| 102 |
+
face_embeds = torch.from_numpy(np.array([face_info["embedding"]]))
|
| 103 |
+
face_embeds = face_embeds.to(device, dtype = torch.float16)
|
| 104 |
+
|
| 105 |
+
image = pipe(
|
| 106 |
+
prompt = prompt,
|
| 107 |
+
negative_prompt = negative_prompt,
|
| 108 |
+
height = 1024,
|
| 109 |
+
width = 1024,
|
| 110 |
+
num_inference_steps= num_inference_steps,
|
| 111 |
+
guidance_scale = guidance_scale,
|
| 112 |
+
num_images_per_prompt = 1,
|
| 113 |
+
generator = generator,
|
| 114 |
+
face_crop_image = crop_image,
|
| 115 |
+
face_insightface_embeds = face_embeds
|
| 116 |
+
).images[0]
|
| 117 |
+
|
| 118 |
+
return image, seed
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
examples = [
|
| 122 |
+
["wearing a full suit sitting in a restaurant with candle lights ", "image/image1.png"],
|
| 123 |
+
["Cowboy, cowboy hat, Wild Cowboy, background is a western town, cactus, sunset, warm colors, shot with XT4 film, noise, vignette, Kodak film, vintage", "image/image2.png"]
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
css="""
|
| 128 |
+
#col-left {
|
| 129 |
+
margin: 0 auto;
|
| 130 |
+
max-width: 600px;
|
| 131 |
+
}
|
| 132 |
+
#col-right {
|
| 133 |
+
margin: 0 auto;
|
| 134 |
+
max-width: 750px;
|
| 135 |
+
}
|
| 136 |
+
#button {
|
| 137 |
+
color: blue;
|
| 138 |
+
}
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
def load_description(fp):
|
| 142 |
+
with open(fp, 'r', encoding='utf-8') as f:
|
| 143 |
+
content = f.read()
|
| 144 |
+
return content
|
| 145 |
+
|
| 146 |
+
with gr.Blocks(css=css) as Kolors:
|
| 147 |
+
gr.HTML(load_description("assets/title.md"))
|
| 148 |
+
with gr.Row():
|
| 149 |
+
with gr.Column(elem_id="col-left"):
|
| 150 |
+
with gr.Row():
|
| 151 |
+
prompt = gr.Textbox(
|
| 152 |
+
label="Prompt",
|
| 153 |
+
placeholder="Enter your prompt",
|
| 154 |
+
lines=2
|
| 155 |
+
)
|
| 156 |
+
with gr.Row():
|
| 157 |
+
image = gr.Image(label="Image", type="pil")
|
| 158 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 159 |
+
negative_prompt = gr.Textbox(
|
| 160 |
+
label="Negative prompt",
|
| 161 |
+
placeholder="Enter a negative prompt",
|
| 162 |
+
visible=True,
|
| 163 |
+
)
|
| 164 |
+
seed = gr.Slider(
|
| 165 |
+
label="Seed",
|
| 166 |
+
minimum=0,
|
| 167 |
+
maximum=MAX_SEED,
|
| 168 |
+
step=1,
|
| 169 |
+
value=0,
|
| 170 |
+
)
|
| 171 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 172 |
+
with gr.Row():
|
| 173 |
+
guidance_scale = gr.Slider(
|
| 174 |
+
label="Guidance scale",
|
| 175 |
+
minimum=0.0,
|
| 176 |
+
maximum=10.0,
|
| 177 |
+
step=0.1,
|
| 178 |
+
value=5.0,
|
| 179 |
+
)
|
| 180 |
+
num_inference_steps = gr.Slider(
|
| 181 |
+
label="Number of inference steps",
|
| 182 |
+
minimum=10,
|
| 183 |
+
maximum=50,
|
| 184 |
+
step=1,
|
| 185 |
+
value=25,
|
| 186 |
+
)
|
| 187 |
+
with gr.Row():
|
| 188 |
+
button = gr.Button("Run", elem_id="button")
|
| 189 |
+
|
| 190 |
+
with gr.Column(elem_id="col-right"):
|
| 191 |
+
result = gr.Image(label="Result", show_label=False)
|
| 192 |
+
seed_used = gr.Number(label="Seed Used")
|
| 193 |
+
|
| 194 |
+
with gr.Row():
|
| 195 |
+
gr.Examples(
|
| 196 |
+
fn = infer,
|
| 197 |
+
examples = examples,
|
| 198 |
+
inputs = [prompt, image],
|
| 199 |
+
outputs = [result, seed_used],
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
button.click(
|
| 203 |
+
fn = infer,
|
| 204 |
+
inputs = [prompt, image, negative_prompt, seed, randomize_seed, guidance_scale, num_inference_steps],
|
| 205 |
+
outputs = [result, seed_used]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
SAK.queue().launch(debug=True)
|