MFAF-Net / index.html
haresh2792005's picture
Deploy MFAF-Net interactive web simulator
4542310 verified
Raw History Blame Contribute Delete
33.8 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MFAF-Net | Cosmetic Surgery Facial Simulator</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0f1d;
--card: #111827;
--input: #1e293b;
--border: #1f2937;
--primary: #2563eb;
--primary-hover: #1d4ed8;
--cyan: #06b6d4;
--green: #10b981;
--amber: #f59e0b;
--rose: #f43f5e;
--text: #f8fafc;
--muted: #94a3b8;
--dim: #64748b;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Inter', system-ui, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
line-height: 1.5;
background-image:
radial-gradient(circle at 15% 15%, rgba(37, 99, 235, 0.1) 0%, transparent 45%),
radial-gradient(circle at 85% 85%, rgba(6, 182, 212, 0.08) 0%, transparent 45%);
}
.header {
background: rgba(17, 24, 39, 0.88);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0.9rem 1.5rem;
position: sticky;
top: 0;
z-index: 50;
}
.header-inner {
max-width: 1380px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 0.75rem;
}
.brand { display: flex; align-items: center; gap: 0.75rem; }
.brand-icon {
width: 38px; height: 38px;
border-radius: 10px;
background: linear-gradient(135deg, var(--primary), var(--cyan));
display: flex; align-items: center; justify-content: center;
font-size: 1.15rem;
}
.brand h1 { font-size: 1.2rem; font-weight: 800; letter-spacing: -0.02em; }
.brand h1 span { color: var(--cyan); }
.brand p { font-size: 0.74rem; color: var(--muted); }
.badge-warn {
font-size: 0.74rem;
padding: 0.35rem 0.75rem;
border-radius: 999px;
background: rgba(245, 158, 11, 0.12);
border: 1px solid rgba(245, 158, 11, 0.3);
color: #fcd34d;
}
.container {
max-width: 1380px;
margin: 1.5rem auto;
padding: 0 1.25rem 3rem;
display: grid;
grid-template-columns: 420px 1fr;
gap: 1.5rem;
align-items: start;
}
@media (max-width: 1024px) {
.container { grid-template-columns: 1fr; }
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 1.35rem;
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.3);
}
.card-title {
font-size: 0.95rem;
font-weight: 700;
margin-bottom: 1rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.form-group { margin-bottom: 1rem; }
.form-label {
display: block;
font-size: 0.74rem;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 0.35rem;
}
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }
.form-control {
width: 100%;
background: var(--input);
border: 1px solid #334155;
border-radius: 8px;
padding: 0.6rem 0.75rem;
color: var(--text);
font-size: 0.88rem;
font-family: inherit;
}
.form-control:focus { outline: none; border-color: var(--primary); }
.upload-zone {
border: 2px dashed #334155;
border-radius: 12px;
padding: 1.4rem 1rem;
text-align: center;
cursor: pointer;
background: rgba(15, 23, 42, 0.45);
transition: border-color 0.2s, background 0.2s;
}
.upload-zone:hover, .upload-zone.dragover {
border-color: var(--cyan);
background: rgba(6, 182, 212, 0.06);
}
.preview-img {
max-width: 100%;
max-height: 210px;
border-radius: 8px;
display: none;
margin: 0.5rem auto 0;
object-fit: contain;
}
.proc-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.55rem;
}
.proc-card {
background: var(--input);
border: 1px solid #334155;
border-radius: 8px;
padding: 0.65rem;
cursor: pointer;
transition: all 0.18s;
}
.proc-card:hover { border-color: #60a5fa; }
.proc-card.active {
border-color: var(--primary);
background: rgba(37, 99, 235, 0.16);
box-shadow: 0 0 0 1px var(--primary);
}
.proc-name { font-size: 0.83rem; font-weight: 700; display: block; }
.proc-desc { font-size: 0.7rem; color: var(--muted); display: block; margin-top: 0.15rem; }
.btn-run {
width: 100%;
margin-top: 0.5rem;
padding: 0.9rem 1.25rem;
border: none;
border-radius: 10px;
background: linear-gradient(135deg, var(--primary), #1d4ed8);
color: #fff;
font-size: 0.95rem;
font-weight: 700;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 0.6rem;
box-shadow: 0 4px 18px rgba(37, 99, 235, 0.4);
transition: transform 0.15s, opacity 0.15s;
}
.btn-run:hover:not(:disabled) { transform: translateY(-1px); }
.btn-run:disabled { opacity: 0.6; cursor: not-allowed; }
.spinner {
width: 18px; height: 18px;
border: 2px solid rgba(255,255,255,0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.75s linear infinite;
display: none;
}
@keyframes spin { to { transform: rotate(360deg); } }
.steps-bar {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 0.5rem;
margin-bottom: 1.25rem;
}
.step-pill {
background: var(--input);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.55rem 0.4rem;
text-align: center;
font-size: 0.72rem;
color: var(--muted);
}
.step-pill.active { border-color: var(--cyan); color: #fff; background: rgba(6,182,212,0.12); }
.step-pill.done { border-color: var(--green); color: #a7f3d0; background: rgba(16,185,129,0.1); }
.step-pill strong { display: block; font-size: 0.65rem; font-family: 'JetBrains Mono', monospace; }
.images-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.9rem;
margin-bottom: 1.25rem;
}
@media (max-width: 820px) { .images-grid { grid-template-columns: 1fr; } }
.img-box {
background: var(--input);
border: 1px solid var(--border);
border-radius: 10px;
padding: 0.65rem;
}
.img-box-head {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.74rem;
font-weight: 700;
color: var(--muted);
text-transform: uppercase;
margin-bottom: 0.45rem;
}
.dl-btn {
background: rgba(37,99,235,0.15);
border: 1px solid rgba(37,99,235,0.35);
color: #93c5fd;
border-radius: 6px;
padding: 0.2rem 0.55rem;
font-size: 0.7rem;
cursor: pointer;
text-decoration: none;
}
.canvas-wrap {
background: #020617;
border-radius: 8px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
min-height: 210px;
}
.canvas-wrap img, .canvas-wrap canvas {
max-width: 100%;
max-height: 310px;
object-fit: contain;
display: block;
}
.metrics-row {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 0.75rem;
margin-bottom: 1.25rem;
}
@media (max-width: 700px) { .metrics-row { grid-template-columns: 1fr 1fr; } }
.metric-card {
background: var(--input);
border: 1px solid var(--border);
border-top: 3px solid var(--cyan);
border-radius: 10px;
padding: 0.85rem;
text-align: center;
}
.metric-card.green { border-top-color: var(--green); }
.metric-card.amber { border-top-color: var(--amber); }
.metric-card.rose { border-top-color: var(--rose); }
.metric-label { font-size: 0.7rem; color: var(--muted); text-transform: uppercase; font-weight: 600; }
.metric-val { font-size: 1.35rem; font-weight: 800; font-family: 'JetBrains Mono', monospace; margin-top: 0.2rem; }
.bottom-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
@media (max-width: 820px) { .bottom-grid { grid-template-columns: 1fr; } }
.measure-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.5rem;
}
.measure-item {
background: var(--input);
border-radius: 8px;
padding: 0.55rem 0.75rem;
}
.measure-item span { display: block; font-size: 0.68rem; color: var(--dim); text-transform: uppercase; }
.measure-item strong { font-size: 0.92rem; font-family: 'JetBrains Mono', monospace; color: var(--cyan); }
.empty-state {
text-align: center;
padding: 4.5rem 1.5rem;
color: var(--muted);
}
.status-chip {
font-size: 0.72rem;
padding: 0.25rem 0.65rem;
border-radius: 999px;
background: rgba(16, 185, 129, 0.14);
border: 1px solid rgba(16, 185, 129, 0.35);
color: #6ee7b7;
}
</style>
</head>
<body>
<header class="header">
<div class="header-inner">
<div class="brand">
<div class="brand-icon">✨</div>
<div>
<h1>MFAF<span>-Net</span></h1>
<p>Multimodal Facial Analysis &amp; Cosmetic Surgery Simulator</p>
</div>
</div>
<div class="badge-warn">Educational Visual Simulation Only — Not a Medical Device</div>
</div>
</header>
<main class="container">
<!-- Left Controls -->
<section class="card">
<div class="card-title">
<span>Patient &amp; Procedure Setup</span>
<span class="status-chip" id="engineStatus">Loading AI Mesh...</span>
</div>
<div class="form-group">
<label class="form-label">1. Upload Facial Photo</label>
<div class="upload-zone" id="dropZone">
<input type="file" id="fileInput" accept="image/*" hidden />
<div id="uploadHint">
<div style="font-size:1.75rem;">📷</div>
<div style="font-weight:600;font-size:0.88rem;">Click or Drag &amp; Drop a Frontal Face Photo</div>
<div style="font-size:0.74rem;color:var(--dim);">JPG, PNG, or WEBP</div>
</div>
<img id="previewImg" class="preview-img" alt="Uploaded preview" />
</div>
</div>
<div class="form-group form-row">
<div>
<label class="form-label" for="ageInput">2. Age</label>
<input type="number" id="ageInput" class="form-control" value="30" min="18" max="90" />
</div>
<div>
<label class="form-label" for="sexInput">Sex</label>
<select id="sexInput" class="form-control">
<option value="female">Female</option>
<option value="male">Male</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="form-group">
<label class="form-label" for="skinInput">3. Fitzpatrick Skin Type</label>
<select id="skinInput" class="form-control">
<option value="1">Type I — Very Fair</option>
<option value="2">Type II — Fair</option>
<option value="3" selected>Type III — Medium</option>
<option value="4">Type IV — Olive</option>
<option value="5">Type V — Brown</option>
<option value="6">Type VI — Dark</option>
</select>
</div>
<div class="form-group">
<label style="display:flex;align-items:center;gap:0.55rem;font-size:0.84rem;color:var(--muted);background:var(--input);padding:0.6rem 0.8rem;border-radius:8px;cursor:pointer;">
<input type="checkbox" id="historyInput" />
Previous facial cosmetic procedures
</label>
</div>
<div class="form-group">
<label class="form-label">4. Select Cosmetic Procedure</label>
<div class="proc-grid" id="procGrid">
<div class="proc-card active" data-proc="rhinoplasty">
<span class="proc-name">👃 Rhinoplasty</span>
<span class="proc-desc">Bridge slimming &amp; tip refinement</span>
</div>
<div class="proc-card" data-proc="blepharoplasty">
<span class="proc-name">👁️ Blepharoplasty</span>
<span class="proc-desc">Upper lid lift &amp; under-eye tightening</span>
</div>
<div class="proc-card" data-proc="rhytidectomy">
<span class="proc-name">✨ Rhytidectomy</span>
<span class="proc-desc">Jawline lift &amp; cheek contour</span>
</div>
<div class="proc-card" data-proc="genioplasty">
<span class="proc-name">📐 Genioplasty</span>
<span class="proc-desc">Chin projection &amp; V-line shaping</span>
</div>
<div class="proc-card" data-proc="forehead_surgery">
<span class="proc-name">🛡️ Forehead Surgery</span>
<span class="proc-desc">Forehead smoothing &amp; elevation</span>
</div>
<div class="proc-card" data-proc="brow_lift">
<span class="proc-name">↗️ Brow Lift</span>
<span class="proc-desc">Eyebrow arch elevation</span>
</div>
</div>
</div>
<button class="btn-run" id="runBtn" type="button">
<span class="spinner" id="btnSpinner"></span>
<span id="btnLabel">Run MFAF-Net Simulation</span>
</button>
</section>
<!-- Right Results Dashboard -->
<section>
<div class="steps-bar">
<div class="step-pill" id="s1"><strong>STEP 1</strong>468 Landmarks</div>
<div class="step-pill" id="s2"><strong>STEP 2</strong>Patient Encoding</div>
<div class="step-pill" id="s3"><strong>STEP 3</strong>Feature Fusion</div>
<div class="step-pill" id="s4"><strong>STEP 4</strong>Facial Simulation</div>
<div class="step-pill" id="s5"><strong>STEP 5</strong>Diff &amp; Metrics</div>
</div>
<div class="card empty-state" id="emptyState">
<div style="font-size:2.5rem;margin-bottom:0.5rem;">🧬</div>
<h2 style="font-size:1.1rem;color:var(--text);margin-bottom:0.4rem;">Ready for Facial Simulation</h2>
<p style="font-size:0.86rem;max-width:460px;margin:0 auto;">
Upload a clear frontal face photo, choose patient details and a procedure on the left, then click <strong>Run MFAF-Net Simulation</strong>.
</p>
</div>
<div id="resultsPanel" style="display:none;">
<div class="card" style="margin-bottom:1rem;">
<div class="card-title">
<span>Simulation Results</span>
<span class="status-chip" id="activeProcBadge">Rhinoplasty</span>
</div>
<div class="images-grid">
<div class="img-box">
<div class="img-box-head">
<span>Original</span>
<a class="dl-btn" id="dlOrig" download="original.png">Save</a>
</div>
<div class="canvas-wrap"><canvas id="cvOrig"></canvas></div>
</div>
<div class="img-box">
<div class="img-box-head">
<span style="color:#60a5fa;">Simulated</span>
<a class="dl-btn" id="dlSim" download="simulated.png">Save</a>
</div>
<div class="canvas-wrap"><canvas id="cvSim"></canvas></div>
</div>
<div class="img-box">
<div class="img-box-head">
<span style="color:#fb7185;">Difference Map</span>
<a class="dl-btn" id="dlDiff" download="difference_map.png">Save</a>
</div>
<div class="canvas-wrap"><canvas id="cvDiff"></canvas></div>
</div>
</div>
<div class="metrics-row">
<div class="metric-card rose">
<div class="metric-label">Changed Pixels</div>
<div class="metric-val" id="mChanged">—</div>
</div>
<div class="metric-card amber">
<div class="metric-label">MAE</div>
<div class="metric-val" id="mMae">—</div>
</div>
<div class="metric-card green">
<div class="metric-label">SSIM</div>
<div class="metric-val" id="mSsim">—</div>
</div>
<div class="metric-card">
<div class="metric-label">PSNR</div>
<div class="metric-val" id="mPsnr">—</div>
</div>
</div>
</div>
<div class="bottom-grid">
<div class="card">
<div class="card-title">
<span>468-Point Facial Landmarks</span>
<a class="dl-btn" id="dlMesh" download="landmarks.png">Save</a>
</div>
<div class="canvas-wrap"><canvas id="cvMesh"></canvas></div>
</div>
<div class="card">
<div class="card-title"><span>Facial Measurements (px)</span></div>
<div class="measure-list" id="measureList"></div>
</div>
</div>
</div>
</section>
</main>
<script type="module">
import { FaceLandmarker, FilesetResolver } from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14/vision_bundle.mjs";
let faceLandmarker = null;
let uploadedImage = null;
let selectedProc = "rhinoplasty";
const engineStatus = document.getElementById("engineStatus");
const dropZone = document.getElementById("dropZone");
const fileInput = document.getElementById("fileInput");
const previewImg = document.getElementById("previewImg");
const uploadHint = document.getElementById("uploadHint");
const runBtn = document.getElementById("runBtn");
async function initMediaPipe() {
try {
const resolver = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14/wasm"
);
faceLandmarker = await FaceLandmarker.createFromOptions(resolver, {
baseOptions: {
modelAssetPath: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",
delegate: "CPU"
},
runningMode: "IMAGE",
numFaces: 1
});
engineStatus.textContent = "AI FaceMesh Ready";
} catch (err) {
engineStatus.textContent = "Mesh Load Error";
engineStatus.style.color = "#fda4af";
console.error(err);
}
}
initMediaPipe();
// Upload handling
dropZone.addEventListener("click", () => fileInput.click());
dropZone.addEventListener("dragover", (e) => { e.preventDefault(); dropZone.classList.add("dragover"); });
dropZone.addEventListener("dragleave", () => dropZone.classList.remove("dragover"));
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
dropZone.classList.remove("dragover");
if (e.dataTransfer.files[0]) loadUploadedFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener("change", (e) => {
if (e.target.files[0]) loadUploadedFile(e.target.files[0]);
});
function loadUploadedFile(file) {
if (!file.type.startsWith("image/")) {
alert("Please upload a valid image file.");
return;
}
const reader = new FileReader();
reader.onload = (ev) => {
const img = new Image();
img.onload = () => {
uploadedImage = img;
previewImg.src = ev.target.result;
previewImg.style.display = "block";
uploadHint.style.display = "none";
};
img.src = ev.target.result;
};
reader.readAsDataURL(file);
}
// Procedure selection
document.getElementById("procGrid").addEventListener("click", (e) => {
const card = e.target.closest(".proc-card");
if (!card) return;
document.querySelectorAll(".proc-card").forEach(c => c.classList.remove("active"));
card.classList.add("active");
selectedProc = card.dataset.proc;
});
// Landmark definitions matching MFAF-Net
const GROUPS = {
nose_bridge_sides: [196, 3, 236, 198, 419, 248, 456, 420],
nose_alar: [129, 98, 49, 209, 358, 327, 279, 429],
nose_tip: [1, 2, 4, 5, 19, 94],
upper_eyelid: [159, 160, 158, 157, 161, 223, 224, 386, 385, 387, 388, 384, 443, 444],
lower_eyelid: [145, 144, 153, 154, 229, 230, 374, 373, 380, 381, 449, 450],
jawline: [172, 136, 150, 149, 176, 58, 132, 397, 365, 379, 378, 400, 288, 361],
cheeks: [205, 206, 50, 123, 425, 426, 280, 352],
chin_tip: [152, 175, 199, 200],
chin_sides: [148, 176, 377, 400],
forehead: [10, 109, 67, 103, 54, 338, 297, 332, 284, 151, 9, 8],
eyebrows: [70, 63, 105, 66, 107, 46, 53, 52, 65, 55, 300, 293, 334, 296, 336, 276, 283, 282, 295, 285]
};
const RULES = {
rhinoplasty: [["nose_bridge_sides", "x", 0.042, "inward"], ["nose_alar", "x", 0.055, "inward"], ["nose_tip", "y", 0.028, -1]],
blepharoplasty: [["upper_eyelid", "y", 0.022, -1], ["lower_eyelid", "y", 0.015, -1]],
rhytidectomy: [["jawline", "y", 0.030, -1], ["jawline", "x", 0.025, "inward"], ["cheeks", "y", 0.020, -1]],
genioplasty: [["chin_tip", "y", 0.036, 1], ["chin_sides", "x", 0.022, "inward"]],
forehead_surgery: [["forehead", "y", 0.026, -1], ["eyebrows", "y", 0.012, -1]],
brow_lift: [["eyebrows", "y", 0.032, -1]]
};
const ANCHORS = {
rhinoplasty: [133, 362, 33, 263, 0, 61, 291, 152],
blepharoplasty: [33, 133, 362, 263, 1, 61, 291, 105, 334],
rhytidectomy: [1, 33, 263, 61, 291, 13, 14, 152, 10],
genioplasty: [14, 17, 61, 291, 1, 172, 397],
forehead_surgery: [159, 386, 33, 263, 1, 152],
brow_lift: [159, 386, 33, 263, 1, 10, 152]
};
const SIGMA_RATIO = {
rhinoplasty: 0.080,
blepharoplasty: 0.055,
rhytidectomy: 0.115,
genioplasty: 0.095,
forehead_surgery: 0.120,
brow_lift: 0.075
};
const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
function jetColor(v) {
const x = v / 255.0;
const r = Math.max(0, Math.min(255, Math.round(255 * Math.min(4 * x - 1.5, -4 * x + 4.5))));
const g = Math.max(0, Math.min(255, Math.round(255 * Math.min(4 * x - 0.5, -4 * x + 3.5))));
const b = Math.max(0, Math.min(255, Math.round(255 * Math.min(4 * x + 0.5, -4 * x + 2.5))));
return [r, g, b];
}
function setStep(idx, state) {
const el = document.getElementById("s" + idx);
el.className = "step-pill " + state;
}
runBtn.addEventListener("click", async () => {
if (!uploadedImage) { alert("Please upload a facial photo first."); return; }
if (!faceLandmarker) { alert("AI face mesh model is still loading, please wait a moment."); return; }
runBtn.disabled = true;
document.getElementById("btnSpinner").style.display = "inline-block";
document.getElementById("btnLabel").textContent = "Running Simulation...";
try {
for (let i = 1; i <= 5; i++) setStep(i, "active");
// Scale working canvas to max 512px for crisp speed
const maxDim = 512;
const scale = Math.min(1, maxDim / Math.max(uploadedImage.naturalWidth, uploadedImage.naturalHeight));
const w = Math.round(uploadedImage.naturalWidth * scale);
const h = Math.round(uploadedImage.naturalHeight * scale);
const cvOrig = document.getElementById("cvOrig");
cvOrig.width = w; cvOrig.height = h;
const ctxOrig = cvOrig.getContext("2d", { willReadFrequently: true });
ctxOrig.drawImage(uploadedImage, 0, 0, w, h);
// Step 1: Extract 468 landmarks
const lmRes = faceLandmarker.detect(cvOrig);
if (!lmRes.faceLandmarks || lmRes.faceLandmarks.length === 0) {
throw new Error("No face detected. Please try a clearer frontal face photo.");
}
const pts = lmRes.faceLandmarks[0].slice(0, 468).map(p => [p.x * w, p.y * h]);
setStep(1, "done");
// Draw landmark mesh overlay
const cvMesh = document.getElementById("cvMesh");
cvMesh.width = w; cvMesh.height = h;
const ctxMesh = cvMesh.getContext("2d");
ctxMesh.drawImage(cvOrig, 0, 0);
ctxMesh.fillStyle = "rgba(148, 163, 184, 0.7)";
for (const [x, y] of pts) {
ctxMesh.beginPath(); ctxMesh.arc(x, y, 1.2, 0, Math.PI * 2); ctxMesh.fill();
}
ctxMesh.fillStyle = "#22d3ee";
for (const [grp, idxs] of Object.entries(GROUPS)) {
for (const id of idxs) {
if (pts[id]) {
ctxMesh.beginPath(); ctxMesh.arc(pts[id][0], pts[id][1], 2.1, 0, Math.PI * 2); ctxMesh.fill();
}
}
}
// Anthropometric measurements
const measurements = {
"Nose Width": dist(pts[129], pts[358]),
"Nose Length": dist(pts[6], pts[1]),
"Eye Width": (dist(pts[133], pts[33]) + dist(pts[362], pts[263])) / 2,
"Face Width": dist(pts[234], pts[454]),
"Jaw Width": dist(pts[172], pts[397]),
"Chin Projection": dist(pts[94], pts[152])
};
// Step 2 & 3: Patient encoding & scaling
const ageNorm = Math.min(1, Math.max(0, (parseFloat(document.getElementById("ageInput").value) || 30) / 100));
const txHist = document.getElementById("historyInput").checked ? 1.0 : 0.0;
const patientScale = Math.min(1.25, Math.max(0.78, 1.0 + 0.18 * (0.35 - ageNorm) - 0.12 * txHist));
setStep(2, "done");
setStep(3, "done");
// Step 4: Displace landmarks & run Gaussian RBF warp
const dstPts = pts.map(p => [p[0], p[1]]);
const centreX = pts[1][0];
const faceW = Math.max(dist(pts[234], pts[454]), 1);
const faceH = Math.max(dist(pts[10], pts[152]), 1);
for (const [grp, axis, factor, dir] of (RULES[selectedProc] || [])) {
const scaled = factor * patientScale;
for (const idx of (GROUPS[grp] || [])) {
if (idx >= dstPts.length) continue;
if (axis === "y") {
dstPts[idx][1] += scaled * faceH * dir;
} else {
const mag = scaled * faceW;
if (dir === "inward") {
dstPts[idx][0] -= (dstPts[idx][0] > centreX ? mag : -mag);
} else {
dstPts[idx][0] += mag * dir;
}
}
}
}
const active = [];
for (let i = 0; i < pts.length; i++) {
const dx = dstPts[i][0] - pts[i][0];
const dy = dstPts[i][1] - pts[i][1];
if (Math.hypot(dx, dy) > 0.25) active.push([pts[i][0], pts[i][1], dx, dy, i]);
}
const activeSet = new Set(active.map(a => a[4]));
const anchors = (ANCHORS[selectedProc] || [])
.filter(i => i < pts.length && !activeSet.has(i))
.map(i => pts[i]);
const sigma = Math.max((SIGMA_RATIO[selectedProc] || 0.08) * faceW, 8.0);
const inv2Sig2 = 1.0 / (2.0 * sigma * sigma);
const anchorSigma = Math.max(0.045 * faceW, 6.0);
const inv2ASig2 = 1.0 / (2.0 * anchorSigma * anchorSigma);
const srcData = ctxOrig.getImageData(0, 0, w, h);
const srcPx = srcData.data;
const simData = ctxOrig.createImageData(w, h);
const simPx = simData.data;
const diffData = ctxOrig.createImageData(w, h);
const diffPx = diffData.data;
let maeSum = 0, changedCount = 0, mseSum = 0;
let sumX = 0, sumY = 0, sumX2 = 0, sumY2 = 0, sumXY = 0;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
let dispX = 0, dispY = 0, wSum = 0;
for (let k = 0; k < active.length; k++) {
const [px, py, dx, dy] = active[k];
const d2 = (x - px) * (x - px) + (y - py) * (y - py);
if (d2 > sigma * sigma * 14) continue;
const wk = Math.exp(-d2 * inv2Sig2);
dispX += wk * dx;
dispY += wk * dy;
wSum += wk;
}
let r, g, b;
const outIdx = (y * w + x) * 4;
if (wSum > 1e-5) {
const norm = Math.max(wSum, 1.0);
dispX /= norm;
dispY /= norm;
let aMask = 1.0;
for (let a = 0; a < anchors.length; a++) {
const [ax, ay] = anchors[a];
const ad2 = (x - ax) * (x - ax) + (y - ay) * (y - ay);
aMask *= (1.0 - 0.92 * Math.exp(-ad2 * inv2ASig2));
}
const sx = Math.min(w - 1.001, Math.max(0, x - dispX * aMask));
const sy = Math.min(h - 1.001, Math.max(0, y - dispY * aMask));
const x0 = sx | 0, y0 = sy | 0;
const fx = sx - x0, fy = sy - y0;
const i00 = (y0 * w + x0) * 4;
const i10 = i00 + 4;
const i01 = i00 + w * 4;
const i11 = i01 + 4;
const w00 = (1 - fx) * (1 - fy);
const w10 = fx * (1 - fy);
const w01 = (1 - fx) * fy;
const w11 = fx * fy;
r = Math.round(srcPx[i00] * w00 + srcPx[i10] * w10 + srcPx[i01] * w01 + srcPx[i11] * w11);
g = Math.round(srcPx[i00 + 1] * w00 + srcPx[i10 + 1] * w10 + srcPx[i01 + 1] * w01 + srcPx[i11 + 1] * w11);
b = Math.round(srcPx[i00 + 2] * w00 + srcPx[i10 + 2] * w10 + srcPx[i01 + 2] * w01 + srcPx[i11 + 2] * w11);
} else {
r = srcPx[outIdx]; g = srcPx[outIdx + 1]; b = srcPx[outIdx + 2];
}
simPx[outIdx] = r; simPx[outIdx + 1] = g; simPx[outIdx + 2] = b; simPx[outIdx + 3] = 255;
const sr = srcPx[outIdx], sg = srcPx[outIdx + 1], sb = srcPx[outIdx + 2];
const dr = Math.abs(sr - r), dg = Math.abs(sg - g), db = Math.abs(sb - b);
maeSum += (dr + dg + db) / 3.0;
mseSum += (dr * dr + dg * dg + db * db) / 3.0;
if (dr > 15 || dg > 15 || db > 15) changedCount++;
const lumO = 0.299 * sr + 0.587 * sg + 0.114 * sb;
const lumS = 0.299 * r + 0.587 * g + 0.114 * b;
sumX += lumO; sumY += lumS;
sumX2 += lumO * lumO; sumY2 += lumS * lumS;
sumXY += lumO * lumS;
const dgGray = 0.299 * dr + 0.587 * dg + 0.114 * db;
const vis = dgGray >= 3 ? Math.min(255, dgGray * 3.5) : 0;
const [jr, jg, jb] = jetColor(vis);
diffPx[outIdx] = jr; diffPx[outIdx + 1] = jg; diffPx[outIdx + 2] = jb; diffPx[outIdx + 3] = 255;
}
}
setStep(4, "done");
const cvSim = document.getElementById("cvSim");
cvSim.width = w; cvSim.height = h;
cvSim.getContext("2d").putImageData(simData, 0, 0);
const cvDiff = document.getElementById("cvDiff");
cvDiff.width = w; cvDiff.height = h;
cvDiff.getContext("2d").putImageData(diffData, 0, 0);
// Step 5: Compute metrics
const N = w * h;
const mae = maeSum / N;
const mse = mseSum / N;
const psnr = mse > 0 ? 10 * Math.log10((255 * 255) / mse) : 99.0;
const changedPct = (changedCount / N) * 100.0;
const muX = sumX / N, muY = sumY / N;
const varX = Math.max(0, sumX2 / N - muX * muX);
const varY = Math.max(0, sumY2 / N - muY * muY);
const covXY = sumXY / N - muX * muY;
const c1 = (0.01 * 255) ** 2, c2 = (0.03 * 255) ** 2;
const ssim = ((2 * muX * muY + c1) * (2 * covXY + c2)) / ((muX * muX + muY * muY + c1) * (varX + varY + c2));
document.getElementById("mChanged").textContent = changedPct.toFixed(2) + "%";
document.getElementById("mMae").textContent = mae.toFixed(2);
document.getElementById("mSsim").textContent = ssim.toFixed(4);
document.getElementById("mPsnr").textContent = psnr.toFixed(1) + " dB";
const mList = document.getElementById("measureList");
mList.innerHTML = Object.entries(measurements).map(([k, v]) =>
`<div class="measure-item"><span>${k}</span><strong>${v.toFixed(1)} px</strong></div>`
).join("");
document.getElementById("dlOrig").href = cvOrig.toDataURL("image/png");
document.getElementById("dlSim").href = cvSim.toDataURL("image/png");
document.getElementById("dlDiff").href = cvDiff.toDataURL("image/png");
document.getElementById("dlMesh").href = cvMesh.toDataURL("image/png");
document.getElementById("activeProcBadge").textContent = selectedProc.replace("_", " ").toUpperCase();
document.getElementById("emptyState").style.display = "none";
document.getElementById("resultsPanel").style.display = "block";
setStep(5, "done");
} catch (err) {
alert(err.message);
for (let i = 1; i <= 5; i++) setStep(i, "");
} finally {
runBtn.disabled = false;
document.getElementById("btnSpinner").style.display = "none";
document.getElementById("btnLabel").textContent = "Run MFAF-Net Simulation";
}
});
</script>
</body>
</html>