Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567891011121314151617181920212223242526272829301 unmodified line3233343536373839404142435 unmodified lines495051525354555657584 unmodified lines63646566676869707172737475766 unmodified lines8384858687888912 unmodified lines1021031041051061071083 unmodified linesimport mathimport jsonfrom PIL import Image# ββ 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,min_detection_confidence=0.4)def analyse_face(image):try: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].landmarkdef dist(a, b):return math.sqrt(1 unmodified line((lm[a].y - lm[b].y) * h) ** 2)# Reference distanceface_ref = dist(33, 263)if face_ref == 0:return json.dumps({"error": "Could not measure face. Please try a different photo."})# Age estimationface_height = dist(10, 152)lower_face_h = dist(168, 152)lower_ratio = lower_face_h / face_height if face_height > 0 else 0.525 unmodified linesnasolabial = ((dist(50, 61) + dist(280, 291)) / 2) / face_refforehead_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 = math.sqrt(abs(z_var)) * 100age_raw = (20+ (lower_ratio - 0.52) * 1204 unmodified linesage_mid = max(18, min(72, round(age_raw)))age_range = f"{max(18, age_mid - 4)}\u2013{age_mid + 4}"# Wrinkle scorewrinkle = round(max(1.0, min(9.9, 1 + texture * 18 + (age_mid - 18) * 0.10)), 1)# Elasticity scorecheek_sag = ((dist(116, 61) + dist(345, 291)) / 2) / face_refelasticity = round(max(1.0, min(9.9, 10 - (cheek_sag - 0.55) * 18 - (age_mid - 18) * 0.10)), 1)# Jawline scorejaw_pts = [234,93,132,58,172,136,150,149,176,148,152,377,400,378,379,365,397,288,361,323,454]jaw_dev = 0.0for i in range(1, len(jaw_pts) - 1):6 unmodified linesjaw_dev /= len(jaw_pts)jawline = round(max(1.0, min(9.9, 10 - jaw_dev * 0.8 - (age_mid - 18) * 0.09)), 1)age_factor = round(max(0, min(1, (age_mid - 18) / 54)), 3)years_younger = max(3, round(age_factor * 14 + 2))landmarks_out = [{"x": float(l.x), "y": float(l.y), "z": float(l.z)} for l in lm]12 unmodified lines})except Exception as e:return json.dumps({"error": str(e)})iface = gr.Interface(3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152531 unmodified line55565758596061626364655 unmodified lines717273747576777879804 unmodified lines85868788899091929394959697986 unmodified lines10510610710810911011112 unmodified lines1241251261271281291301313 unmodified linesimport mathimport jsonfrom PIL import Imagefrom mediapipe.tasks import python as mp_pythonfrom mediapipe.tasks.python import vision as mp_visionimport urllib.requestimport os# ββ Download model if not cached ββMODEL_PATH = "/tmp/face_landmarker.task"MODEL_URL = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task"if not os.path.exists(MODEL_PATH):print("Downloading face landmarker model...")urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)print("Model downloaded.")# ββ Build FaceLandmarker ββbase_options = mp_python.BaseOptions(model_asset_path=MODEL_PATH,delegate=mp_python.BaseOptions.Delegate.CPU)options = mp_vision.FaceLandmarkerOptions(base_options=base_options,output_face_blendshapes=False,output_facial_transformation_matrixes=False,num_faces=1,min_face_detection_confidence=0.4,min_face_presence_confidence=0.4)landmarker = mp_vision.FaceLandmarker.create_from_options(options)print("FaceLandmarker ready.")def analyse_face(image):try:# Convert PIL to MediaPipe Imageimg_rgb = np.array(image.convert("RGB"))h, w = img_rgb.shape[:2]mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img_rgb)result = landmarker.detect(mp_image)if not result.face_landmarks or len(result.face_landmarks) == 0:return json.dumps({"error": "No face detected. Please upload a clear, front-facing photo."})lm = result.face_landmarks[0] # list of NormalizedLandmarkdef dist(a, b):return math.sqrt(1 unmodified line((lm[a].y - lm[b].y) * h) ** 2)face_ref = dist(33, 263)if face_ref == 0:return json.dumps({"error": "Could not measure face. Please try a different photo."})# ββ Age estimation ββface_height = dist(10, 152)lower_face_h = dist(168, 152)lower_ratio = lower_face_h / face_height if face_height > 0 else 0.525 unmodified linesnasolabial = ((dist(50, 61) + dist(280, 291)) / 2) / face_refforehead_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 = math.sqrt(abs(z_var)) * 100age_raw = (20+ (lower_ratio - 0.52) * 1204 unmodified linesage_mid = max(18, min(72, round(age_raw)))age_range = f"{max(18, age_mid - 4)}\u2013{age_mid + 4}"# ββ Wrinkle score ββwrinkle = round(max(1.0, min(9.9, 1 + texture * 18 + (age_mid - 18) * 0.10)), 1)# ββ Elasticity score ββcheek_sag = ((dist(116, 61) + dist(345, 291)) / 2) / face_refelasticity = round(max(1.0, min(9.9, 10 - (cheek_sag - 0.55) * 18 - (age_mid - 18) * 0.10)), 1)# ββ Jawline score ββjaw_pts = [234,93,132,58,172,136,150,149,176,148,152,377,400,378,379,365,397,288,361,323,454]jaw_dev = 0.0for i in range(1, len(jaw_pts) - 1):6 unmodified linesjaw_dev /= len(jaw_pts)jawline = round(max(1.0, min(9.9, 10 - jaw_dev * 0.8 - (age_mid - 18) * 0.09)), 1)age_factor = round(max(0.0, min(1.0, (age_mid - 18) / 54)), 3)years_younger = max(3, round(age_factor * 14 + 2))landmarks_out = [{"x": float(l.x), "y": float(l.y), "z": float(l.z)} for l in lm]12 unmodified lines})except Exception as e:import tracebackreturn json.dumps({"error": str(e), "trace": traceback.format_exc()})iface = gr.Interface(
app.py+48-25