rhinoplasty / app.py
devbucky's picture
resolved mediapipe.solutions error
e944a0a verified
Raw History Blame Contribute Delete
20.8 kB
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
)