Download index.html from Abddeus/ABO: direct link, hf CLI and curl.
- Browser
- Download file 123 kB
-
https://huggingface.co/spaces/Abddeus/ABO/resolve/main/index.html
- Command line
-
hf download hf://spaces/Abddeus/ABO/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Abddeus/ABO/resolve/main/index.html
123 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OrthoCeph Pro | Dual AI ABO, McNamara, Tweed & CVM Suite</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/ort.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
<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&display=swap" rel="stylesheet">
<style>
:root {
--bg-dark: #090d16;
--surface-dark: #111827;
--surface-card: #1e293b;
--surface-border: #334155;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--status-green: #10b981;
--status-red: #f43f5e;
--status-amber: #f59e0b;
--ruler-cyan: #06b6d4;
--teal-accent: #14b8a6;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--bg-dark);
color: var(--text-main);
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
-webkit-font-smoothing: antialiased;
}
/* Header Bar */
header {
background: var(--surface-dark);
border-bottom: 1px solid var(--surface-border);
height: 56px;
padding: 0 16px;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
z-index: 20;
}
.brand { display: flex; align-items: center; gap: 10px; }
.brand-icon {
width: 32px; height: 32px;
background: linear-gradient(135deg, #3b82f6, #1d4ed8);
border-radius: 8px; display: flex; align-items: center;
justify-content: center; font-weight: 800; font-size: 16px; color: white;
}
.brand-title { font-size: 14.5px; font-weight: 700; letter-spacing: -0.02em; }
.brand-subtitle { font-size: 9.5px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; }
.header-actions { display: flex; align-items: center; gap: 6px; }
#status-badge {
display: flex; align-items: center; gap: 6px; font-size: 11px;
font-weight: 600; background: rgba(30, 41, 59, 0.9);
border: 1px solid var(--surface-border); padding: 5px 10px;
border-radius: 20px; color: var(--text-muted);
}
#status-badge .indicator { width: 8px; height: 8px; border-radius: 50%; background-color: var(--status-amber); }
.btn {
background: var(--accent); color: white; border: none; padding: 6px 10px;
border-radius: 6px; font-weight: 600; font-size: 11px; cursor: pointer;
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
transition: all 0.15s ease; white-space: nowrap;
}
.btn svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2.2; }
.btn:hover:not(:disabled) { background: var(--accent-hover); }
.btn:disabled { background: #1e293b; color: #64748b; cursor: not-allowed; }
.btn-secondary { background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main); }
.btn-secondary:hover { background: #334155; }
.btn-danger { background: rgba(244, 63, 94, 0.15); border: 1px solid rgba(244, 63, 94, 0.4); color: #fda4af; }
.btn-danger:hover { background: rgba(244, 63, 94, 0.25); }
.btn-teal { background: rgba(20, 184, 166, 0.15); border: 1px solid rgba(20, 184, 166, 0.45); color: #5eead4; }
.btn-teal:hover { background: rgba(20, 184, 166, 0.28); }
/* Workspace */
.workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }
.sidebar {
width: 325px; background: var(--surface-dark);
border-right: 1px solid var(--surface-border);
padding: 12px; display: flex; flex-direction: column;
gap: 10px; overflow-y: auto; flex-shrink: 0;
}
.section-header {
font-size: 10px; font-weight: 700; text-transform: uppercase;
letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 4px;
display: flex; justify-content: space-between; align-items: center;
}
.card {
background: var(--surface-card); border: 1px solid var(--surface-border);
border-radius: 8px; padding: 9px; display: flex; flex-direction: column; gap: 6px;
}
.form-group { display: flex; flex-direction: column; gap: 2px; }
.form-group label { font-size: 9.5px; font-weight: 600; color: var(--text-muted); }
.input-field {
background: #0f172a; border: 1px solid var(--surface-border);
border-radius: 5px; padding: 5px 8px; color: var(--text-main);
font-size: 11.5px; outline: none; width: 100%;
}
.input-field:focus { border-color: #3b82f6; }
.mode-group { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
.mode-btn {
background: #0f172a; border: 1px solid var(--surface-border);
color: var(--text-muted); padding: 5px 3px; border-radius: 5px;
font-size: 10px; font-weight: 600; cursor: pointer; text-align: center;
transition: all 0.15s;
}
.mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; }
.toggle-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px; }
.toggle-pill {
background: #0f172a; border: 1px solid var(--surface-border);
color: var(--text-muted); padding: 4px; border-radius: 5px;
font-size: 10px; font-weight: 600; cursor: pointer; text-align: center;
}
.toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }
.cvm-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; }
.cvm-btn {
background: #0f172a; border: 1px solid var(--surface-border);
color: var(--text-muted); padding: 5px 2px; border-radius: 4px;
font-size: 10px; font-weight: 700; cursor: pointer; text-align: center;
}
.cvm-btn.active { background: var(--teal-accent); color: #042f2e; border-color: #5eead4; }
.slider-row {
display: flex; align-items: center; justify-content: space-between;
font-size: 10.5px; color: var(--text-muted);
}
.slider-row input[type="range"] { width: 130px; accent-color: var(--accent); cursor: pointer; }
#norms-drawer {
display: none; flex-direction: column; gap: 5px; max-height: 170px;
overflow-y: auto; padding-top: 5px; border-top: 1px solid var(--surface-border);
}
.norm-edit-row {
display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 4px; align-items: center; font-size: 10.5px;
}
.norm-edit-row input {
background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main);
padding: 3px 4px; border-radius: 4px; font-size: 10.5px; width: 100%; text-align: center;
}
/* Viewport */
.viewport {
flex: 1; background: #05070c; position: relative;
overflow: hidden; display: flex; align-items: center; justify-content: center;
}
.viewport.drag-over {
outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
}
#empty-dropzone {
display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 10px; color: var(--text-muted); text-align: center; padding: 35px;
border: 2px dashed var(--surface-border); border-radius: 14px; cursor: pointer;
}
#empty-dropzone:hover { border-color: #3b82f6; color: var(--text-main); }
#viewport-container { position: relative; transform-origin: 0 0; user-select: none; cursor: crosshair; display: none; }
#ceph-image { display: block; max-height: 85vh; max-width: 100%; pointer-events: none; border-radius: 4px; }
#overlay-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; }
#loupe-box {
position: absolute; top: 14px; left: 14px; width: 140px; height: 140px;
border: 2px solid #38bdf8; border-radius: 50%; overflow: hidden;
background: #000; box-shadow: 0 8px 24px rgba(0,0,0,0.7);
display: none; z-index: 25; pointer-events: none;
}
#loupe-canvas { width: 100%; height: 100%; display: block; }
#loupe-label {
position: absolute; bottom: 6px; left: 50%; transform: translateX(-50%);
background: rgba(15, 23, 42, 0.88); color: #38bdf8; font-size: 9.5px;
font-weight: 700; padding: 2px 7px; border-radius: 8px;
}
.viewport-overlay-controls {
position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%);
background: rgba(17, 24, 39, 0.92); backdrop-filter: blur(8px);
border: 1px solid var(--surface-border); border-radius: 25px;
padding: 4px 12px; display: flex; align-items: center; gap: 7px; z-index: 10;
white-space: nowrap;
}
.viewport-overlay-controls button {
background: none; border: none; color: var(--text-main);
cursor: pointer; font-size: 11px; font-weight: 600; padding: 2px 5px;
}
.viewport-overlay-controls button:hover { color: #60a5fa; }
.shortcut-hint { font-size: 9.5px; color: var(--text-muted); }
.landmark-handle { pointer-events: all; cursor: grab; transition: r 0.1s ease; }
.landmark-handle:hover { r: 7.5 !important; stroke: #ffffff !important; stroke-width: 2.5px !important; }
.landmark-handle.dragging { cursor: grabbing !important; r: 9 !important; fill: #38bdf8 !important; }
.landmark-text {
font-family: 'Inter', sans-serif; font-size: 10px; font-weight: 700;
fill: #ffffff; paint-order: stroke; stroke: #000000; stroke-width: 3px;
pointer-events: none; user-select: none;
}
/* Right Analysis Panel */
.analysis-panel {
width: 535px; background: var(--surface-dark);
border-left: 1px solid var(--surface-border);
padding: 12px 16px; display: flex; flex-direction: column;
gap: 10px; overflow-y: auto; flex-shrink: 0;
}
.diagnosis-banner {
background: linear-gradient(135deg, rgba(37, 99, 235, 0.14), rgba(15, 23, 42, 0.92));
border: 1px solid #3b82f6; border-radius: 8px; padding: 10px 12px;
display: flex; flex-direction: column; gap: 5px;
}
.diagnosis-headline { font-size: 12px; font-weight: 800; color: #93c5fd; }
.diagnosis-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 10px; font-size: 10.5px; }
.diag-item { display: flex; flex-direction: column; }
.diag-label { font-size: 9px; color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
.diag-val { font-weight: 600; color: var(--text-main); }
.analysis-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 11px; }
.analysis-table th {
text-align: left; padding: 5px 6px; font-weight: 600; font-size: 9px;
text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);
border-bottom: 1px solid var(--surface-border);
}
.analysis-table td { padding: 5px 6px; border-bottom: 1px solid rgba(51, 65, 85, 0.35); }
.metric-name { font-weight: 600; color: #e2e8f0; }
.metric-norm { color: var(--text-muted); font-size: 10px; }
.metric-val { font-weight: 700; font-feature-settings: "tnum"; }
.metric-diff { font-weight: 600; font-size: 10px; font-feature-settings: "tnum"; }
.pill { display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 8px; font-size: 9px; font-weight: 600; }
.pill-normal { background: rgba(16, 185, 129, 0.15); color: var(--status-green); }
.pill-deviated { background: rgba(244, 63, 94, 0.15); color: var(--status-red); }
.pill-neutral { background: #1e293b; color: var(--text-muted); }
/* Security Modal Lock Screen */
#security-gate {
position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(5, 7, 12, 0.96); backdrop-filter: blur(14px);
z-index: 999999; display: none; align-items: center; justify-content: center;
}
.security-card {
background: var(--surface-card); border: 1px solid var(--surface-border);
border-radius: 12px; padding: 24px; width: 340px; display: flex;
flex-direction: column; gap: 14px; box-shadow: 0 20px 40px rgba(0,0,0,0.8);
text-align: center;
}
/* Mobile Bottom Tab Bar */
.mobile-nav-bar {
display: none; height: 50px; background: var(--surface-dark);
border-top: 1px solid var(--surface-border); position: fixed;
bottom: 0; left: 0; right: 0; z-index: 40; grid-template-columns: repeat(3, 1fr);
}
.mobile-tab-btn {
background: none; border: none; color: var(--text-muted); display: flex;
flex-direction: column; align-items: center; justify-content: center; gap: 2px;
font-size: 9.5px; font-weight: 600; cursor: pointer; padding: 4px;
}
.mobile-tab-btn svg { width: 17px; height: 17px; fill: currentColor; }
.mobile-tab-btn.active { color: #38bdf8; background: rgba(56, 189, 248, 0.08); }
@media screen and (max-width: 1023px) {
body { height: 100dvh; }
header { padding: 0 10px; height: 50px; }
.brand-subtitle { display: none; }
.header-actions { gap: 4px; }
.header-actions .btn { padding: 5px 7px; }
.header-actions .btn .btn-text { display: none; }
#status-badge { padding: 3px 6px; font-size: 9.5px; }
#status-txt { display: none; }
.workspace { height: calc(100dvh - 50px - 50px); flex-direction: column; position: relative; }
.mobile-nav-bar { display: grid; }
.sidebar, .viewport, .analysis-panel { width: 100% !important; height: 100% !important; border: none !important; flex: 1; }
body.tab-tools .sidebar { display: flex !important; }
body.tab-tools .viewport, body.tab-tools .analysis-panel { display: none !important; }
body.tab-viewport .sidebar, body.tab-viewport .analysis-panel { display: none !important; }
body.tab-viewport .viewport { display: flex !important; }
body.tab-analysis .sidebar, body.tab-analysis .viewport { display: none !important; }
body.tab-analysis .analysis-panel { display: flex !important; }
#overlay-svg { touch-action: none; }
}
#toast-msg {
position: fixed; bottom: 20px; right: 20px; background: #1e293b;
border: 1px solid #3b82f6; color: #93c5fd; font-size: 11px; font-weight: 600;
padding: 8px 14px; border-radius: 8px; z-index: 999999;
box-shadow: 0 10px 25px rgba(0,0,0,0.5); display: none; align-items: center; gap: 8px;
}
/* Print-Only Report Container: STRICT 1-PAGE US LETTER */
#print-report-container { display: none; }
@media print {
@page {
size: letter portrait;
margin: 5mm 7mm 5mm 7mm;
}
*, *::before, *::after { box-sizing: border-box !important; }
html, body {
background: #ffffff !important; color: #000000 !important;
height: auto !important; width: 100% !important; overflow: visible !important;
font-size: 8.5px !important; margin: 0 !important; padding: 0 !important;
}
header, .workspace, .sidebar, .viewport, .analysis-panel,
.mobile-nav-bar, .viewport-overlay-controls, #loupe-box,
#empty-dropzone, #security-gate, #toast-msg {
display: none !important; visibility: hidden !important;
height: 0 !important; width: 0 !important; position: absolute !important;
}
#print-report-container {
display: flex !important; flex-direction: column; justify-content: space-between;
width: 100% !important; height: 98vh !important; max-height: 98vh !important;
page-break-inside: avoid !important; break-inside: avoid !important;
}
.print-header-bar {
border-bottom: 2px solid #0f172a; padding-bottom: 3px;
display: flex; justify-content: space-between; align-items: flex-end;
}
.print-title { font-size: 13px; font-weight: 800; color: #0f172a; letter-spacing: -0.01em; }
.print-demographics { display: flex; gap: 10px; font-size: 9px; font-weight: 600; color: #334155; }
.print-grid {
display: grid !important; grid-template-columns: 280px 1fr !important;
gap: 10px; align-items: start; flex: 1; margin-top: 3px;
}
.print-left-col { display: flex; flex-direction: column; gap: 4px; }
.print-ceph-box {
position: relative; width: 280px; height: 300px; border: 1.5px solid #94a3b8;
border-radius: 4px; overflow: hidden; background: #000000;
display: flex; align-items: center; justify-content: center;
}
.print-ceph-box img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
.print-ceph-box svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
.print-diag-card {
border: 1px solid #cbd5e1; border-radius: 4px; padding: 5px 7px;
background: #f8fafc; font-size: 8.5px; display: flex; flex-direction: column; gap: 2px;
}
.print-right-col { display: flex; flex-direction: column; gap: 4px; }
.print-table { width: 100%; border-collapse: collapse; font-size: 8.5px; }
.print-table th {
border-bottom: 1.5px solid #0f172a; padding: 2px 4px; text-align: left;
font-size: 8px; color: #0f172a; font-weight: 700; text-transform: uppercase;
}
.print-table td { border-bottom: 1px solid #e2e8f0; padding: 2px 4px; color: #0f172a; }
.print-table td.diff-dev { color: #dc2626; font-weight: 700; }
.print-table td.diff-norm { color: #15803d; font-weight: 600; }
.print-footer-bar {
border-top: 1px solid #cbd5e1; padding-top: 3px; display: flex;
justify-content: space-between; align-items: flex-end; gap: 12px; margin-top: 3px;
}
.print-disclaimer { font-size: 7.5px; color: #64748b; line-height: 1.25; max-width: 65%; }
.print-signature-wrap { display: flex; flex-direction: column; align-items: center; width: 190px; }
.print-sign-line {
border-top: 1px solid #0f172a; width: 100%; text-align: center;
font-size: 8px; font-weight: 600; color: #334155; padding-top: 2px;
}
}
</style>
</head>
<body>
<!-- Security Gate -->
<div id="security-gate">
<div class="security-card">
<div style="font-size: 32px;">🔒</div>
<div style="font-size: 15px; font-weight: 800; color: #f8fafc;" id="gate-title">Clinical Suite Locked</div>
<div style="font-size: 11px; color: #94a3b8;" id="gate-desc">Enter clinic master passcode to access cephalometric analysis.</div>
<input type="password" id="gate-pass" class="input-field" placeholder="Master passcode..." style="text-align: center; font-size: 14px; padding: 8px;">
<button class="btn" id="btn-unlock-gate" style="padding: 8px; font-size: 12px;">Unlock Suite</button>
<div id="gate-err" style="color: #f43f5e; font-size: 11px; display: none;">Invalid master password.</div>
</div>
</div>
<!-- Header -->
<header>
<div class="brand">
<div class="brand-icon">O</div>
<div>
<div class="brand-title">OrthoCeph Pro</div>
<div class="brand-subtitle">ABO, McNamara, Tweed & Dual AI CVM Suite</div>
</div>
</div>
<div class="header-actions">
<div id="status-badge">
<div class="indicator" id="status-ind"></div>
<span id="status-txt">Loading AI Engine...</span>
</div>
<button class="btn btn-secondary" id="btn-privacy-toggle" title="Toggle HIPAA De-Identification / Presentation Mode">
<svg viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
<span class="btn-text" id="privacy-btn-txt">HIPAA Mask: OFF</span>
</button>
<button class="btn btn-secondary" id="btn-export-svg" title="Export Transparent Vector Overlay (SVG) for Presentations">
<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
<span class="btn-text">Vector SVG</span>
</button>
<button class="btn btn-secondary" id="btn-save-json" title="Save tracing & patient data as .json">
<svg viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
<span class="btn-text">Save JSON</span>
</button>
<button class="btn btn-secondary" onclick="document.getElementById('json-input').click()" title="Load saved .json tracing">
<svg viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
<span class="btn-text">Load JSON</span>
</button>
<input type="file" id="json-input" accept=".json,application/json" style="display:none;">
<button class="btn btn-secondary" id="btn-copy-note" title="Copy clinical summary & diagnosis for chart">
<svg viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<span class="btn-text">Copy Note</span>
</button>
<button class="btn btn-secondary" id="btn-export-csv" title="Download measurements to Excel CSV">
<svg viewBox="0 0 24 24"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
<span class="btn-text">CSV</span>
</button>
<button class="btn btn-secondary" onclick="window.print()" title="Print 1-Page Letter Report">
<svg viewBox="0 0 24 24"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
<span class="btn-text">Print</span>
</button>
<button class="btn btn-secondary" id="btn-lock-suite" title="Lock workspace">
<svg viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
<span class="btn-text">Lock</span>
</button>
<button class="btn btn-danger" id="btn-next-patient" title="Clear current patient">
<svg viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
<span class="btn-text">Next</span>
</button>
</div>
</header>
<div class="workspace">
<!-- Left Sidebar -->
<aside class="sidebar">
<div>
<div class="section-header"><span>1. Radiograph & Patient</span></div>
<div class="card">
<input type="file" id="file-input" accept="image/*,.dcm,application/dicom,.json" class="input-field" style="padding: 4px;">
<div class="form-group">
<label>Patient Name</label>
<input type="text" id="pt-name" class="input-field" placeholder="Patient name...">
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
<div class="form-group">
<label>Chart # / MRN</label>
<input type="text" id="pt-chart" class="input-field" placeholder="MRN">
</div>
<div class="form-group">
<label>Date & Time</label>
<input type="datetime-local" id="pt-datetime" class="input-field">
</div>
</div>
</div>
</div>
<div>
<div class="section-header"><span>2. Focus Mode & Analyses</span></div>
<div class="card">
<div class="mode-group">
<div class="mode-btn active" data-mode="ABO">ABO</div>
<div class="mode-btn" data-mode="MCNAMARA">McNamara</div>
<div class="mode-btn" data-mode="TWEED">Tweed</div>
<div class="mode-btn" data-mode="AIRWAY">Airway</div>
<div class="mode-btn" data-mode="CVM">🦴 CVM</div>
<div class="mode-btn" data-mode="WITS">Wits</div>
<div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
<div class="mode-btn" data-mode="ALL">All Vectors</div>
<div class="mode-btn" data-mode="SUPER" style="background: rgba(56,189,248,0.12); border-color:#38bdf8; color:#38bdf8;">📑 T1/T2/T3</div>
</div>
<div class="toggle-grid" style="margin-top: 3px;">
<div class="toggle-pill active" id="tog-lines">Lines: ON</div>
<div class="toggle-pill active" id="tog-points">Dots: ON</div>
<div class="toggle-pill active" id="tog-labels">Names: ON</div>
</div>
</div>
</div>
<div>
<div class="section-header"><span>3. Retrace & Calibration</span></div>
<div class="card">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
<button id="btn-retrace-all" class="btn btn-secondary">Reset All</button>
<button id="btn-reset-single" class="btn btn-secondary">Reset Dot</button>
</div>
<button id="btn-retrace-scale" class="btn" style="background:#0284c7; width:100%; font-size:10.5px;">
⚡ Recalculate with Calibrated Scale
</button>
<div style="font-size: 9.5px; color: var(--text-muted); text-align: center;">
Selected: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot on x-ray to reset)
</div>
</div>
</div>
<div>
<div class="section-header"><span>4. Cervical Maturation (CVM)</span></div>
<div class="card">
<div class="cvm-grid">
<div class="cvm-btn" data-cvm="CS1">CS1</div>
<div class="cvm-btn" data-cvm="CS2">CS2</div>
<div class="cvm-btn active" data-cvm="CS3">CS3</div>
<div class="cvm-btn" data-cvm="CS4">CS4</div>
<div class="cvm-btn" data-cvm="CS5">CS5</div>
<div class="cvm-btn" data-cvm="CS6">CS6</div>
</div>
<div id="cvm-desc" style="font-size: 9.5px; color: var(--teal-accent); font-weight: 600; text-align: center;">
CS3: Ascending Mandibular Growth Peak (Ideal Timing for Functional Appliances)
</div>
</div>
</div>
<div>
<div class="section-header"><span>5. Longitudinal Series (T1 / T2 / T3)</span></div>
<div class="card">
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px;">
<button id="btn-lock-t1" class="btn btn-teal" style="font-size:9.5px; padding:4px;">📌 T1 Initial</button>
<button id="btn-lock-t2" class="btn" style="background:rgba(59,130,246,0.2); border:1px solid #3b82f6; color:#93c5fd; font-size:9.5px; padding:4px;">📌 T2 Prog</button>
<button id="btn-lock-t3" class="btn" style="background:rgba(217,70,239,0.2); border:1px solid #d946ef; color:#f0abfc; font-size:9.5px; padding:4px;">📌 T3 Final</button>
</div>
<button id="btn-clear-series" class="btn btn-secondary" style="font-size:9.5px; padding:3px; margin-top:2px;">Clear All Baselines</button>
<div class="form-group" style="margin-top: 3px;">
<label>Registration Reference</label>
<select id="super-mode" class="input-field" style="padding: 4px;">
<option value="CRANIAL">Cranial Base (S-N registered at S)</option>
<option value="MAXILLARY">Maxillary Palatal Plane (PNS-ANS at PNS)</option>
<option value="MANDIBULAR">Mandibular Plane (Go-Me registered at Me)</option>
</select>
</div>
<div id="super-status" style="font-size: 9px; color: var(--text-muted); text-align: center; line-height:1.35;">
No baselines locked.
</div>
</div>
</div>
<div>
<div class="section-header">
<span>6. Caliper & Image Equalization</span>
<span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 9.5px;">Reset</span>
</div>
<div class="card">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
<button id="btn-cal" class="btn btn-secondary" style="font-size: 9.5px; padding: 5px 3px;">Ruler: Toggle</button>
<button id="btn-auto-caliper" class="btn" style="background:#0891b2; font-size:9.5px; padding: 5px 3px;">⚡ Auto 10mm</button>
</div>
<span id="cal-status" style="font-size: 10px; color: var(--ruler-cyan); text-align: center; font-weight: 600;">
Scale: 10.00 px/mm
</span>
<div class="form-group" style="margin-top: 2px;">
<label>Density Filter</label>
<select id="filter-mode-select" class="input-field" style="padding: 4px;">
<option value="NORMAL">Standard Radiograph</option>
<option value="EQUALIZED">Bone & Soft Profile Equalization (CLAHE)</option>
<option value="BONE">Cortical Bone Boost</option>
<option value="SOFT">Soft Tissue Profile Focus</option>
</select>
</div>
<div class="slider-row">
<span>Brightness</span>
<input type="range" id="brightness" min="0.5" max="2.0" step="0.05" value="1.0">
</div>
<div class="slider-row">
<span>Contrast</span>
<input type="range" id="contrast" min="0.5" max="2.5" step="0.05" value="1.0">
</div>
<div class="slider-row">
<span>Invert Negative</span>
<input type="checkbox" id="invert">
</div>
</div>
</div>
<div>
<div class="section-header">
<span>7. Reference Norms & Ethnicity</span>
<span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 9.5px; display: none;">Restore</span>
</div>
<div class="card">
<div class="form-group">
<label>Ethnic Population Standard</label>
<select id="ethnicity-select" class="input-field" style="padding: 4px; font-weight: 600; color: #38bdf8;">
<option value="CAUCASIAN">Caucasian (ABO Standard / Michigan)</option>
<option value="EAST_ASIAN">East Asian (Japanese / Chinese / Korean)</option>
<option value="AFRICAN_AMERICAN">African American (Drummond / Alexander)</option>
<option value="HISPANIC">Hispanic / Latino (Bishara / Garcia)</option>
</select>
</div>
<button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 10px; padding: 4px; margin-top: 2px;">
Customize ABO Norms
</button>
<div id="norms-drawer"></div>
</div>
</div>
</aside>
<!-- Center Viewport -->
<main class="viewport" id="viewport-wrapper">
<div id="loupe-box">
<canvas id="loupe-canvas" width="140" height="140"></canvas>
<div id="loupe-label">S</div>
</div>
<div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
<div style="font-size: 32px;">🦷</div>
<div style="font-size: 14px; font-weight: 600; color: var(--text-main);">Drop Lateral Cephalogram (.DCM, .JPG, .PNG) or .JSON Here</div>
<div style="font-size: 11px;">Dual-Neural Localization Active • Drag Points to Fine-Tune</div>
</div>
<div id="viewport-container">
<img id="ceph-image" src="" alt="">
<svg id="overlay-svg"></svg>
</div>
<div class="viewport-overlay-controls">
<button id="btn-zoom-in">Zoom (+)</button>
<button id="btn-zoom-out">Zoom (-)</button>
<button id="btn-zoom-reset">Fit</button>
<span style="color: var(--surface-border);">|</span>
<span class="shortcut-hint">Hold <strong>[SPACE]</strong> to inspect radiograph • Double-click dot to reset</span>
</div>
</main>
<!-- Right Analysis Panel -->
<aside class="analysis-panel">
<div class="diagnosis-banner">
<div class="diagnosis-headline" id="diag-headline">Automated Diagnosis: Awaiting Tracing...</div>
<div class="diagnosis-grid">
<div class="diag-item">
<span class="diag-label">Sagittal Skeletal</span>
<span class="diag-val" id="diag-sagittal">-</span>
</div>
<div class="diag-item">
<span class="diag-label">Vertical Growth</span>
<span class="diag-val" id="diag-vertical">-</span>
</div>
<div class="diag-item">
<span class="diag-label">Incisor Posture</span>
<span class="diag-val" id="diag-dental">-</span>
</div>
<div class="diag-item">
<span class="diag-label">Soft Profile & CVM</span>
<span class="diag-val" id="diag-soft">-</span>
</div>
</div>
</div>
<div id="section-abo">
<div class="section-header" style="color: #60a5fa;">Official ABO Cephalometric Analysis</div>
<table class="analysis-table">
<thead>
<tr>
<th>Parameter</th>
<th>Norm</th>
<th>Measured</th>
<th>Diff</th>
<th id="th-t1-abo" style="display:none; color:#5eead4;">Δ vs T1</th>
<th>Status</th>
</tr>
</thead>
<tbody id="abo-rows">
<tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting radiograph...</td></tr>
</tbody>
</table>
</div>
<div id="section-mcnamara">
<div class="section-header" style="color: #38bdf8;">McNamara Analysis (Maxillomandibular & LAFH)</div>
<table class="analysis-table">
<thead>
<tr>
<th>Parameter</th>
<th>Norm</th>
<th>Measured</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="mcnamara-rows">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
</tbody>
</table>
</div>
<div id="section-tweed">
<div class="section-header" style="color: #fbbf24;">Tweed Diagnostic Triangle</div>
<table class="analysis-table">
<thead>
<tr>
<th>Parameter</th>
<th>Norm</th>
<th>Measured</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="tweed-rows">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
</tbody>
</table>
</div>
<div id="section-airway">
<div class="section-header" style="color: #2dd4bf;">Pharyngeal Airway Space (OSA & Sleep Screening)</div>
<table class="analysis-table">
<thead>
<tr>
<th>Airway Region</th>
<th>Norm</th>
<th>Measured</th>
<th>Status</th>
</tr>
</thead>
<tbody id="airway-rows">
<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
</tbody>
</table>
</div>
<div id="section-cvm-table">
<div class="section-header" style="color: #14b8a6;">Cervical Vertebral Maturation (C2–C4 Morphology)</div>
<table class="analysis-table">
<thead>
<tr>
<th>Feature</th>
<th>Measured</th>
<th>Morphology & Timing</th>
</tr>
</thead>
<tbody id="cvm-metric-rows">
<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 8px;">Select CVM mode or upload radiograph...</td></tr>
</tbody>
</table>
</div>
<div id="section-wits">
<div class="section-header" style="color: #c084fc;">Jacobson Wits Appraisal</div>
<table class="analysis-table">
<thead>
<tr>
<th>Parameter</th>
<th>Norm</th>
<th>Measured</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="wits-rows">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
</tbody>
</table>
</div>
<div id="section-holdaway">
<div class="section-header" style="color: #f472b6;">Holdaway Soft Tissue Analysis</div>
<table class="analysis-table">
<thead>
<tr>
<th>Parameter</th>
<th>Norm</th>
<th>Measured</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="holdaway-rows">
<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
</tbody>
</table>
</div>
</aside>
</div>
<!-- Mobile Navigation Bar -->
<nav class="mobile-nav-bar" id="mobile-nav">
<button class="mobile-tab-btn active" data-tab="tools">
<svg viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
<span>Controls</span>
</button>
<button class="mobile-tab-btn" data-tab="viewport">
<svg viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
<span>Tracing</span>
</button>
<button class="mobile-tab-btn" data-tab="analysis">
<svg viewBox="0 0 24 24"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
<span>Results</span>
</button>
</nav>
<!-- Print 1-Page Letter Layout -->
<div id="print-report-container">
<div class="print-header-bar">
<div>
<div class="print-title">ORTHOCEPH PRO | CLINICAL ABO CEPHALOMETRIC REPORT</div>
<div style="font-size: 8px; color: #64748b; font-weight: 600;">AMERICAN BOARD OF ORTHODONTICS & MCNAMARA COMPLIANT SUMMARY</div>
</div>
<div class="print-demographics">
<div>PATIENT: <strong id="print-pt-name">Unspecified</strong></div>
<div>MRN: <strong id="print-pt-mrn">-</strong></div>
<div>DATE & TIME: <strong id="print-pt-datetime">-</strong></div>
<div id="print-ethnicity-tag" style="color:#0284c7;">ETHNICITY: <strong>Caucasian</strong></div>
</div>
</div>
<div class="print-grid">
<div class="print-left-col">
<div class="print-ceph-box">
<img id="print-img" src="" alt="Cephalogram">
<svg id="print-svg" viewBox="0 0 100 100"></svg>
</div>
<div class="print-diag-card">
<div style="font-weight: 800; color: #1e3a8a; font-size: 9px; border-bottom: 1px solid #e2e8f0; padding-bottom: 2px;" id="print-diag-headline">Diagnosis Summary</div>
<div id="print-diag-sag">Sagittal: -</div>
<div id="print-diag-vert">Vertical: -</div>
<div id="print-diag-dent">Dental: -</div>
<div id="print-diag-soft">Soft Profile: -</div>
</div>
<table class="print-table" id="print-wits-table">
<thead>
<tr><th>Appraisal, Airway & CVM</th><th>Norm</th><th>Measured</th><th>Status</th></tr>
</thead>
<tbody id="print-wits-tbody"></tbody>
</table>
</div>
<div class="print-right-col">
<table class="print-table" id="print-abo-table">
<thead>
<tr>
<th>ABO Parameter</th>
<th>Norm ± SD</th>
<th>Value</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="print-abo-tbody"></tbody>
</table>
<table class="print-table" id="print-mcnamara-table" style="margin-top: 3px;">
<thead>
<tr>
<th>McNamara & Tweed</th>
<th>Norm ± SD</th>
<th>Value</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="print-mcnamara-tbody"></tbody>
</table>
<table class="print-table" id="print-holdaway-table" style="margin-top: 3px;">
<thead>
<tr>
<th>Holdaway Soft Tissue</th>
<th>Norm ± SD</th>
<th>Value</th>
<th>Diff</th>
<th>Status</th>
</tr>
</thead>
<tbody id="print-holdaway-tbody"></tbody>
</table>
</div>
</div>
<div class="print-footer-bar">
<div class="print-disclaimer">
Measurements verified against calibrated millimeter scale. Automated dual-neural cephalometric analysis generated for clinical orthodontic diagnosis and treatment evaluation.
</div>
<div class="print-signature-wrap">
<div class="print-sign-line">Attending Orthodontist Signature / Stamp</div>
</div>
</div>
</div>
<div id="toast-msg">Notification</div>
<script>
// =============================================================
// 1. Constants, Dual Models & 29-Channel Indices
// =============================================================
const MASTER_PASSWORD = "ortho2026"; // Clinic access code
const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
const CVM_MODEL_URL = "./cvm_airway.onnx"; // Secondary CVM/Airway ONNX model if in Space
// 29 Full Channel Landmark Mapping
const LM_INDICES = {
"A": 0, "ANS": 1, "Ar": 2, "B": 3, "Co": 4, "Gn": 5, "Go": 6, "LIA": 7, "LIT": 8,
"LMT": 9, "LPM": 10, "Li": 11, "Ls": 12, "Me": 13, "N": 14, "Or": 16, "PNS": 17,
"Pn": 18, "Po": 19, "Pog": 20, "Pog_soft": 21, "R": 22, "S": 23, "Sn": 24,
"UIA": 25, "UIT": 26, "UMT": 27, "UPM": 28
};
const MODE_LANDMARKS = {
ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft"]),
MCNAMARA: new Set(["N", "Po", "Or", "A", "Pog", "Co", "Gn", "ANS", "Me"]),
TWEED: new Set(["Po", "Or", "Go", "Me", "LIT", "LIA"]),
AIRWAY: new Set(["PNS", "UPW", "P_Palate", "TB", "LPW", "Go", "B", "R"]),
CVM: new Set(["C2_LL", "C2_INF", "C2_LR", "C3_UL", "C3_UR", "C3_LL", "C3_INF", "C3_LR", "C4_UL", "C4_UR", "C4_LL", "C4_INF", "C4_LR", "Ar", "R", "Go"]),
WITS: new Set(["A", "B", "OP_P", "OP_A"]),
HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog", "Co", "Gn"]),
ALL: new Set(["S", "N", "Po", "Or", "A", "B", "Pog", "Me", "Gn", "Go", "ANS", "PNS", "UIT", "UIA", "LIT", "LIA", "Pn", "Sn", "Ls", "Li", "Pog_soft", "OP_P", "OP_A", "Co", "Ar", "R", "UPW", "P_Palate", "TB", "LPW", "C2_LL", "C2_INF", "C2_LR", "C3_UL", "C3_UR", "C3_LL", "C3_INF", "C3_LR", "C4_UL", "C4_UR", "C4_LL", "C4_INF", "C4_LR"])
};
const CVM_INFO = {
CS1: "CS1 (Pre-Peak): Lower borders of C2-C4 are flat. C3 & C4 bodies are tapered trapezoids. Peak is >2 years away.",
CS2: "CS2 (Pre-Peak): Concavity present at lower border of C2. C3 & C4 are trapezoids. Peak is ~1 year away.",
CS3: "CS3 (Ascending Peak): Concavities on C2 & C3. Peak mandibular velocity occurs during this stage (Ideal Functional Appliance Timing).",
CS4: "CS4 (Decelerating Peak): Concavities on C2, C3 & C4. C3 & C4 are horizontal rectangles. Peak occurred 1–2 years ago.",
CS5: "CS5 (Post-Peak): Concavities on C2–C4. At least one of C3 or C4 is square. Peak ended >1 year ago.",
CS6: "CS6 (Completion): Concavities on C2–C4. At least one of C3 or C4 is vertical rectangular. Mandibular growth complete."
};
const ETHNICITY_DATABASE = {
CAUCASIAN: {
label: "Caucasian (ABO Standard / Michigan)",
abo: [
{ id: "SNA", name: "SNA Angle", norm: 82.0, sd: 2.0, unit: "°" },
{ id: "SNB", name: "SNB Angle", norm: 80.0, sd: 2.0, unit: "°" },
{ id: "ANB", name: "ANB Difference", norm: 2.0, sd: 2.0, unit: "°" },
{ id: "FMA", name: "FMA (FH to MP)", norm: 25.0, sd: 4.0, unit: "°" },
{ id: "SNMP", name: "SN to MP Angle", norm: 32.0, sd: 5.0, unit: "°" },
{ id: "IMPA", name: "IMPA (L1 to MP)", norm: 90.0, sd: 5.0, unit: "°" },
{ id: "U1SN", name: "U1 to SN Angle", norm: 102.0, sd: 5.0, unit: "°" },
{ id: "U1NA_deg", name: "U1 to NA Angle", norm: 22.0, sd: 4.0, unit: "°" },
{ id: "U1NA_mm", name: "U1 to NA (mm)", norm: 4.0, sd: 2.0, unit: "mm" },
{ id: "L1NB_deg", name: "L1 to NB Angle", norm: 25.0, sd: 4.0, unit: "°" },
{ id: "L1NB_mm", name: "L1 to NB (mm)", norm: 4.0, sd: 2.0, unit: "mm" },
{ id: "IIA", name: "Interincisal Angle", norm: 130.0, sd: 6.0, unit: "°" },
{ id: "UL_E", name: "Upper Lip to E-Line", norm: -3.0, sd: 2.0, unit: "mm" },
{ id: "LL_E", name: "Lower Lip to E-Line", norm: -1.0, sd: 2.0, unit: "mm" }
],
tweed: [
{ id: "FMA", name: "FMA Angle", norm: 25.0, sd: 4.0, unit: "°" },
{ id: "IMPA", name: "IMPA Angle", norm: 90.0, sd: 5.0, unit: "°" },
{ id: "FMIA", name: "FMIA Angle", norm: 65.0, sd: 5.0, unit: "°" }
]
},
EAST_ASIAN: {
label: "East Asian (Chinese / Japanese / Korean)",
abo: [
{ id: "SNA", name: "SNA Angle", norm: 82.5, sd: 2.5, unit: "°" },
{ id: "SNB", name: "SNB Angle", norm: 79.5, sd: 2.5, unit: "°" },
{ id: "ANB", name: "ANB Difference", norm: 3.0, sd: 2.0, unit: "°" },
{ id: "FMA", name: "FMA (FH to MP)", norm: 27.5, sd: 4.0, unit: "°" },
{ id: "SNMP", name: "SN to MP Angle", norm: 34.5, sd: 5.0, unit: "°" },
{ id: "IMPA", name: "IMPA (L1 to MP)", norm: 96.0, sd: 5.5, unit: "°" },
{ id: "U1SN", name: "U1 to SN Angle", norm: 106.0, sd: 5.5, unit: "°" },
{ id: "U1NA_deg", name: "U1 to NA Angle", norm: 26.0, sd: 4.5, unit: "°" },
{ id: "U1NA_mm", name: "U1 to NA (mm)", norm: 5.5, sd: 2.0, unit: "mm" },
{ id: "L1NB_deg", name: "L1 to NB Angle", norm: 29.0, sd: 4.5, unit: "°" },
{ id: "L1NB_mm", name: "L1 to NB (mm)", norm: 6.0, sd: 2.0, unit: "mm" },
{ id: "IIA", name: "Interincisal Angle", norm: 122.0, sd: 6.5, unit: "°" },
{ id: "UL_E", name: "Upper Lip to E-Line", norm: 0.5, sd: 2.0, unit: "mm" },
{ id: "LL_E", name: "Lower Lip to E-Line", norm: 1.5, sd: 2.0, unit: "mm" }
],
tweed: [
{ id: "FMA", name: "FMA Angle", norm: 27.5, sd: 4.0, unit: "°" },
{ id: "IMPA", name: "IMPA Angle", norm: 96.0, sd: 5.0, unit: "°" },
{ id: "FMIA", name: "FMIA Angle", norm: 56.5, sd: 5.0, unit: "°" }
]
},
AFRICAN_AMERICAN: {
label: "African American (Drummond / Alexander)",
abo: [
{ id: "SNA", name: "SNA Angle", norm: 85.0, sd: 3.0, unit: "°" },
{ id: "SNB", name: "SNB Angle", norm: 81.5, sd: 3.0, unit: "°" },
{ id: "ANB", name: "ANB Difference", norm: 3.5, sd: 2.0, unit: "°" },
{ id: "FMA", name: "FMA (FH to MP)", norm: 28.0, sd: 4.5, unit: "°" },
{ id: "SNMP", name: "SN to MP Angle", norm: 35.0, sd: 5.0, unit: "°" },
{ id: "IMPA", name: "IMPA (L1 to MP)", norm: 100.0, sd: 6.0, unit: "°" },
{ id: "U1SN", name: "U1 to SN Angle", norm: 112.0, sd: 6.0, unit: "°" },
{ id: "U1NA_deg", name: "U1 to NA Angle", norm: 30.0, sd: 5.0, unit: "°" },
{ id: "U1NA_mm", name: "U1 to NA (mm)", norm: 7.0, sd: 2.5, unit: "mm" },
{ id: "L1NB_deg", name: "L1 to NB Angle", norm: 33.0, sd: 5.0, unit: "°" },
{ id: "L1NB_mm", name: "L1 to NB (mm)", norm: 7.5, sd: 2.5, unit: "mm" },
{ id: "IIA", name: "Interincisal Angle", norm: 116.0, sd: 7.0, unit: "°" },
{ id: "UL_E", name: "Upper Lip to E-Line", norm: 3.0, sd: 2.5, unit: "mm" },
{ id: "LL_E", name: "Lower Lip to E-Line", norm: 4.0, sd: 2.5, unit: "mm" }
],
tweed: [
{ id: "FMA", name: "FMA Angle", norm: 28.0, sd: 4.5, unit: "°" },
{ id: "IMPA", name: "IMPA Angle", norm: 100.0, sd: 6.0, unit: "°" },
{ id: "FMIA", name: "FMIA Angle", norm: 52.0, sd: 5.5, unit: "°" }
]
},
HISPANIC: {
label: "Hispanic / Latino (Bishara / Garcia)",
abo: [
{ id: "SNA", name: "SNA Angle", norm: 83.5, sd: 2.5, unit: "°" },
{ id: "SNB", name: "SNB Angle", norm: 80.5, sd: 2.5, unit: "°" },
{ id: "ANB", name: "ANB Difference", norm: 3.0, sd: 2.0, unit: "°" },
{ id: "FMA", name: "FMA (FH to MP)", norm: 26.5, sd: 4.0, unit: "°" },
{ id: "SNMP", name: "SN to MP Angle", norm: 33.5, sd: 5.0, unit: "°" },
{ id: "IMPA", name: "IMPA (L1 to MP)", norm: 95.0, sd: 5.5, unit: "°" },
{ id: "U1SN", name: "U1 to SN Angle", norm: 105.0, sd: 5.5, unit: "°" },
{ id: "U1NA_deg", name: "U1 to NA Angle", norm: 25.0, sd: 4.5, unit: "°" },
{ id: "U1NA_mm", name: "U1 to NA (mm)", norm: 5.0, sd: 2.0, unit: "mm" },
{ id: "L1NB_deg", name: "L1 to NB Angle", norm: 28.0, sd: 4.5, unit: "°" },
{ id: "L1NB_mm", name: "L1 to NB (mm)", norm: 5.5, sd: 2.0, unit: "mm" },
{ id: "IIA", name: "Interincisal Angle", norm: 124.0, sd: 6.5, unit: "°" },
{ id: "UL_E", name: "Upper Lip to E-Line", norm: 0.0, sd: 2.0, unit: "mm" },
{ id: "LL_E", name: "Lower Lip to E-Line", norm: 1.0, sd: 2.0, unit: "mm" }
],
tweed: [
{ id: "FMA", name: "FMA Angle", norm: 26.5, sd: 4.0, unit: "°" },
{ id: "IMPA", name: "IMPA Angle", norm: 95.0, sd: 5.0, unit: "°" },
{ id: "FMIA", name: "FMIA Angle", norm: 58.5, sd: 5.0, unit: "°" }
]
}
};
let activeEthnicity = "CAUCASIAN";
let ABO_NORMS = JSON.parse(localStorage.getItem("custom_abo_norms")) || JSON.parse(JSON.stringify(ETHNICITY_DATABASE.CAUCASIAN.abo));
let TWEED_NORMS = JSON.parse(JSON.stringify(ETHNICITY_DATABASE.CAUCASIAN.tweed));
const MCNAMARA_NORMS = [
{ id: "A_N_PERP", name: "Point A to N-Perp", norm: 0.5, sd: 2.0, unit: "mm" },
{ id: "POG_N_PERP", name: "Pog to N-Perp", norm: -1.0, sd: 3.0, unit: "mm" },
{ id: "CO_A", name: "Effective Midface (Co-A)", norm: 94.0, sd: 4.0, unit: "mm" },
{ id: "CO_GN", name: "Effective Mandible (Co-Gn)", norm: 123.0, sd: 5.0, unit: "mm" },
{ id: "MX_MD_DIFF", name: "Maxillo-Mandibular Diff", norm: 27.0, sd: 3.0, unit: "mm" },
{ id: "LAFH", name: "Lower Face Height (ANS-Me)", norm: 66.0, sd: 4.0, unit: "mm" }
];
const HOLDAWAY_NORMS = [
{ id: "H_ANGLE", name: "H-Angle (H-Line to N'-Pog')", norm: 10.0, sd: 3.0, unit: "°" },
{ id: "SKEL_CONV", name: "Skeletal Convexity (A to N-Pog)", norm: 0.0, sd: 2.0, unit: "mm" },
{ id: "NOSE_PROM", name: "Nose Prominence (Pn to H-Line)", norm: 18.0, sd: 4.0, unit: "mm" },
{ id: "SN_HLINE", name: "Subnasale to H-Line", norm: 5.0, sd: 2.0, unit: "mm" },
{ id: "LL_HLINE", name: "Lower Lip to H-Line", norm: 0.5, sd: 1.0, unit: "mm" },
{ id: "CHIN_THICK", name: "Soft Tissue Chin (Pog to Pog')", norm: 11.0, sd: 2.0, unit: "mm" }
];
// App State
let session = null;
let cvmSession = null;
let coords = {};
let initialAiCoords = {};
let t1Baseline = null;
let t2Baseline = null;
let t3Baseline = null;
let selectedLm = null;
let cvmStage = "CS3";
let pxPerMm = 10.0;
let showRuler = false;
let focusMode = "ABO";
let showLines = true;
let showPoints = true;
let showLabels = true;
let spacebarPeek = false;
let hipaaPrivacyMode = false;
let currentFilterMode = "NORMAL";
let zoomLevel = 1.0;
let draggingLm = null;
let latestMetrics = {};
let latestDiagnosis = { headline: "Awaiting Tracing...", sagittal: "-", vertical: "-", dental: "-", soft: "-" };
const imgElem = document.getElementById("ceph-image");
const svgElem = document.getElementById("overlay-svg");
const statusTxt = document.getElementById("status-txt");
const statusInd = document.getElementById("status-ind");
const container = document.getElementById("viewport-container");
const dropzone = document.getElementById("empty-dropzone");
const calBtn = document.getElementById("btn-cal");
const calStatus = document.getElementById("cal-status");
const loupeBox = document.getElementById("loupe-box");
const loupeCanvas = document.getElementById("loupe-canvas");
const loupeLabel = document.getElementById("loupe-label");
// Auto-fill Current Date & Time
function setAutoDateTime() {
const now = new Date();
const pad = (n) => String(n).padStart(2, '0');
const dateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
document.getElementById("pt-datetime").value = dateStr;
}
setAutoDateTime();
// Toast Helper
function notify(msg, dur = 2600) {
const t = document.getElementById("toast-msg");
t.innerText = msg;
t.style.display = "flex";
clearTimeout(t._tm);
t._tm = setTimeout(() => t.style.display = "none", dur);
}
// Security Gate Logic
const gateElem = document.getElementById("security-gate");
const gatePass = document.getElementById("gate-pass");
const gateErr = document.getElementById("gate-err");
function checkSecurity() {
if (sessionStorage.getItem("orthoceph_auth") === "1") {
gateElem.style.display = "none";
} else {
gateElem.style.display = "flex";
gatePass.value = "";
gateErr.style.display = "none";
setTimeout(() => gatePass.focus(), 100);
}
}
checkSecurity();
document.getElementById("btn-unlock-gate").addEventListener("click", () => {
if (gatePass.value === MASTER_PASSWORD) {
sessionStorage.setItem("orthoceph_auth", "1");
gateElem.style.display = "none";
notify("Clinical Suite Unlocked");
} else {
gateErr.style.display = "block";
gatePass.value = "";
gatePass.focus();
}
});
gatePass.addEventListener("keydown", (e) => {
if (e.key === "Enter") document.getElementById("btn-unlock-gate").click();
});
document.getElementById("btn-lock-suite").addEventListener("click", () => {
sessionStorage.removeItem("orthoceph_auth");
checkSecurity();
});
// Mobile Tabs Setup
const mobileTabBtns = document.querySelectorAll(".mobile-tab-btn");
function setMobileTab(tabName) {
document.body.classList.remove("tab-tools", "tab-viewport", "tab-analysis");
document.body.classList.add(`tab-${tabName}`);
mobileTabBtns.forEach(b => b.classList.toggle("active", b.getAttribute("data-tab") === tabName));
}
setMobileTab("tools");
mobileTabBtns.forEach(b => b.addEventListener("click", () => setMobileTab(b.getAttribute("data-tab"))));
// Custom Norms Drawer
function buildNormsEditor() {
const drawer = document.getElementById("norms-drawer");
drawer.innerHTML = `<div class="norm-edit-row" style="color:var(--text-muted); font-weight:700;"><span>Metric</span><span style="text-align:center;">Mean</span><span style="text-align:center;">± SD</span></div>`;
ABO_NORMS.forEach((m, idx) => {
const row = document.createElement("div");
row.className = "norm-edit-row";
row.innerHTML = `
<span>${m.id}</span>
<input type="number" step="0.5" value="${m.norm}" data-idx="${idx}" data-field="norm">
<input type="number" step="0.5" value="${m.sd}" data-idx="${idx}" data-field="sd">
`;
drawer.appendChild(row);
});
drawer.querySelectorAll("input").forEach(inp => {
inp.addEventListener("input", (e) => {
const i = parseInt(e.target.getAttribute("data-idx"));
const field = e.target.getAttribute("data-field");
const val = parseFloat(e.target.value);
if (!isNaN(val)) {
ABO_NORMS[i][field] = val;
localStorage.setItem("custom_abo_norms", JSON.stringify(ABO_NORMS));
renderAnalysis();
}
});
});
}
buildNormsEditor();
document.getElementById("btn-toggle-norms").addEventListener("click", () => {
const d = document.getElementById("norms-drawer");
const r = document.getElementById("reset-norms");
const open = d.style.display === "flex";
d.style.display = open ? "none" : "flex";
r.style.display = open ? "none" : "inline";
});
document.getElementById("reset-norms").addEventListener("click", () => {
const ethData = ETHNICITY_DATABASE[activeEthnicity] || ETHNICITY_DATABASE.CAUCASIAN;
ABO_NORMS = JSON.parse(JSON.stringify(ethData.abo));
localStorage.removeItem("custom_abo_norms");
buildNormsEditor();
renderAnalysis();
notify("Norms restored to ethnic baseline.");
});
// Ethnicity Select
document.getElementById("ethnicity-select").addEventListener("change", (e) => {
activeEthnicity = e.target.value;
const ethData = ETHNICITY_DATABASE[activeEthnicity] || ETHNICITY_DATABASE.CAUCASIAN;
ABO_NORMS = JSON.parse(JSON.stringify(ethData.abo));
TWEED_NORMS = JSON.parse(JSON.stringify(ethData.tweed));
localStorage.setItem("custom_abo_norms", JSON.stringify(ABO_NORMS));
buildNormsEditor();
renderAnalysis();
notify(`Norms adjusted for ${ethData.label}`);
});
// HIPAA Toggle
document.getElementById("btn-privacy-toggle").addEventListener("click", () => {
hipaaPrivacyMode = !hipaaPrivacyMode;
document.getElementById("privacy-btn-txt").innerText = `HIPAA Mask: ${hipaaPrivacyMode ? 'ON' : 'OFF'}`;
document.getElementById("btn-privacy-toggle").classList.toggle("btn-danger", hipaaPrivacyMode);
renderAnalysis();
notify(hipaaPrivacyMode ? "HIPAA De-Identification Mode Enabled." : "De-Identification Disabled.");
});
// Transparent SVG Export
document.getElementById("btn-export-svg").addEventListener("click", () => {
if (!coords.S || !imgElem.naturalWidth) {
notify("Trace a radiograph first.");
return;
}
const w = imgElem.naturalWidth;
const h = imgElem.naturalHeight;
const svgContent = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" style="background:transparent;">
${svgElem.innerHTML}
</svg>`;
const blob = new Blob([svgContent], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
const ptName = (document.getElementById("pt-name").value || "Patient").replace(/\s+/g, '_');
a.href = url;
a.download = `Ceph_Vectors_${ptName}.svg`;
a.click();
notify("Transparent vector SVG downloaded.");
});
// Auto 10mm Caliper Detection
document.getElementById("btn-auto-caliper").addEventListener("click", () => {
if (!imgElem.src || imgElem.naturalWidth === 0) {
notify("Load a cephalogram first.");
return;
}
autoDetect10mmCaliper();
});
function autoDetect10mmCaliper() {
notify("Scanning cephalostat scale...");
const origW = imgElem.naturalWidth;
const origH = imgElem.naturalHeight;
const scanCanvas = document.createElement("canvas");
const roiW = Math.floor(origW * 0.28);
const roiH = Math.floor(origH * 0.4);
scanCanvas.width = roiW; scanCanvas.height = roiH;
const ctx = scanCanvas.getContext("2d");
ctx.drawImage(imgElem, origW * 0.72, 0, roiW, roiH, 0, 0, roiW, roiH);
const imgData = ctx.getImageData(0, 0, roiW, roiH);
const data = imgData.data;
let bestCol = -1, bestScore = -1;
for (let x = 8; x < roiW - 8; x += 3) {
let variance = 0, prev = 0;
for (let y = 8; y < roiH - 8; y += 2) {
const idx = (y * roiW + x) * 4;
const gray = data[idx] * 0.299 + data[idx + 1] * 0.587 + data[idx + 2] * 0.114;
variance += Math.abs(gray - prev);
prev = gray;
}
if (variance > bestScore) {
bestScore = variance;
bestCol = x;
}
}
const detectedX = origW * 0.72 + (bestCol > 0 ? bestCol : roiW * 0.55);
const detectedY = origH * 0.12;
const estimated10mm = Math.max(70, Math.round(origW * 0.052));
coords.RULER_1 = { x: detectedX, y: detectedY };
coords.RULER_2 = { x: detectedX, y: detectedY + estimated10mm };
pxPerMm = estimated10mm / 10.0;
showRuler = true;
calBtn.innerText = "Ruler: ON";
calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Auto-Locked)`;
renderAnalysis();
notify(`Auto-calibrated scale (${pxPerMm.toFixed(2)} px/mm). Micro-drag dots if needed.`);
}
// Density Filters
document.getElementById("filter-mode-select").addEventListener("change", (e) => {
currentFilterMode = e.target.value;
applyFilters();
});
function applyFilters() {
const b = parseFloat(document.getElementById("brightness").value);
const c = parseFloat(document.getElementById("contrast").value);
const inv = document.getElementById("invert").checked ? 1 : 0;
if (currentFilterMode === "EQUALIZED") {
imgElem.style.filter = `brightness(${b * 1.08}) contrast(${c * 1.55}) invert(${inv})`;
} else if (currentFilterMode === "BONE") {
imgElem.style.filter = `brightness(${b * 0.95}) contrast(${c * 1.85}) invert(${inv})`;
} else if (currentFilterMode === "SOFT") {
imgElem.style.filter = `brightness(${b * 1.25}) contrast(${c * 0.95}) invert(${inv})`;
} else {
imgElem.style.filter = `brightness(${b}) contrast(${c}) invert(${inv})`;
}
}
document.getElementById("brightness").addEventListener("input", applyFilters);
document.getElementById("contrast").addEventListener("input", applyFilters);
document.getElementById("invert").addEventListener("change", applyFilters);
document.getElementById("reset-filters").addEventListener("click", () => {
document.getElementById("brightness").value = 1.0;
document.getElementById("contrast").value = 1.0;
document.getElementById("invert").checked = false;
document.getElementById("filter-mode-select").value = "NORMAL";
currentFilterMode = "NORMAL";
applyFilters();
});
// =============================================================
// 2. Dual-Engine Neural Model Initialization
// =============================================================
async function initModel() {
try {
ort.env.wasm.numThreads = 2;
// Primary 29-Landmark Cephalometric Neural Model
session = await ort.InferenceSession.create(MODEL_URL, { executionProviders: ['wasm'] });
// Attempt to load secondary CVM & Airway ONNX model if present in Space
try {
cvmSession = await ort.InferenceSession.create(CVM_MODEL_URL, { executionProviders: ['wasm'] });
statusTxt.innerText = "Dual AI Active (Ceph29 + CVM ONNX)";
notify("Dual AI Architecture Loaded (Ceph29 + CVM ONNX)");
} catch (_) {
statusTxt.innerText = "AI Active (Ceph29 + Corridor Scanner)";
}
statusInd.style.backgroundColor = "var(--status-green)";
if (imgElem.src && imgElem.naturalWidth > 0 && Object.keys(coords).length === 0) {
runAutoTrace();
}
} catch (err) {
statusInd.style.backgroundColor = "var(--status-red)";
statusTxt.innerText = "Model Load Error";
}
}
initModel();
// =============================================================
// 3. File Loading & Drag-and-Drop
// =============================================================
const viewportWrapper = document.getElementById("viewport-wrapper");
viewportWrapper.addEventListener("dragover", (e) => { e.preventDefault(); viewportWrapper.classList.add("drag-over"); });
viewportWrapper.addEventListener("dragleave", () => viewportWrapper.classList.remove("drag-over"));
viewportWrapper.addEventListener("drop", (e) => {
e.preventDefault();
viewportWrapper.classList.remove("drag-over");
if (e.dataTransfer.files && e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
});
document.getElementById("file-input").addEventListener("change", (e) => {
if (e.target.files[0]) handleFile(e.target.files[0]);
});
document.getElementById("json-input").addEventListener("change", (e) => {
if (e.target.files[0]) loadJsonFile(e.target.files[0]);
});
function handleFile(file) {
const name = file.name.toLowerCase();
if (name.endsWith('.json') || file.type === 'application/json') {
loadJsonFile(file);
return;
}
const isDicom = name.endsWith('.dcm') || file.type === 'application/dicom';
if (isDicom) {
const reader = new FileReader();
reader.onload = (evt) => {
try { parseAndDisplayDicom(new Uint8Array(evt.target.result)); }
catch (err) { notify("DICOM Error: " + err.message); }
};
reader.readAsArrayBuffer(file);
} else {
const reader = new FileReader();
reader.onload = (evt) => setupImage(evt.target.result, true);
reader.readAsDataURL(file);
}
}
// JSON Load & Save
document.getElementById("btn-save-json").addEventListener("click", () => {
if (!coords.S) { notify("No active tracing to save."); return; }
const ptName = document.getElementById("pt-name").value || "Patient";
const ptChart = document.getElementById("pt-chart").value || "";
const ptDateTime = document.getElementById("pt-datetime").value || "";
let exportDataUrl = null;
if (imgElem.src && imgElem.naturalWidth > 0) {
try {
const expCanvas = document.createElement("canvas");
expCanvas.width = imgElem.naturalWidth;
expCanvas.height = imgElem.naturalHeight;
const expCtx = expCanvas.getContext("2d");
expCtx.drawImage(imgElem, 0, 0);
exportDataUrl = expCanvas.toDataURL("image/jpeg", 0.92);
} catch (e) { exportDataUrl = imgElem.src; }
}
const payload = {
version: "3.5",
patient: { name: ptName, chart: ptChart, datetime: ptDateTime, ethnicity: activeEthnicity },
pxPerMm, cvmStage, coords, initialAiCoords,
baselines: { t1: t1Baseline, t2: t2Baseline, t3: t3Baseline },
metrics: latestMetrics, diagnosis: latestDiagnosis,
imageDataUrl: exportDataUrl
};
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `Ceph_${ptName.replace(/\s+/g, '_')}_${ptDateTime.slice(0, 10)}.json`;
a.click();
notify("JSON Case Record Exported");
});
function loadJsonFile(file) {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = JSON.parse(e.target.result);
if (data.patient) {
document.getElementById("pt-name").value = data.patient.name || "";
document.getElementById("pt-chart").value = data.patient.chart || "";
if (data.patient.datetime) document.getElementById("pt-datetime").value = data.patient.datetime;
if (data.patient.ethnicity) {
activeEthnicity = data.patient.ethnicity;
document.getElementById("ethnicity-select").value = activeEthnicity;
}
}
if (data.pxPerMm) {
pxPerMm = data.pxPerMm;
calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (JSON Loaded)`;
}
if (data.cvmStage) {
cvmStage = data.cvmStage;
highlightCvmButton(cvmStage);
}
if (data.baselines) {
t1Baseline = data.baselines.t1 || null;
t2Baseline = data.baselines.t2 || null;
t3Baseline = data.baselines.t3 || null;
updateSuperimpositionStatus();
}
const loadedCoords = data.coords || data.landmarks || null;
if (loadedCoords && loadedCoords.S) {
coords = JSON.parse(JSON.stringify(loadedCoords));
initialAiCoords = data.initialAiCoords ? JSON.parse(JSON.stringify(data.initialAiCoords)) : JSON.parse(JSON.stringify(loadedCoords));
}
if (data.imageDataUrl && data.imageDataUrl.startsWith("data:image")) {
setupImage(data.imageDataUrl, false);
} else {
createReferencePlaceholder();
renderAnalysis();
}
setMobileTab("viewport");
notify("JSON Record Loaded Successfully");
} catch (err) { notify("Invalid JSON: " + err.message); }
};
reader.readAsText(file);
}
function createReferencePlaceholder() {
dropzone.style.display = "none";
container.style.display = "block";
const refCanvas = document.createElement("canvas");
refCanvas.width = 1200; refCanvas.height = 1400;
const ctx = refCanvas.getContext("2d");
ctx.fillStyle = "#020617"; ctx.fillRect(0, 0, 1200, 1400);
ctx.strokeStyle = "#1e293b"; ctx.lineWidth = 1;
for (let x = 0; x < 1200; x += 50) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, 1400); ctx.stroke(); }
for (let y = 0; y < 1400; y += 50) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(1200, y); ctx.stroke(); }
imgElem.src = refCanvas.toDataURL("image/png");
svgElem.setAttribute("viewBox", "0 0 1200 1400");
}
function parseAndDisplayDicom(byteArray) {
const dataSet = dicomParser.parseDicom(byteArray);
const ptName = dataSet.string('x00100010');
if (ptName) document.getElementById('pt-name').value = ptName.replace(/\^/g, ' ').trim();
const ptId = dataSet.string('x00100020');
if (ptId) document.getElementById('pt-chart').value = ptId.trim();
const spacingStr = dataSet.string('x00280030') || dataSet.string('x00181164');
if (spacingStr) {
const parts = spacingStr.split('\\').map(parseFloat);
if (parts[0] > 0) {
pxPerMm = 1.0 / parts[0];
calStatus.innerText = `DICOM Calibrated: ${pxPerMm.toFixed(2)} px/mm`;
}
}
const rows = dataSet.uint16('x00280010');
const cols = dataSet.uint16('x00280011');
const bitsAllocated = dataSet.uint16('x00280100') || 16;
const pixelRep = dataSet.uint16('x00280103') || 0;
const isMonochrome1 = (dataSet.string('x00280004') || '').trim() === 'MONOCHROME1';
const pixelDataElem = dataSet.elements.x7fe00010;
const offCanvas = document.createElement("canvas");
offCanvas.width = cols; offCanvas.height = rows;
const ctx = offCanvas.getContext("2d");
const imgData = ctx.createImageData(cols, rows);
const numPixels = rows * cols;
let slope = parseFloat(dataSet.string('x00281053')) || 1;
let intercept = parseFloat(dataSet.string('x00281052')) || 0;
let wc = parseFloat(dataSet.string('x00281050'));
let ww = parseFloat(dataSet.string('x00281051'));
if (bitsAllocated === 16) {
const u8 = new Uint8Array(byteArray.buffer, byteArray.byteOffset + pixelDataElem.dataOffset, numPixels * 2);
const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
const vals = new Float32Array(numPixels);
let minVal = Infinity, maxVal = -Infinity;
for (let i = 0; i < numPixels; i++) {
let raw = pixelRep === 1 ? dv.getInt16(i * 2, true) : dv.getUint16(i * 2, true);
let v = raw * slope + intercept;
vals[i] = v;
if (v < minVal) minVal = v;
if (v > maxVal) maxVal = v;
}
if (isNaN(wc) || isNaN(ww) || ww <= 0) { wc = (minVal + maxVal) / 2; ww = Math.max(1, maxVal - minVal); }
const low = wc - ww / 2;
for (let i = 0; i < numPixels; i++) {
let intensity = Math.min(255, Math.max(0, ((vals[i] - low) / ww) * 255));
if (isMonochrome1) intensity = 255 - intensity;
const idx = i * 4;
imgData.data[idx] = intensity; imgData.data[idx+1] = intensity; imgData.data[idx+2] = intensity; imgData.data[idx+3] = 255;
}
} else {
const u8 = new Uint8Array(byteArray.buffer, byteArray.byteOffset + pixelDataElem.dataOffset, numPixels);
for (let i = 0; i < numPixels; i++) {
let intensity = isMonochrome1 ? 255 - u8[i] : u8[i];
const idx = i * 4;
imgData.data[idx] = intensity; imgData.data[idx+1] = intensity; imgData.data[idx+2] = intensity; imgData.data[idx+3] = 255;
}
}
ctx.putImageData(imgData, 0, 0);
setupImage(offCanvas.toDataURL("image/png"), true);
}
function setupImage(srcUrl, shouldRunAi = true) {
imgElem.onload = () => {
dropzone.style.display = "none";
container.style.display = "block";
svgElem.setAttribute("viewBox", `0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
svgElem.setAttribute("width", imgElem.clientWidth);
svgElem.setAttribute("height", imgElem.clientHeight);
setMobileTab("viewport");
if (shouldRunAi && session) runAutoTrace();
else renderAnalysis();
};
imgElem.src = srcUrl;
}
// =============================================================
// 4. Dual-Model Inference & Anatomical Corridor Ray-Caster
// =============================================================
async function runAutoTrace() {
if (!session || !imgElem.src) return;
statusInd.style.backgroundColor = "var(--status-amber)";
statusTxt.innerText = "Auto-Tracing Landmarks...";
await new Promise(r => setTimeout(r, 40));
const origW = imgElem.naturalWidth;
const origH = imgElem.naturalHeight;
// 1. Primary 29-Channel Cephalometric Model Inference
const off = document.createElement("canvas");
off.width = 768; off.height = 768;
const ctx = off.getContext("2d");
ctx.drawImage(imgElem, 0, 0, 768, 768);
const data = ctx.getImageData(0, 0, 768, 768).data;
const floatArr = new Float32Array(3 * 768 * 768);
const mean = [0.485, 0.456, 0.406];
const std = [0.229, 0.224, 0.225];
for (let i = 0; i < 768 * 768; i++) {
floatArr[i] = (data[i * 4] / 255.0 - mean[0]) / std[0];
floatArr[768 * 768 + i] = (data[i * 4 + 1] / 255.0 - mean[1]) / std[1];
floatArr[2 * 768 * 768 + i] = (data[i * 4 + 2] / 255.0 - mean[2]) / std[2];
}
const tensor = new ort.Tensor("float32", floatArr, [1, 3, 768, 768]);
const results = await session.run({ [session.inputNames[0]]: tensor });
const heatmaps = results[session.outputNames[0]].data;
coords = {};
for (const [name, ch] of Object.entries(LM_INDICES)) {
let maxVal = -Infinity, maxIdx = 0;
const offset = ch * 192 * 192;
for (let j = 0; j < 192 * 192; j++) {
if (heatmaps[offset + j] > maxVal) { maxVal = heatmaps[offset + j]; maxIdx = j; }
}
coords[name] = {
x: (maxIdx % 192 / 192) * origW,
y: (Math.floor(maxIdx / 192) / 192) * origH
};
}
// Derive Functional Occlusal Plane
if (coords.UIT && coords.LIT) {
coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
}
if (coords.Go && coords.OP_A) {
coords.OP_P = { x: coords.OP_A.x - (coords.OP_A.x - coords.Go.x) * 0.55, y: coords.OP_A.y - 12 };
}
// 2. Airway & Cervical Spine (C2-C4) Detection Pipeline
let cvmInferredFromOnnx = false;
if (cvmSession && coords.Po && coords.Go && coords.Ar) {
try {
const ramusX = coords.R ? coords.R.x : (coords.Ar.x + coords.Go.x) / 2;
const roiX = Math.max(0, Math.floor(coords.Po.x - (ramusX - coords.Po.x) * 0.5));
const roiY = Math.max(0, Math.floor(coords.Ar.y));
const roiW = Math.min(origW - roiX, Math.floor((ramusX - roiX) * 1.3));
const roiH = Math.min(origH - roiY, Math.floor((coords.Go.y - coords.Ar.y) * 2.3));
const roiCanvas = document.createElement("canvas");
roiCanvas.width = 256; roiCanvas.height = 256;
const rCtx = roiCanvas.getContext("2d");
rCtx.drawImage(imgElem, roiX, roiY, roiW, roiH, 0, 0, 256, 256);
const rData = rCtx.getImageData(0, 0, 256, 256).data;
const rFloat = new Float32Array(3 * 256 * 256);
for (let i = 0; i < 256 * 256; i++) {
rFloat[i] = (rData[i * 4] / 255.0 - 0.485) / 0.229;
rFloat[256 * 256 + i] = (rData[i * 4 + 1] / 255.0 - 0.456) / 0.224;
rFloat[2 * 256 * 256 + i] = (rData[i * 4 + 2] / 255.0 - 0.406) / 0.225;
}
const rTensor = new ort.Tensor("float32", rFloat, [1, 3, 256, 256]);
const cvmOut = await cvmSession.run({ [cvmSession.inputNames[0]]: rTensor });
const kps = cvmOut[cvmSession.outputNames[0]].data;
const mapPt = (idx) => ({
x: roiX + kps[idx * 2] * roiW,
y: roiY + kps[idx * 2 + 1] * roiH
});
coords.C2_LL = mapPt(0); coords.C2_INF = mapPt(1); coords.C2_LR = mapPt(2);
coords.C3_UL = mapPt(3); coords.C3_UR = mapPt(4);
coords.C3_LL = mapPt(5); coords.C3_INF = mapPt(6); coords.C3_LR = mapPt(7);
coords.C4_UL = mapPt(8); coords.C4_UR = mapPt(9);
coords.C4_LL = mapPt(10); coords.C4_INF = mapPt(11); coords.C4_LR = mapPt(12);
if (kps.length >= 30) {
coords.UPW = mapPt(13);
coords.LPW = mapPt(14);
}
// Check if Stage Probabilities output is returned
if (cvmSession.outputNames.length > 1 && cvmOut[cvmSession.outputNames[1]]) {
const probs = cvmOut[cvmSession.outputNames[1]].data;
let bestP = -1, bestS = 2;
for (let s = 0; s < 6; s++) {
if (probs[s] > bestP) { bestP = probs[s]; bestS = s; }
}
const stageNames = ["CS1", "CS2", "CS3", "CS4", "CS5", "CS6"];
cvmStage = stageNames[bestS];
highlightCvmButton(cvmStage);
}
cvmInferredFromOnnx = true;
} catch (err) {
console.warn("CVM ONNX inference fallback to corridor scanner:", err);
}
}
// Fallback Anatomical Corridor Scanner for Cervical Spine and Pharynx
if (!cvmInferredFromOnnx && coords.Po && coords.Go && coords.Ar) {
const rx = coords.R ? coords.R.x : (coords.Ar.x + coords.Go.x) / 2;
const vW = Math.max(22, pxPerMm * 18.0); // Human vertebra body width ~18mm
const vH = Math.max(18, pxPerMm * 14.5); // Human vertebra body height ~14.5mm
const spineX = rx - vW * 0.95; // Positioned behind posterior border of mandibular ramus
// C2 (Axis) Inferior Border
const c2Y = coords.Ar.y + (coords.Go.y - coords.Ar.y) * 0.35;
coords.C2_LL = { x: spineX - vW * 0.45, y: c2Y };
coords.C2_INF = { x: spineX, y: c2Y - vH * 0.15 };
coords.C2_LR = { x: spineX + vW * 0.45, y: c2Y + vH * 0.05 };
// C3 Body
const c3Y = c2Y + vH * 0.65;
coords.C3_UL = { x: spineX - vW * 0.45, y: c3Y };
coords.C3_UR = { x: spineX + vW * 0.45, y: c3Y + vH * 0.05 };
coords.C3_LL = { x: spineX - vW * 0.45, y: c3Y + vH };
coords.C3_INF = { x: spineX, y: c3Y + vH - vH * 0.15 };
coords.C3_LR = { x: spineX + vW * 0.45, y: c3Y + vH + vH * 0.05 };
// C4 Body (following cervical lordosis curvature)
const c4Y = c3Y + vH * 1.35;
const lordosisShift = vW * 0.08;
coords.C4_UL = { x: spineX - vW * 0.45 - lordosisShift, y: c4Y };
coords.C4_UR = { x: spineX + vW * 0.45 - lordosisShift, y: c4Y + vH * 0.05 };
coords.C4_LL = { x: spineX - vW * 0.45 - lordosisShift, y: c4Y + vH };
coords.C4_INF = { x: spineX - lordosisShift, y: c4Y + vH - vH * 0.12 };
coords.C4_LR = { x: spineX + vW * 0.45 - lordosisShift, y: c4Y + vH + vH * 0.05 };
}
// Derive Airway Reference Points using Channel 17 (PNS), Channel 22 (R), and Go
if (coords.PNS) {
coords.P_Palate = { x: coords.PNS.x + 8, y: coords.PNS.y + 24 };
if (!coords.UPW) coords.UPW = { x: coords.PNS.x - (pxPerMm * 17.5), y: coords.PNS.y + 24 };
}
if (coords.Go && coords.B) {
coords.TB = { x: coords.Go.x + (coords.B.x - coords.Go.x) * 0.35, y: coords.Go.y - 14 };
if (!coords.LPW) coords.LPW = { x: coords.TB.x - (pxPerMm * 12.0), y: coords.TB.y };
}
// Initial Caliper Ruler
coords.RULER_1 = { x: origW * 0.82, y: origH * 0.12 };
coords.RULER_2 = { x: origW * 0.82, y: origH * 0.12 + (pxPerMm * 10.0) };
initialAiCoords = JSON.parse(JSON.stringify(coords));
statusInd.style.backgroundColor = "var(--status-green)";
statusTxt.innerText = cvmInferredFromOnnx ? "Dual AI Auto-Trace Complete" : "Auto-Trace Complete (Ceph29 + Corridor)";
renderAnalysis();
}
document.getElementById("btn-retrace-all").addEventListener("click", () => {
if (!imgElem.src) return;
if (Object.keys(initialAiCoords).length > 0) {
coords = JSON.parse(JSON.stringify(initialAiCoords));
renderAnalysis();
notify("Landmarks reset to AI prediction");
} else { runAutoTrace(); }
});
document.getElementById("btn-reset-single").addEventListener("click", () => {
if (selectedLm && initialAiCoords[selectedLm]) {
coords[selectedLm] = { ...initialAiCoords[selectedLm] };
renderAnalysis();
notify(`Reset ${selectedLm}`);
} else { notify("Click any landmark dot first to reset it."); }
});
document.getElementById("btn-retrace-scale").addEventListener("click", () => {
if (coords.RULER_1 && coords.RULER_2) {
const d = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
if (d > 1) {
pxPerMm = d / 10.0;
calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Recalibrated)`;
renderAnalysis();
notify(`Recalculated with ${pxPerMm.toFixed(2)} px/mm scale`);
}
}
});
// =============================================================
// 5. Longitudinal Superimposition Engine (T1 vs. T2 vs. T3)
// =============================================================
function lockBaseline(stageKey, label) {
if (!coords.S) {
notify(`Trace a cephalogram first before locking as ${stageKey}.`);
return;
}
const dateStr = (document.getElementById("pt-datetime").value || stageKey).replace("T", " ");
const payload = {
coords: JSON.parse(JSON.stringify(coords)),
metrics: JSON.parse(JSON.stringify(latestMetrics)),
date: dateStr
};
if (stageKey === "T1") t1Baseline = payload;
else if (stageKey === "T2") t2Baseline = payload;
else if (stageKey === "T3") t3Baseline = payload;
updateSuperimpositionStatus();
renderAnalysis();
notify(`${label} baseline locked (${dateStr}).`);
}
function updateSuperimpositionStatus() {
const t1Txt = t1Baseline ? `<span style="color:#5eead4; font-weight:700;">T1: ${t1Baseline.date}</span>` : "T1: -";
const t2Txt = t2Baseline ? `<span style="color:#93c5fd; font-weight:700;">T2: ${t2Baseline.date}</span>` : "T2: -";
const t3Txt = t3Baseline ? `<span style="color:#f0abfc; font-weight:700;">T3: ${t3Baseline.date}</span>` : "T3: -";
document.getElementById("super-status").innerHTML = `${t1Txt} | ${t2Txt} | ${t3Txt}`;
document.getElementById("th-t1-abo").style.display = t1Baseline ? "table-cell" : "none";
}
document.getElementById("btn-lock-t1").addEventListener("click", () => lockBaseline("T1", "T1 Initial"));
document.getElementById("btn-lock-t2").addEventListener("click", () => lockBaseline("T2", "T2 Progress"));
document.getElementById("btn-lock-t3").addEventListener("click", () => lockBaseline("T3", "T3 Final"));
document.getElementById("btn-clear-series").addEventListener("click", () => {
t1Baseline = null; t2Baseline = null; t3Baseline = null;
updateSuperimpositionStatus();
renderAnalysis();
notify("Longitudinal baselines cleared.");
});
function getAlignedCoordsForBaseline(baselineObj) {
if (!baselineObj || !baselineObj.coords.S || !coords.S) return null;
const mode = document.getElementById("super-mode").value;
const s1 = baselineObj.coords.S, s2 = coords.S;
let origin1 = s1, origin2 = s2;
let angle1 = 0, angle2 = 0;
if (mode === "MAXILLARY" && baselineObj.coords.PNS && baselineObj.coords.ANS && coords.PNS && coords.ANS) {
origin1 = baselineObj.coords.PNS; origin2 = coords.PNS;
angle1 = Math.atan2(baselineObj.coords.ANS.y - baselineObj.coords.PNS.y, baselineObj.coords.ANS.x - baselineObj.coords.PNS.x);
angle2 = Math.atan2(coords.ANS.y - coords.PNS.y, coords.ANS.x - coords.PNS.x);
} else if (mode === "MANDIBULAR" && baselineObj.coords.Me && baselineObj.coords.Go && coords.Me && coords.Go) {
origin1 = baselineObj.coords.Me; origin2 = coords.Me;
angle1 = Math.atan2(baselineObj.coords.Go.y - baselineObj.coords.Me.y, baselineObj.coords.Go.x - baselineObj.coords.Me.x);
angle2 = Math.atan2(coords.Go.y - coords.Me.y, coords.Go.x - coords.Me.x);
} else {
if (!baselineObj.coords.N || !coords.N) return null;
angle1 = Math.atan2(baselineObj.coords.N.y - s1.y, baselineObj.coords.N.x - s1.x);
angle2 = Math.atan2(coords.N.y - s2.y, coords.N.x - s2.x);
}
const dTheta = angle2 - angle1;
const cosT = Math.cos(dTheta), sinT = Math.sin(dTheta);
const aligned = {};
for (const [k, pt] of Object.entries(baselineObj.coords)) {
const dx = pt.x - origin1.x;
const dy = pt.y - origin1.y;
aligned[k] = {
x: origin2.x + (dx * cosT - dy * sinT),
y: origin2.y + (dx * sinT + dy * cosT)
};
}
return aligned;
}
// CVM Selector
document.querySelectorAll(".cvm-btn").forEach(btn => {
btn.addEventListener("click", () => {
cvmStage = btn.getAttribute("data-cvm");
highlightCvmButton(cvmStage);
renderAnalysis();
});
});
function highlightCvmButton(stg) {
document.querySelectorAll(".cvm-btn").forEach(b => b.classList.toggle("active", b.getAttribute("data-cvm") === stg));
document.getElementById("cvm-desc").innerText = CVM_INFO[stg] || "CVM Stage Selected";
}
// Focus Modes & View Toggles
document.querySelectorAll(".mode-btn").forEach(btn => {
btn.addEventListener("click", () => {
document.querySelectorAll(".mode-btn").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
focusMode = btn.getAttribute("data-mode");
renderAnalysis();
});
});
function setupToggle(id, label, getter, setter) {
const el = document.getElementById(id);
el.addEventListener("click", () => {
const next = !getter();
setter(next);
el.classList.toggle("active", next);
el.innerText = `${label}: ${next ? 'ON' : 'OFF'}`;
renderAnalysis();
});
}
setupToggle("tog-lines", "Lines", () => showLines, v => showLines = v);
setupToggle("tog-points", "Dots", () => showPoints, v => showPoints = v);
setupToggle("tog-labels", "Names", () => showLabels, v => showLabels = v);
window.addEventListener("keydown", (e) => {
if (e.code === "Space" && document.activeElement.tagName !== "INPUT") {
e.preventDefault();
if (!spacebarPeek) { spacebarPeek = true; svgElem.style.opacity = "0"; }
}
});
window.addEventListener("keyup", (e) => {
if (e.code === "Space") { spacebarPeek = false; svgElem.style.opacity = "1"; }
});
// Ruler & Magnifier Loupe
calBtn.addEventListener("click", () => {
showRuler = !showRuler;
calBtn.innerText = `Ruler: ${showRuler ? 'ON' : 'OFF'}`;
renderAnalysis();
});
function getSVGCoords(e) {
const pt = svgElem.createSVGPoint();
pt.x = e.clientX; pt.y = e.clientY;
return pt.matrixTransform(svgElem.getScreenCTM().inverse());
}
function updateLoupe(pt, name) {
if (!imgElem.src) return;
loupeBox.style.display = "block";
loupeLabel.innerText = name;
const lCtx = loupeCanvas.getContext("2d");
const zoom = 3.0, size = 140, srcSize = size / zoom;
lCtx.clearRect(0, 0, size, size);
lCtx.filter = imgElem.style.filter || "none";
lCtx.drawImage(imgElem, pt.x - srcSize / 2, pt.y - srcSize / 2, srcSize, srcSize, 0, 0, size, size);
lCtx.filter = "none";
lCtx.strokeStyle = "#38bdf8"; lCtx.lineWidth = 1.5;
lCtx.beginPath();
lCtx.moveTo(size/2, 0); lCtx.lineTo(size/2, size/2 - 5);
lCtx.moveTo(size/2, size/2 + 5); lCtx.lineTo(size/2, size);
lCtx.moveTo(0, size/2); lCtx.lineTo(size/2 - 5, size/2);
lCtx.moveTo(size/2 + 5, size/2); lCtx.lineTo(size, size/2);
lCtx.stroke();
}
window.addEventListener("mousemove", (e) => {
if (!draggingLm || !coords[draggingLm]) return;
const p = getSVGCoords(e);
coords[draggingLm].x = p.x;
coords[draggingLm].y = p.y;
if ((draggingLm === "RULER_1" || draggingLm === "RULER_2") && coords.RULER_1 && coords.RULER_2) {
const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
if (dist > 1) {
pxPerMm = dist / 10.0;
calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm`;
}
}
updateLoupe(p, draggingLm);
renderAnalysis();
});
window.addEventListener("mouseup", () => {
if (draggingLm) {
draggingLm = null;
loupeBox.style.display = "none";
document.querySelectorAll(".landmark-handle").forEach(el => el.classList.remove("dragging"));
}
});
// Touch event handlers for mobile
function handleTouchMove(e) {
if (!draggingLm || !coords[draggingLm] || !e.touches[0]) return;
e.preventDefault();
const touch = e.touches[0];
const p = getSVGCoords(touch);
coords[draggingLm].x = p.x; coords[draggingLm].y = p.y;
if ((draggingLm === "RULER_1" || draggingLm === "RULER_2") && coords.RULER_1 && coords.RULER_2) {
const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
if (dist > 1) pxPerMm = dist / 10.0;
}
updateLoupe(p, draggingLm);
renderAnalysis();
}
window.addEventListener("touchmove", handleTouchMove, { passive: false });
window.addEventListener("touchend", () => {
if (draggingLm) {
draggingLm = null;
loupeBox.style.display = "none";
renderAnalysis();
}
});
// Clear Patient
document.getElementById("btn-next-patient").addEventListener("click", () => {
coords = {}; initialAiCoords = {}; latestMetrics = {};
t1Baseline = null; t2Baseline = null; t3Baseline = null;
selectedLm = null; cvmStage = "CS3";
highlightCvmButton("CS3");
updateSuperimpositionStatus();
document.getElementById("selected-lm-label").innerText = "None";
imgElem.src = "";
container.style.display = "none";
dropzone.style.display = "flex";
document.getElementById("file-input").value = "";
document.getElementById("pt-name").value = "";
document.getElementById("pt-chart").value = "";
setAutoDateTime();
document.getElementById("diag-headline").innerText = "Automated Diagnosis: Awaiting Tracing...";
document.getElementById("diag-sagittal").innerText = "-";
document.getElementById("diag-vertical").innerText = "-";
document.getElementById("diag-dental").innerText = "-";
document.getElementById("diag-soft").innerText = "-";
svgElem.innerHTML = "";
setMobileTab("tools");
notify("Patient Session Reset");
});
// =============================================================
// 6. Mathematical & Clinical Analysis Engine
// =============================================================
function getAngle(p1, v, p2) {
if (!p1 || !v || !p2) return null;
const v1 = { x: p1.x - v.x, y: p1.y - v.y };
const v2 = { x: p2.x - v.x, y: p2.y - v.y };
const dot = v1.x * v2.x + v1.y * v2.y;
const m1 = Math.hypot(v1.x, v1.y), m2 = Math.hypot(v2.x, v2.y);
return parseFloat((Math.acos(Math.max(-1, Math.min(1, dot / (m1 * m2 + 1e-7)))) * (180 / Math.PI)).toFixed(1));
}
function getLineAngle(p1, p2, p3, p4) {
if (!p1 || !p2 || !p3 || !p4) return null;
const v1 = { x: p2.x - p1.x, y: p2.y - p1.y };
const v2 = { x: p4.x - p3.x, y: p4.y - p3.y };
const dot = v1.x * v2.x + v1.y * v2.y;
const m1 = Math.hypot(v1.x, v1.y), m2 = Math.hypot(v2.x, v2.y);
let deg = (Math.acos(Math.max(-1, Math.min(1, dot / (m1 * m2 + 1e-7)))) * (180 / Math.PI));
if (deg > 90) deg = 180 - deg;
return parseFloat(deg.toFixed(1));
}
function getPerpDist(pt, l1, l2) {
if (!pt || !l1 || !l2 || !pxPerMm) return null;
const v = { x: l2.x - l1.x, y: l2.y - l1.y };
const len = Math.hypot(v.x, v.y);
if (len === 0) return null;
const cross = v.x * (pt.y - l1.y) - v.y * (pt.x - l1.x);
return parseFloat((cross / len / pxPerMm).toFixed(1));
}
function calculateWits(ptA, ptB, opP, opA) {
if (!ptA || !ptB || !opP || !opA || !pxPerMm) return null;
const vx = opA.x - opP.x, vy = opA.y - opP.y;
const len = Math.hypot(vx, vy);
if (len === 0) return null;
const ux = vx / len, uy = vy / len;
const tA = (ptA.x - opP.x) * ux + (ptA.y - opP.y) * uy;
const tB = (ptB.x - opP.x) * ux + (ptB.y - opP.y) * uy;
return { distMm: parseFloat(((tA - tB) / pxPerMm).toFixed(1)), ao: { x: opP.x + tA * ux, y: opP.y + tA * uy }, bo: { x: opP.x + tB * ux, y: opP.y + tB * uy } };
}
function evaluateCvmMorphology() {
if (!coords.C3_LL || !coords.C3_LR || !coords.C3_INF || !coords.C4_LL || !coords.C4_LR || !coords.C4_INF) return null;
const c3Concavity = Math.abs(getPerpDist(coords.C3_INF, coords.C3_LL, coords.C3_LR));
const c4Concavity = Math.abs(getPerpDist(coords.C4_INF, coords.C4_LL, coords.C4_LR));
const c3W = Math.hypot(coords.C3_LR.x - coords.C3_LL.x, coords.C3_LR.y - coords.C3_LL.y);
const c3H = Math.hypot(coords.C3_LL.x - coords.C3_UL.x, coords.C3_LL.y - coords.C3_UL.y);
const c3Ratio = parseFloat((c3W / (c3H + 1e-5)).toFixed(2));
let shape = "Horizontal Rectangular";
if (c3Ratio > 1.35) shape = "Trapezoid / Tapered";
else if (c3Ratio >= 0.92 && c3Ratio <= 1.12) shape = "Square";
else if (c3Ratio < 0.92) shape = "Vertical Rectangular";
return { c3Concavity, c4Concavity, c3Ratio, shape };
}
function getNormObj(id) {
return ABO_NORMS.find(x => x.id === id) || { norm: 0, sd: 1 };
}
function updateClinicalDiagnosis(m) {
if (m.ANB === null) return;
const anbN = getNormObj("ANB");
const snaN = getNormObj("SNA");
const snbN = getNormObj("SNB");
let skelClass = "Skeletal Class I";
if (m.ANB > anbN.norm + anbN.sd) skelClass = "Skeletal Class II";
else if (m.ANB < anbN.norm - anbN.sd) skelClass = "Skeletal Class III";
let jawNote = [];
if (m.SNA > snaN.norm + snaN.sd) jawNote.push("Maxillary Prognathism");
else if (m.SNA < snaN.norm - snaN.sd) jawNote.push("Maxillary Retrognathism");
if (m.SNB > snbN.norm + snbN.sd) jawNote.push("Mandibular Prognathism");
else if (m.SNB < snbN.norm - snbN.sd) jawNote.push("Mandibular Retrognathism");
const sagStr = jawNote.length > 0 ? `${skelClass} (${jawNote.join(", ")})` : `${skelClass} (Orthognathic Base)`;
const fmaN = getNormObj("FMA");
const snmpN = getNormObj("SNMP");
let vertClass = "Normodivergent";
if (m.FMA > fmaN.norm + fmaN.sd || m.SNMP > snmpN.norm + snmpN.sd) vertClass = "Hyperdivergent (High Angle)";
else if (m.FMA < fmaN.norm - fmaN.sd || m.SNMP < snmpN.norm - snmpN.sd) vertClass = "Hypodivergent (Low Angle)";
const u1N = getNormObj("U1SN");
const impaN = getNormObj("IMPA");
let u1Str = "Normal U1";
if (m.U1SN > u1N.norm + u1N.sd) u1Str = "Proclined U1";
else if (m.U1SN < u1N.norm - u1N.sd) u1Str = "Retroclined U1";
let l1Str = "Normal L1";
if (m.IMPA > impaN.norm + impaN.sd) l1Str = "Proclined L1";
else if (m.IMPA < impaN.norm - impaN.sd) l1Str = "Retroclined L1";
const dentStr = `${u1Str}, ${l1Str}`;
const llN = getNormObj("LL_E");
let softStr = "Balanced Lips";
if (m.LL_E > llN.norm + llN.sd) softStr = "Protrusive Lips";
else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";
const softAndCvm = `${softStr} | CVM: ${cvmStage}`;
const headline = `${skelClass} • ${vertClass} • ${dentStr} • [${cvmStage}]`;
latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
document.getElementById("diag-headline").innerText = headline;
document.getElementById("diag-sagittal").innerText = sagStr;
document.getElementById("diag-vertical").innerText = vertClass;
document.getElementById("diag-dental").innerText = dentStr;
document.getElementById("diag-soft").innerText = softAndCvm;
}
// =============================================================
// 7. Vector Rendering Engine & Tables
// =============================================================
function renderAnalysis() {
svgElem.innerHTML = "";
if (!coords.S) return;
function line(p1, p2, col, w = 2.5, dash = null) {
if (!p1 || !p2) return;
const l = document.createElementNS("http://www.w3.org/2000/svg", "line");
l.setAttribute("x1", p1.x); l.setAttribute("y1", p1.y);
l.setAttribute("x2", p2.x); l.setAttribute("y2", p2.y);
l.setAttribute("stroke", col);
l.setAttribute("stroke-width", w);
l.setAttribute("stroke-linecap", "round");
if (dash) l.setAttribute("stroke-dasharray", dash);
svgElem.appendChild(l);
}
const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
const cvmMorph = evaluateCvmMorphology();
// 1. Draw Longitudinal Superimpositions (T1, T2, T3)
const drawSuperLines = (alCoords, col, dash) => {
if (!alCoords) return;
line(alCoords.S, alCoords.N, col, 2.5, dash);
line(alCoords.N, alCoords.A, col, 2, dash);
line(alCoords.N, alCoords.B, col, 2, dash);
line(alCoords.Go, alCoords.Me, col, 2.5, dash);
line(alCoords.UIT, alCoords.UIA, col, 2, dash);
line(alCoords.LIT, alCoords.LIA, col, 2, dash);
};
if (focusMode === "SUPER" || focusMode === "ALL") {
if (t1Baseline) drawSuperLines(getAlignedCoordsForBaseline(t1Baseline), "#94a3b8", "4,3");
if (t2Baseline) drawSuperLines(getAlignedCoordsForBaseline(t2Baseline), "#3b82f6", "5,2");
if (t3Baseline) drawSuperLines(getAlignedCoordsForBaseline(t3Baseline), "#d946ef", "3,2");
}
// 2. Current Tracing Vectors
if (showLines) {
const isSuper = focusMode === "SUPER";
if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
line(coords.S, coords.N, isSuper ? "#f43f5e" : "#38bdf8", 3);
line(coords.N, coords.A, isSuper ? "#f43f5e" : "#4ade80", 2);
line(coords.N, coords.B, isSuper ? "#f43f5e" : "#4ade80", 2);
line(coords.Po, coords.Or, isSuper ? "#f43f5e" : "#fbbf24", 2.5);
line(coords.Go, coords.Me, isSuper ? "#f43f5e" : "#f43f5e", 3);
line(coords.UIT, coords.UIA, isSuper ? "#f43f5e" : "#2dd4bf", 2.5);
line(coords.LIT, coords.LIA, isSuper ? "#f43f5e" : "#d946ef", 2.5);
line(coords.Pn, coords.Pog_soft, isSuper ? "#f43f5e" : "#fb923c", 2);
}
if (focusMode === "MCNAMARA" || focusMode === "ALL") {
line(coords.Co, coords.A, "#38bdf8", 2.5);
line(coords.Co, coords.Gn, "#38bdf8", 2.5);
line(coords.ANS, coords.Me, "#ec4899", 2.5);
if (coords.N && coords.Po && coords.Or) {
const fhAngle = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
const perpAngle = fhAngle + Math.PI / 2;
const pLen = 180;
const nPerpEnd = { x: coords.N.x + Math.cos(perpAngle) * pLen, y: coords.N.y + Math.sin(perpAngle) * pLen };
line(coords.N, nPerpEnd, "#f59e0b", 2, "4,3");
}
}
if (focusMode === "TWEED" || focusMode === "ALL") {
line(coords.Po, coords.Or, "#fbbf24", 2.5);
line(coords.Go, coords.Me, "#f43f5e", 2.5);
line(coords.LIT, coords.LIA, "#d946ef", 2.5);
}
if (focusMode === "AIRWAY" || focusMode === "ALL") {
if (coords.P_Palate && coords.UPW) line(coords.P_Palate, coords.UPW, "#2dd4bf", 3);
if (coords.TB && coords.LPW) line(coords.TB, coords.LPW, "#2dd4bf", 3);
if (coords.PNS && coords.P_Palate) line(coords.PNS, coords.P_Palate, "#14b8a6", 1.5, "3,3");
}
if ((focusMode === "CVM" || focusMode === "ALL") && coords.C3_UL) {
// C2 Lower Border
if (coords.C2_LL && coords.C2_INF && coords.C2_LR) {
line(coords.C2_LL, coords.C2_INF, "#facc15", 2.5);
line(coords.C2_INF, coords.C2_LR, "#facc15", 2.5);
}
// C3 Contour
line(coords.C3_UL, coords.C3_UR, "#14b8a6", 2);
line(coords.C3_UR, coords.C3_LR, "#14b8a6", 2);
line(coords.C3_UL, coords.C3_LL, "#14b8a6", 2);
line(coords.C3_LL, coords.C3_INF, "#facc15", 2.5);
line(coords.C3_INF, coords.C3_LR, "#facc15", 2.5);
line(coords.C3_LL, coords.C3_LR, "#14b8a6", 1.2, "3,3");
// C4 Contour
line(coords.C4_UL, coords.C4_UR, "#14b8a6", 2);
line(coords.C4_UR, coords.C4_LR, "#14b8a6", 2);
line(coords.C4_UL, coords.C4_LL, "#14b8a6", 2);
line(coords.C4_LL, coords.C4_INF, "#facc15", 2.5);
line(coords.C4_INF, coords.C4_LR, "#facc15", 2.5);
line(coords.C4_LL, coords.C4_LR, "#14b8a6", 1.2, "3,3");
// Ramus Anterior Guide
if (coords.Ar && coords.R && coords.Go) {
line(coords.Ar, coords.R, "#64748b", 1.5, "4,3");
line(coords.R, coords.Go, "#64748b", 1.5, "4,3");
}
}
if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
line(coords.Ls, coords.Pog_soft, "#ec4899", 2.5);
line(coords.N, coords.Pog_soft, "#c084fc", 1.5, "4,4");
line(coords.N, coords.Pog, "#94a3b8", 1.5, "4,4");
}
if ((focusMode === "WITS" || focusMode === "ALL") && coords.OP_P && coords.OP_A) {
const dx = coords.OP_A.x - coords.OP_P.x, dy = coords.OP_A.y - coords.OP_P.y;
const extP = { x: coords.OP_P.x - dx * 0.35, y: coords.OP_P.y - dy * 0.35 };
const extA = { x: coords.OP_A.x + dx * 0.35, y: coords.OP_A.y + dy * 0.35 };
line(extP, extA, "#a855f7", 2.5);
if (wits) {
line(coords.A, wits.ao, "#a855f7", 2, "3,3");
line(coords.B, wits.bo, "#a855f7", 2, "3,3");
}
}
}
// 3. Ruler (10mm)
if (showRuler && coords.RULER_1 && coords.RULER_2) {
line(coords.RULER_1, coords.RULER_2, "#06b6d4", 2.5, "4,3");
["RULER_1", "RULER_2"].forEach((rKey, idx) => {
const pt = coords[rKey];
const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
c.setAttribute("r", 6.5); c.setAttribute("fill", "#06b6d4");
c.setAttribute("stroke", "#0f172a"); c.setAttribute("stroke-width", 2);
c.setAttribute("class", "landmark-handle");
const startDrag = (e) => { e.stopPropagation(); draggingLm = rKey; c.classList.add("dragging"); };
c.addEventListener("mousedown", startDrag);
c.addEventListener("touchstart", startDrag);
g.appendChild(c);
const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
t.setAttribute("x", pt.x + 10); t.setAttribute("y", pt.y + 4);
t.setAttribute("class", "landmark-text");
t.style.fill = "#22d3ee";
t.textContent = idx === 0 ? "0 mm" : "10 mm";
g.appendChild(t);
svgElem.appendChild(g);
});
}
// 4. HIPAA Privacy Mask
if (hipaaPrivacyMode && coords.N && coords.Or) {
const mask = document.createElementNS("http://www.w3.org/2000/svg", "rect");
const mLeft = Math.min(coords.N.x, coords.Or.x) - 40;
const mTop = Math.min(coords.N.y, coords.Or.y) - 35;
const mWidth = Math.max(120, Math.abs(coords.N.x - coords.Or.x) + 90);
mask.setAttribute("x", mLeft); mask.setAttribute("y", mTop);
mask.setAttribute("width", mWidth); mask.setAttribute("height", 65);
mask.setAttribute("fill", "#05070c");
mask.setAttribute("rx", "6");
svgElem.appendChild(mask);
}
// 5. Draw Landmark Dots
const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
if (showPoints) {
for (const [name, pt] of Object.entries(coords)) {
if (name === "RULER_1" || name === "RULER_2") continue;
if (!activeSet.has(name)) continue;
const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
c.setAttribute("r", selectedLm === name ? 7 : 5);
let handleColor = "#facc15";
if (name === "Sn") handleColor = "#ec4899";
if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
if (name === "Co" || name === "Gn" || name === "Ar" || name === "R" || name === "PNS") handleColor = "#38bdf8";
if (name === "P_Palate" || name === "UPW" || name === "TB" || name === "LPW") handleColor = "#2dd4bf";
if (name.startsWith("C2_") || name.startsWith("C3_") || name.startsWith("C4_")) handleColor = "#14b8a6";
if (selectedLm === name) handleColor = "#38bdf8";
c.setAttribute("fill", handleColor);
c.setAttribute("stroke", "#0f172a");
c.setAttribute("stroke-width", 2);
c.setAttribute("class", "landmark-handle");
const onStart = (e) => {
e.stopPropagation();
draggingLm = name; selectedLm = name;
document.getElementById("selected-lm-label").innerText = name;
c.classList.add("dragging");
updateLoupe(pt, name);
};
c.addEventListener("mousedown", onStart);
c.addEventListener("touchstart", onStart);
c.addEventListener("dblclick", (e) => {
e.stopPropagation();
if (initialAiCoords[name]) {
coords[name] = { ...initialAiCoords[name] };
notify(`Reset ${name} to AI position`);
renderAnalysis();
}
});
g.appendChild(c);
if (showLabels) {
const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
t.setAttribute("x", pt.x + 8); t.setAttribute("y", pt.y - 4);
t.setAttribute("class", "landmark-text");
t.textContent = name;
g.appendChild(t);
}
svgElem.appendChild(g);
}
}
// 6. Metrics Calculations
const sna = getAngle(coords.S, coords.N, coords.A);
const snb = getAngle(coords.S, coords.N, coords.B);
const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
const fma = getLineAngle(coords.Po, coords.Or, coords.Go, coords.Me);
const snmp = getLineAngle(coords.S, coords.N, coords.Go, coords.Me);
const impa = getLineAngle(coords.LIT, coords.LIA, coords.Go, coords.Me);
const u1sn = getLineAngle(coords.UIT, coords.UIA, coords.S, coords.N);
const u1na_deg = getLineAngle(coords.UIT, coords.UIA, coords.N, coords.A);
const u1na_mm = getPerpDist(coords.UIT, coords.N, coords.A);
const l1nb_deg = getLineAngle(coords.LIT, coords.LIA, coords.N, coords.B);
const l1nb_mm = getPerpDist(coords.LIT, coords.N, coords.B);
const iia = getLineAngle(coords.UIT, coords.UIA, coords.LIT, coords.LIA);
const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);
// Tweed Triangle: FMA + IMPA + FMIA = 180°
const fmia = (fma !== null && impa !== null) ? parseFloat((180.0 - (fma + impa)).toFixed(1)) : null;
// McNamara Analysis
let a_n_perp = null, pog_n_perp = null;
if (coords.N && coords.Po && coords.Or && coords.A && coords.Pog) {
const fhA = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
const pA = fhA + Math.PI / 2;
const nRef = { x: coords.N.x + Math.cos(pA) * 100, y: coords.N.y + Math.sin(pA) * 100 };
a_n_perp = getPerpDist(coords.A, coords.N, nRef);
pog_n_perp = getPerpDist(coords.Pog, coords.N, nRef);
}
const co_a = (coords.Co && coords.A && pxPerMm) ? parseFloat((Math.hypot(coords.A.x - coords.Co.x, coords.A.y - coords.Co.y) / pxPerMm).toFixed(1)) : null;
const co_gn = (coords.Co && coords.Gn && pxPerMm) ? parseFloat((Math.hypot(coords.Gn.x - coords.Co.x, coords.Gn.y - coords.Co.y) / pxPerMm).toFixed(1)) : null;
const mx_md_diff = (co_a !== null && co_gn !== null) ? parseFloat((co_gn - co_a).toFixed(1)) : null;
const lafh = (coords.ANS && coords.Me && pxPerMm) ? parseFloat((Math.hypot(coords.Me.x - coords.ANS.x, coords.Me.y - coords.ANS.y) / pxPerMm).toFixed(1)) : null;
// Pharyngeal Airway Dimensions
const ups = (coords.P_Palate && coords.UPW && pxPerMm) ? parseFloat((Math.hypot(coords.P_Palate.x - coords.UPW.x, coords.P_Palate.y - coords.UPW.y) / pxPerMm).toFixed(1)) : null;
const lps = (coords.TB && coords.LPW && pxPerMm) ? parseFloat((Math.hypot(coords.TB.x - coords.LPW.x, coords.TB.y - coords.LPW.y) / pxPerMm).toFixed(1)) : null;
// Holdaway
const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
const skel_conv = getPerpDist(coords.A, coords.N, coords.Pog);
const nose_prom = getPerpDist(coords.Pn, coords.Ls, coords.Pog_soft);
const sn_hline = getPerpDist(coords.Sn, coords.Ls, coords.Pog_soft);
const ll_hline = getPerpDist(coords.Li, coords.Ls, coords.Pog_soft);
const chin_thick = (coords.Pog && coords.Pog_soft && pxPerMm) ? parseFloat((Math.hypot(coords.Pog_soft.x - coords.Pog.x, coords.Pog_soft.y - coords.Pog.y) / pxPerMm).toFixed(1)) : null;
latestMetrics = {
SNA: sna, SNB: snb, ANB: anb, FMA: fma, SNMP: snmp, IMPA: impa,
U1SN: u1sn, U1NA_deg: u1na_deg, U1NA_mm: u1na_mm, L1NB_deg: l1nb_deg,
L1NB_mm: l1nb_mm, IIA: iia, UL_E: ul_e, LL_E: ll_e,
FMIA: fmia,
A_N_PERP: a_n_perp, POG_N_PERP: pog_n_perp, CO_A: co_a, CO_GN: co_gn,
MX_MD_DIFF: mx_md_diff, LAFH: lafh,
UPS: ups, LPS: lps,
WITS: wits ? wits.distMm : null,
H_ANGLE: h_angle, SKEL_CONV: skel_conv, NOSE_PROM: nose_prom,
SN_HLINE: sn_hline, LL_HLINE: ll_hline, CHIN_THICK: chin_thick
};
updateClinicalDiagnosis(latestMetrics);
populateAboTable(ABO_NORMS, latestMetrics);
populateTable("mcnamara-rows", MCNAMARA_NORMS, latestMetrics);
populateTable("tweed-rows", TWEED_NORMS, latestMetrics);
populateTable("holdaway-rows", HOLDAWAY_NORMS, latestMetrics);
populateWitsTable(latestMetrics.WITS);
populateAirwayTable(ups, lps);
populateCvmTable(cvmMorph);
}
function populateAboTable(normsList, valuesDict) {
const tbody = document.getElementById("abo-rows");
tbody.innerHTML = "";
normsList.forEach(m => {
const val = valuesDict[m.id];
let statusHtml = `<span class="pill pill-neutral">-</span>`;
let measuredText = "-", diffText = "-", diffColor = "var(--text-muted)";
let deltaT1Html = "";
if (val !== null && val !== undefined) {
measuredText = `${val.toFixed(1)}${m.unit}`;
const rawDiff = val - m.norm;
const isNormal = Math.abs(rawDiff) <= m.sd;
diffText = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
diffColor = isNormal ? "var(--status-green)" : "var(--status-red)";
statusHtml = isNormal ? `<span class="pill pill-normal">Normal</span>` : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High' : 'Low'}</span>`;
}
if (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[m.id] !== undefined) {
const dT1 = val - t1Baseline.metrics[m.id];
deltaT1Html = `<td style="color:#5eead4; font-weight:700;">${dT1 > 0 ? '+' : ''}${dT1.toFixed(1)}${m.unit}</td>`;
} else if (t1Baseline) { deltaT1Html = `<td>-</td>`; }
const tr = document.createElement("tr");
tr.innerHTML = `
<td><span class="metric-name">${m.name}</span></td>
<td><span class="metric-norm">${m.norm}${m.unit} ± ${m.sd}</span></td>
<td><span class="metric-val">${measuredText}</span></td>
<td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
${deltaT1Html}
<td>${statusHtml}</td>
`;
tbody.appendChild(tr);
});
}
function populateTable(elemId, normsList, valuesDict) {
const tbody = document.getElementById(elemId);
tbody.innerHTML = "";
normsList.forEach(m => {
const val = valuesDict[m.id];
let statusHtml = `<span class="pill pill-neutral">-</span>`;
let measuredText = "-", diffText = "-", diffColor = "var(--text-muted)";
if (val !== null && val !== undefined) {
measuredText = `${val.toFixed(1)}${m.unit}`;
const rawDiff = val - m.norm;
const isNormal = Math.abs(rawDiff) <= m.sd;
diffText = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
diffColor = isNormal ? "var(--status-green)" : "var(--status-red)";
statusHtml = isNormal ? `<span class="pill pill-normal">Normal</span>` : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High' : 'Low'}</span>`;
}
const tr = document.createElement("tr");
tr.innerHTML = `
<td><span class="metric-name">${m.name}</span></td>
<td><span class="metric-norm">${m.norm}${m.unit} ± ${m.sd}</span></td>
<td><span class="metric-val">${measuredText}</span></td>
<td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
<td>${statusHtml}</td>
`;
tbody.appendChild(tr);
});
}
function populateWitsTable(val) {
const tbody = document.getElementById("wits-rows");
tbody.innerHTML = "";
if (val === null || val === undefined) return;
const isNorm = val >= -1.0 && val <= 1.0;
const tr = document.createElement("tr");
tr.innerHTML = `
<td><span class="metric-name">Wits (AO to BO)</span></td>
<td><span class="metric-norm">0.0 ± 1.0 mm</span></td>
<td><span class="metric-val" style="color: #c084fc;">${val > 0 ? '+' : ''}${val.toFixed(1)} mm</span></td>
<td><span class="metric-diff" style="color: ${isNorm ? 'var(--status-green)' : 'var(--status-red)'};">${val > 0 ? '+' : ''}${val.toFixed(1)} mm</span></td>
<td><span class="pill ${isNorm ? 'pill-normal' : 'pill-deviated'}">${val > 1.0 ? 'Class II' : (val < -1.0 ? 'Class III' : 'Class I')}</span></td>
`;
tbody.appendChild(tr);
}
function populateAirwayTable(ups, lps) {
const tbody = document.getElementById("airway-rows");
tbody.innerHTML = "";
const makeRow = (name, val, normMin, normMax) => {
let stat = `<span class="pill pill-neutral">-</span>`;
let valStr = "-";
if (val !== null) {
valStr = `${val.toFixed(1)} mm`;
if (val < normMin) stat = `<span class="pill pill-deviated">Constricted</span>`;
else stat = `<span class="pill pill-normal">Patent / Normal</span>`;
}
return `<tr>
<td><span class="metric-name">${name}</span></td>
<td><span class="metric-norm">${normMin}–${normMax} mm</span></td>
<td><span class="metric-val" style="color:#2dd4bf;">${valStr}</span></td>
<td>${stat}</td>
</tr>`;
};
tbody.innerHTML += makeRow("Upper Pharyngeal Space (UPS)", ups, 15, 20);
tbody.innerHTML += makeRow("Lower Pharyngeal Space (LPS)", lps, 11, 13);
}
function populateCvmTable(morph) {
const tbody = document.getElementById("cvm-metric-rows");
if (!tbody) return;
tbody.innerHTML = "";
if (!morph) {
tbody.innerHTML = `<tr><td colspan="3" style="text-align:center; color:var(--text-muted); padding:8px;">Switch to CVM focus mode to inspect vertebral boundaries</td></tr>`;
return;
}
tbody.innerHTML = `
<tr>
<td><span class="metric-name">C3 Inferior Border Concavity</span></td>
<td><span class="metric-val">${morph.c3Concavity.toFixed(1)} mm</span></td>
<td>${morph.c3Concavity >= 0.8 ? '<span class="pill pill-normal">Concavity Present</span>' : '<span class="pill pill-neutral">Flat (<0.8mm)</span>'}</td>
</tr>
<tr>
<td><span class="metric-name">C4 Inferior Border Concavity</span></td>
<td><span class="metric-val">${morph.c4Concavity.toFixed(1)} mm</span></td>
<td>${morph.c4Concavity >= 0.8 ? '<span class="pill pill-normal">Concavity Present</span>' : '<span class="pill pill-neutral">Flat (<0.8mm)</span>'}</td>
</tr>
<tr>
<td><span class="metric-name">C3 Width-to-Height Ratio</span></td>
<td><span class="metric-val">${morph.c3Ratio}</span></td>
<td><span style="color:#5eead4; font-weight:600;">${morph.shape}</span></td>
</tr>
<tr>
<td><span class="metric-name">Assigned Maturation Stage</span></td>
<td colspan="2"><span class="metric-val" style="color:#2dd4bf;">${cvmStage}</span></td>
</tr>
`;
}
// =============================================================
// 8. 1-Page Letter Print Synchronization
// =============================================================
window.addEventListener("beforeprint", () => {
const rawName = document.getElementById("pt-name").value || "Patient";
const rawChart = document.getElementById("pt-chart").value || "MRN-N/A";
const dtStr = document.getElementById("pt-datetime").value || "";
const displayDt = dtStr ? dtStr.replace("T", " ") : new Date().toLocaleString();
document.getElementById("print-pt-name").innerText = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
document.getElementById("print-pt-mrn").innerText = hipaaPrivacyMode ? "ANON-001" : rawChart;
document.getElementById("print-pt-datetime").innerText = displayDt;
document.getElementById("print-ethnicity-tag").innerText = `ETHNICITY: ${ETHNICITY_DATABASE[activeEthnicity].label.split(' ')[0]}`;
// Mirror Cephalogram & Vector Overlay
document.getElementById("print-img").src = imgElem.src;
const printSvg = document.getElementById("print-svg");
printSvg.innerHTML = svgElem.innerHTML;
printSvg.setAttribute("viewBox", svgElem.getAttribute("viewBox") || "0 0 100 100");
// Mirror Diagnosis
document.getElementById("print-diag-headline").innerText = latestDiagnosis.headline;
document.getElementById("print-diag-sag").innerText = `Sagittal: ${latestDiagnosis.sagittal}`;
document.getElementById("print-diag-vert").innerText = `Vertical: ${latestDiagnosis.vertical}`;
document.getElementById("print-diag-dent").innerText = `Dental: ${latestDiagnosis.dental}`;
document.getElementById("print-diag-soft").innerText = `Soft & CVM: ${latestDiagnosis.soft}`;
// Populate Print ABO Table
const pAboBody = document.getElementById("print-abo-tbody");
pAboBody.innerHTML = "";
ABO_NORMS.forEach(m => {
const val = latestMetrics[m.id];
let diff = "-", stat = "-", diffClass = "";
if (val !== null && val !== undefined) {
const rawDiff = val - m.norm;
const isNorm = Math.abs(rawDiff) <= m.sd;
diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
diffClass = isNorm ? "diff-norm" : "diff-dev";
}
pAboBody.innerHTML += `<tr>
<td><strong>${m.name}</strong></td>
<td>${m.norm}${m.unit} ± ${m.sd}</td>
<td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
<td class="${diffClass}">${diff}</td>
<td>${stat}</td>
</tr>`;
});
// Populate Print McNamara & Tweed Table
const pMcBody = document.getElementById("print-mcnamara-tbody");
pMcBody.innerHTML = "";
const combinedSecondary = [...MCNAMARA_NORMS, ...TWEED_NORMS];
combinedSecondary.forEach(m => {
const val = latestMetrics[m.id];
let diff = "-", stat = "-", diffClass = "";
if (val !== null && val !== undefined) {
const rawDiff = val - m.norm;
const isNorm = Math.abs(rawDiff) <= m.sd;
diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
diffClass = isNorm ? "diff-norm" : "diff-dev";
}
pMcBody.innerHTML += `<tr>
<td><strong>${m.name}</strong></td>
<td>${m.norm}${m.unit} ± ${m.sd}</td>
<td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
<td class="${diffClass}">${diff}</td>
<td>${stat}</td>
</tr>`;
});
// Populate Print Holdaway Table
const pHoldBody = document.getElementById("print-holdaway-tbody");
pHoldBody.innerHTML = "";
HOLDAWAY_NORMS.forEach(m => {
const val = latestMetrics[m.id];
let diff = "-", stat = "-", diffClass = "";
if (val !== null && val !== undefined) {
const rawDiff = val - m.norm;
const isNorm = Math.abs(rawDiff) <= m.sd;
diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
diffClass = isNorm ? "diff-norm" : "diff-dev";
}
pHoldBody.innerHTML += `<tr>
<td><strong>${m.name}</strong></td>
<td>${m.norm}${m.unit} ± ${m.sd}</td>
<td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
<td class="${diffClass}">${diff}</td>
<td>${stat}</td>
</tr>`;
});
// Populate Print Wits, Airway & CVM Table
const pWitsBody = document.getElementById("print-wits-tbody");
pWitsBody.innerHTML = "";
if (latestMetrics.WITS !== null && latestMetrics.WITS !== undefined) {
const w = latestMetrics.WITS;
const stat = w > 1.0 ? "Class II" : (w < -1.0 ? "Class III" : "Class I");
pWitsBody.innerHTML += `<tr>
<td>Wits (AO-BO)</td><td>0.0 ± 1.0 mm</td>
<td><strong>${w > 0 ? '+' : ''}${w.toFixed(1)} mm</strong></td>
<td>${stat}</td>
</tr>`;
}
if (latestMetrics.UPS !== null) {
pWitsBody.innerHTML += `<tr>
<td>Upper Airway</td><td>15–20 mm</td>
<td><strong>${latestMetrics.UPS.toFixed(1)} mm</strong></td>
<td>${latestMetrics.UPS < 15 ? 'Constricted' : 'Patent'}</td>
</tr>`;
}
if (latestMetrics.LPS !== null) {
pWitsBody.innerHTML += `<tr>
<td>Lower Airway</td><td>11–13 mm</td>
<td><strong>${latestMetrics.LPS.toFixed(1)} mm</strong></td>
<td>${latestMetrics.LPS < 11 ? 'Constricted' : 'Patent'}</td>
</tr>`;
}
pWitsBody.innerHTML += `<tr>
<td>Skeletal CVM</td><td>Baccetti Stage</td>
<td><strong>${cvmStage}</strong></td>
<td>Active</td>
</tr>`;
});
// CSV Export
document.getElementById("btn-export-csv").addEventListener("click", () => {
if (!latestMetrics.SNA) { notify("Trace a cephalogram first."); return; }
const rawName = document.getElementById("pt-name").value || "Patient";
const ptName = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
const ptChart = hipaaPrivacyMode ? "ANON-001" : (document.getElementById("pt-chart").value || "N/A");
const ptDateTime = document.getElementById("pt-datetime").value || "";
let csv = "Patient,MRN,Date_Time,Diagnosis,Ethnicity,CVM_Stage,Category,Parameter,Norm_SD,Value,Diff,Unit,Status\n";
const addCategory = (cat, list) => {
list.forEach(m => {
const v = latestMetrics[m.id];
if (v === null || v === undefined) return;
const diff = (v - m.norm).toFixed(1);
const stat = Math.abs(v - m.norm) <= m.sd ? "Normal" : (v > m.norm ? "High" : "Low");
csv += `"${ptName}","${ptChart}","${ptDateTime}","${latestDiagnosis.headline}","${activeEthnicity}","${cvmStage}","${cat}","${m.name}","${m.norm} +/- ${m.sd}",${v.toFixed(1)},${diff > 0 ? '+' + diff : diff},"${m.unit}","${stat}"\n`;
});
};
addCategory("ABO", ABO_NORMS);
addCategory("McNamara", MCNAMARA_NORMS);
addCategory("Tweed", TWEED_NORMS);
addCategory("Holdaway", HOLDAWAY_NORMS);
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `Ceph_Analysis_${ptName.replace(/\s+/g, '_')}_${ptDateTime.slice(0, 10)}.csv`;
a.click();
notify("CSV Analysis Exported");
});
// Copy Note
document.getElementById("btn-copy-note").addEventListener("click", () => {
if (!latestMetrics.SNA) return;
const rawName = document.getElementById("pt-name").value || "Patient";
const ptName = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
const dt = document.getElementById("pt-datetime").value.replace("T", " ") || "";
const m = latestMetrics;
const note = [
`CEPHALOMETRIC DIAGNOSIS (${ptName} | ${dt}): ${latestDiagnosis.headline}`,
`• Sagittal: ${latestDiagnosis.sagittal} | SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°, Wits ${m.WITS} mm`,
`• Vertical & Tweed: ${latestDiagnosis.vertical} | FMA ${m.FMA}°, SNMP ${m.SNMP}°, FMIA ${m.FMIA}°`,
`• McNamara: A to N-Perp ${m.A_N_PERP}mm, Pog to N-Perp ${m.POG_N_PERP}mm, Co-A ${m.CO_A}mm, Co-Gn ${m.CO_GN}mm (Diff: ${m.MX_MD_DIFF}mm), LAFH ${m.LAFH}mm`,
`• Dental: ${latestDiagnosis.dental} | IMPA ${m.IMPA}°, U1-SN ${m.U1SN}°, U1-NA ${m.U1NA_deg}°/${m.U1NA_mm}mm, L1-NB ${m.L1NB_deg}°/${m.L1NB_mm}mm, IIA ${m.IIA}°`,
`• Soft Tissue & Airway: ${latestDiagnosis.soft} | Holdaway H-Angle ${m.H_ANGLE}°, Upper Airway ${m.UPS}mm, Lower Airway ${m.LPS}mm`
].join("\n");
const ta = document.createElement("textarea");
ta.value = note;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
notify("Clinical EMR Note Copied");
});
// Viewport Zoom
document.getElementById("btn-zoom-in").addEventListener("click", () => {
zoomLevel += 0.2; container.style.transform = `scale(${zoomLevel})`;
});
document.getElementById("btn-zoom-out").addEventListener("click", () => {
if (zoomLevel > 0.4) { zoomLevel -= 0.2; container.style.transform = `scale(${zoomLevel})`; }
});
document.getElementById("btn-zoom-reset").addEventListener("click", () => {
zoomLevel = 1.0; container.style.transform = "scale(1.0)";
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OrthoCeph Pro | Dual AI ABO, McNamara, Tweed & CVM Suite</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/ort.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
<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&display=swap" rel="stylesheet">
<style>
:root {
--bg-dark: #090d16;
--surface-dark: #111827;
--surface-card: #1e293b;
--surface-border: #334155;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--status-green: #10b981;
--status-red: #f43f5e;
--status-amber: #f59e0b;
--ruler-cyan: #06b6d4;
--teal-accent: #14b8a6;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--bg-dark);
color: var(--text-main);
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
-webkit-font-smoothing: antialiased;
}
/* Header Bar */
header {
background: var(--surface-dark);
border-bottom: 1px solid var(--surface-border);
height: 56px;
padding: 0 16px;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
z-index: 20;
}
.brand { display: flex; align-items: center; gap: 10px; }
.brand-icon {
width: 32px; height: 32px;
background: linear-gradient(135deg, #3b82f6, #1d4ed8);
border-radius: 8px; display: flex; align-items: center;
justify-content: center; font-weight: 800; font-size: 16px; color: white;
}
.brand-title { font-size: 14.5px; font-weight: 700; letter-spacing: -0.02em; }
.brand-subtitle { font-size: 9.5px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; }
.header-actions { display: flex; align-items: center; gap: 6px; }
#status-badge {
display: flex; align-items: center; gap: 6px; font-size: 11px;
font-weight: 600; background: rgba(30, 41, 59, 0.9);
border: 1px solid var(--surface-border); padding: 5px 10px;
border-radius: 20px; color: var(--text-muted);
}
#status-badge .indicator { width: 8px; height: 8px; border-radius: 50%; background-color: var(--status-amber); }
.btn {
background: var(--accent); color: white; border: none; padding: 6px 10px;
border-radius: 6px; font-weight: 600; font-size: 11px; cursor: pointer;
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
transition: all 0.15s ease; white-space: nowrap;
}
.btn svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2.2; }
.btn:hover:not(:disabled) { background: var(--accent-hover); }
.btn:disabled { background: #1e293b; color: #64748b; cursor: not-allowed; }
.btn-secondary { background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main); }
.btn-secondary:hover { background: #334155; }
.btn-danger { background: rgba(244, 63, 94, 0.15); border: 1px solid rgba(244, 63, 94, 0.4); color: #fda4af; }
.btn-danger:hover { background: rgba(244, 63, 94, 0.25); }
.btn-teal { background: rgba(20, 184, 166, 0.15); border: 1px solid rgba(20, 184, 166, 0.45); color: #5eead4; }
.btn-teal:hover { background: rgba(20, 184, 166, 0.28); }
/* Workspace */
.workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }
.sidebar {
width: 325px; background: var(--surface-dark);
border-right: 1px solid var(--surface-border);
padding: 12px; display: flex; flex-direction: column;
gap: 10px; overflow-y: auto; flex-shrink: 0;
}
.section-header {