Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -61,9 +61,8 @@ with open("sdxl_loras.json", "r") as file:
|
|
| 61 |
|
| 62 |
with open("defaults_data.json", "r") as file:
|
| 63 |
lora_defaults = json.load(file)
|
| 64 |
-
|
| 65 |
|
| 66 |
-
device = "cuda"
|
| 67 |
|
| 68 |
# Cache for LoRA state dicts
|
| 69 |
state_dicts = {}
|
|
@@ -81,7 +80,7 @@ for item in sdxl_loras_raw:
|
|
| 81 |
}
|
| 82 |
|
| 83 |
sdxl_loras_raw = [item for item in sdxl_loras_raw if item.get("new") != True]
|
| 84 |
-
|
| 85 |
# Download models
|
| 86 |
hf_hub_download(
|
| 87 |
repo_id="InstantX/InstantID",
|
|
@@ -112,7 +111,6 @@ app.prepare(ctx_id=0, det_size=(768, 768))
|
|
| 112 |
face_adapter = f'/data/checkpoints/ip-adapter.bin'
|
| 113 |
controlnet_path = f'/data/checkpoints/ControlNetModel'
|
| 114 |
|
| 115 |
-
# Load IdentityNet
|
| 116 |
st = time.time()
|
| 117 |
identitynet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
|
| 118 |
zoedepthnet = ControlNetModel.from_pretrained("diffusers/controlnet-zoe-depth-sdxl-1.0", torch_dtype=torch.float16)
|
|
@@ -159,6 +157,101 @@ last_lora = ""
|
|
| 159 |
last_fused = False
|
| 160 |
lora_archive = "/data"
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
def update_selection(selected_state: gr.SelectData, sdxl_loras, face_strength, image_strength, weight, depth_control_scale, negative, is_new=False):
|
| 163 |
lora_repo = sdxl_loras[selected_state.index]["repo"]
|
| 164 |
new_placeholder = "Type a prompt to use your selected LoRA"
|
|
@@ -212,9 +305,13 @@ def resize_image_aspect_ratio(img, max_dim=1280):
|
|
| 212 |
|
| 213 |
|
| 214 |
def run_lora(face_image, prompt, negative, lora_scale, selected_state, face_strength, image_strength,
|
| 215 |
-
guidance_scale, depth_control_scale, sdxl_loras, custom_lora,
|
|
|
|
| 216 |
"""
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
| 218 |
"""
|
| 219 |
print("Custom LoRA:", custom_lora)
|
| 220 |
custom_lora_path = custom_lora[0] if custom_lora else None
|
|
@@ -223,41 +320,42 @@ def run_lora(face_image, prompt, negative, lora_scale, selected_state, face_stre
|
|
| 223 |
st = time.time()
|
| 224 |
face_image = resize_image_aspect_ratio(face_image)
|
| 225 |
|
| 226 |
-
#
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
face_emb =
|
| 232 |
-
face_kps =
|
| 233 |
-
|
| 234 |
-
|
| 235 |
face_emb = None
|
| 236 |
face_kps = face_image
|
|
|
|
| 237 |
|
| 238 |
et = time.time()
|
| 239 |
print('Face processing took:', et - st, 'seconds')
|
| 240 |
|
| 241 |
st = time.time()
|
| 242 |
|
| 243 |
-
#
|
| 244 |
if custom_lora_path and custom_lora[1]:
|
| 245 |
prompt = f"{prompt} {custom_lora[1]}"
|
| 246 |
else:
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
prompt = prompt_full.replace("<subject>", prompt)
|
| 253 |
|
| 254 |
print("Prompt:", prompt)
|
| 255 |
if prompt == "":
|
| 256 |
-
prompt = "a person"
|
| 257 |
print(f"Executing prompt: {prompt}")
|
| 258 |
|
| 259 |
if negative == "":
|
| 260 |
-
negative
|
|
|
|
| 261 |
|
| 262 |
print("Custom Loaded LoRA:", custom_lora_path)
|
| 263 |
|
|
@@ -267,11 +365,8 @@ def run_lora(face_image, prompt, negative, lora_scale, selected_state, face_stre
|
|
| 267 |
repo_name = custom_lora_path
|
| 268 |
full_path_lora = custom_lora_path
|
| 269 |
else:
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
full_path_lora = state_dicts[repo_name]["saved_name"]
|
| 273 |
-
else:
|
| 274 |
-
raise gr.Error("Invalid selection")
|
| 275 |
|
| 276 |
repo_name = repo_name.rstrip("/").lower()
|
| 277 |
|
|
@@ -280,8 +375,15 @@ def run_lora(face_image, prompt, negative, lora_scale, selected_state, face_stre
|
|
| 280 |
et = time.time()
|
| 281 |
print('Prompt processing took:', et - st, 'seconds')
|
| 282 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
st = time.time()
|
| 284 |
-
|
| 285 |
image = generate_image(
|
| 286 |
prompt, negative, face_emb, face_image, face_kps, image_strength,
|
| 287 |
guidance_scale, face_strength, depth_control_scale, repo_name,
|
|
@@ -302,9 +404,14 @@ def generate_image(prompt, negative, face_emb, face_image, face_kps, image_stren
|
|
| 302 |
print("Loaded state dict:", loaded_state_dict)
|
| 303 |
print("Last LoRA:", last_lora, "| Current LoRA:", repo_name)
|
| 304 |
|
| 305 |
-
#
|
| 306 |
-
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
|
| 309 |
# Handle custom LoRA from HuggingFace
|
| 310 |
if repo_name.startswith("https://huggingface.co"):
|
|
@@ -321,19 +428,20 @@ def generate_image(prompt, negative, face_emb, face_image, face_kps, image_stren
|
|
| 321 |
else:
|
| 322 |
full_path_lora = loaded_state_dict
|
| 323 |
|
| 324 |
-
# LoRA loading
|
| 325 |
if last_lora != repo_name:
|
| 326 |
if last_fused:
|
| 327 |
pipe.unfuse_lora()
|
| 328 |
pipe.unload_lora_weights()
|
| 329 |
pipe.unload_textual_inversion()
|
| 330 |
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
|
|
|
| 337 |
is_pivotal = sdxl_loras[selected_state_index]["is_pivotal"]
|
| 338 |
if is_pivotal:
|
| 339 |
text_embedding_name = sdxl_loras[selected_state_index]["text_embedding_weights"]
|
|
@@ -351,11 +459,17 @@ def generate_image(prompt, negative, face_emb, face_image, face_kps, image_stren
|
|
| 351 |
text_encoder=pipe.text_encoder_2,
|
| 352 |
tokenizer=pipe.tokenizer_2
|
| 353 |
)
|
|
|
|
|
|
|
|
|
|
| 354 |
|
| 355 |
print("Processing prompt...")
|
| 356 |
conditioning, pooled = compel(prompt)
|
| 357 |
negative_conditioning, negative_pooled = compel(negative) if negative else (None, None)
|
| 358 |
|
|
|
|
|
|
|
|
|
|
| 359 |
print("Generating image...")
|
| 360 |
image = pipe(
|
| 361 |
prompt_embeds=conditioning,
|
|
@@ -368,7 +482,7 @@ def generate_image(prompt, negative, face_emb, face_image, face_kps, image_stren
|
|
| 368 |
image=face_image,
|
| 369 |
strength=1-image_strength,
|
| 370 |
control_image=control_images,
|
| 371 |
-
num_inference_steps=
|
| 372 |
guidance_scale=guidance_scale,
|
| 373 |
controlnet_conditioning_scale=control_scales,
|
| 374 |
).images[0]
|
|
@@ -459,7 +573,7 @@ def get_civitai_safetensors(link):
|
|
| 459 |
gr.Warning("We couldn't find a SDXL LoRA on the model you've sent")
|
| 460 |
raise Exception("We couldn't find a SDXL LoRA on the model you've sent")
|
| 461 |
return model_data["name"], f"{lora_archive}/{safetensors_name}", trigger_word, image_url
|
| 462 |
-
|
| 463 |
def check_custom_model(link):
|
| 464 |
if(link.startswith("https://")):
|
| 465 |
if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
|
|
@@ -501,12 +615,12 @@ with gr.Blocks(css="custom.css") as demo:
|
|
| 501 |
gr_sdxl_loras = gr.State(value=sdxl_loras_raw)
|
| 502 |
title = gr.HTML(
|
| 503 |
"""<h1><img src="https://i.imgur.com/DVoGw04.png">
|
| 504 |
-
<span>
|
| 505 |
font-size: 13px;
|
| 506 |
display: block;
|
| 507 |
font-weight: normal;
|
| 508 |
opacity: 0.75;
|
| 509 |
-
"
|
| 510 |
elem_id="title",
|
| 511 |
)
|
| 512 |
selected_state = gr.State()
|
|
@@ -515,10 +629,10 @@ with gr.Blocks(css="custom.css") as demo:
|
|
| 515 |
with gr.Row(elem_id="main_app"):
|
| 516 |
with gr.Column(scale=4, elem_id="box_column"):
|
| 517 |
with gr.Group(elem_id="gallery_box"):
|
| 518 |
-
photo = gr.Image(label="Upload a picture", interactive=True, type="pil", height=300)
|
| 519 |
selected_loras = gr.Gallery(label="Selected LoRAs", height=80, show_share_button=False, visible=False, elem_id="gallery_selected")
|
| 520 |
gallery = gr.Gallery(
|
| 521 |
-
label="
|
| 522 |
allow_preview=False,
|
| 523 |
columns=4,
|
| 524 |
elem_id="gallery",
|
|
@@ -532,7 +646,7 @@ with gr.Blocks(css="custom.css") as demo:
|
|
| 532 |
with gr.Column(scale=5):
|
| 533 |
with gr.Row():
|
| 534 |
prompt = gr.Textbox(label="Prompt", show_label=False, lines=1, max_lines=1,
|
| 535 |
-
info="Describe your subject", value="a person", elem_id="prompt")
|
| 536 |
button = gr.Button("Run", elem_id="run_button")
|
| 537 |
|
| 538 |
result = ImageSlider(
|
|
@@ -545,22 +659,15 @@ with gr.Blocks(css="custom.css") as demo:
|
|
| 545 |
share_button = gr.Button("Share to community", elem_id="share-btn")
|
| 546 |
|
| 547 |
with gr.Accordion("Advanced options", open=False):
|
|
|
|
| 548 |
negative = gr.Textbox(label="Negative Prompt")
|
| 549 |
-
weight = gr.Slider(0, 10, value=0.
|
| 550 |
-
face_strength = gr.Slider(
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
info="Higher values preserve more of the original structure"
|
| 557 |
-
)
|
| 558 |
-
guidance_scale = gr.Slider(
|
| 559 |
-
0, 50, value=8, step=0.1, label="Guidance Scale"
|
| 560 |
-
)
|
| 561 |
-
depth_control_scale = gr.Slider(
|
| 562 |
-
0, 1, value=0.8, step=0.01, label="Zoe Depth ControlNet strength"
|
| 563 |
-
)
|
| 564 |
|
| 565 |
prompt_title = gr.Markdown(
|
| 566 |
value="### Click on a LoRA in the gallery to select it",
|
|
@@ -594,7 +701,7 @@ with gr.Blocks(css="custom.css") as demo:
|
|
| 594 |
).success(
|
| 595 |
fn=run_lora,
|
| 596 |
inputs=[photo, prompt, negative, weight, selected_state, face_strength, image_strength,
|
| 597 |
-
guidance_scale, depth_control_scale, gr_sdxl_loras, custom_loaded_lora],
|
| 598 |
outputs=[result, share_group],
|
| 599 |
)
|
| 600 |
|
|
@@ -605,7 +712,7 @@ with gr.Blocks(css="custom.css") as demo:
|
|
| 605 |
).success(
|
| 606 |
fn=run_lora,
|
| 607 |
inputs=[photo, prompt, negative, weight, selected_state, face_strength, image_strength,
|
| 608 |
-
guidance_scale, depth_control_scale, gr_sdxl_loras, custom_loaded_lora],
|
| 609 |
outputs=[result, share_group],
|
| 610 |
)
|
| 611 |
|
|
|
|
| 61 |
|
| 62 |
with open("defaults_data.json", "r") as file:
|
| 63 |
lora_defaults = json.load(file)
|
|
|
|
| 64 |
|
| 65 |
+
device = "cuda"
|
| 66 |
|
| 67 |
# Cache for LoRA state dicts
|
| 68 |
state_dicts = {}
|
|
|
|
| 80 |
}
|
| 81 |
|
| 82 |
sdxl_loras_raw = [item for item in sdxl_loras_raw if item.get("new") != True]
|
| 83 |
+
|
| 84 |
# Download models
|
| 85 |
hf_hub_download(
|
| 86 |
repo_id="InstantX/InstantID",
|
|
|
|
| 111 |
face_adapter = f'/data/checkpoints/ip-adapter.bin'
|
| 112 |
controlnet_path = f'/data/checkpoints/ControlNetModel'
|
| 113 |
|
|
|
|
| 114 |
st = time.time()
|
| 115 |
identitynet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
|
| 116 |
zoedepthnet = ControlNetModel.from_pretrained("diffusers/controlnet-zoe-depth-sdxl-1.0", torch_dtype=torch.float16)
|
|
|
|
| 157 |
last_fused = False
|
| 158 |
lora_archive = "/data"
|
| 159 |
|
| 160 |
+
# Improved face detection with multi-face support
|
| 161 |
+
def detect_faces(face_image, use_multiple_faces=False):
|
| 162 |
+
"""
|
| 163 |
+
Detect faces in the image
|
| 164 |
+
Returns: list of face info dictionaries, or empty list if no faces
|
| 165 |
+
"""
|
| 166 |
+
try:
|
| 167 |
+
face_info_list = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))
|
| 168 |
+
|
| 169 |
+
if not face_info_list or len(face_info_list) == 0:
|
| 170 |
+
print("No faces detected")
|
| 171 |
+
return []
|
| 172 |
+
|
| 173 |
+
# Sort faces by size (largest first)
|
| 174 |
+
face_info_list = sorted(
|
| 175 |
+
face_info_list,
|
| 176 |
+
key=lambda x: (x['bbox'][2] - x['bbox'][0]) * (x['bbox'][3] - x['bbox'][1]),
|
| 177 |
+
reverse=True
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if use_multiple_faces:
|
| 181 |
+
print(f"Detected {len(face_info_list)} faces")
|
| 182 |
+
return face_info_list
|
| 183 |
+
else:
|
| 184 |
+
print(f"Using largest face (detected {len(face_info_list)} total)")
|
| 185 |
+
return [face_info_list[0]]
|
| 186 |
+
|
| 187 |
+
except Exception as e:
|
| 188 |
+
print(f"Face detection error: {e}")
|
| 189 |
+
return []
|
| 190 |
+
|
| 191 |
+
def process_face_embeddings(face_info_list):
|
| 192 |
+
"""
|
| 193 |
+
Process face embeddings - average multiple faces or return single face
|
| 194 |
+
"""
|
| 195 |
+
if not face_info_list:
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
if len(face_info_list) == 1:
|
| 199 |
+
return face_info_list[0]['embedding']
|
| 200 |
+
|
| 201 |
+
# Average embeddings for multiple faces
|
| 202 |
+
embeddings = [face_info['embedding'] for face_info in face_info_list]
|
| 203 |
+
avg_embedding = np.mean(embeddings, axis=0)
|
| 204 |
+
return avg_embedding
|
| 205 |
+
|
| 206 |
+
def create_face_kps_image(face_image, face_info_list):
|
| 207 |
+
"""
|
| 208 |
+
Create keypoints image from face info
|
| 209 |
+
"""
|
| 210 |
+
if not face_info_list:
|
| 211 |
+
return face_image
|
| 212 |
+
|
| 213 |
+
# For multiple faces, draw all keypoints
|
| 214 |
+
if len(face_info_list) > 1:
|
| 215 |
+
return draw_multiple_kps(face_image, [f['kps'] for f in face_info_list])
|
| 216 |
+
else:
|
| 217 |
+
return draw_kps(face_image, face_info_list[0]['kps'])
|
| 218 |
+
|
| 219 |
+
def draw_multiple_kps(image_pil, kps_list, color_list=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]):
|
| 220 |
+
"""
|
| 221 |
+
Draw keypoints for multiple faces
|
| 222 |
+
"""
|
| 223 |
+
stickwidth = 4
|
| 224 |
+
limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
|
| 225 |
+
|
| 226 |
+
w, h = image_pil.size
|
| 227 |
+
out_img = np.zeros([h, w, 3])
|
| 228 |
+
|
| 229 |
+
for kps in kps_list:
|
| 230 |
+
kps = np.array(kps)
|
| 231 |
+
|
| 232 |
+
for i in range(len(limbSeq)):
|
| 233 |
+
index = limbSeq[i]
|
| 234 |
+
color = color_list[index[0]]
|
| 235 |
+
|
| 236 |
+
x = kps[index][:, 0]
|
| 237 |
+
y = kps[index][:, 1]
|
| 238 |
+
length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
|
| 239 |
+
angle = np.degrees(np.arctan2(y[0] - y[1], x[0] - x[1]))
|
| 240 |
+
polygon = cv2.ellipse2Poly(
|
| 241 |
+
(int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1
|
| 242 |
+
)
|
| 243 |
+
out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
|
| 244 |
+
|
| 245 |
+
out_img = (out_img * 0.6).astype(np.uint8)
|
| 246 |
+
|
| 247 |
+
for idx_kp, kp in enumerate(kps):
|
| 248 |
+
color = color_list[idx_kp]
|
| 249 |
+
x, y = kp
|
| 250 |
+
out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
|
| 251 |
+
|
| 252 |
+
out_img_pil = Image.fromarray(out_img.astype(np.uint8))
|
| 253 |
+
return out_img_pil
|
| 254 |
+
|
| 255 |
def update_selection(selected_state: gr.SelectData, sdxl_loras, face_strength, image_strength, weight, depth_control_scale, negative, is_new=False):
|
| 256 |
lora_repo = sdxl_loras[selected_state.index]["repo"]
|
| 257 |
new_placeholder = "Type a prompt to use your selected LoRA"
|
|
|
|
| 305 |
|
| 306 |
|
| 307 |
def run_lora(face_image, prompt, negative, lora_scale, selected_state, face_strength, image_strength,
|
| 308 |
+
guidance_scale, depth_control_scale, sdxl_loras, custom_lora, use_multiple_faces=False,
|
| 309 |
+
progress=gr.Progress(track_tqdm=True)):
|
| 310 |
"""
|
| 311 |
+
Enhanced run_lora with support for:
|
| 312 |
+
- No faces (landscape mode)
|
| 313 |
+
- Multiple faces
|
| 314 |
+
- Improved results
|
| 315 |
"""
|
| 316 |
print("Custom LoRA:", custom_lora)
|
| 317 |
custom_lora_path = custom_lora[0] if custom_lora else None
|
|
|
|
| 320 |
st = time.time()
|
| 321 |
face_image = resize_image_aspect_ratio(face_image)
|
| 322 |
|
| 323 |
+
# Enhanced face detection
|
| 324 |
+
face_info_list = detect_faces(face_image, use_multiple_faces)
|
| 325 |
+
face_detected = len(face_info_list) > 0
|
| 326 |
+
|
| 327 |
+
if face_detected:
|
| 328 |
+
face_emb = process_face_embeddings(face_info_list)
|
| 329 |
+
face_kps = create_face_kps_image(face_image, face_info_list)
|
| 330 |
+
print(f"Processing with {len(face_info_list)} face(s)")
|
| 331 |
+
else:
|
| 332 |
face_emb = None
|
| 333 |
face_kps = face_image
|
| 334 |
+
print("No faces detected - using landscape/depth mode only")
|
| 335 |
|
| 336 |
et = time.time()
|
| 337 |
print('Face processing took:', et - st, 'seconds')
|
| 338 |
|
| 339 |
st = time.time()
|
| 340 |
|
| 341 |
+
# Enhanced prompt processing
|
| 342 |
if custom_lora_path and custom_lora[1]:
|
| 343 |
prompt = f"{prompt} {custom_lora[1]}"
|
| 344 |
else:
|
| 345 |
+
for lora_list in lora_defaults:
|
| 346 |
+
if lora_list["model"] == sdxl_loras[selected_state_index]["repo"]:
|
| 347 |
+
prompt_full = lora_list.get("prompt", None)
|
| 348 |
+
if prompt_full:
|
| 349 |
+
prompt = prompt_full.replace("<subject>", prompt)
|
|
|
|
| 350 |
|
| 351 |
print("Prompt:", prompt)
|
| 352 |
if prompt == "":
|
| 353 |
+
prompt = "a beautiful scene" if not face_detected else "a person"
|
| 354 |
print(f"Executing prompt: {prompt}")
|
| 355 |
|
| 356 |
if negative == "":
|
| 357 |
+
# Enhanced negative prompt for better quality
|
| 358 |
+
negative = "worst quality, low quality, blurry, distorted, deformed" if not face_detected else None
|
| 359 |
|
| 360 |
print("Custom Loaded LoRA:", custom_lora_path)
|
| 361 |
|
|
|
|
| 365 |
repo_name = custom_lora_path
|
| 366 |
full_path_lora = custom_lora_path
|
| 367 |
else:
|
| 368 |
+
repo_name = sdxl_loras[selected_state_index]["repo"]
|
| 369 |
+
full_path_lora = state_dicts[repo_name]["saved_name"]
|
|
|
|
|
|
|
|
|
|
| 370 |
|
| 371 |
repo_name = repo_name.rstrip("/").lower()
|
| 372 |
|
|
|
|
| 375 |
et = time.time()
|
| 376 |
print('Prompt processing took:', et - st, 'seconds')
|
| 377 |
|
| 378 |
+
# Adjust parameters based on face detection
|
| 379 |
+
if not face_detected:
|
| 380 |
+
# For landscape/no face mode, reduce face strength and increase depth control
|
| 381 |
+
face_strength = 0.0
|
| 382 |
+
depth_control_scale = max(depth_control_scale, 0.9)
|
| 383 |
+
image_strength = min(image_strength, 0.4)
|
| 384 |
+
print("Adjusted parameters for no-face mode")
|
| 385 |
+
|
| 386 |
st = time.time()
|
|
|
|
| 387 |
image = generate_image(
|
| 388 |
prompt, negative, face_emb, face_image, face_kps, image_strength,
|
| 389 |
guidance_scale, face_strength, depth_control_scale, repo_name,
|
|
|
|
| 404 |
print("Loaded state dict:", loaded_state_dict)
|
| 405 |
print("Last LoRA:", last_lora, "| Current LoRA:", repo_name)
|
| 406 |
|
| 407 |
+
# Prepare control images and scales based on face detection
|
| 408 |
+
if face_detected:
|
| 409 |
+
control_images = [face_kps, zoe(face_image)]
|
| 410 |
+
control_scales = [face_strength, depth_control_scale]
|
| 411 |
+
else:
|
| 412 |
+
# Only use depth control for landscapes
|
| 413 |
+
control_images = [zoe(face_image)]
|
| 414 |
+
control_scales = [depth_control_scale]
|
| 415 |
|
| 416 |
# Handle custom LoRA from HuggingFace
|
| 417 |
if repo_name.startswith("https://huggingface.co"):
|
|
|
|
| 428 |
else:
|
| 429 |
full_path_lora = loaded_state_dict
|
| 430 |
|
| 431 |
+
# Improved LoRA loading and caching
|
| 432 |
if last_lora != repo_name:
|
| 433 |
if last_fused:
|
| 434 |
pipe.unfuse_lora()
|
| 435 |
pipe.unload_lora_weights()
|
| 436 |
pipe.unload_textual_inversion()
|
| 437 |
|
| 438 |
+
# Load LoRA with better error handling
|
| 439 |
+
try:
|
| 440 |
+
pipe.load_lora_weights(full_path_lora)
|
| 441 |
+
pipe.fuse_lora(lora_scale)
|
| 442 |
+
last_fused = True
|
| 443 |
+
|
| 444 |
+
# Handle pivotal tuning embeddings
|
| 445 |
is_pivotal = sdxl_loras[selected_state_index]["is_pivotal"]
|
| 446 |
if is_pivotal:
|
| 447 |
text_embedding_name = sdxl_loras[selected_state_index]["text_embedding_weights"]
|
|
|
|
| 459 |
text_encoder=pipe.text_encoder_2,
|
| 460 |
tokenizer=pipe.tokenizer_2
|
| 461 |
)
|
| 462 |
+
except Exception as e:
|
| 463 |
+
print(f"Error loading LoRA: {e}")
|
| 464 |
+
raise gr.Error(f"Failed to load LoRA: {str(e)}")
|
| 465 |
|
| 466 |
print("Processing prompt...")
|
| 467 |
conditioning, pooled = compel(prompt)
|
| 468 |
negative_conditioning, negative_pooled = compel(negative) if negative else (None, None)
|
| 469 |
|
| 470 |
+
# Enhanced generation parameters
|
| 471 |
+
num_inference_steps = 40 # Increased for better quality
|
| 472 |
+
|
| 473 |
print("Generating image...")
|
| 474 |
image = pipe(
|
| 475 |
prompt_embeds=conditioning,
|
|
|
|
| 482 |
image=face_image,
|
| 483 |
strength=1-image_strength,
|
| 484 |
control_image=control_images,
|
| 485 |
+
num_inference_steps=num_inference_steps,
|
| 486 |
guidance_scale=guidance_scale,
|
| 487 |
controlnet_conditioning_scale=control_scales,
|
| 488 |
).images[0]
|
|
|
|
| 573 |
gr.Warning("We couldn't find a SDXL LoRA on the model you've sent")
|
| 574 |
raise Exception("We couldn't find a SDXL LoRA on the model you've sent")
|
| 575 |
return model_data["name"], f"{lora_archive}/{safetensors_name}", trigger_word, image_url
|
| 576 |
+
|
| 577 |
def check_custom_model(link):
|
| 578 |
if(link.startswith("https://")):
|
| 579 |
if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
|
|
|
|
| 615 |
gr_sdxl_loras = gr.State(value=sdxl_loras_raw)
|
| 616 |
title = gr.HTML(
|
| 617 |
"""<h1><img src="https://i.imgur.com/DVoGw04.png">
|
| 618 |
+
<span>Face to All - Enhanced<br><small style="
|
| 619 |
font-size: 13px;
|
| 620 |
display: block;
|
| 621 |
font-weight: normal;
|
| 622 |
opacity: 0.75;
|
| 623 |
+
">🔥 Supports: No faces (landscape), Multiple faces, Improved quality, Custom LoRAs<br> diffusers InstantID + ControlNet</small></span></h1>""",
|
| 624 |
elem_id="title",
|
| 625 |
)
|
| 626 |
selected_state = gr.State()
|
|
|
|
| 629 |
with gr.Row(elem_id="main_app"):
|
| 630 |
with gr.Column(scale=4, elem_id="box_column"):
|
| 631 |
with gr.Group(elem_id="gallery_box"):
|
| 632 |
+
photo = gr.Image(label="Upload a picture (with or without faces)", interactive=True, type="pil", height=300)
|
| 633 |
selected_loras = gr.Gallery(label="Selected LoRAs", height=80, show_share_button=False, visible=False, elem_id="gallery_selected")
|
| 634 |
gallery = gr.Gallery(
|
| 635 |
+
label="Pick a style from the gallery",
|
| 636 |
allow_preview=False,
|
| 637 |
columns=4,
|
| 638 |
elem_id="gallery",
|
|
|
|
| 646 |
with gr.Column(scale=5):
|
| 647 |
with gr.Row():
|
| 648 |
prompt = gr.Textbox(label="Prompt", show_label=False, lines=1, max_lines=1,
|
| 649 |
+
info="Describe your subject or scene", value="a person", elem_id="prompt")
|
| 650 |
button = gr.Button("Run", elem_id="run_button")
|
| 651 |
|
| 652 |
result = ImageSlider(
|
|
|
|
| 659 |
share_button = gr.Button("Share to community", elem_id="share-btn")
|
| 660 |
|
| 661 |
with gr.Accordion("Advanced options", open=False):
|
| 662 |
+
use_multiple_faces = gr.Checkbox(label="Use multiple faces (if detected)", value=False)
|
| 663 |
negative = gr.Textbox(label="Negative Prompt")
|
| 664 |
+
weight = gr.Slider(0, 10, value=0.9, step=0.1, label="LoRA weight")
|
| 665 |
+
face_strength = gr.Slider(0, 2, value=0.9, step=0.01, label="Face strength",
|
| 666 |
+
info="Higher values increase face likeness (auto-adjusted for no-face images)")
|
| 667 |
+
image_strength = gr.Slider(0, 1, value=0.20, step=0.01, label="Image strength",
|
| 668 |
+
info="Higher values increase similarity with original structure/colors")
|
| 669 |
+
guidance_scale = gr.Slider(0, 50, value=8, step=0.1, label="Guidance Scale")
|
| 670 |
+
depth_control_scale = gr.Slider(0, 1, value=0.8, step=0.01, label="Zoe Depth ControlNet strength")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
|
| 672 |
prompt_title = gr.Markdown(
|
| 673 |
value="### Click on a LoRA in the gallery to select it",
|
|
|
|
| 701 |
).success(
|
| 702 |
fn=run_lora,
|
| 703 |
inputs=[photo, prompt, negative, weight, selected_state, face_strength, image_strength,
|
| 704 |
+
guidance_scale, depth_control_scale, gr_sdxl_loras, custom_loaded_lora, use_multiple_faces],
|
| 705 |
outputs=[result, share_group],
|
| 706 |
)
|
| 707 |
|
|
|
|
| 712 |
).success(
|
| 713 |
fn=run_lora,
|
| 714 |
inputs=[photo, prompt, negative, weight, selected_state, face_strength, image_strength,
|
| 715 |
+
guidance_scale, depth_control_scale, gr_sdxl_loras, custom_loaded_lora, use_multiple_faces],
|
| 716 |
outputs=[result, share_group],
|
| 717 |
)
|
| 718 |
|