Spaces:
Build error
Build error
File size: 20,754 Bytes
662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a 662ffc4 e944a0a | 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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | import gradio as gr
import cv2
import numpy as np
from PIL import Image
import mediapipe as mp
import google.genai as genai
import os
import replicate
import base64
from io import BytesIO
# 30 user-provided landmark indices outlining the nose
USER_NOSE_POINTS = [
107, 9, 336, 285, 413, 464, 465, 412, 399, 456,
420, 429, 279, 327, 326, 2, 97, 98, 64, 129,
49, 131, 198, 217, 114, 188, 245, 193, 55, 107]
def detect_face_first(image_rgb):
mp_face_detection = mp.solutions.face_detection
with mp_face_detection.FaceDetection(
model_selection=1,
min_detection_confidence=0.3
) as face_detection:
results = face_detection.process(image_rgb)
if not results.detections:
return False, 0, "No face detected in the image."
num_faces = len(results.detections)
if num_faces > 1:
return False, num_faces, f"Multiple faces detected! Found {num_faces} faces. Please upload an image with ONLY ONE person."
return True, 1, "Face detected successfully."
def is_profile_face(landmarks, image_width, image_height):
lm = landmarks.landmark
left_eye_indices = [33, 133, 160, 159, 158]
right_eye_indices = [362, 263, 385, 386, 387]
left_eye_visible = 0
right_eye_visible = 0
for idx in left_eye_indices:
if idx < len(lm):
if lm[idx].visibility > 0.5:
left_eye_visible += 1
for idx in right_eye_indices:
if idx < len(lm):
if lm[idx].visibility > 0.5:
right_eye_visible += 1
total_visible = left_eye_visible + right_eye_visible
if total_visible < 3:
return True
visibility_ratio = abs(left_eye_visible - right_eye_visible) / max(total_visible, 1)
return visibility_ratio > 0.6
def generate_nose_mask(image: Image.Image):
"""Generate nose mask. Returns (mask_image, info_message)"""
if image is None:
return None, "No image uploaded."
img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
img_rgb = np.array(image)
h, w = img_bgr.shape[:2]
if w < 100 or h < 100:
return None, "Image is too small. Minimum size is 100x100 pixels."
face_detected, num_faces, detection_msg = detect_face_first(img_rgb)
if not face_detected:
return None, detection_msg
mp_face_mesh = mp.solutions.face_mesh
results = None
with mp_face_mesh.FaceMesh(
static_image_mode=True,
refine_landmarks=True,
max_num_faces=1,
min_detection_confidence=0.3
) as face_mesh:
results = face_mesh.process(img_rgb)
if not results or not results.multi_face_landmarks:
with mp_face_mesh.FaceMesh(
static_image_mode=True,
refine_landmarks=False,
max_num_faces=1,
min_detection_confidence=0.1
) as face_mesh_relaxed:
results = face_mesh_relaxed.process(img_rgb)
if not results or not results.multi_face_landmarks:
with mp_face_mesh.FaceMesh(
static_image_mode=True,
refine_landmarks=False,
max_num_faces=1,
min_detection_confidence=0.01
) as face_mesh_ultra_relaxed:
results = face_mesh_ultra_relaxed.process(img_rgb)
if not results or not results.multi_face_landmarks:
with mp_face_mesh.FaceMesh(
static_image_mode=False,
refine_landmarks=False,
max_num_faces=1,
min_detection_confidence=0.01,
min_tracking_confidence=0.01
) as face_mesh_video:
results = face_mesh_video.process(img_rgb)
if not results or not results.multi_face_landmarks:
return None, "Face detected but could not extract facial landmarks."
lm = results.multi_face_landmarks[0]
is_profile = is_profile_face(lm, w, h)
face_type = "side profile" if is_profile else "frontal face"
nose_points = USER_NOSE_POINTS
min_points_required = 3 if is_profile else 5
pts = []
for idx in nose_points:
if idx < len(lm.landmark):
landmark = lm.landmark[idx]
x_px = int(landmark.x * w)
y_px = int(landmark.y * h)
if is_profile:
if -10 <= x_px < w + 10 and -10 <= y_px < h + 10:
x_px = max(0, min(w - 1, x_px))
y_px = max(0, min(h - 1, y_px))
pts.append((x_px, y_px))
else:
if 0 <= x_px < w and 0 <= y_px < h:
pts.append((x_px, y_px))
if len(pts) < min_points_required:
fallback_indices = [1, 2, 4, 5, 6, 19, 94, 168, 195]
for idx in fallback_indices:
if idx < len(lm.landmark):
landmark = lm.landmark[idx]
x_px = int(landmark.x * w)
y_px = int(landmark.y * h)
if -10 <= x_px < w + 10 and -10 <= y_px < h + 10:
x_px = max(0, min(w - 1, x_px))
y_px = max(0, min(h - 1, y_px))
pts.append((x_px, y_px))
if len(pts) < 3:
return None, f"Unable to generate mask: Only {len(pts)} nose landmarks detected."
hull = cv2.convexHull(np.array(pts, dtype=np.int32))
mask = np.zeros((h, w), dtype=np.uint8)
cv2.fillPoly(mask, [hull], 255)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
mask = cv2.dilate(mask, kernel, iterations=2)
mask = cv2.GaussianBlur(mask, (5, 5), 0)
_, mask = cv2.threshold(mask, 128, 255, cv2.THRESH_BINARY)
success_msg = f"✓ Detected {face_type} with {len(pts)} nose landmarks."
return Image.fromarray(mask), success_msg
def generate_canny_edge(image: Image.Image, low_threshold=100, high_threshold=200):
"""Generate Canny edge map. Returns (canny_image, info_message)"""
if image is None:
return None, "No image provided."
try:
img_array = np.array(image)
if len(img_array.shape) == 3:
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
else:
gray = img_array
blurred = cv2.GaussianBlur(gray, (5, 5), 1.4)
canny = cv2.Canny(blurred, low_threshold, high_threshold)
canny_3channel = cv2.cvtColor(canny, cv2.COLOR_GRAY2RGB)
canny_pil = Image.fromarray(canny_3channel)
return canny_pil, "✓ Canny edge map generated."
except Exception as e:
return None, f"Error: {str(e)}"
def generate_gemini_prompt(image: Image.Image, user_modification: str, api_key: str):
"""Use Gemini to generate detailed prompt. Returns (prompt, status)"""
if image is None:
return None, "No image provided."
if not user_modification or user_modification.strip() == "":
return None, "Please describe desired nose modifications."
if not api_key or api_key.strip() == "":
return None, "Please provide Gemini API key."
try:
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-2.0-flash-exp')
system_prompt = f"""You are an expert AI prompt engineer for rhinoplasty simulation using Stable Diffusion inpainting.
The user wants: "{user_modification}"
Analyze this face image and create an OPTIMAL BALANCED PROMPT following this exact structure:
**STRUCTURE:**
[NOSE MODIFICATION DETAILS] + [STRICT PRESERVATION] + [QUALITY KEYWORDS]
**REQUIREMENTS:**
1. **Modification Section**: Describe the nose changes in natural, specific, visual terms (not medical jargon)
- Be concrete: "reduce bridge height by making it straighter and lower"
- Use visual descriptors with CAPS for emphasis on key structural features
- Reference the user's request: {user_modification}
**CRITICAL TIP SHAPE RULES:**
- If user wants "button nose", "rounded tip", or "fuller tip": USE CAPS like "ROUNDED BULBOUS tip", "FULLER WIDER tip (NOT narrow, NOT pointed)"
- If user wants "narrow tip", "refined tip", "pointed tip": USE "narrower, more refined tip"
- For "upturned": emphasize "lifted upward" but also specify tip roundness if needed
- For "Roman": emphasize "narrow pointed tip extending downward"
- For "Nubian": emphasize "WIDER FULLER ROUNDED tip with expanded width"
**AVOID conflicting words**: Don't use "refined" or "delicate" when describing tips that should be fuller/rounder
2. **Preservation Section**: Use STRONG language to preserve identity
- MUST include: "CRITICAL: preserve exact skin texture, skin tone, facial structure, eyes, lips, cheeks, expression, lighting, shadows, and background completely unchanged"
- Use words like: "identical", "exact same", "preserve", "keep unchanged"
3. **Quality Section**: Add photorealism keywords
- Include: "photorealistic, high resolution, professional photography, natural blending, 8k, sharp focus, detailed skin texture"
**EXAMPLE OUTPUTS:**
For button/rounded nose:
"Nose modification: create a button nose with SHORT COMPACT structure, ROUNDED BULBOUS TIP that is FULLER and WIDER (explicitly NOT narrow or pointed), low gentle bridge with soft slope, maintain the rounded ball-like quality of the tip. CRITICAL: preserve exact skin texture, skin tone, facial structure, eyes, lips, expression, lighting, and background completely unchanged. Photorealistic, high resolution, professional photography, natural blending, 8k, sharp focus, detailed skin texture."
For refined/narrow nose:
"Nose refinement: reduce the bridge height for a straighter profile, narrow and refine the nasal tip to be more delicate and pointed, slightly lift the tip angle. CRITICAL: preserve exact skin texture, skin tone, facial structure, eyes, lips, expression, lighting, and background completely unchanged. Photorealistic, high resolution, professional photography, natural blending, 8k, sharp focus, detailed skin texture."
**OUTPUT RULES:**
- Maximum 3 sentences total
- Natural language (avoid medical terms like "dorsum", "alar base", "osteotomy")
- Focus on VISUAL outcomes, not surgical procedures
- Use CAPS for critical structural features that need emphasis
- Balance specificity with clarity
- Do NOT use bullet points or lists, use flowing prose
Generate the prompt now:"""
response = model.generate_content([system_prompt, image])
generated_prompt = response.text.strip()
return generated_prompt, "✓ Gemini analysis completed."
except Exception as e:
return None, f"Gemini error: {str(e)}"
def image_to_data_uri(image: Image.Image):
"""Convert PIL Image to data URI for Replicate"""
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()
return f"data:image/png;base64,{img_str}"
# ============================================
# MODEL-SPECIFIC FUNCTIONS (3 MODELS ONLY)
# ============================================
def run_sdxl_inpainting(original_image, mask_image, prompt, replicate_api_key):
"""Model 1: Flux Fill Dev - Uses: image + mask + prompt"""
try:
os.environ["REPLICATE_API_TOKEN"] = replicate_api_key.strip()
w, h = original_image.size
mask_image = mask_image.resize((w, h))
image_uri = image_to_data_uri(original_image)
mask_uri = image_to_data_uri(mask_image)
output = replicate.run(
"black-forest-labs/flux-fill-dev",
input={
"image": image_uri,
"mask": mask_uri,
"prompt": prompt,
"guidance": 33,
"steps": 28,
"output_format": "png",
"output_quality": 95
}
)
if output:
import requests
if isinstance(output, list):
image_url = str(output[0]) if hasattr(output[0], '__str__') else output[0].url
else:
image_url = str(output)
response = requests.get(image_url)
result_image = Image.open(BytesIO(response.content))
return result_image, "✓ Flux Fill Dev completed!"
else:
return None, "No output from model."
except Exception as e:
return None, f"Error: {str(e)}"
def run_flux_fill_pro(original_image, mask_image, prompt, replicate_api_key):
"""Model 2: Flux Fill Pro - Uses: image + mask + prompt (requires min 256x256)"""
try:
os.environ["REPLICATE_API_TOKEN"] = replicate_api_key.strip()
w, h = original_image.size
if w < 256 or h < 256:
scale_factor = max(256 / w, 256 / h)
new_w = int(w * scale_factor)
new_h = int(h * scale_factor)
original_image = original_image.resize((new_w, new_h))
mask_image = mask_image.resize((new_w, new_h))
status_msg = f"✓ Flux Fill Pro completed! (Upscaled from {w}x{h} to {new_w}x{new_h} to meet 256px minimum)"
else:
mask_image = mask_image.resize((w, h))
status_msg = "✓ Flux Fill Pro completed!"
image_uri = image_to_data_uri(original_image)
mask_uri = image_to_data_uri(mask_image)
output = replicate.run(
"black-forest-labs/flux-fill-pro",
input={
"image": image_uri,
"mask": mask_uri,
"prompt": prompt,
"steps": 25,
"guidance": 3.0,
}
)
if output:
import requests
if isinstance(output, list):
image_url = str(output[0]) if hasattr(output[0], '__str__') else output[0].url
else:
image_url = str(output)
response = requests.get(image_url)
result_image = Image.open(BytesIO(response.content))
return result_image, status_msg
else:
return None, "No output from model."
except Exception as e:
return None, f"Error: {str(e)}"
def run_bria_genfill(original_image, mask_image, prompt, replicate_api_key):
"""Model 3: Bria GenFill - Uses: image + mask + prompt"""
try:
os.environ["REPLICATE_API_TOKEN"] = replicate_api_key.strip()
w, h = original_image.size
mask_image = mask_image.resize((w, h))
image_uri = image_to_data_uri(original_image)
mask_uri = image_to_data_uri(mask_image)
enhanced_prompt = f"{prompt}, seamlessly blended with facial features, matching existing skin tone and texture, natural transitions, photorealistic medical photography quality"
output = replicate.run(
"bria/genfill",
input={
"image": image_uri,
"mask": mask_uri,
"prompt": enhanced_prompt,
}
)
if output:
import requests
if isinstance(output, list):
image_url = str(output[0]) if hasattr(output[0], '__str__') else output[0].url
else:
image_url = str(output)
response = requests.get(image_url)
result_image = Image.open(BytesIO(response.content))
return result_image, "✓ Bria GenFill completed!"
else:
return None, "No output from model."
except Exception as e:
return None, f"Error: {str(e)}"
# ============================================
# PIPELINE
# ============================================
def rhinoplasty_pipeline(image, modification_text, use_gemini_enhancer, gemini_api_key, replicate_api_key, model_choice):
"""Complete rhinoplasty simulation pipeline"""
status_log = []
status_log.append(f"🎯 Selected Model: {model_choice}\n")
if image is None:
return None, "No image uploaded."
# Step 1: Generate nose mask
status_log.append("Step 1: Generating nose mask...")
mask, mask_msg = generate_nose_mask(image)
status_log.append(f" {mask_msg}")
if mask is None:
return None, "\n".join(status_log)
# Step 2: Generate canny edge (kept for future use)
status_log.append("\nStep 2: Generating canny edge map (for future ControlNet use)...")
canny, canny_msg = generate_canny_edge(image)
status_log.append(f" {canny_msg}")
# Step 3: Prepare prompt
if use_gemini_enhancer:
status_log.append("\nStep 3: Analyzing face with Gemini...")
prompt, gemini_msg = generate_gemini_prompt(image, modification_text, gemini_api_key)
status_log.append(f" {gemini_msg}")
if prompt is None:
return None, "\n".join(status_log)
status_log.append(f"\nEnhanced Prompt:\n{prompt}")
else:
status_log.append("\nStep 3: Using structured prompt (Gemini disabled)...")
prompt = f"""Nose modification: {modification_text}, creating a natural and harmonious appearance. CRITICAL: preserve exact skin texture, skin tone, facial structure, eyes, lips, cheeks, eyebrows, expression, lighting, shadows, hair, and background completely unchanged. Keep the person's identity identical. Photorealistic, high resolution, professional photography, natural blending, 8k, sharp focus, detailed skin texture, natural lighting."""
status_log.append(f" ✓ Structured prompt prepared.")
status_log.append(f"\nPrompt Used:\n{prompt}")
# Step 4: Run selected model
status_log.append(f"\n\nStep 4: Running {model_choice}...")
status_log.append(" (This may take 20-60 seconds...)")
if model_choice == "Flux Fill Dev (Recommended)":
result, result_msg = run_sdxl_inpainting(image, mask, prompt, replicate_api_key)
elif model_choice == "Flux Fill Pro (Premium)":
result, result_msg = run_flux_fill_pro(image, mask, prompt, replicate_api_key)
elif model_choice == "Bria GenFill (Budget)":
result, result_msg = run_bria_genfill(image, mask, prompt, replicate_api_key)
else:
return None, "Invalid model selection."
status_log.append(f" {result_msg}")
if result is None:
return None, "\n".join(status_log)
status_log.append(f"\n💰 Estimated cost: ~$0.01-0.03")
return result, "\n".join(status_log)
# ============================================
# GRADIO INTERFACE
# ============================================
default_gemini_key = os.getenv("GEMINI_API_KEY", "")
default_replicate_key = os.getenv("REPLICATE_API_TOKEN", "")
iface = gr.Interface(
fn=rhinoplasty_pipeline,
api_name="predict",
inputs=[
gr.Image(type="pil", label="Upload Face Image"),
gr.Textbox(
label="Desired Nose Modification",
placeholder="Examples: 'button nose with ROUNDED FULLER tip' | 'Roman nose with dorsal hump' | 'upturned nose'",
lines=2,
info="Use CAPS for emphasis on key features like 'ROUNDED', 'FULLER', 'WIDER'"
),
gr.Checkbox(
label="Use Gemini Prompt Enhancer",
value=True,
info="Enable AI-powered prompt enhancement (requires Gemini API key)"
),
gr.Textbox(
label="Gemini API Key (Optional - only if enhancer enabled)",
placeholder="Get free at: https://makersuite.google.com/app/apikey",
value=default_gemini_key,
type="password",
lines=1
),
gr.Textbox(
label="Replicate API Key (Required)",
placeholder="Get at: https://replicate.com/account/api-tokens",
value=default_replicate_key,
type="password",
lines=1
),
gr.Dropdown(
label="Select AI Model",
choices=[
"Flux Fill Dev (Recommended)",
"Flux Fill Pro (Premium)",
"Bria GenFill (Budget)"
],
value="Flux Fill Dev (Recommended)",
info="Choose your preferred model"
)
],
outputs=[
gr.Image(label="Result"),
gr.Textbox(label="Processing Log", lines=18)
],
title="🔬Simulator",
description="""
**Simulation**
""",
examples=[],
)
if __name__ == "__main__":
# Launch with explicit settings for Hugging Face Spaces
iface.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True,
quiet=False
) |