Abddeus commited on
Commit
623c4cb
·
verified ·
1 Parent(s): 56a37dd

Delete index (1).html

Browse files
Files changed (1) hide show
  1. index (1).html +0 -849
index (1).html DELETED
@@ -1,849 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>OrthoCeph Pro v3.4 — Accuracy-First Cephalometrics</title>
7
- <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/ort.min.js"></script>
8
- <script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
9
- <style>
10
- :root{--bg:#0b1220;--panel:#111a2e;--panel2:#0f172a;--line:#1e293b;--txt:#e2e8f0;--mut:#94a3b8;--acc:#38bdf8;--grn:#34d399;--amb:#fbbf24;--red:#f87171;--pur:#c084fc}
11
- *{box-sizing:border-box;margin:0;padding:0}
12
- body{background:var(--bg);color:var(--txt);font-family:Segoe UI,system-ui,Arial,sans-serif;font-size:13px;overflow:hidden}
13
- header{display:flex;gap:10px;align-items:center;padding:8px 12px;background:var(--panel);border-bottom:1px solid var(--line);flex-wrap:wrap}
14
- header h1{font-size:16px;color:var(--acc);white-space:nowrap}
15
- header h1 small{color:var(--mut);font-size:11px;display:block;font-weight:400}
16
- header input{background:var(--panel2);border:1px solid var(--line);color:var(--txt);border-radius:6px;padding:6px 8px}
17
- #status-wrap{display:flex;align-items:center;gap:6px;margin-left:auto;font-weight:600}
18
- #status-ind{width:11px;height:11px;border-radius:50%;background:var(--amb)}
19
- main{display:grid;grid-template-columns:270px 1fr 400px;height:calc(100vh - 53px)}
20
- aside{background:var(--panel);overflow-y:auto;padding:10px}
21
- aside.left{border-right:1px solid var(--line)} aside.right{border-left:1px solid var(--line)}
22
- .sec{margin-bottom:14px}.sec h3{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--acc);margin-bottom:7px;border-bottom:1px solid var(--line);padding-bottom:4px}
23
- .btn{background:#1e3a5f;color:var(--txt);border:1px solid #2b4a73;border-radius:6px;padding:6px 9px;cursor:pointer;font-size:12px;margin:2px 0;width:100%;text-align:left}
24
- .btn:hover{background:#274b7a}.btn.primary{background:#0369a1;border-color:#0284c7;font-weight:700;text-align:center}
25
- .btn.warn{background:#713f12;border-color:#92400e}.btn:disabled{opacity:.45;cursor:not-allowed}
26
- .btnrow{display:flex;gap:5px}.btnrow .btn{text-align:center}
27
- input[type=file]{display:none}
28
- label{display:block;color:var(--mut);margin:5px 0 2px;font-size:11px}
29
- input[type=range]{width:100%}
30
- select{background:var(--panel2);color:var(--txt);border:1px solid var(--line);border-radius:6px;padding:5px;width:100%}
31
- #viewport-wrapper{position:relative;overflow:auto;background:#020617;display:flex;flex-direction:column;align-items:center;justify-content:flex-start}
32
- #viewport-container{position:relative;transform-origin:top center;margin:10px}
33
- #ceph-image{max-width:100%;display:block;user-select:none;-webkit-user-drag:none}
34
- #overlay-svg{position:absolute;top:0;left:0;overflow:visible}
35
- #empty-dropzone{position:absolute;inset:0;display:flex;flex-direction:column;gap:10px;align-items:center;justify-content:center;color:var(--mut);text-align:center;padding:30px}
36
- #empty-dropzone .big{font-size:44px}
37
- .drag-over{outline:3px dashed var(--acc);outline-offset:-8px}
38
- #loupe-box{position:fixed;right:420px;top:70px;width:154px;height:178px;background:#000;border:2px solid var(--acc);border-radius:8px;display:none;z-index:50;text-align:center}
39
- #loupe-label{color:var(--acc);font-weight:700;font-size:12px;padding:2px}
40
- table{width:100%;border-collapse:collapse;font-size:12px}
41
- th,td{padding:4px 5px;border-bottom:1px solid var(--line);text-align:right}
42
- th:first-child,td:first-child{text-align:left}
43
- th{color:var(--mut);font-weight:600}
44
- .st-Normal{color:var(--grn)}.st-High{color:var(--red)}.st-Low{color:var(--amb)}.st-na{color:var(--mut)}
45
- .badge{font-size:9px;padding:1px 4px;border-radius:4px;font-weight:700;vertical-align:middle}
46
- .b-est{background:#581c87;color:#e9d5ff}.b-unc{background:#713f12;color:#fde68a}.b-rev{background:#422006;color:#fcd34d}
47
- .tabs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px}
48
- .tab{background:var(--panel2);border:1px solid var(--line);color:var(--mut);border-radius:14px;padding:4px 10px;cursor:pointer;font-size:11px}
49
- .tab.active{background:#0369a1;color:#fff;border-color:#0284c7}
50
- .lm-row{display:flex;align-items:center;gap:6px;padding:3px 5px;border-radius:5px;cursor:pointer}
51
- .lm-row:hover{background:#1e293b}.lm-row.sel{background:#164e63}
52
- .lm-dot{width:9px;height:9px;border-radius:50%;flex:none}
53
- .lm-row .nm{flex:1}.lm-row .full{color:var(--mut);font-size:10px;display:block}
54
- .lm-row .vf{color:var(--grn);font-weight:700}
55
- .lm-row .mv{color:var(--mut);font-size:10px}
56
- #progress-wrap{background:var(--panel2);border-radius:6px;height:16px;position:relative;overflow:hidden;border:1px solid var(--line)}
57
- #progress-bar{background:#059669;height:100%;width:0%}
58
- #progress-txt{position:absolute;inset:0;text-align:center;font-size:11px;line-height:16px;font-weight:700}
59
- .diag{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:8px;line-height:1.5}
60
- .diag b{color:var(--acc)}
61
- .kbd{background:#1e293b;border:1px solid #334155;border-radius:3px;padding:0 4px;font-size:10px}
62
- .note{color:var(--mut);font-size:11px;line-height:1.45}
63
- .lm-handle{cursor:grab}.lm-handle.dragging{cursor:grabbing}
64
- #place-banner{display:none;background:#7c2d12;color:#ffedd5;padding:7px 10px;border-radius:6px;margin-bottom:8px;line-height:1.4}
65
- #print-report{display:none}
66
- @media print{ header,main{display:none!important} body{overflow:visible;background:#fff}
67
- #print-report{display:block!important;color:#000;font-size:12px;font-family:Georgia,serif}
68
- #print-report h1{font-size:17px;margin-bottom:4px} #print-report h2{font-size:13px;margin:13px 0 5px;border-bottom:2px solid #000;padding-bottom:2px}
69
- #print-report table{width:100%;border-collapse:collapse;font-size:11.5px}
70
- #print-report th,#print-report td{border:1px solid #999;padding:3px 5px;text-align:right;color:#000}
71
- #print-report th:first-child,#print-report td:first-child{text-align:left}
72
- .pr-film{position:relative;width:100%;max-width:620px;margin:10px auto}
73
- .pr-film img{width:100%;display:block}
74
- .pr-film svg{position:absolute;top:0;left:0;width:100%;height:100%}
75
- #print-report svg text{fill:#000;stroke:none;font-weight:700}
76
- #print-report svg line{stroke:#555}
77
- .pr-diag{border:1.5px solid #000;padding:7px 9px;margin:8px 0;line-height:1.55}
78
- .pr-meta{color:#222;line-height:1.5}
79
- .pr-foot{margin-top:12px;font-size:10px;color:#444;border-top:1px solid #999;padding-top:5px} }
80
- #overlay-svg{touch-action:none}
81
- .lm-handle{touch-action:none}
82
- #nudge-bar{display:none;width:100%;background:var(--panel);border-top:1px solid var(--line);padding:7px 8px;gap:6px;align-items:center;justify-content:center;flex-wrap:wrap}
83
- #nudge-bar.show{display:flex}
84
- #nudge-bar .nb-name{font-weight:700;color:var(--acc);min-width:110px;text-align:center}
85
- #nudge-bar button{background:#1e3a5f;color:var(--txt);border:1px solid #2b4a73;border-radius:8px;padding:9px 13px;font-size:15px;cursor:pointer;min-width:46px}
86
- #nudge-bar button:active{background:#0369a1}
87
- #nudge-bar button.vf{background:#065f46;border-color:#059669;font-size:13px;font-weight:700}
88
- #nudge-bar button.nx{background:#713f12;border-color:#92400e;font-size:13px;font-weight:700}
89
- @media (max-width:1100px){ body{overflow:auto} main{display:flex;flex-direction:column;height:auto}
90
- #viewport-wrapper{order:-1;position:sticky;top:0;z-index:40;min-height:52vh;max-height:62vh;width:100%;box-shadow:0 6px 16px rgba(0,0,0,.55)}
91
- aside.left,aside.right{border:none;width:100%}
92
- #ceph-image{width:100%}
93
- #loupe-box{right:8px;top:auto;bottom:8px;position:fixed}
94
- header input{flex:1;min-width:110px} }
95
- </style>
96
- </head>
97
- <body>
98
- <header>
99
- <h1>🦷 OrthoCeph Pro v3.4<small>Accuracy-first • AI proposes, you verify • No fake numbers</small></h1>
100
- <input id="pt-name" placeholder="Patient name" style="width:150px">
101
- <input id="pt-chart" placeholder="Chart #" style="width:90px">
102
- <input id="pt-date" type="date">
103
- <div id="status-wrap"><span id="status-ind"></span><span id="status-txt">Loading AI model…</span></div>
104
- </header>
105
- <main>
106
- <aside class="left">
107
- <div class="sec"><h3>1 · Film</h3>
108
- <label class="btn primary" for="file-input" style="text-align:center">📂 Upload Ceph (JPG / PNG / DICOM)</label>
109
- <input type="file" id="file-input" accept=".jpg,.jpeg,.png,.dcm">
110
- <label class="btn" for="json-input" style="text-align:center">Open Saved Record (JSON)</label>
111
- <input type="file" id="json-input" accept=".json">
112
- <div class="btnrow"><button class="btn" id="btn-bright">Brightness / Contrast</button></div>
113
- <div id="filter-box" style="display:none">
114
- <label>Brightness</label><input type="range" id="brightness" min="0.4" max="2" step="0.05" value="1">
115
- <label>Contrast</label><input type="range" id="contrast" min="0.4" max="2.5" step="0.05" value="1">
116
- <label style="display:flex;gap:6px;align-items:center"><input type="checkbox" id="invert" style="width:auto"> Invert</label>
117
- <button class="btn" id="reset-filters">Reset filters</button>
118
- </div>
119
- <div class="btnrow">
120
- <button class="btn" id="btn-zoom-out">−</button><button class="btn" id="btn-zoom-reset">Zoom 100%</button><button class="btn" id="btn-zoom-in">+</button>
121
- </div>
122
- </div>
123
- <div class="sec"><h3>2 · Calibration (required for mm)</h3>
124
- <div id="cal-status" class="note" style="color:var(--amb)">⚠ UNCALIBRATED — angles valid, mm values are provisional.</div>
125
- <button class="btn" id="btn-cal">📐 Place 10 mm Ruler</button>
126
- <p class="note">Click the 0 mm mark, then the 10 mm mark on the ruler in the film — or drag the cyan ruler dots onto two ticks exactly 10 mm apart (zoom in first). <b>The moment the 2nd click lands, every mm value recalculates automatically</b> — no re-trace, nothing else to press, and the points do not move. Angles are unaffected. Redo it for each new film. DICOM spacing is only a starting value — magnification still needs the ruler.</p>
127
- </div>
128
- <div class="sec"><h3>3 · Trace</h3>
129
- <button class="btn primary" id="btn-autotrace">🤖 Run AI Auto-Trace</button>
130
- <button class="btn" id="btn-manual">✍️ Guided Manual Placement</button>
131
- <label style="display:flex;gap:6px;align-items:flex-start;color:var(--txt);font-size:12px;line-height:1.4"><input type="checkbox" id="tta-toggle" checked style="width:auto;margin-top:2px"> <span><b>Steady mode (TTA):</b> 2 AI passes — normal + mirrored — averaged. Disagreement between passes lowers that point's confidence. Slower, steadier.</span></label>
132
- <div style="border:1px solid var(--line);border-radius:8px;padding:8px;margin-top:8px">
133
- <b style="font-size:12px">Engine B — HRNet-W48 second opinion (optional)</b>
134
- <p class="note" style="margin:4px 0">A second, larger AI whose own recorded validation is MRE ≈1.10 mm / 87.6% within 2 mm. Its channel order was verified landmark-by-landmark against Engine A on real films before being wired in. When loaded, Auto-Trace <b>averages both engines</b> per landmark and drops confidence where they disagree (shown as A↔B Δ). Engine B is slower — expect a longer trace. ~63 MB one-time download; the browser caches it.</p>
135
- <input id="engineb-url" style="width:100%;background:var(--panel2);border:1px solid var(--line);color:var(--txt);border-radius:6px;padding:6px" placeholder="Engine B model URL (.onnx)">
136
- <button class="btn" id="btn-engineb-url">⬇ Load Engine B from URL</button>
137
- <button class="btn" id="btn-engineb-file">📁 Load Engine B from a file</button>
138
- <input type="file" id="engineb-file" accept=".onnx" style="display:none">
139
- <label style="display:flex;gap:6px;align-items:flex-start;color:var(--txt);font-size:12px;line-height:1.4;margin-top:6px"><input type="checkbox" id="ensemble-toggle" checked style="width:auto;margin-top:2px"> <span><b>Ensemble:</b> average Engine A + Engine B on Auto-Trace</span></label>
140
- <p id="engineb-detail" class="note" style="margin:4px 0 0"></p>
141
- </div>
142
- <button class="btn" id="btn-review">🔍 Review Queue (worst first)</button>
143
- <p id="model-detail" class="note" style="color:var(--red)"></p>
144
- <button class="btn" id="btn-retrace-all">Reset All to AI</button>
145
- <button class="btn" id="btn-reset-single">Reset Selected to AI</button>
146
- <div id="place-banner"></div>
147
- <p class="note">Drag points on the film. Select a point, then: <span class="kbd">←→↑↓</span> nudge 0.5 px · <span class="kbd">Shift</span>+arrows 0.1 px · <span class="kbd">V</span> mark verified · <span class="kbd">Ctrl+Z</span> undo · <span class="kbd">Space</span> hold to peek at clean film.</p>
148
- </div>
149
- <div class="sec"><h3>Verification</h3>
150
- <div id="progress-wrap"><div id="progress-bar"></div><div id="progress-txt">0 / 0 verified</div></div>
151
- <p class="note" style="margin-top:5px">Selected: <b id="selected-lm-label">None</b></p>
152
- <button class="btn" id="btn-verify-sel">✓ Mark Selected Verified (V)</button>
153
- <button class="btn" id="btn-verify-all-conf">✓✓ Verify All High-Confidence AI Points</button>
154
- </div>
155
- <div class="sec"><h3>Landmarks</h3>
156
- <input id="lm-search" placeholder="Search landmarks…" style="width:100%;background:var(--panel2);border:1px solid var(--line);color:var(--txt);border-radius:6px;padding:6px">
157
- <div id="lm-list" style="margin-top:6px"></div>
158
- <p class="note">Dot = confidence: <span style="color:var(--grn)">● high</span> <span style="color:var(--amb)">● medium</span> <span style="color:var(--red)">● low</span> <span style="color:var(--pur)">● estimate — place/verify manually</span>. “moved” = how far you moved it from AI, in mm.</p>
159
- </div>
160
- </aside>
161
-
162
- <section id="viewport-wrapper">
163
- <div id="empty-dropzone"><div class="big">🦷</div><div><b>Drop a lateral ceph here</b><br>JPG / PNG / uncompressed DICOM.</div><label class="btn primary" for="file-input" style="text-align:center;width:auto;padding:10px 22px;font-size:14px">📂 Upload Ceph</label><div>Workflow: Upload → Calibrate ruler → AI trace → Review Queue → Verify → Export.</div></div>
164
- <div id="viewport-container" style="display:none">
165
- <img id="ceph-image" alt="cephalogram">
166
- <svg id="overlay-svg"></svg>
167
- </div>
168
- <div id="loupe-box"><div id="loupe-label">—</div><canvas id="loupe-canvas" width="150" height="150"></canvas></div>
169
- <div id="nudge-bar"><span class="nb-name" id="nb-name">No point selected</span>
170
- <button data-dx="0" data-dy="-1" title="Nudge up">▲</button>
171
- <button data-dx="-1" data-dy="0" title="Nudge left">◀</button>
172
- <button data-dx="1" data-dy="0" title="Nudge right">▶</button>
173
- <button data-dx="0" data-dy="1" title="Nudge down">▼</button>
174
- <button id="nb-step" title="Toggle nudge step">Step: 1px</button>
175
- <button class="vf" id="nb-verify">✓ Verify</button>
176
- <button class="nx" id="nb-next">Next unverified →</button>
177
- </div>
178
- </section>
179
-
180
- <aside class="right">
181
- <div class="sec"><h3>Diagnosis (auto, from verified math)</h3>
182
- <div class="diag" id="diag-box"><b id="diag-headline">Awaiting tracing…</b><br>
183
- Sagittal: <span id="diag-sagittal">-</span><br>Vertical: <span id="diag-vertical">-</span><br>
184
- Dental: <span id="diag-dental">-</span><br>Soft tissue: <span id="diag-soft">-</span></div>
185
- </div>
186
- <div class="sec"><h3>Analyses</h3>
187
- <div class="tabs" id="analysis-tabs"></div>
188
- <div id="analysis-tables"></div>
189
- <p class="note" style="margin-top:6px">— = a required landmark is missing, the number is <b>not</b> guessed. <span class="badge b-est">EST</span> uses an unverified estimate landmark. <span class="badge b-unc">UNCAL</span> mm value before ruler calibration.</p>
190
- </div>
191
- <div class="sec"><h3>Superimposition (T1 / T2)</h3>
192
- <button class="btn" id="btn-lock-t1">🔒 Lock Current as T1</button>
193
- <label>Registration</label>
194
- <select id="super-mode"><option value="CRANIAL">Cranial Base (S–N at S)</option><option value="MAXILLARY">Maxillary (Palatal Plane at PNS)</option><option value="MANDIBULAR">Mandibular (Me–Go at Me)</option></select>
195
- <div id="super-status" class="note" style="margin-top:5px">No T1 baseline locked.</div>
196
- <button class="btn" id="btn-clear-t1">Clear T1</button>
197
- </div>
198
- <div class="sec"><h3>Export</h3>
199
- <button class="btn primary" id="btn-save-json">💾 Save Record (JSON — incl. AI vs final + confidence)</button>
200
- <button class="btn" id="btn-export-csv">📊 Export CSV</button>
201
- <button class="btn" id="btn-copy-note">📋 Copy Clinical Note</button>
202
- <button class="btn" id="btn-print">🖨 Print Report</button>
203
- <button class="btn warn" id="btn-next-patient">⏭ Next Patient (clears everything)</button>
204
- <p class="note">The JSON is your validation dataset: it stores AI position, your final position, confidence and verified status per landmark. Send me these files and I can measure the AI's real error on your films, landmark by landmark.</p>
205
- </div>
206
- <div class="sec"><h3>View</h3>
207
- <div class="btnrow"><button class="btn" id="tog-lines">Lines: ON</button><button class="btn" id="tog-points">Dots: ON</button><button class="btn" id="tog-labels">Names: ON</button></div>
208
- <div class="btnrow"><button class="btn" id="tog-trace">Tracing outline: ON</button></div>
209
- </div>
210
- </aside>
211
- </main>
212
- <div id="print-report"></div>
213
- <script>
214
- "use strict";
215
- /* ============================================================
216
- OrthoCeph Pro v3.4 — accuracy-first rebuild
217
- Rules enforced in code:
218
- 1. No measurement is computed from missing landmarks (no guessing,
219
- no fabricated occlusal plane like v2.3).
220
- 2. mm values require calibration; otherwise they are flagged UNCAL.
221
- 3. Signed distances are anatomy-based (anterior-positive), identical
222
- for left- and right-facing films.
223
- 4. Every AI landmark carries a confidence score; hard/low-confidence
224
- points are queued for human review first.
225
- 5. AI vs final positions + verified flags are saved in the JSON —
226
- that file IS the validation dataset.
227
- ============================================================ */
228
- const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.int8.onnx";
229
-
230
- /* Landmark catalogue.
231
- model: cepha29 channel index verified in v2.3 map, or null = manual/estimate.
232
- tier: 1 easy, 2 medium, 3 hard (literature: larger mean radial error) */
233
- const LANDMARKS = {
234
- S: {full:"Sella", model:23, tier:1, def:"Center of sella turcica."},
235
- N: {full:"Nasion", model:14, tier:1, def:"Most anterior point of frontonasal suture."},
236
- Po: {full:"Porion", model:19, tier:3, def:"Most superior point of external auditory meatus."},
237
- Or: {full:"Orbitale", model:16, tier:3, def:"Most inferior point of orbital rim."},
238
- ANS: {full:"Anterior Nasal Spine", model:1, tier:1, def:"Tip of anterior nasal spine."},
239
- PNS: {full:"Posterior Nasal Spine", model:17, tier:2, def:"Tip of posterior nasal spine (model ch 17, confirmed from the official model card)."},
240
- A: {full:"A-Point", model:0, tier:2, def:"Deepest point on maxillary alveolar concavity."},
241
- B: {full:"B-Point", model:3, tier:2, def:"Deepest point on mandibular alveolar concavity."},
242
- Pog: {full:"Pogonion", model:20, tier:2, def:"Most anterior point of bony chin."},
243
- Gn: {full:"Gnathion", model:5, tier:2, def:"Most antero-inferior point of chin."},
244
- Me: {full:"Menton", model:13, tier:1, def:"Most inferior point of symphysis."},
245
- Go: {full:"Gonion", model:6, tier:3, def:"Most postero-inferior point of mandibular angle (bisector construction)."},
246
- UIT: {full:"U1 Incisal Tip", model:26, tier:1, def:"Incisal edge of maxillary central incisor."},
247
- UIA: {full:"U1 Apex", model:25, tier:3, def:"Root apex of maxillary central incisor."},
248
- LIT: {full:"L1 Incisal Tip", model:8, tier:1, def:"Incisal edge of mandibular central incisor."},
249
- LIA: {full:"L1 Apex", model:7, tier:3, def:"Root apex of mandibular central incisor."},
250
- Pn: {full:"Pronasale (nose tip)", model:18, tier:1, def:"Most anterior point of nose."},
251
- Sn: {full:"Subnasale", model:24, tier:1, def:"Junction of columella and upper lip."},
252
- Ls: {full:"Labrale Superius", model:12, tier:2, def:"Most anterior point of upper lip."},
253
- Li: {full:"Labrale Inferius", model:11, tier:2, def:"Most anterior point of lower lip."},
254
- PogS:{full:"Soft Pogonion", model:21, tier:2, def:"Most anterior point of soft-tissue chin."},
255
- Co: {full:"Condylion", model:4, tier:3, def:"Most postero-superior point of mandibular condyle. Model-predicted (ch 4) but HARD — always verify."},
256
- Ar: {full:"Articulare", model:2, tier:3, def:"Intersection of posterior border of ramus and cranial base. Model-predicted (ch 2), hard — verify."},
257
- Ba: {full:"Basion", model:null, tier:2, def:"Most postero-inferior point of clivus. MANUAL."},
258
- Pt: {full:"Pterygoid Point", model:null, tier:3, def:"Most postero-superior point of pterygomaxillary fissure. MANUAL."},
259
- D: {full:"D-Point (SND)", model:null, tier:2, def:"Center of bony symphysis. MANUAL."},
260
- U6T: {full:"U6 Mesial Cusp", model:27, tier:2, def:"Mesial cusp of upper first molar (model UMT, ch 27). Required for a real occlusal plane and Wits."},
261
- L6T: {full:"L6 Mesial Cusp", model:9, tier:2, def:"Mesial cusp of lower first molar (model LMT, ch 9). Required for Wits."},
262
- NS: {full:"Soft Nasion", model:15, tier:2, def:"Soft-tissue nasion (model N', ch 15)."},
263
- MeS: {full:"Soft Menton", model:null, tier:2, def:"Most inferior soft-tissue point of chin. MANUAL."}
264
- };
265
- const ABO_REQUIRED = ["S","N","A","B","Me","Go","UIT","UIA","LIT","LIA","U6T","L6T","Pn","PogS"];
266
-
267
- /* ==================== ENGINE START ====================
268
- Pure geometry + measurement engine. No DOM access in this block.
269
- coords: {CODE:{x,y}} in image pixels. pxPerMm converts to mm.
270
- Every function returns null when a required point is missing. */
271
- function _p(c,k){const v=c&&c[k];return (v&&isFinite(v.x)&&isFinite(v.y))?v:null;}
272
- function _dist(a,b){return Math.hypot(a.x-b.x,a.y-b.y);}
273
- function angleAt(p1,v,p2){ if(!p1||!v||!p2)return null;
274
- const a={x:p1.x-v.x,y:p1.y-v.y},b={x:p2.x-v.x,y:p2.y-v.y};
275
- const m=Math.hypot(a.x,a.y)*Math.hypot(b.x,b.y); if(!m)return null;
276
- return Math.acos(Math.max(-1,Math.min(1,(a.x*b.x+a.y*b.y)/m)))*180/Math.PI; }
277
- function lineIntersect(a1,a2,b1,b2){ if(!a1||!a2||!b1||!b2)return null;
278
- const d=(a2.x-a1.x)*(b2.y-b1.y)-(a2.y-a1.y)*(b2.x-b1.x); if(Math.abs(d)<1e-9)return null;
279
- const t=((b1.x-a1.x)*(b2.y-b1.y)-(b1.y-a1.y)*(b2.x-b1.x))/d;
280
- return {x:a1.x+t*(a2.x-a1.x), y:a1.y+t*(a2.y-a1.y)}; }
281
- /* Angle between two lines at their intersection, rays toward r1 side of line1 and r2 side of line2.
282
- Used for plane/incisor angles so the CLINICAL (interior/posterior) angle is returned, not a folded acute. */
283
- function planeAngle(l1a,l1b,r1,l2a,l2b,r2){ const X=lineIntersect(l1a,l1b,l2a,l2b); if(!X)return null; return angleAt(r1,X,r2); }
284
- function planeAngleAcute(a1,a2,b1,b2){ if(!a1||!a2||!b1||!b2)return null;
285
- const v1={x:a2.x-a1.x,y:a2.y-a1.y},v2={x:b2.x-b1.x,y:b2.y-b1.y};
286
- const m=Math.hypot(v1.x,v1.y)*Math.hypot(v2.x,v2.y); if(!m)return null;
287
- return Math.acos(Math.min(1,Math.abs(v1.x*v2.x+v1.y*v2.y)/m))*180/Math.PI; }
288
- function faceDir(c){ const s=_p(c,"S"),n=_p(c,"N"); if(!s||!n)return 1; return n.x>=s.x?1:-1; }
289
- /* Signed perpendicular distance in mm. Sign: + = point lies ANTERIOR to the line, − = posterior.
290
- Independent of image facing because anterior is derived from S→N. */
291
- function signedPerpMm(c,pt,a,b,ppm){ pt=_p(c,pt);a=_p(c,a);b=_p(c,b); if(!pt||!a||!b||!ppm)return null;
292
- const vx=b.x-a.x, vy=b.y-a.y, len=Math.hypot(vx,vy); if(!len)return null;
293
- const t=((pt.x-a.x)*vx+(pt.y-a.y)*vy)/(len*len);
294
- const proj={x:a.x+t*vx,y:a.y+t*vy};
295
- const px=pt.x-proj.x, py=pt.y-proj.y, mag=Math.hypot(px,py)/ppm;
296
- if(mag<1e-9)return 0;
297
- const ant={x:faceDir(c),y:0}; const s=Math.sign(px*ant.x+py*ant.y);
298
- return (s===0?1:s)*mag; }
299
- function distMm(c,k1,k2,ppm){ const a=_p(c,k1),b=_p(c,k2); if(!a||!b||!ppm)return null; return _dist(a,b)/ppm; }
300
- /* Functional occlusal plane points: anterior = midpoint of incisor tips, posterior = midpoint of molar cusps. */
301
- function occlusalPoints(c){ const uit=_p(c,"UIT"),lit=_p(c,"LIT"),u6=_p(c,"U6T"),l6=_p(c,"L6T");
302
- if(!uit||!lit||!u6||!l6)return null;
303
- return {ant:{x:(uit.x+lit.x)/2,y:(uit.y+lit.y)/2}, post:{x:(u6.x+l6.x)/2,y:(u6.y+l6.y)/2}}; }
304
- function projectOnto(pt,o,u){ return (pt.x-o.x)*u.x+(pt.y-o.y)*u.y; }
305
-
306
- const MEASURES = [
307
- /* ---- ABO FOCUS ---- */
308
- {id:"SNA", an:"ABO", name:"SNA", norm:82, sd:2, unit:"°", req:["S","N","A"], f:c=>angleAt(_p(c,"S"),_p(c,"N"),_p(c,"A"))},
309
- {id:"SNB", an:"ABO", name:"SNB", norm:80, sd:2, unit:"°", req:["S","N","B"], f:c=>angleAt(_p(c,"S"),_p(c,"N"),_p(c,"B"))},
310
- {id:"ANB", an:"ABO", name:"ANB", norm:2, sd:2, unit:"°", req:["S","N","A","B"], f:c=>{const a=angleAt(_p(c,"S"),_p(c,"N"),_p(c,"A")),b=angleAt(_p(c,"S"),_p(c,"N"),_p(c,"B"));return (a==null||b==null)?null:a-b;}},
311
- {id:"WITS", an:"ABO", name:"Wits Appraisal", norm:0, sd:1, unit:"mm", req:["A","B","UIT","LIT","U6T","L6T"], f:(c,ppm)=>{const op=occlusalPoints(c);const A=_p(c,"A"),B=_p(c,"B");if(!op||!A||!B||!ppm)return null;const v={x:op.ant.x-op.post.x,y:op.ant.y-op.post.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const u={x:v.x/L,y:v.y/L};return (projectOnto(A,op.post,u)-projectOnto(B,op.post,u))/ppm;}},
312
- {id:"SNGOGN", an:"ABO", name:"SN–GoGn", norm:32, sd:5, unit:"°", req:["S","N","Go","Gn"], f:c=>planeAngle(_p(c,"S"),_p(c,"N"),_p(c,"N"),_p(c,"Go"),_p(c,"Gn"),_p(c,"Gn"))},
313
- {id:"FMA", an:"ABO", name:"FMA (FH–MP)", norm:25, sd:4, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"),_p(c,"Me"))},
314
- {id:"IMPA", an:"ABO", name:"IMPA (L1–MP)", norm:90, sd:5, unit:"°", req:["LIT","LIA","Go","Me"], f:c=>planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Go"),_p(c,"Go"),_p(c,"Me"),_p(c,"LIT"))},
315
- {id:"U1SN", an:"ABO", name:"U1–SN", norm:102, sd:5, unit:"°", req:["UIT","UIA","S","N"], f:c=>planeAngle(_p(c,"UIT"),_p(c,"UIA"),_p(c,"S"),_p(c,"S"),_p(c,"N"),_p(c,"UIT"))},
316
- {id:"U1NA_D", an:"ABO", name:"U1–NA Angle", norm:22, sd:4, unit:"°", req:["UIT","UIA","N","A"], f:c=>planeAngleAcute(_p(c,"UIT"),_p(c,"UIA"),_p(c,"N"),_p(c,"A"))},
317
- {id:"U1NA_M", an:"ABO", name:"U1–NA", norm:4, sd:2, unit:"mm", req:["UIT","N","A"], f:(c,ppm)=>signedPerpMm(c,"UIT","N","A",ppm)},
318
- {id:"L1NB_D", an:"ABO", name:"L1–NB Angle", norm:25, sd:4, unit:"°", req:["LIT","LIA","N","B"], f:c=>planeAngleAcute(_p(c,"LIT"),_p(c,"LIA"),_p(c,"N"),_p(c,"B"))},
319
- {id:"L1NB_M", an:"ABO", name:"L1–NB", norm:4, sd:2, unit:"mm", req:["LIT","N","B"], f:(c,ppm)=>signedPerpMm(c,"LIT","N","B",ppm)},
320
- {id:"IIA", an:"ABO", name:"Interincisal Angle", norm:130, sd:6, unit:"°", req:["UIT","UIA","LIT","LIA"], f:c=>{const a=_p(c,"UIT"),b=_p(c,"UIA"),d=_p(c,"LIT"),e=_p(c,"LIA");if(!a||!b||!d||!e)return null;const v1={x:a.x-b.x,y:a.y-b.y},v2={x:d.x-e.x,y:d.y-e.y};const m=Math.hypot(v1.x,v1.y)*Math.hypot(v2.x,v2.y);return m?Math.acos(Math.max(-1,Math.min(1,(v1.x*v2.x+v1.y*v2.y)/m)))*180/Math.PI:null;}},
321
- {id:"OJ", an:"ABO", name:"Overjet (occl. proj.)", norm:2.5, sd:1, unit:"mm", req:["UIT","LIT","U6T","L6T"], f:(c,ppm)=>{const op=occlusalPoints(c);if(!op||!ppm)return null;const v={x:op.ant.x-op.post.x,y:op.ant.y-op.post.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const u={x:v.x/L,y:v.y/L};return (projectOnto(_p(c,"UIT"),op.post,u)-projectOnto(_p(c,"LIT"),op.post,u))/ppm;}},
322
- {id:"OB", an:"ABO", name:"Overbite (perp. to occl.)", norm:2.5, sd:1, unit:"mm", req:["UIT","LIT","U6T","L6T"], f:(c,ppm)=>{const op=occlusalPoints(c);if(!op||!ppm)return null;const v={x:op.ant.x-op.post.x,y:op.ant.y-op.post.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const n={x:-v.y/L,y:v.x/L};const d=(projectOnto(_p(c,"LIT"),op.post,n)-projectOnto(_p(c,"UIT"),op.post,n));return Math.abs(d)/ppm*(faceDir(c)>0?1:1);}},
323
- {id:"UL_E", an:"ABO", name:"Upper Lip to E-Line", norm:-3, sd:2, unit:"mm", req:["Ls","Pn","PogS"], f:(c,ppm)=>signedPerpMm(c,"Ls","Pn","PogS",ppm)},
324
- {id:"LL_E", an:"ABO", name:"Lower Lip to E-Line", norm:-1, sd:2, unit:"mm", req:["Li","Pn","PogS"], f:(c,ppm)=>signedPerpMm(c,"Li","Pn","PogS",ppm)},
325
- /* ---- STEINER ---- */
326
- {id:"SND", an:"Steiner", name:"SND", norm:76, sd:2, unit:"°", req:["S","N","D"], f:c=>angleAt(_p(c,"S"),_p(c,"N"),_p(c,"D"))},
327
- {id:"OCCSN", an:"Steiner", name:"Occlusal Plane–SN", norm:14, sd:4, unit:"°", req:["S","N","UIT","LIT","U6T","L6T"], f:c=>{const op=occlusalPoints(c);if(!op)return null;return planeAngleAcute(_p(c,"S"),_p(c,"N"),op.post,op.ant);}},
328
- {id:"GOGNSN", an:"Steiner", name:"GoGn–SN", norm:32, sd:5, unit:"°", req:["S","N","Go","Gn"], f:c=>planeAngle(_p(c,"S"),_p(c,"N"),_p(c,"N"),_p(c,"Go"),_p(c,"Gn"),_p(c,"Gn"))},
329
- {id:"POGNB", an:"Steiner", name:"Pog–NB", norm:null, sd:null, unit:"mm", req:["Pog","N","B"], f:(c,ppm)=>signedPerpMm(c,"Pog","N","B",ppm), note:"Compare with L1–NB mm (Holdaway ratio ≈ 1:1)"},
330
- {id:"SE", an:"Steiner", name:"S–E (condyle proxy: S to L1-midpoint line)", norm:22, sd:3, unit:"mm", req:["S","LIT","LIA"], f:(c,ppm)=>{const a=_p(c,"LIT"),b=_p(c,"LIA");if(!a||!b)return null;const mid={x:(a.x+b.x)/2,y:(a.y+b.y)/2};const s=_p(c,"S");return ppm?_dist(s,mid)/ppm:null;}},
331
- {id:"SL", an:"Steiner", name:"S–L (S to Pog-perp on SN)", norm:51, sd:3, unit:"mm", req:["S","N","Pog"], f:(c,ppm)=>{const s=_p(c,"S"),n=_p(c,"N"),g=_p(c,"Pog");if(!s||!n||!g||!ppm)return null;const v={x:n.x-s.x,y:n.y-s.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(g,s,u)/ppm;}},
332
- /* ---- DOWNS ---- */
333
- {id:"FACIAL", an:"Downs", name:"Facial Angle (FH–NPog)", norm:87.8, sd:3.6, unit:"°", req:["Po","Or","N","Pog"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"N"),_p(c,"Pog"),_p(c,"Pog"))},
334
- {id:"CONVEX", an:"Downs", name:"Angle of Convexity (N–A–Pog)", norm:0, sd:5, unit:"°", req:["N","A","Pog"], f:c=>{const a=angleAt(_p(c,"N"),_p(c,"A"),_p(c,"Pog"));if(a==null)return null;const s=signedPerpMm(c,"A","N","Pog",10);return (s==null?1:Math.sign(s))*(180-a);}},
335
- {id:"ABPLANE", an:"Downs", name:"A–B Plane Angle (to Facial Plane)", norm:-4.6, sd:3.7, unit:"°", req:["A","B","N","Pog"], f:c=>{const x=planeAngleAcute(_p(c,"A"),_p(c,"B"),_p(c,"N"),_p(c,"Pog"));return x==null?null:-x;}},
336
- {id:"MPFH", an:"Downs", name:"Mandibular Plane–FH", norm:21.9, sd:5, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngleAcute(_p(c,"Po"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"))},
337
- {id:"YAXIS", an:"Downs", name:"Y-Axis (FH–SGn)", norm:59.4, sd:3.8, unit:"°", req:["Po","Or","S","Gn"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"S"),_p(c,"Gn"),_p(c,"Gn"))},
338
- {id:"OCCFH", an:"Downs", name:"Occlusal Plane–FH", norm:9.3, sd:3.8, unit:"°", req:["Po","Or","UIT","LIT","U6T","L6T"], f:c=>{const op=occlusalPoints(c);if(!op)return null;return planeAngleAcute(_p(c,"Po"),_p(c,"Or"),op.post,op.ant);}},
339
- {id:"L1OCC", an:"Downs", name:"L1–Occlusal Plane", norm:14.5, sd:3.5, unit:"°", req:["LIT","LIA","UIT","U6T","L6T"], f:c=>{const op=occlusalPoints(c);if(!op)return null;const x=planeAngleAcute(_p(c,"LIT"),_p(c,"LIA"),op.post,op.ant);return x==null?null:90-x;}},
340
- {id:"L1MP_D", an:"Downs", name:"L1–Mandibular Plane", norm:-28.8, sd:5.5, unit:"°", req:["LIT","LIA","Go","Me"], f:c=>{const impa=planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Go"),_p(c,"Go"),_p(c,"Me"),_p(c,"LIT"));return impa==null?null:-(90-impa);}},
341
- {id:"U1APOG_M", an:"Downs", name:"U1–APog", norm:2.7, sd:1.8, unit:"mm", req:["UIT","A","Pog"], f:(c,ppm)=>signedPerpMm(c,"UIT","A","Pog",ppm)},
342
- /* ---- TWEED ---- */
343
- {id:"T_FMA", an:"Tweed", name:"FMA", norm:25, sd:4, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"),_p(c,"Me"))},
344
- {id:"T_IMPA", an:"Tweed", name:"IMPA", norm:90, sd:5, unit:"°", req:["LIT","LIA","Go","Me"], f:c=>planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Go"),_p(c,"Go"),_p(c,"Me"),_p(c,"LIT"))},
345
- {id:"FMIA", an:"Tweed", name:"FMIA", norm:65, sd:5, unit:"°", req:["LIT","LIA","Po","Or"], f:c=>planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Po"),_p(c,"Po"),_p(c,"Or"),_p(c,"LIA"))},
346
- /* ---- McNAMARA ---- */
347
- {id:"NPERPA", an:"McNamara", name:"Nasion Perp – A Point", norm:0, sd:3.1, unit:"mm", req:["N","Po","Or","A"], f:(c,ppm)=>{const n=_p(c,"N"),a=_p(c,"A"),po=_p(c,"Po"),or=_p(c,"Or");if(!n||!a||!po||!or||!ppm)return null;const v={x:or.x-po.x,y:or.y-po.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(a,n,u)/ppm;}, note:"Along FH direction from N-perp"},
348
- {id:"NPERPPOG", an:"McNamara", name:"Nasion Perp – Pog", norm:-4, sd:5.3, unit:"mm", req:["N","Po","Or","Pog"], f:(c,ppm)=>{const n=_p(c,"N"),a=_p(c,"Pog"),po=_p(c,"Po"),or=_p(c,"Or");if(!n||!a||!po||!or||!ppm)return null;const v={x:or.x-po.x,y:or.y-po.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(a,n,u)/ppm;}},
349
- {id:"COA", an:"McNamara", name:"Effective Midface Length (Co–A)", norm:null, sd:null, unit:"mm", req:["Co","A"], f:(c,ppm)=>distMm(c,"Co","A",ppm), note:"Norm varies with age/sex — compare to Co–Gn"},
350
- {id:"COGN", an:"McNamara", name:"Effective Mandibular Length (Co–Gn)", norm:null, sd:null, unit:"mm", req:["Co","Gn"], f:(c,ppm)=>distMm(c,"Co","Gn",ppm), note:"Norm varies with age/sex"},
351
- {id:"MXMDIFF", an:"McNamara", name:"Mx–Md Differential (CoGn − CoA)", norm:null, sd:null, unit:"mm", req:["Co","A","Gn"], f:(c,ppm)=>{const a=distMm(c,"Co","A",ppm),b=distMm(c,"Co","Gn",ppm);return (a==null||b==null)?null:b-a;}, note:"~20 mm small, ~27 medium, ~34 large (McNamara)"},
352
- {id:"LAFH", an:"McNamara", name:"Lower Anterior Face Height (ANS–Me)", norm:null, sd:null, unit:"mm", req:["ANS","Me"], f:(c,ppm)=>distMm(c,"ANS","Me",ppm), note:"~60–62 mm small, ~65–67 medium, ~70–72 large"},
353
- {id:"U1AVERT", an:"McNamara", name:"U1 to A-Point Vertical", norm:4, sd:1, unit:"mm", req:["UIT","A","ANS","PNS"], f:(c,ppm)=>{const a=_p(c,"A"),t=_p(c,"UIT"),an=_p(c,"ANS"),pn=_p(c,"PNS");if(!a||!t||!an||!pn||!ppm)return null;const v={x:an.x-pn.x,y:an.y-pn.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const u={x:v.x/L,y:v.y/L};return projectOnto(t,a,u)/ppm;}, note:"Distance along palatal plane from the vertical through A"},
354
- {id:"L1APOG", an:"McNamara", name:"L1 to A–Pog Line", norm:1, sd:2, unit:"mm", req:["LIT","A","Pog"], f:(c,ppm)=>signedPerpMm(c,"LIT","A","Pog",ppm)},
355
- /* ---- RICKETTS ---- */
356
- {id:"FACAXIS", an:"Ricketts", name:"Facial Axis (Ba–N to Pt–Gn)", norm:90, sd:3, unit:"°", req:["Ba","N","Pt","Gn"], f:c=>planeAngleAcute(_p(c,"Ba"),_p(c,"N"),_p(c,"Pt"),_p(c,"Gn"))},
357
- {id:"FACDEPTH", an:"Ricketts", name:"Facial Depth (FH–NPog)", norm:87, sd:3, unit:"°", req:["Po","Or","N","Pog"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"N"),_p(c,"Pog"),_p(c,"Pog"))},
358
- {id:"R_MP", an:"Ricketts", name:"Mandibular Plane Angle (FH–GoMe)", norm:26, sd:4, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngleAcute(_p(c,"Po"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"))},
359
- {id:"CONVEX_R", an:"Ricketts", name:"Convexity (A to N–Pog)", norm:2, sd:2, unit:"mm", req:["A","N","Pog"], f:(c,ppm)=>signedPerpMm(c,"A","N","Pog",ppm)},
360
- {id:"L1APOG_D", an:"Ricketts", name:"L1 to A–Pog Angle", norm:22, sd:4, unit:"°", req:["LIT","LIA","A","Pog"], f:c=>planeAngleAcute(_p(c,"LIT"),_p(c,"LIA"),_p(c,"A"),_p(c,"Pog"))},
361
- {id:"L1APOG_M", an:"Ricketts", name:"L1 to A–Pog", norm:1, sd:2, unit:"mm", req:["LIT","A","Pog"], f:(c,ppm)=>signedPerpMm(c,"LIT","A","Pog",ppm)},
362
- {id:"U6PTV", an:"Ricketts", name:"U6 to PTV", norm:null, sd:null, unit:"mm", req:["U6T","Pt","Po","Or"], f:(c,ppm)=>{const pt=_p(c,"Pt"),u6=_p(c,"U6T"),po=_p(c,"Po"),or=_p(c,"Or");if(!pt||!u6||!po||!or||!ppm)return null;const v={x:or.x-po.x,y:or.y-po.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(u6,pt,u)/ppm;}, note:"Norm ≈ age + 3 mm"},
363
- {id:"LL_E_R", an:"Ricketts", name:"Lower Lip to E-Plane", norm:-2, sd:2, unit:"mm", req:["Li","Pn","PogS"], f:(c,ppm)=>signedPerpMm(c,"Li","Pn","PogS",ppm)},
364
- /* ---- HOLDAWAY ---- */
365
- {id:"HANGLE", an:"Holdaway", name:"H-Angle", norm:10, sd:3, unit:"°", req:["NS","PogS","Sn","Ls"], f:c=>{const a=_p(c,"NS")||_p(c,"N");return planeAngleAcute(a,_p(c,"PogS"),_p(c,"Sn"),_p(c,"Ls"));}},
366
- {id:"SKELCONV_H", an:"Holdaway", name:"Skeletal Convexity (A to N–Pog)", norm:0, sd:2, unit:"mm", req:["A","N","Pog"], f:(c,ppm)=>signedPerpMm(c,"A","N","Pog",ppm)},
367
- {id:"NOSEPROM", an:"Holdaway", name:"Nose Prominence (Pn to H-Line)", norm:18, sd:4, unit:"mm", req:["Pn","NS","PogS"], f:(c,ppm)=>{const a=_p(c,"NS")||_p(c,"N");const cc=Object.assign({},c);if(!_p(c,"NS")){return signedPerpMm(c,"Pn","N","PogS",ppm);}return signedPerpMm(c,"Pn","NS","PogS",ppm);}},
368
- {id:"SNH", an:"Holdaway", name:"Subnasale to H-Line", norm:5, sd:2, unit:"mm", req:["Sn","NS","PogS"], f:(c,ppm)=>signedPerpMm(c,"Sn",_p(c,"NS")?"NS":"N","PogS",ppm)},
369
- {id:"LLH", an:"Holdaway", name:"Lower Lip to H-Line", norm:0.5, sd:1, unit:"mm", req:["Li","NS","PogS"], f:(c,ppm)=>signedPerpMm(c,"Li",_p(c,"NS")?"NS":"N","PogS",ppm)},
370
- {id:"CHINTHICK", an:"Holdaway", name:"Soft Tissue Chin Thickness (Pog–Pog')", norm:11, sd:2, unit:"mm", req:["Pog","PogS"], f:(c,ppm)=>distMm(c,"Pog","PogS",ppm)},
371
- /* ---- JARABAK / BJORK ---- */
372
- {id:"SADDLE", an:"Jarabak", name:"Saddle Angle (N–S–Ar)", norm:123, sd:5, unit:"°", req:["N","S","Ar"], f:c=>angleAt(_p(c,"N"),_p(c,"S"),_p(c,"Ar"))},
373
- {id:"ARTIC", an:"Jarabak", name:"Articular Angle (S–Ar–Go)", norm:143, sd:6, unit:"°", req:["S","Ar","Go"], f:c=>angleAt(_p(c,"S"),_p(c,"Ar"),_p(c,"Go"))},
374
- {id:"GONIAL", an:"Jarabak", name:"Gonial Angle (Ar–Go–Me)", norm:130, sd:7, unit:"°", req:["Ar","Go","Me"], f:c=>angleAt(_p(c,"Ar"),_p(c,"Go"),_p(c,"Me"))},
375
- {id:"BJORKSUM", an:"Jarabak", name:"Björk Sum", norm:396, sd:6, unit:"°", req:["N","S","Ar","Go","Me"], f:c=>{const a=angleAt(_p(c,"N"),_p(c,"S"),_p(c,"Ar")),b=angleAt(_p(c,"S"),_p(c,"Ar"),_p(c,"Go")),d=angleAt(_p(c,"Ar"),_p(c,"Go"),_p(c,"Me"));return (a==null||b==null||d==null)?null:a+b+d;}},
376
- {id:"PFHAFH", an:"Jarabak", name:"PFH/AFH Ratio (S–Go / N–Me)", norm:62, sd:4, unit:"%", req:["S","Go","N","Me"], f:(c,ppm)=>{const a=distMm(c,"S","Go",ppm||10),b=distMm(c,"N","Me",ppm||10);return (a==null||b==null||!b)?null:100*a/b;}},
377
- {id:"ANS_ME_R", an:"Jarabak", name:"LAFH/TAFH (ANS–Me / N–Me)", norm:55, sd:3, unit:"%", req:["ANS","Me","N"], f:(c,ppm)=>{const a=distMm(c,"ANS","Me",ppm||10),b=distMm(c,"N","Me",ppm||10);return (a==null||b==null||!b)?null:100*a/b;}}
378
- ];
379
- function computeAll(c, ppm){ const out={}; for(const m of MEASURES){ let v=null; try{ v=m.f(c,ppm); }catch(e){ v=null; } out[m.id]=(v==null||!isFinite(v))?null:Math.round(v*10)/10; } return out; }
380
- /* ==================== ENGINE END ==================== */
381
-
382
-
383
- /* ==================== APP STATE ==================== */
384
- let session=null, coords={}, aiCoords={}, confidence={}, verified={}, source={}; // source: 'ai'|'manual'|'estimate'
385
- let pxPerMm=null, calibrated=false, calMethod="", calStep=0, showRuler=false;
386
- let selectedLm=null, draggingLm=null, dragMoved=false, lastDragEnd=0, placingLm=null, manualQueue=[];
387
- let t1Baseline=null, latestMetrics={}, undoStack=[];
388
- let showLines=true, showPoints=true, showLabels=true, showTrace=true, zoomLevel=1, spacePeek=false;
389
- const $=id=>document.getElementById(id);
390
- const imgElem=$("ceph-image"), svgElem=$("overlay-svg"), container=$("viewport-container"), dropzone=$("empty-dropzone");
391
- $("pt-date").valueAsDate=new Date();
392
-
393
- function setStatus(txt,color){ $("status-txt").innerText=txt; $("status-ind").style.backgroundColor=color||"var(--grn)"; }
394
- function downloadBlob(blob,fn){ const u=URL.createObjectURL(blob); const a=document.createElement("a"); a.href=u; a.download=fn; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(u),4000); }
395
- function pushUndo(){ undoStack.push(JSON.stringify({coords,verified,pxPerMm,calibrated})); if(undoStack.length>60)undoStack.shift(); }
396
- function calStatusUpdate(){ const el=$("cal-status");
397
- if(calibrated){ el.style.color="var(--grn)"; el.innerHTML=`✓ Calibrated: ${pxPerMm.toFixed(2)} px/mm (${calMethod}). mm values valid.`; }
398
- else { el.style.color="var(--amb)"; el.innerHTML="⚠ UNCALIBRATED — angles valid, mm values are provisional."; } }
399
-
400
- /* ==================== MODEL ==================== */
401
- let modelLoading=false;
402
- async function initModel(){ if(session||modelLoading)return; modelLoading=true;
403
- const detail=$("model-detail");
404
- try{
405
- if(typeof ort==="undefined") throw new Error("AI library (onnxruntime-web) did not download from the CDN — check your internet connection, then tap Run AI Auto-Trace to retry.");
406
- ort.env.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/";
407
- ort.env.wasm.numThreads=1;
408
- setStatus("Downloading AI model (~28 MB, one time — browser caches it)…","var(--amb)");
409
- const resp=await fetch(MODEL_URL);
410
- if(!resp.ok) throw new Error("Model download failed: HTTP "+resp.status);
411
- const total=parseInt(resp.headers.get("Content-Length")||"29745715",10);
412
- const reader=resp.body.getReader(); const chunks=[]; let got=0;
413
- while(true){ const rd=await reader.read(); if(rd.done)break; chunks.push(rd.value); got+=rd.value.length;
414
- setStatus("Downloading AI model… "+Math.round(got/1048576)+" / "+Math.round(total/1048576)+" MB","var(--amb)"); }
415
- const buf=new Uint8Array(got); let offb=0; for(const ch of chunks){ buf.set(ch,offb); offb+=ch.length; }
416
- setStatus("Starting AI engine…","var(--amb)");
417
- session=await ort.InferenceSession.create(buf,{executionProviders:["wasm"]});
418
- if(detail)detail.innerText="";
419
- setStatus("AI Ready — upload a film, calibrate, then Auto-Trace","var(--grn)");
420
- if(imgElem.src&&imgElem.naturalWidth&&!coords.S) runAutoTrace();
421
- }catch(e){ session=null;
422
- setStatus("AI model failed to load — tap Run AI Auto-Trace to retry. Manual Placement works now.","var(--red)");
423
- if(detail)detail.innerText="AI error detail: "+(e&&e.message?e.message:String(e))+" — If you opened this file directly on a phone (content:// or file:// address), use the hosted Hugging Face link instead: phone browsers restrict WebAssembly and large downloads on local files.";
424
- } finally{ modelLoading=false; } }
425
- initModel();
426
-
427
- /* ==================== FILES ==================== */
428
- $("file-input").addEventListener("change",e=>{const f=e.target.files[0]; e.target.value=""; if(f)handleFile(f);});
429
- $("json-input").addEventListener("change",e=>{const f=e.target.files[0]; e.target.value=""; if(f)loadJsonFile(f);});
430
- const vw=$("viewport-wrapper");
431
- vw.addEventListener("dragover",e=>{e.preventDefault();vw.classList.add("drag-over");});
432
- vw.addEventListener("dragleave",()=>vw.classList.remove("drag-over"));
433
- vw.addEventListener("drop",e=>{e.preventDefault();vw.classList.remove("drag-over"); if(e.dataTransfer.files[0])handleFile(e.dataTransfer.files[0]);});
434
- function handleFile(file){ const n=file.name.toLowerCase();
435
- if(n.endsWith(".json")){loadJsonFile(file);return;}
436
- if(n.endsWith(".dcm")){ const r=new FileReader(); r.onload=ev=>{try{parseDicom(new Uint8Array(ev.target.result));}catch(err){alert("DICOM error: "+err.message);}}; r.readAsArrayBuffer(file); return; }
437
- const r=new FileReader(); r.onload=ev=>setupImage(ev.target.result,true); r.readAsDataURL(file); }
438
- function setupImage(src,runAi,onReady){ if(runAi&&!onReady){coords={};aiCoords={};confidence={};verified={};source={};pxPerMm=null;calibrated=false;calMethod="";calStatusUpdate();}
439
- let fired=false; const done=()=>{ if(fired)return; fired=true; imgElem.style.display=""; dropzone.style.display="none"; container.style.display="block";
440
- svgElem.setAttribute("viewBox",`0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
441
- if(onReady)onReady(); else if(runAi&&session)runAutoTrace(); else renderAll(); };
442
- imgElem.onload=done; imgElem.onerror=()=>{ if(fired)return; fired=true; if(onReady)onReady(); else alert("Could not load that image."); };
443
- imgElem.src=src; if(imgElem.complete&&imgElem.naturalWidth>0)done(); }
444
- function parseDicom(bytes){ if(typeof dicomParser==="undefined")throw new Error("DICOM library not loaded — check connection and reload.");
445
- const ds=dicomParser.parseDicom(bytes); const ts=(ds.string("x00020010")||"").trim();
446
- if(ts.indexOf("1.2.840.10008.1.2.4")===0)throw new Error("JPEG-compressed DICOM can't be decoded in-browser. Export uncompressed (Explicit VR Little Endian) or PNG/JPG.");
447
- const pn=ds.string("x00100010"); if(pn)$("pt-name").value=pn.replace(/\^/g," ").trim();
448
- const pid=ds.string("x00100020"); if(pid)$("pt-chart").value=pid.trim();
449
- const rows=ds.uint16("x00280010"), cols=ds.uint16("x00280011"); const el=ds.elements.x7fe00010;
450
- if(!rows||!cols||!el)throw new Error("No readable pixel data in this DICOM.");
451
- const bits=ds.uint16("x00280100")||16, rep=ds.uint16("x00280103")||0, mono1=(ds.string("x00280004")||"").trim()==="MONOCHROME1";
452
- const slope=parseFloat(ds.string("x00281053"))||1, icept=parseFloat(ds.string("x00281052"))||0;
453
- let wc=parseFloat(ds.string("x00281050")), ww=parseFloat(ds.string("x00281051"));
454
- const cv=document.createElement("canvas"); cv.width=cols; cv.height=rows; const ctx=cv.getContext("2d"); const im=ctx.createImageData(cols,rows); const N=rows*cols;
455
- if(bits===16){ const u8=new Uint8Array(bytes.buffer,bytes.byteOffset+el.dataOffset,N*2); const dv=new DataView(u8.buffer,u8.byteOffset,u8.byteLength);
456
- const vals=new Float32Array(N); let mn=Infinity,mx=-Infinity;
457
- for(let i=0;i<N;i++){const v=(rep===1?dv.getInt16(i*2,true):dv.getUint16(i*2,true))*slope+icept; vals[i]=v; if(v<mn)mn=v; if(v>mx)mx=v;}
458
- if(isNaN(wc)||isNaN(ww)||ww<=0){wc=(mn+mx)/2; ww=Math.max(1,mx-mn);} const low=wc-ww/2;
459
- for(let i=0;i<N;i++){let g=Math.min(255,Math.max(0,((vals[i]-low)/ww)*255)); if(mono1)g=255-g; const j=i*4; im.data[j]=im.data[j+1]=im.data[j+2]=g; im.data[j+3]=255;}
460
- } else { const u8=new Uint8Array(bytes.buffer,bytes.byteOffset+el.dataOffset,N);
461
- for(let i=0;i<N;i++){let g=mono1?255-u8[i]:u8[i]; const j=i*4; im.data[j]=im.data[j+1]=im.data[j+2]=g; im.data[j+3]=255;} }
462
- ctx.putImageData(im,0,0);
463
- const sp=ds.string("x00280030")||ds.string("x00181164");
464
- setupImage(cv.toDataURL("image/png"),true);
465
- if(sp){ const p0=parseFloat(sp.split("\\")[0]); if(p0>0){ pxPerMm=1/p0; calibrated=false; calMethod="DICOM spacing (unverified — confirm with ruler)"; calStatusUpdate();
466
- $("cal-status").innerHTML=`DICOM spacing gives ${pxPerMm.toFixed(2)} px/mm — <b>still flagged UNCALIBRATED</b>: detector spacing ≠ magnification-corrected scale. Confirm with the ruler.`; } } }
467
-
468
- /* ==================== JSON SAVE / LOAD (v3) ==================== */
469
- $("btn-save-json").addEventListener("click",()=>{ if(!coords.S){alert("No tracing to save.");return;}
470
- const payload={version:"3.4", engines:sessionB?"A+B":"A", patient:{name:$("pt-name").value||"Patient",chart:$("pt-chart").value||"",date:$("pt-date").value||""},
471
- pxPerMm, calibrated, calMethod, coords, aiCoords, confidence, verified, source, metrics:latestMetrics,
472
- imageSize:{w:imgElem.naturalWidth||0,h:imgElem.naturalHeight||0}, imageDataUrl:imgElem.src||null};
473
- downloadBlob(new Blob([JSON.stringify(payload,null,2)],{type:"application/json"}),`Ceph_v3_${(payload.patient.name).replace(/\s+/g,"_")}_${payload.patient.date}.json`);
474
- setStatus("Record saved (includes AI-vs-final validation data)","var(--grn)"); });
475
- function loadJsonFile(file){ const r=new FileReader(); r.onload=e=>{ try{ const d=JSON.parse(e.target.result);
476
- const lc=d.coords||d.landmarks; if(!lc||!lc.S)throw new Error("Not an OrthoCeph record — no 'coords' object with landmarks. Only files saved by OrthoCeph can be loaded; send me any other format and I'll build an importer.");
477
- for(const k of Object.keys(lc)){ if(Array.isArray(lc[k]))lc[k]={x:lc[k][0],y:lc[k][1]}; }
478
- coords=JSON.parse(JSON.stringify(lc)); aiCoords=d.aiCoords?JSON.parse(JSON.stringify(d.aiCoords)):JSON.parse(JSON.stringify(d.initialAiCoords||lc));
479
- confidence=d.confidence||{}; verified=d.verified||{}; source=d.source||{};
480
- if(d.patient){$("pt-name").value=d.patient.name||"";$("pt-chart").value=d.patient.chart||""; if(d.patient.date)$("pt-date").value=d.patient.date;}
481
- pxPerMm=d.pxPerMm||null; calibrated=!!d.calibrated; calMethod=d.calMethod||""; calStatusUpdate();
482
- const after=()=>{ dropzone.style.display="none"; container.style.display="block";
483
- const w=(d.imageSize&&d.imageSize.w)||imgElem.naturalWidth||1200, h=(d.imageSize&&d.imageSize.h)||imgElem.naturalHeight||1200;
484
- svgElem.setAttribute("viewBox",`0 0 ${w} ${h}`); renderAll(); setStatus(`Record loaded (${Object.keys(coords).length} landmarks)`,"var(--grn)"); };
485
- if(d.imageDataUrl)setupImage(d.imageDataUrl,false,after); else { imgElem.style.display="none"; after(); }
486
- }catch(err){ alert("Invalid file: "+err.message); } }; r.readAsText(file); }
487
-
488
- /* ==================== AUTO-TRACE (letterboxed, with confidence) ==================== */
489
- let ttaGap={};
490
- async function inferPass(flip){
491
- const SZ=768, W=imgElem.naturalWidth, H=imgElem.naturalHeight;
492
- const scale=Math.min(SZ/W,SZ/H), nW=Math.round(W*scale), nH=Math.round(H*scale), padX=(SZ-nW)/2, padY=(SZ-nH)/2;
493
- const off=document.createElement("canvas"); off.width=SZ; off.height=SZ; const ctx=off.getContext("2d");
494
- ctx.fillStyle="#000"; ctx.fillRect(0,0,SZ,SZ);
495
- if(flip){ ctx.save(); ctx.translate(SZ,0); ctx.scale(-1,1); ctx.drawImage(imgElem,padX,padY,nW,nH); ctx.restore(); }
496
- else ctx.drawImage(imgElem,padX,padY,nW,nH);
497
- const data=ctx.getImageData(0,0,SZ,SZ).data; const fa=new Float32Array(3*SZ*SZ);
498
- const mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225];
499
- for(let i=0;i<SZ*SZ;i++){ fa[i]=(data[i*4]/255-mean[0])/std[0]; fa[SZ*SZ+i]=(data[i*4+1]/255-mean[1])/std[1]; fa[2*SZ*SZ+i]=(data[i*4+2]/255-mean[2])/std[2]; }
500
- const res=await session.run({[session.inputNames[0]]:new ort.Tensor("float32",fa,[1,3,SZ,SZ])});
501
- const out=res[session.outputNames[0]]; const hm=out.data, hmH=out.dims[2], hmW=out.dims[3];
502
- const pts={}, conf={};
503
- for(const [code,def] of Object.entries(LANDMARKS)){ if(def.model==null)continue; const ch=def.model; const off0=ch*hmH*hmW;
504
- let peak=-Infinity, mi=0;
505
- for(let j=0;j<hmH*hmW;j++){ if(hm[off0+j]>peak){peak=hm[off0+j]; mi=j;} }
506
- const mx=mi%hmW, my=Math.floor(mi/hmW);
507
- let ws=0,xs=0,ys=0; for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++){ const xx=mx+dx,yy=my+dy; if(xx<0||yy<0||xx>=hmW||yy>=hmH)continue; const w=Math.max(0,hm[off0+yy*hmW+xx]); ws+=w; xs+=xx*w; ys+=yy*w; }
508
- const fx=ws>0?xs/ws:mx, fy=ws>0?ys/ws:my;
509
- let varr=0; for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++){ const xx=mx+dx,yy=my+dy; if(xx<0||yy<0||xx>=hmW||yy>=hmH)continue; const w=Math.max(0,hm[off0+yy*hmW+xx]); varr+=w*((xx-fx)**2+(yy-fy)**2); }
510
- const spread=ws>0?Math.sqrt(varr/ws):9;
511
- let imgX=((fx/hmW)*SZ-padX)/scale; const imgY=((fy/hmH)*SZ-padY)/scale;
512
- if(flip) imgX=W-imgX;
513
- pts[code]={x:imgX,y:imgY};
514
- let cf=Math.max(0.03,Math.min(0.99,(peak*1.4)*(1/(1+spread*0.55))));
515
- if(def.tier===3)cf*=0.85; conf[code]=Math.round(cf*100)/100;
516
- }
517
- return {pts,conf};
518
- }
519
- /* ==================== ENGINE B (HRNet-W48 second opinion) ====================
520
- Converted from MFouda128/Cephalometric-AI-Models (HRNet-W48, concat head).
521
- Its channel order is NOT the cepha29 order: ENGINE_B_MAP was verified
522
- empirically on two real films against Engine A (25 channels matched a
523
- unique landmark on both films; the 4 molar channels were split by
524
- upper/lower + mesial position, consistent on both films). Channels for
525
- R, LPM, UPM are unused — the app has no such landmarks. Engine B was
526
- trained on GRAYSCALE films, so its input is grayscaled first. */
527
- const ENGINE_B_MAP={0:"A",1:"ANS",2:"B",3:"Me",4:"N",5:"Or",6:"Pog",7:"PNS",8:"Pn",10:"S",11:"Ar",12:"Co",13:"Gn",14:"Go",15:"Po",17:"LIT",18:"L6T",20:"UIA",21:"UIT",22:"U6T",23:"LIA",24:"Li",25:"Ls",26:"NS",27:"PogS",28:"Sn"};
528
- let sessionB=null, engineBLoading=false, engGap={};
529
- async function initEngineB(bufOrUrl){
530
- if(sessionB||engineBLoading)return; engineBLoading=true;
531
- const detail=$("engineb-detail");
532
- try{
533
- if(typeof ort==="undefined") throw new Error("AI library (onnxruntime-web) not loaded — check connection and reload the page.");
534
- ort.env.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/";
535
- ort.env.wasm.numThreads=1;
536
- let buf;
537
- if(typeof bufOrUrl==="string"){
538
- setStatus("Downloading Engine B (~63 MB, one time — browser caches it)\u2026","var(--amb)");
539
- const resp=await fetch(bufOrUrl);
540
- if(!resp.ok) throw new Error("Download failed: HTTP "+resp.status+". The default URL is relative — it only works when orthoceph_engine_b_int8.onnx sits next to this page (e.g. uploaded into the same Hugging Face Space). Otherwise paste a direct .onnx link or use Load from a file.");
541
- const total=parseInt(resp.headers.get("Content-Length")||"66451611",10);
542
- const reader=resp.body.getReader(); const chunks=[]; let got=0;
543
- while(true){ const rd=await reader.read(); if(rd.done)break; chunks.push(rd.value); got+=rd.value.length;
544
- setStatus("Downloading Engine B\u2026 "+Math.round(got/1048576)+" / "+Math.round(total/1048576)+" MB","var(--amb)"); }
545
- buf=new Uint8Array(got); let o=0; for(const c of chunks){ buf.set(c,o); o+=c.length; }
546
- } else { setStatus("Loading Engine B from file\u2026","var(--amb)"); buf=new Uint8Array(bufOrUrl); }
547
- setStatus("Starting Engine B\u2026","var(--amb)");
548
- sessionB=await ort.InferenceSession.create(buf,{executionProviders:["wasm"]});
549
- if(detail)detail.innerText="Engine B ready \u2713 — Auto-Trace now averages both engines.";
550
- setStatus("Engine B ready — Auto-Trace will use the A+B ensemble","var(--grn)");
551
- }catch(e){ sessionB=null;
552
- if(detail)detail.innerText="Engine B failed: "+(e&&e.message?e.message:String(e));
553
- setStatus("Engine B failed to load — Engine A still works","var(--red)");
554
- } finally{ engineBLoading=false; }
555
- }
556
- async function inferPassB(flip){
557
- const SZ=768, W=imgElem.naturalWidth, H=imgElem.naturalHeight;
558
- const scale=Math.min(SZ/W,SZ/H), nW=Math.round(W*scale), nH=Math.round(H*scale), padX=(SZ-nW)/2, padY=(SZ-nH)/2;
559
- const off=document.createElement("canvas"); off.width=SZ; off.height=SZ; const ctx=off.getContext("2d");
560
- ctx.fillStyle="#000"; ctx.fillRect(0,0,SZ,SZ);
561
- if(flip){ ctx.save(); ctx.translate(SZ,0); ctx.scale(-1,1); ctx.drawImage(imgElem,padX,padY,nW,nH); ctx.restore(); }
562
- else ctx.drawImage(imgElem,padX,padY,nW,nH);
563
- const idata=ctx.getImageData(0,0,SZ,SZ); const data=idata.data;
564
- for(let i=0;i<data.length;i+=4){ const g=0.299*data[i]+0.587*data[i+1]+0.114*data[i+2]; data[i]=g; data[i+1]=g; data[i+2]=g; }
565
- const fa=new Float32Array(3*SZ*SZ);
566
- const mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225];
567
- for(let i=0;i<SZ*SZ;i++){ fa[i]=(data[i*4]/255-mean[0])/std[0]; fa[SZ*SZ+i]=(data[i*4+1]/255-mean[1])/std[1]; fa[2*SZ*SZ+i]=(data[i*4+2]/255-mean[2])/std[2]; }
568
- const res=await sessionB.run({[sessionB.inputNames[0]]:new ort.Tensor("float32",fa,[1,3,SZ,SZ])});
569
- const out=res[sessionB.outputNames[0]]; const hm=out.data, hmH=out.dims[2], hmW=out.dims[3];
570
- const pts={}, conf={};
571
- for(const [chStr,code] of Object.entries(ENGINE_B_MAP)){ const ch=+chStr; const off0=ch*hmH*hmW;
572
- let peak=-Infinity, mi=0;
573
- for(let j=0;j<hmH*hmW;j++){ if(hm[off0+j]>peak){peak=hm[off0+j]; mi=j;} }
574
- const mx=mi%hmW, my=Math.floor(mi/hmW);
575
- let ws=0,xs=0,ys=0; for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++){ const xx=mx+dx,yy=my+dy; if(xx<0||yy<0||xx>=hmW||yy>=hmH)continue; const w=Math.max(0,hm[off0+yy*hmW+xx]); ws+=w; xs+=xx*w; ys+=yy*w; }
576
- const fx=ws>0?xs/ws:mx, fy=ws>0?ys/ws:my;
577
- let varr=0; for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++){ const xx=mx+dx,yy=my+dy; if(xx<0||yy<0||xx>=hmW||yy>=hmH)continue; const w=Math.max(0,hm[off0+yy*hmW+xx]); varr+=w*((xx-fx)**2+(yy-fy)**2); }
578
- const spread=ws>0?Math.sqrt(varr/ws):9;
579
- let imgX=((fx/hmW)*SZ-padX)/scale; const imgY=((fy/hmH)*SZ-padY)/scale;
580
- if(flip) imgX=W-imgX;
581
- pts[code]={x:imgX,y:imgY};
582
- let cf=Math.max(0.03,Math.min(0.99,peak*(1/(1+spread*0.55))));
583
- const def=LANDMARKS[code]; if(def&&def.tier===3)cf*=0.85; conf[code]=Math.round(cf*100)/100;
584
- }
585
- return {pts,conf};
586
- }
587
- async function runAutoTrace(){
588
- if(!session&&!sessionB){ initModel(); alert("AI is (re)loading — watch the status line at the top. If it fails again, the red note in the Trace section shows the exact reason."); return; }
589
- if(!imgElem.src||!imgElem.naturalWidth)return;
590
- const W=imgElem.naturalWidth, H=imgElem.naturalHeight;
591
- const useTTA=!!($("tta-toggle")&&$("tta-toggle").checked);
592
- const useEns=!!(sessionB&&$("ensemble-toggle")&&$("ensemble-toggle").checked);
593
- let finalPts=null, finalConf=null; ttaGap={}; engGap={};
594
- if(session){
595
- setStatus("Auto-tracing — Engine A pass 1 of "+(useTTA?2:1)+"\u2026","var(--amb)");
596
- await new Promise(r=>setTimeout(r,30));
597
- const a=await inferPass(false);
598
- finalPts=a.pts; finalConf=a.conf;
599
- if(useTTA){
600
- setStatus("Auto-tracing — Engine A pass 2 of 2 (mirrored)\u2026","var(--amb)");
601
- const bb=await inferPass(true); finalPts={}; finalConf={};
602
- for(const code of Object.keys(a.pts)){
603
- if(bb.pts[code]){ const d=Math.hypot(a.pts[code].x-bb.pts[code].x,a.pts[code].y-bb.pts[code].y); ttaGap[code]=d;
604
- finalPts[code]={x:(a.pts[code].x+bb.pts[code].x)/2, y:(a.pts[code].y+bb.pts[code].y)/2};
605
- finalConf[code]=Math.round(Math.max(0.03,((a.conf[code]+bb.conf[code])/2)/(1+d/(W*0.004)))*100)/100;
606
- } else { finalPts[code]=a.pts[code]; finalConf[code]=a.conf[code]; }
607
- }
608
- }
609
- }
610
- if(sessionB&&(useEns||!finalPts)){
611
- setStatus("Auto-tracing — Engine B (HRNet-W48)\u2026","var(--amb)");
612
- const b=await inferPassB(false);
613
- if(!finalPts){ finalPts=b.pts; finalConf=b.conf; }
614
- else{
615
- for(const code of Object.keys(b.pts)){
616
- if(finalPts[code]){ const d=Math.hypot(finalPts[code].x-b.pts[code].x,finalPts[code].y-b.pts[code].y); engGap[code]=d;
617
- finalConf[code]=Math.round(Math.max(0.03,((finalConf[code]+b.conf[code])/2)/(1+d/(W*0.004)))*100)/100;
618
- finalPts[code]={x:(finalPts[code].x+b.pts[code].x)/2, y:(finalPts[code].y+b.pts[code].y)/2};
619
- } else { finalPts[code]=b.pts[code]; finalConf[code]=b.conf[code]; }
620
- }
621
- }
622
- }
623
- pushUndo(); coords={}; aiCoords={}; confidence={}; source={}; verified={};
624
- for(const code of Object.keys(finalPts)){ coords[code]=finalPts[code]; confidence[code]=finalConf[code]; source[code]="ai"; verified[code]=false; }
625
- placeEstimates();
626
- aiCoords=JSON.parse(JSON.stringify(coords));
627
- coords.RULER_1={x:W*0.84,y:H*0.10}; coords.RULER_2={x:W*0.84,y:H*0.10+(pxPerMm?pxPerMm*10:H*0.08)};
628
- setStatus("Auto-trace complete"+(Object.keys(engGap).length?" (Engine A+B ensemble averaged)":(useTTA?" (2-pass averaged)":""))+" — work the Review Queue, verify, then export","var(--grn)");
629
- renderAll();
630
- }
631
- $("engineb-url").value=localStorage.getItem("ocp_engineb_url")||"orthoceph_engine_b_int8.onnx";
632
- $("btn-engineb-url").addEventListener("click",()=>{ const u=$("engineb-url").value.trim(); if(!u)return; localStorage.setItem("ocp_engineb_url",u); initEngineB(u); });
633
- $("btn-engineb-file").addEventListener("click",()=>$("engineb-file").click());
634
- $("engineb-file").addEventListener("change",e=>{ const f=e.target.files[0]; e.target.value=""; if(!f)return; const r=new FileReader(); r.onload=ev=>initEngineB(ev.target.result); r.readAsArrayBuffer(f); });
635
-
636
- /* Rough geometric starting positions for landmarks the model cannot predict.
637
- They are ALWAYS flagged as estimates and must be moved + verified by hand. */
638
- function placeEstimates(){ const g=k=>coords[k]; if(!g("S")||!g("N"))return;
639
- /* Only Ba, Pt, D, MeS remain manual: the model has no channels for them.
640
- Starting points use fractions of S–N length, so they scale to any film.
641
- They are ALWAYS purple ESTIMATES — drag to the true position + verify. */
642
- const S=g("S"), N=g("N"); const L=Math.hypot(N.x-S.x,N.y-S.y); const fd=faceDir(coords);
643
- const est={};
644
- est.Ba={x:S.x-fd*0.30*L, y:S.y+0.12*L};
645
- if(g("ANS")) est.Pt={x:S.x+fd*0.42*L, y:g("ANS").y-0.18*L};
646
- if(g("B")&&g("Pog")) est.D={x:(g("B").x+g("Pog").x)/2, y:(g("B").y+g("Pog").y)/2};
647
- if(g("Me")) est.MeS={x:g("Me").x+fd*0.01*L, y:g("Me").y+0.055*L};
648
- for(const [k,v] of Object.entries(est)){ if(!coords[k]){ coords[k]=v; source[k]="estimate"; confidence[k]=0.1; verified[k]=false; } } }
649
- $("btn-autotrace").addEventListener("click",runAutoTrace);
650
- $("btn-retrace-all").addEventListener("click",()=>{ if(Object.keys(aiCoords).length){ pushUndo(); coords=JSON.parse(JSON.stringify(aiCoords)); verified={}; renderAll(); setStatus("Reset all to AI positions — re-verify","var(--amb)"); } else runAutoTrace(); });
651
- $("btn-reset-single").addEventListener("click",()=>{ if(selectedLm&&aiCoords[selectedLm]){ pushUndo(); coords[selectedLm]={...aiCoords[selectedLm]}; verified[selectedLm]=false; renderAll(); } else alert("Select a landmark first."); });
652
-
653
- /* ==================== MANUAL PLACEMENT ==================== */
654
- $("btn-manual").addEventListener("click",()=>{ manualQueue=Object.keys(LANDMARKS).filter(k=>!coords[k]);
655
- if(!manualQueue.length){ alert("All landmarks already placed. Click any landmark in the list, then click the film to re-place it."); return; }
656
- nextPlace(); });
657
- function nextPlace(){ placingLm=manualQueue.shift()||null; const b=$("place-banner");
658
- if(!placingLm){ b.style.display="none"; setStatus("Manual placement complete","var(--grn)"); renderAll(); return; }
659
- b.style.display="block"; b.innerHTML=`✍️ <b>Click the film to place ${placingLm} — ${LANDMARKS[placingLm].full}</b><br>${LANDMARKS[placingLm].def}<br>${manualQueue.length} remaining after this.`; renderAll(); }
660
- $("btn-review").addEventListener("click",()=>{ const rows=Object.keys(coords).filter(k=>LANDMARKS[k]&&!verified[k])
661
- .sort((a,b)=>((confidence[a]??0.1)+(LANDMARKS[a].tier===3?0.25:0))-((confidence[b]??0.1)+(LANDMARKS[b].tier===3?0.25:0)));
662
- if(!rows.length){alert("Nothing to review — every placed landmark is verified. ✓");return;}
663
- selectLm(rows[0]); setStatus(`Review Queue: ${rows.length} unverified — starting with ${rows[0]} (lowest confidence / hardest)`,"var(--amb)");
664
- alert("Review Queue order:\n"+rows.map((k,i)=>`${i+1}. ${k} — ${LANDMARKS[k].full} — confidence ${Math.round((confidence[k]??0)*100)}%${LANDMARKS[k].tier===3?" (hard landmark)":""}${source[k]==="estimate"?" (ESTIMATE — must move)":""}`).join("\n")+"\n\nDrag each point to correct it, press V to verify, and the next in queue is one click on Review Queue away."); });
665
-
666
- /* ==================== RENDERING ==================== */
667
- const TRACE_LINES=[["S","N"],["Po","Or"],["N","A"],["N","B"],["N","Pog"],["S","Go"],["Go","Me"],["Go","Gn"],["ANS","PNS"],["UIT","UIA"],["LIT","LIA"],["A","Pog"],["Pn","PogS"],["Sn","Ls"],["Co","Go"],["Co","Gn"],["Ba","N"],["Pt","Gn"],["S","Ar"],["Ar","Go"]];
668
- let activeTab="ABO";
669
- const TABS=["ABO","Steiner","Downs","Tweed","McNamara","Ricketts","Holdaway","Jarabak"];
670
- function confColor(k){ if(source[k]==="estimate")return "var(--pur)"; const c=confidence[k]; if(c==null)return "#94a3b8"; return c>=0.7?"#34d399":c>=0.45?"#fbbf24":"#f87171"; }
671
- function movedMm(k){ if(!aiCoords[k]||!coords[k]||!pxPerMm)return null; return Math.hypot(coords[k].x-aiCoords[k].x,coords[k].y-aiCoords[k].y)/pxPerMm; }
672
- function usesEstimate(m){ return m.req.some(k=>coords[k]&&!verified[k]&&(source[k]==="estimate")); }
673
- function renderAll(){ renderSVG(); renderLmList(); renderAnalyses(); renderProgress(); }
674
- function renderProgress(){ const ks=Object.keys(LANDMARKS).filter(k=>coords[k]); const v=ks.filter(k=>verified[k]).length;
675
- $("progress-bar").style.width=ks.length?(100*v/ks.length)+"%":"0%"; $("progress-txt").innerText=`${v} / ${ks.length} verified`; }
676
- function renderSVG(){ const W=imgElem.naturalWidth,H=imgElem.naturalHeight; if(!W)return;
677
- svgElem.setAttribute("width",imgElem.clientWidth); svgElem.setAttribute("height",imgElem.clientHeight);
678
- const R=Math.max(3,W/260); let h="";
679
- const op=occlusalPoints(coords);
680
- if(showLines){ for(const [a,b] of TRACE_LINES){ if(coords[a]&&coords[b])h+=`<line x1="${coords[a].x}" y1="${coords[a].y}" x2="${coords[b].x}" y2="${coords[b].y}" stroke="rgba(56,189,248,.55)" stroke-width="${R*0.45}"/>`; }
681
- if(op)h+=`<line x1="${op.post.x}" y1="${op.post.y}" x2="${op.ant.x}" y2="${op.ant.y}" stroke="rgba(52,211,153,.8)" stroke-width="${R*0.5}"/>`; }
682
- if(showRuler||calStep>0){ if(coords.RULER_1&&coords.RULER_2){ h+=`<line x1="${coords.RULER_1.x}" y1="${coords.RULER_1.y}" x2="${coords.RULER_2.x}" y2="${coords.RULER_2.y}" stroke="#22d3ee" stroke-width="${R*0.6}"/>`;
683
- for(const rk of ["RULER_1","RULER_2"])h+=`<circle class="lm-handle" data-lm="${rk}" cx="${coords[rk].x}" cy="${coords[rk].y}" r="${R*1.5}" fill="#22d3ee" stroke="#fff" stroke-width="1"/>`; } }
684
- if(t1Baseline){ const al=getSuperCoords(); if(al){ for(const [a,b] of TRACE_LINES){ if(al[a]&&al[b])h+=`<line x1="${al[a].x}" y1="${al[a].y}" x2="${al[b].x}" y2="${al[b].y}" stroke="rgba(251,191,36,.5)" stroke-width="${R*0.4}" stroke-dasharray="6 4"/>`; }
685
- for(const k of Object.keys(al)){ if(LANDMARKS[k])h+=`<circle cx="${al[k].x}" cy="${al[k].y}" r="${R*0.8}" fill="none" stroke="#fbbf24" stroke-width="1.2"/>`; } } }
686
- if(showPoints){ for(const k of Object.keys(LANDMARKS)){ const p=coords[k]; if(!p)continue; const sel=k===selectedLm;
687
- h+=`<circle class="lm-handle" data-lm="${k}" cx="${p.x}" cy="${p.y}" r="${sel?R*1.7:R*1.25}" fill="${confColor(k)}" fill-opacity="${sel?1:.85}" stroke="${verified[k]?"#34d399":sel?"#fff":"#0b1220"}" stroke-width="${verified[k]?2.2:1.2}"/>`;
688
- if(showLabels)h+=`<text x="${p.x+R*2}" y="${p.y-R*1.4}" fill="#e2e8f0" font-size="${R*2.6}" font-weight="600" style="paint-order:stroke;stroke:#000;stroke-width:3px">${k}${verified[k]?" ✓":""}</text>`; } }
689
- svgElem.innerHTML=h;
690
- svgElem.querySelectorAll(".lm-handle").forEach(el=>{ el.addEventListener("pointerdown",e=>{ e.preventDefault(); e.stopPropagation(); draggingLm=el.getAttribute("data-lm"); dragMoved=false; pushUndo(); el.classList.add("dragging"); if(LANDMARKS[draggingLm])selectLm(draggingLm,false); });
691
- el.addEventListener("dblclick",()=>{ const k=el.getAttribute("data-lm"); if(aiCoords[k]){ pushUndo(); coords[k]={...aiCoords[k]}; verified[k]=false; renderAll(); } }); }); }
692
- function renderLmList(){ const q=($("lm-search").value||"").toLowerCase(); let h="";
693
- for(const [k,d] of Object.entries(LANDMARKS)){ if(q&&!(k.toLowerCase().includes(q)||d.full.toLowerCase().includes(q)))continue; const p=coords[k]; const mv=movedMm(k);
694
- h+=`<div class="lm-row ${k===selectedLm?"sel":""}" data-k="${k}"><span class="lm-dot" style="background:${p?confColor(k):"#334155"}"></span><span class="nm"><b>${k}</b>${p&&verified[k]?' <span class="vf">✓ verified</span>':""}<span class="full">${d.full}${d.tentative?" ⚠ index tentative":""}</span></span>${p?`<span class="mv">${confidence[k]!=null?Math.round(confidence[k]*100)+"%":"manual"}${mv!=null?`<br>moved ${mv.toFixed(1)}mm`:""}${ttaGap[k]!=null&&pxPerMm?`<br>2-pass Δ ${(ttaGap[k]/pxPerMm).toFixed(1)}mm`:""}${engGap[k]!=null&&pxPerMm?`<br>A↔B Δ ${(engGap[k]/pxPerMm).toFixed(1)}mm`:""}</span>`:`<span class="mv">not placed</span>`}</div>`; }
695
- $("lm-list").innerHTML=h||'<p class="note">No match.</p>';
696
- $("lm-list").querySelectorAll(".lm-row").forEach(r=>r.addEventListener("click",()=>selectLm(r.getAttribute("data-k")))); }
697
- $("lm-search").addEventListener("input",renderLmList);
698
- function selectLm(k,focus=true){ selectedLm=k; $("selected-lm-label").innerText=k?`${k} — ${LANDMARKS[k].full}`:"None"; renderSVG(); renderLmList();
699
- if(focus&&coords[k]){ /* gentle status hint with the definition */ setStatus(`${k}: ${LANDMARKS[k].def}`,"var(--amb)"); } }
700
- function renderAnalyses(){ latestMetrics=computeAll(coords,pxPerMm||10);
701
- let tabs=""; for(const t of TABS)tabs+=`<span class="tab ${t===activeTab?"active":""}" data-t="${t}">${t==="ABO"?"ABO Focus":t}</span>`;
702
- $("analysis-tabs").innerHTML=tabs; $("analysis-tabs").querySelectorAll(".tab").forEach(el=>el.addEventListener("click",()=>{activeTab=el.getAttribute("data-t"); renderAnalyses();}));
703
- const rows=MEASURES.filter(m=>m.an===activeTab); const t1m=t1Baseline?t1Baseline.metrics:null;
704
- let h=`<table><tr><th>Measurement</th><th>Norm</th><th>Value</th>${t1m?"<th>T1</th><th>Δ</th>":""}<th>Status</th></tr>`;
705
- for(const m of rows){ const v=latestMetrics[m.id];
706
- if(v==null){ h+=`<tr><td>${m.name}${m.note?`<br><span class="note">${m.note}</span>`:""}</td><td>${m.norm==null?"—":m.norm+" ±"+m.sd}</td><td class="st-na">—</td>${t1m?"<td>—</td><td>—</td>":""}<td class="st-na">missing: ${m.req.filter(k=>!coords[k]).join(", ")||"—"}</td></tr>`; continue; }
707
- const st=m.norm==null?"":(Math.abs(v-m.norm)<=m.sd?"Normal":v>m.norm?"High":"Low");
708
- const badges=(usesEstimate(m)?' <span class="badge b-est">EST</span>':"")+((m.unit==="mm"&&!calibrated)?' <span class="badge b-unc">UNCAL</span>':"")+((m.req.some(k=>coords[k]&&!verified[k]))?' <span class="badge b-rev">UNVERIFIED</span>':"");
709
- h+=`<tr><td>${m.name}${m.note?`<br><span class="note">${m.note}</span>`:""}</td><td>${m.norm==null?"see note":m.norm+" ±"+m.sd}</td><td><b>${v.toFixed(1)}${m.unit}</b>${badges}</td>${t1m?`<td>${t1m[m.id]==null?"—":t1m[m.id].toFixed(1)}</td><td>${t1m[m.id]==null?"—":(v-t1m[m.id]).toFixed(1)}</td>`:""}<td class="st-${st}">${st}</td></tr>`; }
710
- h+="</table>"; $("analysis-tables").innerHTML=h; updateDiagnosis(); }
711
- function updateDiagnosis(){ const m=latestMetrics; if(m.ANB==null){$("diag-headline").innerText="Awaiting tracing…";return;}
712
- const skel=m.ANB>4?"Skeletal Class II":m.ANB<0?"Skeletal Class III":"Skeletal Class I";
713
- const sag=`${skel} — SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°${m.WITS!=null?`, Wits ${m.WITS} mm${calibrated?"":" (uncal)"}`:""}`;
714
- const vert=(m.FMA!=null&&m.FMA>29)||(m.SNGOGN!=null&&m.SNGOGN>37)?"Hyperdivergent (high angle)":(m.FMA!=null&&m.FMA<21)||(m.SNGOGN!=null&&m.SNGOGN<27)?"Hypodivergent (low angle)":"Normodivergent";
715
- const dent=`U1-SN ${m.U1SN}° (${m.U1SN>107?"proclined":m.U1SN<97?"retroclined":"normal"}), IMPA ${m.IMPA}° (${m.IMPA>95?"proclined":m.IMPA<85?"retroclined":"normal"}), IIA ${m.IIA}°`;
716
- const soft=`UL E-line ${m.UL_E} mm, LL E-line ${m.LL_E} mm`;
717
- $("diag-headline").innerText=`${skel} • ${vert}`; $("diag-sagittal").innerText=sag; $("diag-vertical").innerText=vert; $("diag-dental").innerText=dent; $("diag-soft").innerText=soft;
718
- latestMetrics._diag={skel,vert,dent,soft}; }
719
-
720
- /* ==================== INTERACTION ==================== */
721
- function getSVGCoords(e){ const pt=svgElem.createSVGPoint(); pt.x=e.clientX; pt.y=e.clientY; return pt.matrixTransform(svgElem.getScreenCTM().inverse()); }
722
- function updateLoupe(p,name){ if(!imgElem.src)return; $("loupe-box").style.display="block"; $("loupe-label").innerText=name;
723
- const cv=$("loupe-canvas"),ctx=cv.getContext("2d"); const size=150,zoom=3,src=size/zoom;
724
- ctx.clearRect(0,0,size,size); ctx.filter=imgElem.style.filter||"none";
725
- ctx.drawImage(imgElem,p.x-src/2,p.y-src/2,src,src,0,0,size,size); ctx.filter="none";
726
- ctx.strokeStyle="#38bdf8"; ctx.lineWidth=1.5; ctx.beginPath();
727
- ctx.moveTo(size/2,0);ctx.lineTo(size/2,size/2-6);ctx.moveTo(size/2,size/2+6);ctx.lineTo(size/2,size);
728
- ctx.moveTo(0,size/2);ctx.lineTo(size/2-6,size/2);ctx.moveTo(size/2+6,size/2);ctx.lineTo(size,size/2);ctx.stroke(); }
729
- window.addEventListener("pointermove",e=>{ if(!draggingLm||!coords[draggingLm])return; dragMoved=true; const p=getSVGCoords(e);
730
- coords[draggingLm].x=p.x; coords[draggingLm].y=p.y;
731
- if(draggingLm==="RULER_1"||draggingLm==="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; calibrated=true; calMethod="10 mm ruler"; calStatusUpdate(); } }
732
- else if(LANDMARKS[draggingLm]&&source[draggingLm]==="ai") source[draggingLm]="ai-edited";
733
- updateLoupe(p,draggingLm); renderAll(); });
734
- window.addEventListener("pointerup",()=>{ if(draggingLm){ if(dragMoved)lastDragEnd=Date.now(); draggingLm=null; dragMoved=false; $("loupe-box").style.display="none"; renderAll(); } });
735
- container.addEventListener("click",e=>{ if(Date.now()-lastDragEnd<300)return; if(!imgElem.naturalWidth)return; const p=getSVGCoords(e);
736
- if(placingLm){ pushUndo(); coords[placingLm]={x:p.x,y:p.y}; source[placingLm]="manual"; confidence[placingLm]=null; verified[placingLm]=false; selectLm(placingLm,false); nextPlace(); return; }
737
- if(selectedLm&&!coords[selectedLm]&&LANDMARKS[selectedLm]){ pushUndo(); coords[selectedLm]={x:p.x,y:p.y}; source[selectedLm]="manual"; confidence[selectedLm]=null; verified[selectedLm]=false; renderAll(); return; }
738
- if(calStep===1){ coords.RULER_1={x:p.x,y:p.y}; coords.RULER_2={x:p.x,y:p.y+80}; calStep=2; showRuler=true; $("btn-cal").innerText="Now click the 10 mm mark…"; renderAll(); return; }
739
- if(calStep===2){ coords.RULER_2={x:p.x,y:p.y}; const d=Math.hypot(coords.RULER_2.x-coords.RULER_1.x,coords.RULER_2.y-coords.RULER_1.y);
740
- if(d>1){ pxPerMm=d/10; calibrated=true; calMethod="10 mm ruler"; calStatusUpdate(); } calStep=0; $("btn-cal").innerText="📐 Place 10 mm Ruler"; renderAll(); } });
741
- $("btn-cal").addEventListener("click",()=>{ if(!imgElem.src&&!coords.S){alert("Upload a film first.");return;} showRuler=true; calStep=1; $("btn-cal").innerText="Click the 0 mm mark on the ruler…"; renderAll(); });
742
- window.addEventListener("keydown",e=>{ const tag=document.activeElement&&document.activeElement.tagName;
743
- if(e.code==="Space"&&!["INPUT","SELECT","TEXTAREA"].includes(tag)){ e.preventDefault(); if(!spacePeek){spacePeek=true; svgElem.style.opacity="0";} return; }
744
- if(["INPUT","TEXTAREA"].includes(tag))return;
745
- if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="z"){ const s=undoStack.pop(); if(s){ const d=JSON.parse(s); coords=d.coords; verified=d.verified; pxPerMm=d.pxPerMm; calibrated=d.calibrated; calStatusUpdate(); renderAll(); } return; }
746
- if(!selectedLm||!coords[selectedLm])return;
747
- const step=e.shiftKey?0.1:0.5; let used=true;
748
- if(e.key==="ArrowLeft")coords[selectedLm].x-=step; else if(e.key==="ArrowRight")coords[selectedLm].x+=step;
749
- else if(e.key==="ArrowUp")coords[selectedLm].y-=step; else if(e.key==="ArrowDown")coords[selectedLm].y+=step;
750
- else if(e.key.toLowerCase()==="v"){ verified[selectedLm]=true; setStatus(`${selectedLm} verified ✓`,"var(--grn)"); }
751
- else used=false;
752
- if(used){ e.preventDefault(); renderAll(); } });
753
- window.addEventListener("keyup",e=>{ if(e.code==="Space"){ spacePeek=false; svgElem.style.opacity="1"; } });
754
- $("btn-verify-sel").addEventListener("click",()=>{ if(selectedLm&&coords[selectedLm]){ verified[selectedLm]=true; renderAll(); } });
755
- $("btn-verify-all-conf").addEventListener("click",()=>{ let n=0; for(const k of Object.keys(coords)){ if(LANDMARKS[k]&&source[k]==="ai"&&(confidence[k]||0)>=0.7){ verified[k]=true; n++; } } renderAll(); setStatus(`Verified ${n} high-confidence AI points — hard/low-confidence points still need your eyes`,"var(--grn)"); });
756
-
757
- /* ==================== SUPERIMPOSITION ==================== */
758
- $("btn-lock-t1").addEventListener("click",()=>{ if(!coords.S){alert("Trace T1 first.");return;}
759
- t1Baseline={coords:JSON.parse(JSON.stringify(coords)),metrics:JSON.parse(JSON.stringify(latestMetrics)),date:$("pt-date").value||"T1"};
760
- $("super-status").innerHTML=`<span style="color:#5eead4;font-weight:700">✓ T1 locked (${t1Baseline.date})</span> — now load the T2 film.`; renderAll(); });
761
- $("btn-clear-t1").addEventListener("click",()=>{ t1Baseline=null; $("super-status").innerText="No T1 baseline locked."; renderAll(); });
762
- $("super-mode").addEventListener("change",renderAll);
763
- function getSuperCoords(){ if(!t1Baseline||!t1Baseline.coords.S||!coords.S)return null; const mode=$("super-mode").value;
764
- const t=t1Baseline.coords; let o1=t.S,o2=coords.S,a1=0,a2=0;
765
- if(mode==="MAXILLARY"&&t.PNS&&t.ANS&&coords.PNS&&coords.ANS){ o1=t.PNS; o2=coords.PNS; a1=Math.atan2(t.ANS.y-t.PNS.y,t.ANS.x-t.PNS.x); a2=Math.atan2(coords.ANS.y-coords.PNS.y,coords.ANS.x-coords.PNS.x); }
766
- else if(mode==="MANDIBULAR"&&t.Me&&t.Go&&coords.Me&&coords.Go){ o1=t.Me; o2=coords.Me; a1=Math.atan2(t.Go.y-t.Me.y,t.Go.x-t.Me.x); a2=Math.atan2(coords.Go.y-coords.Me.y,coords.Go.x-coords.Me.x); }
767
- else { if(!t.N||!coords.N)return null; a1=Math.atan2(t.N.y-t.S.y,t.N.x-t.S.x); a2=Math.atan2(coords.N.y-coords.S.y,coords.N.x-coords.S.x); }
768
- const d=a2-a1, co=Math.cos(d), si=Math.sin(d), out={};
769
- for(const [k,pt] of Object.entries(t)){ const dx=pt.x-o1.x, dy=pt.y-o1.y; out[k]={x:o2.x+dx*co-dy*si, y:o2.y+dx*si+dy*co}; } return out; }
770
-
771
- /* ==================== EXPORTS / MISC ==================== */
772
- $("btn-export-csv").addEventListener("click",()=>{ if(latestMetrics.ANB==null){alert("Trace a film first.");return;}
773
- const nm=$("pt-name").value||"Patient", ch=$("pt-chart").value||"", dt=$("pt-date").value||"";
774
- let csv="Patient,Chart,Date,Analysis,Measurement,Norm,SD,Value,Unit,Status,Calibrated,UsesEstimate\n";
775
- for(const m of MEASURES){ const v=latestMetrics[m.id]; if(v==null)continue; const st=m.norm==null?"":(Math.abs(v-m.norm)<=m.sd?"Normal":v>m.norm?"High":"Low");
776
- csv+=`"${nm}","${ch}","${dt}","${m.an}","${m.name}","${m.norm??""}","${m.sd??""}",${v.toFixed(1)},"${m.unit}","${st}","${calibrated}","${usesEstimate(m)}"\n`; }
777
- downloadBlob(new Blob([csv],{type:"text/csv"}),`Ceph_v3_${nm.replace(/\s+/g,"_")}_${dt}.csv`); });
778
- $("btn-copy-note").addEventListener("click",()=>{ if(latestMetrics.ANB==null)return; const m=latestMetrics, d=m._diag||{};
779
- const unver=ABO_REQUIRED.filter(k=>coords[k]&&!verified[k]);
780
- const note=[`CEPHALOMETRIC ANALYSIS — ${$("pt-name").value||"Patient"} (${$("pt-date").value||""}) — OrthoCeph Pro v3.4`,
781
- `Diagnosis: ${d.skel||""} • ${d.vert||""}`,
782
- `Sagittal: SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°, Wits ${m.WITS} mm`,
783
- `Vertical: FMA ${m.FMA}°, SN-GoGn ${m.SNGOGN}°`,
784
- `Dental: U1-SN ${m.U1SN}°, U1-NA ${m.U1NA_D}°/${m.U1NA_M}mm, L1-NB ${m.L1NB_D}°/${m.L1NB_M}mm, IMPA ${m.IMPA}°, IIA ${m.IIA}°, OJ ${m.OJ} mm, OB ${m.OB} mm`,
785
- `Soft tissue: UL E-line ${m.UL_E} mm, LL E-line ${m.LL_E} mm, H-angle ${m.HANGLE}°`,
786
- `Calibration: ${calibrated?calMethod+" ("+pxPerMm.toFixed(2)+" px/mm)":"UNCALIBRATED — mm values provisional"}`,
787
- unver.length?`⚠ Unverified ABO landmarks: ${unver.join(", ")}`:"✓ All ABO landmarks verified"].join("\n");
788
- const done=()=>{ $("btn-copy-note").innerText="✓ Copied"; setTimeout(()=>$("btn-copy-note").innerText="📋 Copy Clinical Note",1800); };
789
- if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(note).then(done).catch(()=>{prompt("Copy the note:",note);});
790
- else prompt("Copy the note:",note); });
791
- $("btn-print").addEventListener("click",()=>{ buildPrintReport(); window.print(); });
792
- function buildPrintReport(){ const pr=$("print-report"); const m=latestMetrics;
793
- const ks=Object.keys(LANDMARKS).filter(k=>coords[k]); const nv=ks.filter(k=>verified[k]).length;
794
- let tables="";
795
- for(const t of TABS){ const rows=MEASURES.filter(x=>x.an===t); if(!rows.length)continue;
796
- tables+=`<h2>${t==="ABO"?"ABO Focus":t} Analysis</h2><table><tr><th>Measurement</th><th>Norm</th><th>Value</th><th>Status</th></tr>`;
797
- for(const mm of rows){ const v=m[mm.id];
798
- if(v==null){ tables+=`<tr><td>${mm.name}</td><td>${mm.norm==null?"—":mm.norm+" ±"+mm.sd}</td><td>—</td><td>missing landmark</td></tr>`; continue; }
799
- const st=mm.norm==null?"":(Math.abs(v-mm.norm)<=mm.sd?"Normal":v>mm.norm?"High":"Low");
800
- tables+=`<tr><td>${mm.name}</td><td>${mm.norm==null?"see note":mm.norm+" ±"+mm.sd}</td><td>${v.toFixed(1)} ${mm.unit}${usesEstimate(mm)?" (estimate)":""}${mm.unit==="mm"&&!calibrated?" (uncalibrated)":""}</td><td>${st}</td></tr>`; }
801
- tables+="</table>"; }
802
- const film=(coords.S&&imgElem.src)?`<div class="pr-film"><img src="${imgElem.src}"><svg viewBox="${svgElem.getAttribute("viewBox")||""}">${svgElem.innerHTML}</svg></div>`:"";
803
- pr.innerHTML=`<h1>Cephalometric Report — OrthoCeph Pro v3.4</h1>
804
- <div class="pr-meta">Patient: <b>${$("pt-name").value||"—"}</b> &nbsp;|&nbsp; Chart: ${$("pt-chart").value||"—"} &nbsp;|&nbsp; Date: ${$("pt-date").value||"—"}<br>
805
- Calibration: ${calibrated?calMethod+" ("+pxPerMm.toFixed(2)+" px/mm)":"UNCALIBRATED — mm values provisional"} &nbsp;|&nbsp; Landmarks verified: ${nv} / ${ks.length}</div>
806
- <div class="pr-diag"><b>${$("diag-headline").innerText}</b><br>Sagittal: ${$("diag-sagittal").innerText}<br>Vertical: ${$("diag-vertical").innerText}<br>Dental: ${$("diag-dental").innerText}<br>Soft tissue: ${$("diag-soft").innerText}</div>
807
- ${film}${tables}
808
- <div class="pr-foot">AI-assisted tracing (Engine A: HRNet-W32 cepha29, published MRE 1.24 mm; Engine B when loaded: HRNet-W48, recorded MRE 1.10 mm; ensemble averages both). Every landmark requires clinician verification before clinical use; values marked (estimate) depend on an unverified landmark and (uncalibrated) values await ruler calibration. Generated ${new Date().toLocaleString()}.</div>`;
809
- }
810
- function setZoom(z){ zoomLevel=Math.min(3,Math.max(0.4,z)); container.style.transform=`scale(${zoomLevel})`; }
811
- $("btn-zoom-in").addEventListener("click",()=>setZoom(zoomLevel+0.2));
812
- $("btn-zoom-out").addEventListener("click",()=>setZoom(zoomLevel-0.2));
813
- $("btn-zoom-reset").addEventListener("click",()=>setZoom(1));
814
- vw.addEventListener("wheel",e=>{ if(!coords.S)return; e.preventDefault(); setZoom(zoomLevel+(e.deltaY<0?0.1:-0.1)); },{passive:false});
815
- $("btn-bright").addEventListener("click",()=>{ const b=$("filter-box"); b.style.display=b.style.display==="none"?"block":"none"; });
816
- function applyFilters(){ imgElem.style.filter=`brightness(${$("brightness").value}) contrast(${$("contrast").value}) invert(${$("invert").checked?1:0})`; }
817
- $("brightness").addEventListener("input",applyFilters); $("contrast").addEventListener("input",applyFilters); $("invert").addEventListener("change",applyFilters);
818
- $("reset-filters").addEventListener("click",()=>{ $("brightness").value=1; $("contrast").value=1; $("invert").checked=false; applyFilters(); });
819
- function mkToggle(id,get,set){ $(id).addEventListener("click",()=>{ const v=!get(); set(v); $(id).innerText=$(id).innerText.replace(/ON|OFF/,v?"ON":"OFF"); renderAll(); }); }
820
- mkToggle("tog-lines",()=>showLines,v=>showLines=v); mkToggle("tog-points",()=>showPoints,v=>showPoints=v);
821
- mkToggle("tog-labels",()=>showLabels,v=>showLabels=v); mkToggle("tog-trace",()=>showTrace,v=>{showTrace=v; showLines=v;});
822
- $("btn-next-patient").addEventListener("click",()=>{ if(!confirm("Clear this patient and start fresh? Unsaved work will be lost."))return;
823
- coords={}; aiCoords={}; confidence={}; verified={}; source={}; t1Baseline=null; pxPerMm=null; calibrated=false; calMethod=""; calStep=0; showRuler=false; selectedLm=null; undoStack=[];
824
- imgElem.src=""; container.style.display="none"; dropzone.style.display="flex"; svgElem.innerHTML="";
825
- $("pt-name").value=""; $("pt-chart").value=""; $("pt-date").valueAsDate=new Date(); $("super-status").innerText="No T1 baseline locked.";
826
- $("selected-lm-label").innerText="None"; calStatusUpdate(); renderAll(); setStatus("Ready for next patient","var(--amb)"); });
827
- window.addEventListener("resize",()=>renderSVG());
828
- /* ==================== NUDGE BAR (touch / no-keyboard control) ==================== */
829
- let nudgeStep=1;
830
- function reviewOrder(){ return Object.keys(coords).filter(k=>LANDMARKS[k]&&!verified[k])
831
- .sort((a,b)=>((confidence[a]??0.1)+(LANDMARKS[a].tier===3?0.25:0))-((confidence[b]??0.1)+(LANDMARKS[b].tier===3?0.25:0))); }
832
- function updateNudgeBar(){ const bar=$("nudge-bar"); if(!bar)return;
833
- if(selectedLm&&coords[selectedLm]){ bar.classList.add("show"); $("nb-name").innerText=selectedLm+" — "+LANDMARKS[selectedLm].full+(verified[selectedLm]?" ✓":""); }
834
- else bar.classList.remove("show"); }
835
- document.querySelectorAll("#nudge-bar button[data-dx]").forEach(b=>b.addEventListener("click",()=>{
836
- if(!selectedLm||!coords[selectedLm])return; pushUndo();
837
- coords[selectedLm].x+=parseFloat(b.getAttribute("data-dx"))*nudgeStep;
838
- coords[selectedLm].y+=parseFloat(b.getAttribute("data-dy"))*nudgeStep;
839
- if(source[selectedLm]==="ai")source[selectedLm]="ai-edited"; renderAll(); }));
840
- $("nb-step").addEventListener("click",()=>{ nudgeStep=nudgeStep===1?0.2:1; $("nb-step").innerText="Step: "+(nudgeStep===1?"1px":"0.2px"); });
841
- $("nb-verify").addEventListener("click",()=>{ if(selectedLm&&coords[selectedLm]){ verified[selectedLm]=true; renderAll(); updateNudgeBar(); } });
842
- $("nb-next").addEventListener("click",()=>{ const q=reviewOrder(); if(!q.length){ alert("All placed landmarks are verified. ✓"); return; }
843
- const nxt=q.find(k=>k!==selectedLm)||q[0]; selectLm(nxt); });
844
- const _selectLmOrig=selectLm;
845
- selectLm=function(k,focus=true){ _selectLmOrig(k,focus); updateNudgeBar(); };
846
- calStatusUpdate(); renderAll();
847
- </script>
848
- </body>
849
- </html>