Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import gradio as grimport mediapipe as mpimport numpy as npimport cv2import base64import jsonimport mathfrom PIL import Imageimport io
# ββ MediaPipe setup ββmp_face_mesh = mp.solutions.face_meshface_mesh = mp_face_mesh.FaceMesh( static_image_mode=True, max_num_faces=1, refine_landmarks=True, # gives 478 landmarks including irises min_detection_confidence=0.4)
def analyse_face(image): """ Accepts a PIL Image. Returns JSON string with landmarks + calculated scores. """ try: # Convert PIL to numpy BGR for MediaPipe img_rgb = np.array(image.convert("RGB")) h, w = img_rgb.shape[:2]
results = face_mesh.process(img_rgb)
if not results.multi_face_landmarks: return json.dumps({"error": "No face detected. Please upload a clear, front-facing photo."})
lm = results.multi_face_landmarks[0].landmark # 478 normalised landmarks
# ββ Helper: pixel distance between two landmark indices ββ def dist(a, b): return math.sqrt( ((lm[a].x - lm[b].x) * w) ** 2 + ((lm[a].y - lm[b].y) * h) ** 2 )
# ββ 1. AGE RANGE ESTIMATION ββ # Based on published facial ageing geometry research face_ref = dist(33, 263) # inter-ocular distance (scale reference) face_height = dist(10, 152) # top to chin lower_face_h = dist(168, 152) # nose bridge to chin lower_ratio = lower_face_h / face_height if face_height > 0 else 0.52
# Orbital descent: eye outer corner Y vs face outer Y eye_drop_l = ((lm[33].y - lm[234].y) * h) eye_drop_r = ((lm[263].y - lm[454].y) * h) orbital_drop = ((eye_drop_l + eye_drop_r) / 2) / face_ref if face_ref > 0 else 0
# Nasolabial fold proxy nasolabial_l = dist(50, 61) / face_ref if face_ref > 0 else 0.38 nasolabial_r = dist(280, 291) / face_ref if face_ref > 0 else 0.38 nasolabial = (nasolabial_l + nasolabial_r) / 2
# Z-depth variance in forehead region (texture/wrinkle proxy) forehead_idx = [10,109,67,103,54,21,162,127,234, 338,297,332,284,251,389,356,454] z_vals = [lm[i].z for i in forehead_idx] z_mean = sum(z_vals) / len(z_vals) z_var = sum((z - z_mean) ** 2 for z in z_vals) / len(z_vals) texture_depth = math.sqrt(abs(z_var)) * 100
age_raw = (20 + (lower_ratio - 0.52) * 120 + orbital_drop * 80 + (nasolabial - 0.38) * 60 + texture_depth * 28)
age_mid = max(18, min(72, round(age_raw))) age_low = max(18, age_mid - 4) age_high = age_mid + 4 age_range = f"{age_low}β{age_high}"
# ββ 2. WRINKLE SCORE (1β10) ββ wrinkle_raw = 1 + texture_depth * 18 + (age_mid - 18) * 0.10 wrinkle = round(max(1.0, min(9.9, wrinkle_raw)), 1)
# ββ 3. SKIN ELASTICITY SCORE (1β10) ββ cheek_sag_l = dist(116, 61) / face_ref if face_ref > 0 else 0.55 cheek_sag_r = dist(345, 291) / face_ref if face_ref > 0 else 0.55 cheek_sag = (cheek_sag_l + cheek_sag_r) / 2
elasticity_raw = 10 - (cheek_sag - 0.55) * 18 - (age_mid - 18) * 0.10 elasticity = round(max(1.0, min(9.9, elasticity_raw)), 1)
# ββ 4. JAWLINE SCORE (1β10) ββ jaw_points = [234,93,132,58,172,136,150,149,176, 148,152,377,400,378,379,365,397,288, 361,323,454] jaw_deviation = 0.0 for i in range(1, len(jaw_points) - 1): prev = jaw_points[i - 1] curr = jaw_points[i] nxt = jaw_points[i + 1] ax = (lm[curr].x - lm[prev].x) * w ay = (lm[curr].y - lm[prev].y) * h bx = (lm[nxt].x - lm[curr].x) * w by = (lm[nxt].y - lm[curr].y) * h jaw_deviation += abs(ax * by - ay * bx) / (face_ref ** 2) if face_ref > 0 else 0 jaw_deviation /= len(jaw_points)
jawline_raw = 10 - jaw_deviation * 0.8 - (age_mid - 18) * 0.09 jawline = round(max(1.0, min(9.9, jawline_raw)), 1)
# ββ 5. YEARS YOUNGER potential ββ age_factor = max(0, min(1, (age_mid - 18) / 54)) years_younger = max(3, round(age_factor * 14 + 2))
# ββ 6. Serialize landmarks for browser mesh drawing ββ landmarks_out = [ {"x": float(l.x), "y": float(l.y), "z": float(l.z)} for l in lm ]
return json.dumps({ "age_range": age_range, "age_mid": age_mid, "wrinkle": wrinkle, "elasticity": elasticity, "jawline": jawline, "years_younger": years_younger, "age_factor": round(age_factor, 3), "landmarks": landmarks_out, "image_width": w, "image_height": h })
except Exception as e: return json.dumps({"error": str(e)})
# ββ Gradio interface ββiface = gr.Interface( fn=analyse_face, inputs=gr.Image(type="pil", label="Upload Face Photo"), outputs=gr.Textbox(label="Analysis JSON"), title="AgeAI Face Analysis", description="Returns facial landmark coordinates and skin ageing scores as JSON.")
iface.launch()app.pyAdded+147