Abddeus commited on
Commit
5ca2eba
·
verified ·
1 Parent(s): 6745db6

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +558 -347
index.html CHANGED
@@ -8,11 +8,11 @@
8
  <script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
9
  <link rel="preconnect" href="https://fonts.googleapis.com">
10
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
12
  <style>
13
  :root {
14
- --bg-dark: #090d16;
15
- --surface-dark: #111827;
16
  --surface-card: #1e293b;
17
  --surface-border: #334155;
18
  --accent: #2563eb;
@@ -41,13 +41,13 @@
41
  header {
42
  background: var(--surface-dark);
43
  border-bottom: 1px solid var(--surface-border);
44
- height: 58px;
45
- padding: 0 18px;
46
  display: flex;
47
  align-items: center;
48
  justify-content: space-between;
49
  flex-shrink: 0;
50
- z-index: 10;
51
  }
52
 
53
  .brand { display: flex; align-items: center; gap: 10px; }
@@ -56,27 +56,28 @@
56
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
57
  border-radius: 8px; display: flex; align-items: center;
58
  justify-content: center; font-weight: 700; font-size: 16px; color: white;
 
59
  }
60
- .brand-title { font-size: 15px; font-weight: 700; letter-spacing: -0.02em; }
61
- .brand-subtitle { font-size: 10px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; }
62
 
63
- .header-actions { display: flex; align-items: center; gap: 8px; }
64
 
65
  #status-badge {
66
  display: flex; align-items: center; gap: 7px; font-size: 11px;
67
- font-weight: 600; background: rgba(30, 41, 59, 0.9);
68
  border: 1px solid var(--surface-border); padding: 5px 11px;
69
  border-radius: 20px; color: var(--text-muted); margin-right: 4px;
70
  }
71
  #status-badge .indicator { width: 8px; height: 8px; border-radius: 50%; background-color: var(--status-amber); }
72
 
73
- .workspace { display: flex; flex: 1; height: calc(100vh - 58px); overflow: hidden; }
74
 
75
  .sidebar {
76
- width: 320px; background: var(--surface-dark);
77
  border-right: 1px solid var(--surface-border);
78
- padding: 14px; display: flex; flex-direction: column;
79
- gap: 12px; overflow-y: auto; flex-shrink: 0;
80
  }
81
 
82
  .section-header {
@@ -94,73 +95,74 @@
94
  .form-group label { font-size: 10px; font-weight: 600; color: var(--text-muted); }
95
 
96
  .input-field {
97
- background: #0f172a; border: 1px solid var(--surface-border);
98
  border-radius: 6px; padding: 6px 9px; color: var(--text-main);
99
- font-size: 12px; outline: none; width: 100%;
100
  }
101
  .input-field:focus { border-color: #3b82f6; }
102
 
103
  .btn {
104
- background: var(--accent); color: white; border: none; padding: 7px 11px;
105
  border-radius: 6px; font-weight: 600; font-size: 11px; cursor: pointer;
106
  display: inline-flex; align-items: center; justify-content: center; gap: 5px;
107
- transition: all 0.15s ease;
108
  }
109
  .btn:hover:not(:disabled) { background: var(--accent-hover); }
110
- .btn:disabled { background: #1e293b; color: #64748b; cursor: not-allowed; }
111
- .btn-secondary { background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main); }
112
- .btn-secondary:hover { background: #334155; }
113
- .btn-danger { background: rgba(244, 63, 94, 0.15); border: 1px solid rgba(244, 63, 94, 0.4); color: #fda4af; }
114
- .btn-danger:hover { background: rgba(244, 63, 94, 0.25); }
115
- .btn-teal { background: rgba(20, 184, 166, 0.15); border: 1px solid rgba(20, 184, 166, 0.45); color: #5eead4; }
116
- .btn-teal:hover { background: rgba(20, 184, 166, 0.28); }
117
-
118
- .mode-group { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 5px; }
119
  .mode-btn {
120
- background: #0f172a; border: 1px solid var(--surface-border);
121
- color: var(--text-muted); padding: 6px 4px; border-radius: 6px;
122
  font-size: 10.5px; font-weight: 600; cursor: pointer; text-align: center;
123
- transition: all 0.15s;
124
  }
125
- .mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; }
126
 
127
- .toggle-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 5px; }
128
  .toggle-pill {
129
- background: #0f172a; border: 1px solid var(--surface-border);
130
- color: var(--text-muted); padding: 5px; border-radius: 6px;
131
- font-size: 10.5px; font-weight: 600; cursor: pointer; text-align: center;
132
  }
133
  .toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }
134
 
135
- .cvm-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; }
136
  .cvm-btn {
137
- background: #0f172a; border: 1px solid var(--surface-border);
138
- color: var(--text-muted); padding: 6px 2px; border-radius: 5px;
139
- font-size: 11px; font-weight: 700; cursor: pointer; text-align: center;
140
  }
141
- .cvm-btn.active { background: var(--cvm-teal); color: #042f2e; border-color: #5eead4; }
142
 
143
  .slider-row {
144
  display: flex; align-items: center; justify-content: space-between;
145
- font-size: 11px; color: var(--text-muted);
146
  }
147
- .slider-row input[type="range"] { width: 135px; accent-color: var(--accent); cursor: pointer; }
148
 
149
  #norms-drawer {
150
- display: none; flex-direction: column; gap: 6px; max-height: 180px;
151
  overflow-y: auto; padding-top: 6px; border-top: 1px solid var(--surface-border);
152
  }
153
  .norm-edit-row {
154
- display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 5px; align-items: center; font-size: 11px;
155
  }
156
  .norm-edit-row input {
157
- background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main);
158
- padding: 3px 5px; border-radius: 4px; font-size: 11px; width: 100%; text-align: center;
159
  }
160
 
161
  .viewport {
162
- flex: 1; background: #05070c; position: relative;
163
  overflow: hidden; display: flex; align-items: center; justify-content: center;
 
164
  }
165
  .viewport.drag-over {
166
  outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
@@ -168,96 +170,109 @@
168
 
169
  #empty-dropzone {
170
  display: flex; flex-direction: column; align-items: center; justify-content: center;
171
- gap: 12px; color: var(--text-muted); text-align: center; padding: 40px;
172
  border: 2px dashed var(--surface-border); border-radius: 16px; cursor: pointer;
 
173
  }
174
- #empty-dropzone:hover { border-color: #3b82f6; color: var(--text-main); }
175
 
176
- #viewport-container { position: relative; transform-origin: 0 0; user-select: none; cursor: crosshair; display: none; }
177
- #ceph-image { display: block; max-height: 84vh; max-width: 100%; pointer-events: none; border-radius: 4px; }
178
- #overlay-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; }
 
 
 
179
 
180
  #loupe-box {
181
- position: absolute; top: 16px; left: 16px; width: 150px; height: 150px;
182
  border: 2px solid #38bdf8; border-radius: 50%; overflow: hidden;
183
- background: #000; box-shadow: 0 8px 24px rgba(0,0,0,0.7);
184
- display: none; z-index: 20; pointer-events: none;
185
  }
186
  #loupe-canvas { width: 100%; height: 100%; display: block; }
187
  #loupe-label {
188
  position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%);
189
- background: rgba(15, 23, 42, 0.85); color: #38bdf8; font-size: 10px;
190
- font-weight: 700; padding: 2px 8px; border-radius: 10px;
191
  }
192
 
193
  .viewport-overlay-controls {
194
  position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%);
195
- background: rgba(17, 24, 39, 0.92); backdrop-filter: blur(8px);
196
  border: 1px solid var(--surface-border); border-radius: 30px;
197
- padding: 5px 14px; display: flex; align-items: center; gap: 8px; z-index: 5;
198
- white-space: nowrap;
199
  }
200
  .viewport-overlay-controls button {
201
  background: none; border: none; color: var(--text-main);
202
- cursor: pointer; font-size: 11px; font-weight: 600; padding: 3px 5px;
203
  }
204
- .viewport-overlay-controls button:hover { color: #60a5fa; }
205
  .shortcut-hint { font-size: 10px; color: var(--text-muted); }
206
 
207
- .landmark-handle { pointer-events: all; cursor: grab; transition: r 0.1s ease; }
208
- .landmark-handle:hover { r: 7.5 !important; stroke: #ffffff !important; stroke-width: 2.5px !important; }
209
  .landmark-handle.dragging { cursor: grabbing !important; r: 9 !important; fill: #38bdf8 !important; }
210
  .landmark-text {
211
- font-family: 'Inter', sans-serif; font-size: 11px; font-weight: 700;
212
  fill: #ffffff; paint-order: stroke; stroke: #000000; stroke-width: 3px;
213
  pointer-events: none; user-select: none;
214
  }
215
 
216
  .analysis-panel {
217
- width: 550px; background: var(--surface-dark);
218
  border-left: 1px solid var(--surface-border);
219
- padding: 14px 18px; display: flex; flex-direction: column;
220
  gap: 12px; overflow-y: auto; flex-shrink: 0;
221
  }
222
 
223
  .diagnosis-banner {
224
- background: linear-gradient(135deg, rgba(37, 99, 235, 0.14), rgba(15, 23, 42, 0.9));
225
  border: 1px solid #3b82f6;
226
- border-radius: 10px;
227
- padding: 11px 13px;
228
  display: flex;
229
  flex-direction: column;
230
  gap: 6px;
231
  }
232
- .diagnosis-headline { font-size: 12.5px; font-weight: 700; color: #93c5fd; }
233
- .diagnosis-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px 12px; font-size: 11px; }
234
  .diag-item { display: flex; flex-direction: column; }
235
- .diag-label { font-size: 9.5px; color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
236
  .diag-val { font-weight: 600; color: var(--text-main); }
237
 
238
- .analysis-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 11.5px; }
239
  .analysis-table th {
240
- text-align: left; padding: 6px 7px; font-weight: 600; font-size: 9.5px;
241
  text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);
242
  border-bottom: 1px solid var(--surface-border);
243
  }
244
- .analysis-table td { padding: 6px 7px; border-bottom: 1px solid rgba(51, 65, 85, 0.4); }
245
  .metric-name { font-weight: 600; color: #e2e8f0; }
246
- .metric-norm { color: var(--text-muted); font-size: 10.5px; }
247
- .metric-val { font-weight: 700; font-feature-settings: "tnum"; }
248
- .metric-diff { font-weight: 600; font-size: 10.5px; font-feature-settings: "tnum"; }
249
 
250
- .pill { display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 10px; font-size: 9.5px; font-weight: 600; }
251
  .pill-normal { background: rgba(16, 185, 129, 0.15); color: var(--status-green); }
252
  .pill-deviated { background: rgba(244, 63, 94, 0.15); color: var(--status-red); }
253
  .pill-neutral { background: #1e293b; color: var(--text-muted); }
254
 
 
 
 
 
 
 
 
 
 
255
  @media print {
256
  body { background: white !important; color: black !important; height: auto !important; overflow: visible !important; }
257
- header, .sidebar, .viewport-overlay-controls, #loupe-box, #empty-dropzone { display: none !important; }
258
  .workspace { display: block !important; height: auto !important; }
259
- .viewport { background: white !important; margin-bottom: 14px; justify-content: center; }
260
- #ceph-image { max-height: 360px !important; }
261
  .analysis-panel { width: 100% !important; border: none !important; background: white !important; color: black !important; padding: 0 !important; }
262
  .diagnosis-banner { background: #f8fafc !important; border: 1px solid #94a3b8 !important; color: black !important; margin-bottom: 10px; }
263
  .diagnosis-headline { color: #1e3a8a !important; }
@@ -271,44 +286,46 @@
271
  </head>
272
  <body>
273
 
 
 
274
  <header>
275
  <div class="brand">
276
  <div class="brand-icon">O</div>
277
  <div>
278
  <div class="brand-title">OrthoCeph Pro</div>
279
- <div class="brand-subtitle">ABO, Regional Superimposition & CVM Clinical Suite</div>
280
  </div>
281
  </div>
282
 
283
  <div class="header-actions">
284
  <div id="status-badge">
285
  <div class="indicator" id="status-ind"></div>
286
- <span id="status-txt">Loading AI Engine...</span>
287
  </div>
288
- <button class="btn btn-secondary" id="btn-save-json" title="Save tracing & patient data as .json">
289
  💾 Save JSON
290
  </button>
291
- <button class="btn btn-secondary" onclick="document.getElementById('json-input').click()" title="Load saved .json tracing">
292
  📂 Load JSON
293
  </button>
294
  <input type="file" id="json-input" accept=".json,application/json" style="display:none;">
295
- <button class="btn btn-secondary" id="btn-copy-note" title="Copy clinical summary & diagnosis for chart">
296
  📋 Copy Note
297
  </button>
298
- <button class="btn btn-secondary" id="btn-export-csv" title="Download measurements to Excel CSV">
299
  📊 CSV
300
  </button>
301
- <button class="btn btn-secondary" onclick="window.print()">
302
  🖨️ Print
303
  </button>
304
- <button class="btn btn-danger" id="btn-next-patient">
305
  🔄 Next Patient
306
  </button>
307
  </div>
308
  </header>
309
 
310
  <div class="workspace">
311
- <!-- Left Sidebar -->
312
  <aside class="sidebar">
313
  <div>
314
  <div class="section-header"><span>1. Radiograph & Patient</span></div>
@@ -316,15 +333,15 @@
316
  <input type="file" id="file-input" accept="image/*,.dcm,application/dicom,.json" class="input-field" style="padding: 4px;">
317
  <div class="form-group">
318
  <label>Patient Name</label>
319
- <input type="text" id="pt-name" class="input-field" placeholder="Auto-fills on DICOM/JSON...">
320
  </div>
321
  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
322
  <div class="form-group">
323
- <label>Chart #</label>
324
- <input type="text" id="pt-chart" class="input-field" placeholder="MRN">
325
  </div>
326
  <div class="form-group">
327
- <label>Date</label>
328
  <input type="date" id="pt-date" class="input-field">
329
  </div>
330
  </div>
@@ -339,7 +356,7 @@
339
  <div class="mode-btn" data-mode="WITS">Wits</div>
340
  <div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
341
  <div class="mode-btn" data-mode="CVM">🦴 CVM</div>
342
- <div class="mode-btn" data-mode="SUPER">重ね T1/T2</div>
343
  <div class="mode-btn" data-mode="ALL">All</div>
344
  </div>
345
 
@@ -352,24 +369,24 @@
352
  </div>
353
 
354
  <div>
355
- <div class="section-header"><span>3. Retrace & Reset Point</span></div>
356
  <div class="card">
357
  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
358
- <button id="btn-retrace-all" class="btn btn-secondary" title="Re-run AI and reset all landmarks">
359
- 🔄 Re-Trace All
360
  </button>
361
- <button id="btn-reset-single" class="btn btn-secondary" title="Snap selected point back to AI prediction">
362
  🎯 Reset Dot
363
  </button>
364
  </div>
365
- <div style="font-size: 10px; color: var(--text-muted); text-align: center;">
366
- Selected Dot: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot to reset)
367
  </div>
368
  </div>
369
  </div>
370
 
371
  <div>
372
- <div class="section-header"><span>4. CVM Skeletal Maturation (Baccetti)</span></div>
373
  <div class="card">
374
  <div class="cvm-grid">
375
  <div class="cvm-btn" data-cvm="CS1">CS1</div>
@@ -379,8 +396,8 @@
379
  <div class="cvm-btn" data-cvm="CS5">CS5</div>
380
  <div class="cvm-btn" data-cvm="CS6">CS6</div>
381
  </div>
382
- <div id="cvm-desc" style="font-size: 10px; color: var(--cvm-teal); font-weight: 600; text-align: center;">
383
- Select C2–C4 stage or switch to CVM Focus Mode
384
  </div>
385
  </div>
386
  </div>
@@ -392,28 +409,28 @@
392
  <button id="btn-lock-t1" class="btn btn-teal">📌 Lock as T1</button>
393
  <button id="btn-clear-t1" class="btn btn-secondary">Clear T1</button>
394
  </div>
395
- <div class="form-group" style="margin-top: 4px;">
396
- <label>Superimposition Registration Method</label>
397
- <select id="super-mode" class="input-field" style="padding: 5px;">
398
  <option value="CRANIAL">Cranial Base (S-N at S)</option>
399
  <option value="MAXILLARY">Maxillary (Palatal Plane at PNS)</option>
400
  <option value="MANDIBULAR">Mandibular (Symphysis & Canal)</option>
401
  </select>
402
  </div>
403
  <div id="super-status" style="font-size: 9.5px; color: var(--text-muted); text-align: center;">
404
- No T1 baseline locked. Lock T1, then load T2 ceph/JSON.
405
  </div>
406
  </div>
407
  </div>
408
 
409
  <div>
410
  <div class="section-header">
411
- <span>6. 10mm Ruler & X-Ray Filters</span>
412
  <span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 10px;">Reset</span>
413
  </div>
414
  <div class="card">
415
- <button id="btn-cal" class="btn btn-secondary">📐 Place / Show 10mm Ruler</button>
416
- <span id="cal-status" style="font-size: 10.5px; color: var(--ruler-cyan); text-align: center; font-weight: 600;">
417
  Scale: 10.00 px/mm
418
  </span>
419
  <div class="slider-row">
@@ -437,7 +454,7 @@
437
  <span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 10px; display: none;">Restore Defaults</span>
438
  </div>
439
  <div class="card">
440
- <button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 11px; padding: 5px;">
441
  ⚙️ Customize ABO Norms
442
  </button>
443
  <div id="norms-drawer"></div>
@@ -445,52 +462,52 @@
445
  </div>
446
  </aside>
447
 
448
- <!-- Center Viewport -->
449
  <main class="viewport" id="viewport-wrapper">
450
  <div id="loupe-box">
451
- <canvas id="loupe-canvas" width="150" height="150"></canvas>
452
  <div id="loupe-label">S</div>
453
  </div>
454
 
455
  <div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
456
- <div style="font-size: 36px;">🦷</div>
457
- <div style="font-size: 15px; font-weight: 600; color: var(--text-main);">Drop Patient Lateral Ceph (.DCM, .JPG, .PNG) or Saved .JSON Here</div>
458
- <div style="font-size: 12px;">AI Auto-Traces Immediately • Double-Click Any Dot to Reset to AI Prediction</div>
459
  </div>
460
 
461
  <div id="viewport-container">
462
- <img id="ceph-image" src="" alt="">
463
  <svg id="overlay-svg"></svg>
464
  </div>
465
 
466
  <div class="viewport-overlay-controls">
467
- <button id="btn-zoom-in">Zoom (+)</button>
468
- <button id="btn-zoom-out">Zoom (-)</button>
469
- <button id="btn-zoom-reset">Fit Screen</button>
470
  <span style="color: var(--surface-border);">|</span>
471
- <span class="shortcut-hint">Hold <strong>[SPACE]</strong> to peek bone • <strong>Double-Click Dot</strong> to reset</span>
472
  </div>
473
  </main>
474
 
475
  <!-- Right Analysis Panel -->
476
  <aside class="analysis-panel">
477
  <div class="diagnosis-banner">
478
- <div class="diagnosis-headline" id="diag-headline">Automated Clinical Diagnosis: Awaiting Tracing...</div>
479
  <div class="diagnosis-grid">
480
  <div class="diag-item">
481
  <span class="diag-label">Sagittal Skeletal</span>
482
  <span class="diag-val" id="diag-sagittal">-</span>
483
  </div>
484
  <div class="diag-item">
485
- <span class="diag-label">Vertical Growth</span>
486
  <span class="diag-val" id="diag-vertical">-</span>
487
  </div>
488
  <div class="diag-item">
489
- <span class="diag-label">Incisor Posture</span>
490
  <span class="diag-val" id="diag-dental">-</span>
491
  </div>
492
  <div class="diag-item">
493
- <span class="diag-label">Soft Tissue & CVM</span>
494
  <span class="diag-val" id="diag-soft">-</span>
495
  </div>
496
  </div>
@@ -510,7 +527,7 @@
510
  </tr>
511
  </thead>
512
  <tbody id="abo-rows">
513
- <tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 15px;">Awaiting radiograph...</td></tr>
514
  </tbody>
515
  </table>
516
  </div>
@@ -524,11 +541,11 @@
524
  <th>Norm</th>
525
  <th>Measured</th>
526
  <th>Diff</th>
527
- <th>Status</th>
528
  </tr>
529
  </thead>
530
  <tbody id="wits-rows">
531
- <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 10px;">Awaiting radiograph...</td></tr>
532
  </tbody>
533
  </table>
534
  </div>
@@ -546,23 +563,23 @@
546
  </tr>
547
  </thead>
548
  <tbody id="holdaway-rows">
549
- <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 10px;">Awaiting radiograph...</td></tr>
550
  </tbody>
551
  </table>
552
  </div>
553
 
554
  <div id="section-cvm">
555
- <div class="section-header" style="color: #2dd4bf;">Cervical Vertebral Maturation (C2–C4 Geometry)</div>
556
  <table class="analysis-table">
557
  <thead>
558
  <tr>
559
- <th>Vertebral Feature</th>
560
  <th>Measured</th>
561
- <th>Morphology / Clinical Timing</th>
562
  </tr>
563
  </thead>
564
  <tbody id="cvm-rows">
565
- <tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 10px;">Switch to CVM Focus Mode or select CS1–CS6...</td></tr>
566
  </tbody>
567
  </table>
568
  </div>
@@ -571,7 +588,7 @@
571
 
572
  <script>
573
  // -------------------------------------------------------------
574
- // 1. Constants, CVM Definitions & Norms
575
  // -------------------------------------------------------------
576
  const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
577
 
@@ -582,21 +599,31 @@ const LM_INDICES = {
582
  };
583
 
584
  const MODE_LANDMARKS = {
585
- ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft"]),
586
  WITS: new Set(["A", "B", "OP_P", "OP_A"]),
587
  HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
588
- CVM: new Set(["C3_UL", "C3_UR", "C3_LL", "C3_LR", "C3_INF", "C4_UL", "C4_UR", "C4_LL", "C4_LR", "C4_INF"]),
 
 
 
 
589
  SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog"]),
590
- 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", "C3_UL", "C3_UR", "C3_LL", "C3_LR", "C3_INF", "C4_UL", "C4_UR", "C4_LL", "C4_LR", "C4_INF"])
 
 
 
 
 
 
591
  };
592
 
593
  const CVM_INFO = {
594
- CS1: "CS1 (Pre-Peak): Flat lower borders C2-C4; C3/C4 tapered trapezoid. >2 yrs before mandibular peak.",
595
- CS2: "CS2 (Pre-Peak): Concavity at lower border of C2; C3/C4 trapezoid. ~1 yr before peak growth.",
596
- CS3: "CS3 (Ascending Peak): Concavities on C2 & C3; C3/C4 trapezoid or horiz. rectangle. Peak occurs within 1 yr (Ideal Functional Appliance Timing).",
597
- CS4: "CS4 (Decelerating Peak): Concavities on C2, C3 & C4; C3/C4 horizontal rectangular. Peak occurred 1–2 yrs ago.",
598
- CS5: "CS5 (Post-Peak): Concavities on C2–C4; at least one of C3 or C4 is square. Peak ended >1 yr ago.",
599
- CS6: "CS6 (Completion): Concavities on C2–C4; at least one of C3 or C4 is vertical rectangular. Growth complete."
600
  };
601
 
602
  const DEFAULT_ABO_NORMS = [
@@ -616,7 +643,7 @@ const DEFAULT_ABO_NORMS = [
616
  { id: "LL_E", name: "Lower Lip to E-Line", norm: -1.0, sd: 2.0, unit: "mm" }
617
  ];
618
 
619
- let ABO_NORMS = JSON.parse(localStorage.getItem("custom_abo_norms")) || JSON.parse(JSON.stringify(DEFAULT_ABO_NORMS));
620
 
621
  const HOLDAWAY_NORMS = [
622
  { id: "H_ANGLE", name: "H-Angle (H-Line to N'-Pog')", norm: 10.0, sd: 3.0, unit: "°" },
@@ -624,7 +651,7 @@ const HOLDAWAY_NORMS = [
624
  { id: "NOSE_PROM", name: "Nose Prominence (Pn to H-Line)", norm: 18.0, sd: 4.0, unit: "mm" },
625
  { id: "SN_HLINE", name: "Subnasale to H-Line", norm: 5.0, sd: 2.0, unit: "mm" },
626
  { id: "LL_HLINE", name: "Lower Lip to H-Line", norm: 0.5, sd: 1.0, unit: "mm" },
627
- { id: "CHIN_THICK", name: "Soft Tissue Chin (Pog to Pog')", norm: 11.0, sd: 2.0, unit: "mm" }
628
  ];
629
 
630
  // App State
@@ -642,7 +669,14 @@ let showLines = true;
642
  let showPoints = true;
643
  let showLabels = true;
644
  let spacebarPeek = false;
 
 
645
  let zoomLevel = 1.0;
 
 
 
 
 
646
  let draggingLm = null;
647
  let latestMetrics = {};
648
  let latestDiagnosis = { headline: "", sagittal: "-", vertical: "-", dental: "-", soft: "-" };
@@ -658,13 +692,20 @@ const calStatus = document.getElementById("cal-status");
658
  const loupeBox = document.getElementById("loupe-box");
659
  const loupeCanvas = document.getElementById("loupe-canvas");
660
  const loupeLabel = document.getElementById("loupe-label");
 
661
 
662
  document.getElementById("pt-date").valueAsDate = new Date();
663
  updateSectionVisibility();
664
  buildNormsEditor();
665
 
 
 
 
 
 
 
666
  // -------------------------------------------------------------
667
- // 2. Custom Norms Drawer
668
  // -------------------------------------------------------------
669
  function buildNormsEditor() {
670
  const drawer = document.getElementById("norms-drawer");
@@ -687,7 +728,7 @@ function buildNormsEditor() {
687
  const val = parseFloat(e.target.value);
688
  if (!isNaN(val)) {
689
  ABO_NORMS[i][field] = val;
690
- localStorage.setItem("custom_abo_norms", JSON.stringify(ABO_NORMS));
691
  renderAnalysis();
692
  }
693
  });
@@ -704,32 +745,33 @@ document.getElementById("btn-toggle-norms").addEventListener("click", () => {
704
 
705
  document.getElementById("reset-norms").addEventListener("click", () => {
706
  ABO_NORMS = JSON.parse(JSON.stringify(DEFAULT_ABO_NORMS));
707
- localStorage.removeItem("custom_abo_norms");
708
  buildNormsEditor();
709
  renderAnalysis();
 
710
  });
711
 
712
  // -------------------------------------------------------------
713
- // 3. Initialize Neural Model
714
  // -------------------------------------------------------------
715
  async function initModel() {
716
  try {
717
  ort.env.wasm.numThreads = 2;
718
  session = await ort.InferenceSession.create(MODEL_URL, { executionProviders: ['wasm'] });
719
  statusInd.style.backgroundColor = "var(--status-green)";
720
- statusTxt.innerText = "AI Ready (Auto-Trace Active)";
721
  if (imgElem.src && imgElem.naturalWidth > 0 && Object.keys(coords).length === 0) {
722
  runAutoTrace();
723
  }
724
  } catch (err) {
725
  statusInd.style.backgroundColor = "var(--status-red)";
726
- statusTxt.innerText = "Model Load Error";
727
  }
728
  }
729
  initModel();
730
 
731
  // -------------------------------------------------------------
732
- // 4. File Upload (DICOM, Image, or JSON) & Drag-and-Drop
733
  // -------------------------------------------------------------
734
  const viewportWrapper = document.getElementById("viewport-wrapper");
735
 
@@ -766,8 +808,11 @@ function handleFile(file) {
766
  if (isDicom) {
767
  const reader = new FileReader();
768
  reader.onload = (evt) => {
769
- try { parseAndDisplayDicom(new Uint8Array(evt.target.result)); }
770
- catch (err) { alert("DICOM Error: " + err.message); }
 
 
 
771
  };
772
  reader.readAsArrayBuffer(file);
773
  } else {
@@ -778,11 +823,11 @@ function handleFile(file) {
778
  }
779
 
780
  // -------------------------------------------------------------
781
- // 5. Save & Load JSON Records
782
  // -------------------------------------------------------------
783
  document.getElementById("btn-save-json").addEventListener("click", () => {
784
  if (!coords.S) {
785
- alert("No active tracing to save.");
786
  return;
787
  }
788
  const ptName = document.getElementById("pt-name").value || "Patient";
@@ -790,7 +835,8 @@ document.getElementById("btn-save-json").addEventListener("click", () => {
790
  const ptDate = document.getElementById("pt-date").value || "";
791
 
792
  const payload = {
793
- version: "2.1",
 
794
  patient: { name: ptName, chart: ptChart, date: ptDate },
795
  pxPerMm,
796
  cvmStage,
@@ -798,15 +844,17 @@ document.getElementById("btn-save-json").addEventListener("click", () => {
798
  initialAiCoords,
799
  metrics: latestMetrics,
800
  diagnosis: latestDiagnosis,
801
- imageDataUrl: imgElem.src || null
802
  };
803
 
804
  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
805
  const url = URL.createObjectURL(blob);
806
  const a = document.createElement("a");
807
  a.href = url;
808
- a.download = `Ceph_Record_${ptName.replace(/\s+/g, '_')}_${ptDate}.json`;
809
  a.click();
 
 
810
  });
811
 
812
  function loadJsonFile(file) {
@@ -819,16 +867,16 @@ function loadJsonFile(file) {
819
  document.getElementById("pt-chart").value = data.patient.chart || "";
820
  if (data.patient.date) document.getElementById("pt-date").value = data.patient.date;
821
  }
822
- if (data.pxPerMm) {
823
  pxPerMm = data.pxPerMm;
824
- calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Loaded from JSON)`;
825
  }
826
  if (data.cvmStage) {
827
  cvmStage = data.cvmStage;
828
  highlightCvmButton(cvmStage);
829
  }
830
 
831
- const loadedCoords = data.coords || data.landmarks || data;
832
  if (loadedCoords && loadedCoords.S) {
833
  coords = JSON.parse(JSON.stringify(loadedCoords));
834
  initialAiCoords = data.initialAiCoords
@@ -836,21 +884,50 @@ function loadJsonFile(file) {
836
  : JSON.parse(JSON.stringify(loadedCoords));
837
  }
838
 
839
- if (data.imageDataUrl) {
 
840
  setupImage(data.imageDataUrl, false);
841
  } else {
842
- renderAnalysis();
 
843
  }
844
- statusTxt.innerText = "JSON Record Loaded";
845
  } catch (err) {
846
- alert("Invalid JSON file: " + err.message);
847
  }
848
  };
849
  reader.readAsText(file);
850
  }
851
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852
  // -------------------------------------------------------------
853
- // 6. DICOM & Image Setup
854
  // -------------------------------------------------------------
855
  function parseAndDisplayDicom(byteArray) {
856
  const dataSet = dicomParser.parseDicom(byteArray);
@@ -868,7 +945,7 @@ function parseAndDisplayDicom(byteArray) {
868
  const parts = spacingStr.split('\\').map(parseFloat);
869
  if (parts[0] > 0) {
870
  pxPerMm = 1.0 / parts[0];
871
- calStatus.innerText = `DICOM Calibrated: ${pxPerMm.toFixed(2)} px/mm`;
872
  }
873
  }
874
 
@@ -929,24 +1006,54 @@ function setupImage(srcUrl, shouldRunAi = true) {
929
  imgElem.onload = () => {
930
  dropzone.style.display = "none";
931
  container.style.display = "block";
932
- svgElem.setAttribute("viewBox", `0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
933
- svgElem.setAttribute("width", imgElem.clientWidth);
934
- svgElem.setAttribute("height", imgElem.clientHeight);
935
- if (shouldRunAi && session) runAutoTrace();
936
- else renderAnalysis();
 
 
 
 
 
 
 
 
 
 
 
 
937
  };
938
  imgElem.src = srcUrl;
939
  }
940
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
941
  // -------------------------------------------------------------
942
- // 7. Deep Learning Auto-Tracing & Point Reset Logic
943
  // -------------------------------------------------------------
944
  async function runAutoTrace() {
945
  if (!session || !imgElem.src) return;
946
  statusInd.style.backgroundColor = "var(--status-amber)";
947
- statusTxt.innerText = "Auto-Tracing Landmarks...";
948
 
949
- await new Promise(r => setTimeout(r, 40));
950
 
951
  const off = document.createElement("canvas");
952
  off.width = 768; off.height = 768;
@@ -987,39 +1094,63 @@ async function runAutoTrace() {
987
  };
988
  }
989
 
 
 
 
 
 
 
 
 
 
 
 
 
990
  if (coords.UIT && coords.LIT) {
991
  coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
992
  }
993
  if (coords.Go && coords.OP_A) {
994
- coords.OP_P = { x: coords.OP_A.x - (coords.OP_A.x - coords.Go.x) * 0.55, y: coords.OP_A.y - 12 };
995
  }
996
 
997
- if (coords.Go && coords.Po) {
998
- const cx = coords.Po.x - (coords.Go.x - coords.Po.x) * 0.35;
999
- const cy = coords.Go.y + (coords.Go.y - coords.Po.y) * 0.05;
1000
- const s = Math.max(18, origW * 0.022);
1001
-
1002
- coords.C3_UL = { x: cx - s, y: cy - s };
1003
- coords.C3_UR = { x: cx + s, y: cy - s * 0.85 };
1004
- coords.C3_LL = { x: cx - s, y: cy + s };
1005
- coords.C3_LR = { x: cx + s, y: cy + s };
1006
- coords.C3_INF = { x: cx, y: cy + s * 0.78 };
1007
-
1008
- const c4y = cy + s * 2.5;
1009
- coords.C4_UL = { x: cx - s, y: c4y - s };
1010
- coords.C4_UR = { x: cx + s, y: c4y - s * 0.85 };
1011
- coords.C4_LL = { x: cx - s, y: c4y + s };
1012
- coords.C4_LR = { x: cx + s, y: c4y + s };
1013
- coords.C4_INF = { x: cx, y: c4y + s * 0.82 };
 
 
 
 
 
 
 
 
 
 
 
 
1014
  }
1015
 
1016
- coords.RULER_1 = { x: origW * 0.82, y: origH * 0.12 };
1017
- coords.RULER_2 = { x: origW * 0.82, y: origH * 0.12 + (pxPerMm * 10.0) };
 
1018
 
1019
  initialAiCoords = JSON.parse(JSON.stringify(coords));
1020
-
1021
  statusInd.style.backgroundColor = "var(--status-green)";
1022
- statusTxt.innerText = "Auto-Trace Complete";
1023
  renderAnalysis();
1024
  }
1025
 
@@ -1028,7 +1159,7 @@ document.getElementById("btn-retrace-all").addEventListener("click", () => {
1028
  if (Object.keys(initialAiCoords).length > 0) {
1029
  coords = JSON.parse(JSON.stringify(initialAiCoords));
1030
  renderAnalysis();
1031
- statusTxt.innerText = "All Landmarks Reset to AI Prediction";
1032
  } else {
1033
  runAutoTrace();
1034
  }
@@ -1038,14 +1169,14 @@ document.getElementById("btn-reset-single").addEventListener("click", () => {
1038
  if (selectedLm && initialAiCoords[selectedLm]) {
1039
  coords[selectedLm] = { ...initialAiCoords[selectedLm] };
1040
  renderAnalysis();
1041
- statusTxt.innerText = `Reset ${selectedLm} to AI position`;
1042
  } else {
1043
- alert("Click any landmark dot first (or double-click a dot directly on the x-ray) to reset it.");
1044
  }
1045
  });
1046
 
1047
  // -------------------------------------------------------------
1048
- // 8. CVM Selector & Regional Superimposition Controls
1049
  // -------------------------------------------------------------
1050
  document.querySelectorAll(".cvm-btn").forEach(btn => {
1051
  btn.addEventListener("click", () => {
@@ -1060,12 +1191,12 @@ function highlightCvmButton(stage) {
1060
  document.querySelectorAll(".cvm-btn").forEach(b => {
1061
  b.classList.toggle("active", b.getAttribute("data-cvm") === stage);
1062
  });
1063
- document.getElementById("cvm-desc").innerText = CVM_INFO[stage] || "Geometric CVM Evaluation Active";
1064
  }
1065
 
1066
  document.getElementById("btn-lock-t1").addEventListener("click", () => {
1067
  if (!coords.S) {
1068
- alert("Trace a baseline (T1) cephalogram first.");
1069
  return;
1070
  }
1071
  t1Baseline = {
@@ -1073,8 +1204,9 @@ document.getElementById("btn-lock-t1").addEventListener("click", () => {
1073
  metrics: JSON.parse(JSON.stringify(latestMetrics)),
1074
  date: document.getElementById("pt-date").value || "T1"
1075
  };
1076
- document.getElementById("super-status").innerHTML = `<span style="color:#5eead4; font-weight:700;">✅ T1 Locked (${t1Baseline.date})</span> — Now upload T2 or switch to Superimposition Mode`;
1077
  document.getElementById("th-t1-abo").style.display = "table-cell";
 
1078
  renderAnalysis();
1079
  });
1080
 
@@ -1085,7 +1217,6 @@ document.getElementById("btn-clear-t1").addEventListener("click", () => {
1085
  renderAnalysis();
1086
  });
1087
 
1088
- // Regional Superimposition Alignment Engine
1089
  function getSuperimposedT1Coords() {
1090
  if (!t1Baseline || !t1Baseline.coords.S || !coords.S) return null;
1091
  const mode = document.getElementById("super-mode").value;
@@ -1095,19 +1226,17 @@ function getSuperimposedT1Coords() {
1095
  let angle1 = 0, angle2 = 0;
1096
 
1097
  if (mode === "MAXILLARY" && t1Baseline.coords.PNS && t1Baseline.coords.ANS && coords.PNS && coords.ANS) {
1098
- // Register on Palatal Plane (PNS–ANS) at PNS
1099
  origin1 = t1Baseline.coords.PNS;
1100
  origin2 = coords.PNS;
1101
  angle1 = Math.atan2(t1Baseline.coords.ANS.y - t1Baseline.coords.PNS.y, t1Baseline.coords.ANS.x - t1Baseline.coords.PNS.x);
1102
  angle2 = Math.atan2(coords.ANS.y - coords.PNS.y, coords.ANS.x - coords.PNS.x);
1103
  } else if (mode === "MANDIBULAR" && t1Baseline.coords.Me && t1Baseline.coords.Go && coords.Me && coords.Go) {
1104
- // Register on Mandibular Symphysis / Inferior Border
1105
  origin1 = t1Baseline.coords.Me;
1106
  origin2 = coords.Me;
1107
  angle1 = Math.atan2(t1Baseline.coords.Go.y - t1Baseline.coords.Me.y, t1Baseline.coords.Go.x - t1Baseline.coords.Me.x);
1108
  angle2 = Math.atan2(coords.Go.y - coords.Me.y, coords.Go.x - coords.Me.x);
1109
  } else {
1110
- // Cranial Base: S-N at S
1111
  if (!t1Baseline.coords.N || !coords.N) return null;
1112
  angle1 = Math.atan2(t1Baseline.coords.N.y - s1.y, t1Baseline.coords.N.x - s1.x);
1113
  angle2 = Math.atan2(coords.N.y - s2.y, coords.N.x - s2.x);
@@ -1129,7 +1258,7 @@ function getSuperimposedT1Coords() {
1129
  }
1130
 
1131
  // -------------------------------------------------------------
1132
- // 9. Focus Modes, Layer Toggles & Spacebar Peek
1133
  // -------------------------------------------------------------
1134
  document.querySelectorAll(".mode-btn").forEach(btn => {
1135
  btn.addEventListener("click", () => {
@@ -1179,14 +1308,12 @@ window.addEventListener("keyup", (e) => {
1179
  });
1180
 
1181
  // -------------------------------------------------------------
1182
- // 10. Draggable 10mm Ruler & Precision Magnifier Loupe
1183
  // -------------------------------------------------------------
1184
  calBtn.addEventListener("click", () => {
1185
  if (!imgElem.src) return;
1186
- showRuler = true;
1187
- calStep = 1;
1188
- calBtn.innerText = "Click 0mm Point on X-Ray (or Drag Cyan Dots)";
1189
- calBtn.style.background = "#0891b2";
1190
  renderAnalysis();
1191
  });
1192
 
@@ -1198,12 +1325,12 @@ function getSVGCoords(e) {
1198
  }
1199
 
1200
  function updateLoupe(pt, name) {
1201
- if (!imgElem.src) return;
1202
  loupeBox.style.display = "block";
1203
  loupeLabel.innerText = name;
1204
  const lCtx = loupeCanvas.getContext("2d");
1205
  const zoom = 3.0;
1206
- const size = 150;
1207
  const srcSize = size / zoom;
1208
 
1209
  lCtx.clearRect(0, 0, size, size);
@@ -1215,6 +1342,7 @@ function updateLoupe(pt, name) {
1215
  );
1216
  lCtx.filter = "none";
1217
 
 
1218
  lCtx.strokeStyle = "#38bdf8";
1219
  lCtx.lineWidth = 1.5;
1220
  lCtx.beginPath();
@@ -1225,7 +1353,40 @@ function updateLoupe(pt, name) {
1225
  lCtx.stroke();
1226
  }
1227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1228
  window.addEventListener("mousemove", (e) => {
 
 
 
 
 
 
 
1229
  if (!draggingLm || !coords[draggingLm]) return;
1230
  const p = getSVGCoords(e);
1231
  coords[draggingLm].x = p.x;
@@ -1235,7 +1396,7 @@ window.addEventListener("mousemove", (e) => {
1235
  const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
1236
  if (dist > 1) {
1237
  pxPerMm = dist / 10.0;
1238
- calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (10mm Ruler Active)`;
1239
  }
1240
  }
1241
 
@@ -1244,6 +1405,10 @@ window.addEventListener("mousemove", (e) => {
1244
  });
1245
 
1246
  window.addEventListener("mouseup", () => {
 
 
 
 
1247
  if (draggingLm) {
1248
  draggingLm = null;
1249
  loupeBox.style.display = "none";
@@ -1251,31 +1416,19 @@ window.addEventListener("mouseup", () => {
1251
  }
1252
  });
1253
 
1254
- container.addEventListener("click", (e) => {
1255
- if (calStep === 0) return;
1256
- const p = getSVGCoords(e);
1257
- if (calStep === 1) {
1258
- coords.RULER_1 = { x: p.x, y: p.y };
1259
- coords.RULER_2 = { x: p.x, y: p.y + 80 };
1260
- calStep = 2;
1261
- calBtn.innerText = "Now Click 10mm Mark on Ruler...";
1262
- renderAnalysis();
1263
- } else if (calStep === 2) {
1264
- coords.RULER_2 = { x: p.x, y: p.y };
1265
- const d = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
1266
- if (d > 1) {
1267
- pxPerMm = d / 10.0;
1268
- calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Drag cyan dots to adjust)`;
1269
- }
1270
- calStep = 0;
1271
- calBtn.innerText = "📐 Re-Click 10mm Ruler";
1272
- calBtn.style.background = "#0f172a";
1273
- renderAnalysis();
1274
- }
1275
  });
 
 
 
 
 
1276
 
1277
  // -------------------------------------------------------------
1278
- // 11. Image Filters & Next Patient Reset
1279
  // -------------------------------------------------------------
1280
  function applyFilters() {
1281
  const b = document.getElementById("brightness").value;
@@ -1298,6 +1451,7 @@ document.getElementById("btn-next-patient").addEventListener("click", () => {
1298
  coords = {};
1299
  initialAiCoords = {};
1300
  latestMetrics = {};
 
1301
  selectedLm = null;
1302
  cvmStage = "Auto";
1303
  highlightCvmButton("");
@@ -1309,16 +1463,22 @@ document.getElementById("btn-next-patient").addEventListener("click", () => {
1309
  document.getElementById("pt-name").value = "";
1310
  document.getElementById("pt-chart").value = "";
1311
  document.getElementById("pt-date").valueAsDate = new Date();
1312
- document.getElementById("diag-headline").innerText = "Automated Clinical Diagnosis: Awaiting Tracing...";
1313
  document.getElementById("diag-sagittal").innerText = "-";
1314
  document.getElementById("diag-vertical").innerText = "-";
1315
  document.getElementById("diag-dental").innerText = "-";
1316
  document.getElementById("diag-soft").innerText = "-";
 
1317
  svgElem.innerHTML = "";
 
 
 
 
 
1318
  });
1319
 
1320
  // -------------------------------------------------------------
1321
- // 12. Vector Math, CVM Geometry & Diagnosis Engine
1322
  // -------------------------------------------------------------
1323
  function getAngle(p1, v, p2) {
1324
  if (!p1 || !v || !p2) return null;
@@ -1365,28 +1525,48 @@ function calculateWits(ptA, ptB, opP, opA) {
1365
  return { distMm, ao, bo };
1366
  }
1367
 
 
1368
  function evaluateCvmGeometry() {
1369
  if (!coords.C3_LL || !coords.C3_LR || !coords.C3_INF || !coords.C4_LL || !coords.C4_LR || !coords.C4_INF) return null;
1370
- const c3Concavity = Math.abs(getPerpDist(coords.C3_INF, coords.C3_LL, coords.C3_LR));
1371
- const c4Concavity = Math.abs(getPerpDist(coords.C4_INF, coords.C4_LL, coords.C4_LR));
1372
 
 
 
 
 
 
 
 
 
 
 
 
1373
  const c3Width = Math.hypot(coords.C3_LR.x - coords.C3_LL.x, coords.C3_LR.y - coords.C3_LL.y);
1374
  const c3Height = Math.hypot(coords.C3_LL.x - coords.C3_UL.x, coords.C3_LL.y - coords.C3_UL.y);
1375
  const c3Ratio = parseFloat((c3Width / (c3Height + 1e-5)).toFixed(2));
1376
 
 
1377
  let shape = "Horizontal Rectangular";
1378
  if (c3Ratio > 1.35) shape = "Trapezoid / Tapered";
1379
- else if (c3Ratio >= 0.92 && c3Ratio <= 1.12) shape = "Square";
1380
- else if (c3Ratio < 0.92) shape = "Vertical Rectangular";
1381
-
1382
- let autoStage = "CS3 (Peak Growth)";
1383
- if (c3Concavity < 0.8 && c4Concavity < 0.8) autoStage = "CS1–CS2 (Pre-Peak)";
1384
- else if (c3Concavity >= 0.8 && c4Concavity < 0.8) autoStage = "CS3 (Ascending Peak)";
1385
- else if (c4Concavity >= 0.8 && shape === "Horizontal Rectangular") autoStage = "CS4 (Decelerating Peak)";
 
 
 
 
 
 
 
1386
  else if (shape === "Square") autoStage = "CS5 (Post-Peak)";
1387
  else if (shape === "Vertical Rectangular") autoStage = "CS6 (Maturation Complete)";
 
1388
 
1389
  return {
 
1390
  c3Concavity,
1391
  c4Concavity,
1392
  c3Ratio,
@@ -1400,7 +1580,7 @@ function getNormObj(id) {
1400
  }
1401
 
1402
  function updateClinicalDiagnosis(m, cvmData) {
1403
- if (m.ANB === null) return;
1404
 
1405
  const anbN = getNormObj("ANB");
1406
  const snaN = getNormObj("SNA");
@@ -1446,8 +1626,8 @@ function updateClinicalDiagnosis(m, cvmData) {
1446
  else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";
1447
 
1448
  const stageLabel = cvmData ? cvmData.finalStage : cvmStage;
1449
- const softAndCvm = `${softStr} | CVM: ${stageLabel}`;
1450
- const headline = `${skelClass} • ${vertClass} • ${dentStr} • [${stageLabel}]`;
1451
 
1452
  latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
1453
 
@@ -1459,7 +1639,7 @@ function updateClinicalDiagnosis(m, cvmData) {
1459
  }
1460
 
1461
  // -------------------------------------------------------------
1462
- // 13. Render Engine
1463
  // -------------------------------------------------------------
1464
  function renderAnalysis() {
1465
  svgElem.innerHTML = "";
@@ -1477,14 +1657,26 @@ function renderAnalysis() {
1477
  svgElem.appendChild(l);
1478
  }
1479
 
 
 
 
 
 
 
 
 
 
 
 
 
1480
  const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
1481
  const cvmData = evaluateCvmGeometry();
1482
 
1483
- // 1. Draw T1 Baseline Superimposition if Locked
1484
  const t1Aligned = getSuperimposedT1Coords();
1485
  if (t1Aligned && (focusMode === "SUPER" || focusMode === "ALL" || focusMode === "ABO")) {
1486
  const drawT1Line = (a, b) => {
1487
- line(a, b, "#000000", 5);
1488
  line(a, b, "#94a3b8", 2, "5,3");
1489
  };
1490
  drawT1Line(t1Aligned.S, t1Aligned.N);
@@ -1493,24 +1685,26 @@ function renderAnalysis() {
1493
  drawT1Line(t1Aligned.Go, t1Aligned.Me);
1494
  drawT1Line(t1Aligned.UIT, t1Aligned.UIA);
1495
  drawT1Line(t1Aligned.LIT, t1Aligned.LIA);
 
1496
  }
1497
 
1498
- // 2. Draw Current Tracing Vectors
1499
  if (showLines) {
1500
  const isSuper = focusMode === "SUPER";
1501
  if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
1502
- line(coords.S, coords.N, isSuper ? "#ff1744" : "#38bdf8", 3);
1503
- line(coords.N, coords.A, isSuper ? "#ff1744" : "#4ade80", 2);
1504
- line(coords.N, coords.B, isSuper ? "#ff1744" : "#4ade80", 2);
1505
- line(coords.Po, coords.Or, isSuper ? "#ff1744" : "#fbbf24", 2.5);
1506
- line(coords.Go, coords.Me, isSuper ? "#ff1744" : "#f43f5e", 3);
1507
- line(coords.UIT, coords.UIA, isSuper ? "#ff1744" : "#2dd4bf", 2.5);
1508
- line(coords.LIT, coords.LIA, isSuper ? "#ff1744" : "#d946ef", 2.5);
1509
- line(coords.Pn, coords.Pog_soft, isSuper ? "#ff1744" : "#fb923c", 2);
 
1510
  }
1511
 
1512
  if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
1513
- line(coords.Ls, coords.Pog_soft, "#ec4899", 2.5);
1514
  line(coords.N, coords.Pog_soft, "#c084fc", 1.5, "4,4");
1515
  line(coords.N, coords.Pog, "#94a3b8", 1.5, "4,4");
1516
  }
@@ -1519,39 +1713,43 @@ function renderAnalysis() {
1519
  const dx = coords.OP_A.x - coords.OP_P.x, dy = coords.OP_A.y - coords.OP_P.y;
1520
  const extP = { x: coords.OP_P.x - dx * 0.35, y: coords.OP_P.y - dy * 0.35 };
1521
  const extA = { x: coords.OP_A.x + dx * 0.35, y: coords.OP_A.y + dy * 0.35 };
1522
- line(extP, extA, "#a855f7", 2.5);
1523
  if (wits) {
1524
  line(coords.A, wits.ao, "#a855f7", 2, "3,3");
1525
  line(coords.B, wits.bo, "#a855f7", 2, "3,3");
1526
  }
1527
  }
1528
 
 
1529
  if ((focusMode === "CVM" || focusMode === "ALL") && coords.C3_UL) {
1530
- line(coords.C3_UL, coords.C3_UR, "#14b8a6", 2);
1531
- line(coords.C3_UR, coords.C3_LR, "#14b8a6", 2);
1532
- line(coords.C3_UL, coords.C3_LL, "#14b8a6", 2);
 
 
 
 
 
 
1533
  line(coords.C3_LL, coords.C3_INF, "#facc15", 2.5);
1534
  line(coords.C3_INF, coords.C3_LR, "#facc15", 2.5);
1535
- line(coords.C3_LL, coords.C3_LR, "#14b8a6", 1.2, "3,3");
1536
 
1537
- line(coords.C4_UL, coords.C4_UR, "#14b8a6", 2);
1538
- line(coords.C4_UR, coords.C4_LR, "#14b8a6", 2);
1539
- line(coords.C4_UL, coords.C4_LL, "#14b8a6", 2);
1540
  line(coords.C4_LL, coords.C4_INF, "#facc15", 2.5);
1541
  line(coords.C4_INF, coords.C4_LR, "#facc15", 2.5);
1542
- line(coords.C4_LL, coords.C4_LR, "#14b8a6", 1.2, "3,3");
1543
  }
1544
  }
1545
 
1546
- // 3. Draw 10mm Ruler
1547
  if (showRuler && coords.RULER_1 && coords.RULER_2) {
1548
- line(coords.RULER_1, coords.RULER_2, "#06b6d4", 2.5, "4,3");
1549
  ["RULER_1", "RULER_2"].forEach((rKey, idx) => {
1550
  const pt = coords[rKey];
1551
  const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
1552
  const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1553
  c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
1554
- c.setAttribute("r", 6.5); c.setAttribute("fill", "#06b6d4");
1555
  c.setAttribute("stroke", "#0f172a"); c.setAttribute("stroke-width", 2);
1556
  c.setAttribute("class", "landmark-handle");
1557
  c.addEventListener("mousedown", (e) => {
@@ -1571,7 +1769,7 @@ function renderAnalysis() {
1571
  });
1572
  }
1573
 
1574
- // 4. Draw Landmark Dots
1575
  const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
1576
 
1577
  if (showPoints) {
@@ -1582,16 +1780,18 @@ function renderAnalysis() {
1582
  const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
1583
  const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1584
  c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
1585
- c.setAttribute("r", selectedLm === name ? 7 : 5);
1586
 
1587
  let handleColor = "#facc15";
1588
  if (name === "Sn") handleColor = "#ec4899";
 
1589
  if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
1590
- if (name.startsWith("C3_") || name.startsWith("C4_")) handleColor = "#14b8a6";
 
1591
  if (selectedLm === name) handleColor = "#38bdf8";
1592
 
1593
  c.setAttribute("fill", handleColor);
1594
- c.setAttribute("stroke", "#0f172a");
1595
  c.setAttribute("stroke-width", 2);
1596
  c.setAttribute("class", "landmark-handle");
1597
 
@@ -1608,7 +1808,7 @@ function renderAnalysis() {
1608
  e.stopPropagation();
1609
  if (initialAiCoords[name]) {
1610
  coords[name] = { ...initialAiCoords[name] };
1611
- statusTxt.innerText = `Reset ${name} to AI position`;
1612
  renderAnalysis();
1613
  }
1614
  });
@@ -1627,6 +1827,7 @@ function renderAnalysis() {
1627
  }
1628
  }
1629
 
 
1630
  const sna = getAngle(coords.S, coords.N, coords.A);
1631
  const snb = getAngle(coords.S, coords.N, coords.B);
1632
  const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
@@ -1642,6 +1843,7 @@ function renderAnalysis() {
1642
  const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
1643
  const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);
1644
 
 
1645
  const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
1646
  const skel_conv = getPerpDist(coords.A, coords.N, coords.Pog);
1647
  const nose_prom = getPerpDist(coords.Pn, coords.Ls, coords.Pog_soft);
@@ -1679,7 +1881,7 @@ function populateAboTable(normsList, valuesDict) {
1679
  let diffColor = "var(--text-muted)";
1680
  let deltaT1Html = "";
1681
 
1682
- if (val !== null && val !== undefined) {
1683
  measuredText = `${val.toFixed(1)}${metric.unit}`;
1684
  const rawDiff = val - metric.norm;
1685
  const isNormal = Math.abs(rawDiff) <= metric.sd;
@@ -1694,8 +1896,12 @@ function populateAboTable(normsList, valuesDict) {
1694
 
1695
  if (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[metric.id] !== undefined) {
1696
  const t1Val = t1Baseline.metrics[metric.id];
1697
- const dT1 = val - t1Val;
1698
- deltaT1Html = `<td style="color:#5eead4; font-weight:700;">${dT1 > 0 ? '+' : ''}${dT1.toFixed(1)}${metric.unit}</td>`;
 
 
 
 
1699
  } else if (t1Baseline) {
1700
  deltaT1Html = `<td>-</td>`;
1701
  }
@@ -1724,7 +1930,7 @@ function populateTable(elementId, normsList, valuesDict) {
1724
  let diffText = "-";
1725
  let diffColor = "var(--text-muted)";
1726
 
1727
- if (val !== null && val !== undefined) {
1728
  measuredText = `${val.toFixed(1)}${metric.unit}`;
1729
  const rawDiff = val - metric.norm;
1730
  const isNormal = Math.abs(rawDiff) <= metric.sd;
@@ -1750,17 +1956,20 @@ function populateTable(elementId, normsList, valuesDict) {
1750
  function populateWitsTable(val) {
1751
  const tbody = document.getElementById("wits-rows");
1752
  tbody.innerHTML = "";
1753
- if (val === null || val === undefined) return;
 
 
 
1754
 
1755
  const diffFromZero = val.toFixed(1);
1756
  let statusHtml = `<span class="pill pill-normal">Class I</span>`;
1757
  let diffColor = "var(--status-green)";
1758
 
1759
  if (val > 1.0) {
1760
- statusHtml = `<span class="pill pill-deviated">Class II</span>`;
1761
  diffColor = "var(--status-red)";
1762
  } else if (val < -2.0) {
1763
- statusHtml = `<span class="pill pill-deviated">Class III</span>`;
1764
  diffColor = "var(--status-red)";
1765
  }
1766
 
@@ -1777,48 +1986,86 @@ function populateWitsTable(val) {
1777
 
1778
  function populateCvmTable(cvm) {
1779
  const tbody = document.getElementById("cvm-rows");
1780
- if (!cvm) return;
 
 
 
1781
  tbody.innerHTML = `
1782
  <tr>
1783
- <td><span class="metric-name">C3 Inferior Border Concavity</span></td>
 
 
 
 
 
1784
  <td><span class="metric-val">${cvm.c3Concavity.toFixed(1)} mm</span></td>
1785
- <td>${cvm.c3Concavity >= 0.8 ? '<span class="pill pill-normal">Concave (Present)</span>' : '<span class="pill pill-neutral">Flat (<0.8mm)</span>'}</td>
1786
  </tr>
1787
  <tr>
1788
- <td><span class="metric-name">C4 Inferior Border Concavity</span></td>
1789
  <td><span class="metric-val">${cvm.c4Concavity.toFixed(1)} mm</span></td>
1790
- <td>${cvm.c4Concavity >= 0.8 ? '<span class="pill pill-normal">Concave (Present)</span>' : '<span class="pill pill-neutral">Flat (<0.8mm)</span>'}</td>
1791
  </tr>
1792
  <tr>
1793
- <td><span class="metric-name">C3 Width-to-Height Ratio</span></td>
1794
  <td><span class="metric-val">${cvm.c3Ratio}</span></td>
1795
- <td><span style="color:#5eead4; font-weight:600;">${cvm.shape}</span></td>
1796
  </tr>
1797
  <tr>
1798
  <td><span class="metric-name">Assigned Maturation Stage</span></td>
1799
- <td colspan="2"><span class="metric-val" style="color:#2dd4bf;">${cvm.finalStage}</span></td>
1800
  </tr>
1801
  `;
1802
  }
1803
 
1804
  // -------------------------------------------------------------
1805
- // 14. CSV Export & Clinical Note Copy
1806
  // -------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1807
  document.getElementById("btn-export-csv").addEventListener("click", () => {
1808
  if (!latestMetrics.SNA) {
1809
- alert("Please upload and trace a cephalogram first.");
1810
  return;
1811
  }
1812
- const ptName = document.getElementById("pt-name").value || "Unnamed_Patient";
1813
  const ptChart = document.getElementById("pt-chart").value || "N/A";
1814
  const ptDate = document.getElementById("pt-date").value || "";
1815
 
1816
- let csv = "Patient Name,Chart ID,Date,Clinical Diagnosis,CVM Stage,Category,Parameter,Standard Norm,Measured Value,Difference,Unit,Status\n";
1817
 
1818
  const addRows = (category, list) => {
1819
  list.forEach(m => {
1820
  const val = latestMetrics[m.id];
1821
- if (val === null || val === undefined) return;
1822
  const diff = (val - m.norm).toFixed(1);
1823
  const status = Math.abs(val - m.norm) <= m.sd ? "Normal" : (val > m.norm ? "High" : "Low");
1824
  csv += `"${ptName}","${ptChart}","${ptDate}","${latestDiagnosis.headline}","${cvmStage}","${category}","${m.name}","${m.norm} +/- ${m.sd}",${val.toFixed(1)},${diff > 0 ? '+' + diff : diff},"${m.unit}","${status}"\n`;
@@ -1826,7 +2073,7 @@ document.getElementById("btn-export-csv").addEventListener("click", () => {
1826
  };
1827
 
1828
  addRows("ABO", ABO_NORMS);
1829
- if (latestMetrics.WITS !== null) {
1830
  const w = latestMetrics.WITS;
1831
  const wStat = w > 1.0 ? "Class II" : (w < -2.0 ? "Class III" : "Class I");
1832
  csv += `"${ptName}","${ptChart}","${ptDate}","${latestDiagnosis.headline}","${cvmStage}","Wits","Wits Appraisal (AO-BO)","0.0 +/- 1.0",${w.toFixed(1)},${w.toFixed(1)},"mm","${wStat}"\n`;
@@ -1837,46 +2084,10 @@ document.getElementById("btn-export-csv").addEventListener("click", () => {
1837
  const url = URL.createObjectURL(blob);
1838
  const a = document.createElement("a");
1839
  a.href = url;
1840
- a.download = `Ceph_ABO_${ptName.replace(/\s+/g, '_')}_${ptDate}.csv`;
1841
  a.click();
1842
- });
1843
-
1844
- document.getElementById("btn-copy-note").addEventListener("click", () => {
1845
- if (!latestMetrics.SNA) return;
1846
- const ptName = document.getElementById("pt-name").value || "Patient";
1847
- const m = latestMetrics;
1848
- const note = [
1849
- `CEPHALOMETRIC DIAGNOSIS (${ptName}): ${latestDiagnosis.headline}`,
1850
- `• Sagittal: ${latestDiagnosis.sagittal} | SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°, Wits ${m.WITS} mm`,
1851
- `• Vertical: ${latestDiagnosis.vertical} | FMA ${m.FMA}°, SN-MP ${m.SNMP}°`,
1852
- `• 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}°`,
1853
- `• Soft Tissue & Maturation: ${latestDiagnosis.soft} | UL E-Line ${m.UL_E} mm, LL E-Line ${m.LL_E} mm, Holdaway H-Angle ${m.H_ANGLE}°`
1854
- ].join("\n");
1855
-
1856
- navigator.clipboard.writeText(note).then(() => {
1857
- const btn = document.getElementById("btn-copy-note");
1858
- const orig = btn.innerText;
1859
- btn.innerText = "✅ Copied!";
1860
- setTimeout(() => btn.innerText = orig, 2000);
1861
- });
1862
- });
1863
-
1864
- // -------------------------------------------------------------
1865
- // 15. Zoom Controls
1866
- // -------------------------------------------------------------
1867
- document.getElementById("btn-zoom-in").addEventListener("click", () => {
1868
- zoomLevel += 0.2;
1869
- container.style.transform = `scale(${zoomLevel})`;
1870
- });
1871
- document.getElementById("btn-zoom-out").addEventListener("click", () => {
1872
- if (zoomLevel > 0.4) {
1873
- zoomLevel -= 0.2;
1874
- container.style.transform = `scale(${zoomLevel})`;
1875
- }
1876
- });
1877
- document.getElementById("btn-zoom-reset").addEventListener("click", () => {
1878
- zoomLevel = 1.0;
1879
- container.style.transform = "scale(1.0)";
1880
  });
1881
  </script>
1882
  </body>
 
8
  <script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
9
  <link rel="preconnect" href="https://fonts.googleapis.com">
10
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
12
  <style>
13
  :root {
14
+ --bg-dark: #080c14;
15
+ --surface-dark: #0f172a;
16
  --surface-card: #1e293b;
17
  --surface-border: #334155;
18
  --accent: #2563eb;
 
41
  header {
42
  background: var(--surface-dark);
43
  border-bottom: 1px solid var(--surface-border);
44
+ height: 56px;
45
+ padding: 0 16px;
46
  display: flex;
47
  align-items: center;
48
  justify-content: space-between;
49
  flex-shrink: 0;
50
+ z-index: 30;
51
  }
52
 
53
  .brand { display: flex; align-items: center; gap: 10px; }
 
56
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
57
  border-radius: 8px; display: flex; align-items: center;
58
  justify-content: center; font-weight: 700; font-size: 16px; color: white;
59
+ box-shadow: 0 2px 8px rgba(37,99,235,0.4);
60
  }
61
+ .brand-title { font-size: 14.5px; font-weight: 700; letter-spacing: -0.01em; }
62
+ .brand-subtitle { font-size: 9.5px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; }
63
 
64
+ .header-actions { display: flex; align-items: center; gap: 6px; }
65
 
66
  #status-badge {
67
  display: flex; align-items: center; gap: 7px; font-size: 11px;
68
+ font-weight: 600; background: rgba(30, 41, 59, 0.85);
69
  border: 1px solid var(--surface-border); padding: 5px 11px;
70
  border-radius: 20px; color: var(--text-muted); margin-right: 4px;
71
  }
72
  #status-badge .indicator { width: 8px; height: 8px; border-radius: 50%; background-color: var(--status-amber); }
73
 
74
+ .workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }
75
 
76
  .sidebar {
77
+ width: 310px; background: var(--surface-dark);
78
  border-right: 1px solid var(--surface-border);
79
+ padding: 12px; display: flex; flex-direction: column;
80
+ gap: 10px; overflow-y: auto; flex-shrink: 0;
81
  }
82
 
83
  .section-header {
 
95
  .form-group label { font-size: 10px; font-weight: 600; color: var(--text-muted); }
96
 
97
  .input-field {
98
+ background: #090e1a; border: 1px solid var(--surface-border);
99
  border-radius: 6px; padding: 6px 9px; color: var(--text-main);
100
+ font-size: 11.5px; outline: none; width: 100%; transition: border-color 0.15s;
101
  }
102
  .input-field:focus { border-color: #3b82f6; }
103
 
104
  .btn {
105
+ background: var(--accent); color: white; border: none; padding: 6px 11px;
106
  border-radius: 6px; font-weight: 600; font-size: 11px; cursor: pointer;
107
  display: inline-flex; align-items: center; justify-content: center; gap: 5px;
108
+ transition: all 0.15s ease; white-space: nowrap; user-select: none;
109
  }
110
  .btn:hover:not(:disabled) { background: var(--accent-hover); }
111
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
112
+ .btn-secondary { background: #131c2e; border: 1px solid var(--surface-border); color: var(--text-main); }
113
+ .btn-secondary:hover { background: #1e293b; border-color: #475569; }
114
+ .btn-danger { background: rgba(244, 63, 94, 0.15); border: 1px solid rgba(244, 63, 94, 0.35); color: #fda4af; }
115
+ .btn-danger:hover { background: rgba(244, 63, 94, 0.28); }
116
+ .btn-teal { background: rgba(20, 184, 166, 0.15); border: 1px solid rgba(20, 184, 166, 0.4); color: #5eead4; }
117
+ .btn-teal:hover { background: rgba(20, 184, 166, 0.25); }
118
+
119
+ .mode-group { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
120
  .mode-btn {
121
+ background: #090e1a; border: 1px solid var(--surface-border);
122
+ color: var(--text-muted); padding: 5px 3px; border-radius: 5px;
123
  font-size: 10.5px; font-weight: 600; cursor: pointer; text-align: center;
124
+ transition: all 0.15s; user-select: none;
125
  }
126
+ .mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; box-shadow: 0 0 8px rgba(37,99,235,0.4); }
127
 
128
+ .toggle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
129
  .toggle-pill {
130
+ background: #090e1a; border: 1px solid var(--surface-border);
131
+ color: var(--text-muted); padding: 5px; border-radius: 5px;
132
+ font-size: 10px; font-weight: 600; cursor: pointer; text-align: center; user-select: none;
133
  }
134
  .toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }
135
 
136
+ .cvm-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; }
137
  .cvm-btn {
138
+ background: #090e1a; border: 1px solid var(--surface-border);
139
+ color: var(--text-muted); padding: 5px 1px; border-radius: 5px;
140
+ font-size: 10.5px; font-weight: 700; cursor: pointer; text-align: center; user-select: none;
141
  }
142
+ .cvm-btn.active { background: var(--cvm-teal); color: #022c22; border-color: #5eead4; font-weight: 800; }
143
 
144
  .slider-row {
145
  display: flex; align-items: center; justify-content: space-between;
146
+ font-size: 10.5px; color: var(--text-muted);
147
  }
148
+ .slider-row input[type="range"] { width: 130px; accent-color: var(--accent); cursor: pointer; }
149
 
150
  #norms-drawer {
151
+ display: none; flex-direction: column; gap: 5px; max-height: 170px;
152
  overflow-y: auto; padding-top: 6px; border-top: 1px solid var(--surface-border);
153
  }
154
  .norm-edit-row {
155
+ display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 5px; align-items: center; font-size: 10.5px;
156
  }
157
  .norm-edit-row input {
158
+ background: #090e1a; border: 1px solid var(--surface-border); color: var(--text-main);
159
+ padding: 3px 5px; border-radius: 4px; font-size: 10.5px; width: 100%; text-align: center;
160
  }
161
 
162
  .viewport {
163
+ flex: 1; background: #030712; position: relative;
164
  overflow: hidden; display: flex; align-items: center; justify-content: center;
165
+ user-select: none;
166
  }
167
  .viewport.drag-over {
168
  outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
 
170
 
171
  #empty-dropzone {
172
  display: flex; flex-direction: column; align-items: center; justify-content: center;
173
+ gap: 12px; color: var(--text-muted); text-align: center; padding: 45px 30px;
174
  border: 2px dashed var(--surface-border); border-radius: 16px; cursor: pointer;
175
+ max-width: 520px; transition: all 0.2s;
176
  }
177
+ #empty-dropzone:hover { border-color: #3b82f6; color: var(--text-main); background: rgba(30,41,59,0.3); }
178
 
179
+ #viewport-container {
180
+ position: absolute; transform-origin: 0 0; user-select: none;
181
+ cursor: crosshair; display: none; left: 0; top: 0;
182
+ }
183
+ #ceph-image { display: block; pointer-events: none; }
184
+ #overlay-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
185
 
186
  #loupe-box {
187
+ position: absolute; top: 16px; left: 16px; width: 140px; height: 140px;
188
  border: 2px solid #38bdf8; border-radius: 50%; overflow: hidden;
189
+ background: #000; box-shadow: 0 8px 24px rgba(0,0,0,0.85);
190
+ display: none; z-index: 25; pointer-events: none;
191
  }
192
  #loupe-canvas { width: 100%; height: 100%; display: block; }
193
  #loupe-label {
194
  position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%);
195
+ background: rgba(15, 23, 42, 0.9); color: #38bdf8; font-size: 10px;
196
+ font-weight: 700; padding: 2px 8px; border-radius: 10px; border: 1px solid #38bdf8;
197
  }
198
 
199
  .viewport-overlay-controls {
200
  position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%);
201
+ background: rgba(15, 23, 42, 0.9); backdrop-filter: blur(8px);
202
  border: 1px solid var(--surface-border); border-radius: 30px;
203
+ padding: 4px 14px; display: flex; align-items: center; gap: 8px; z-index: 20;
204
+ white-space: nowrap; box-shadow: 0 4px 14px rgba(0,0,0,0.5);
205
  }
206
  .viewport-overlay-controls button {
207
  background: none; border: none; color: var(--text-main);
208
+ cursor: pointer; font-size: 11px; font-weight: 600; padding: 3px 6px; border-radius: 4px;
209
  }
210
+ .viewport-overlay-controls button:hover { color: #60a5fa; background: rgba(255,255,255,0.05); }
211
  .shortcut-hint { font-size: 10px; color: var(--text-muted); }
212
 
213
+ .landmark-handle { pointer-events: all; cursor: grab; transition: r 0.12s ease; }
214
+ .landmark-handle:hover { r: 8 !important; stroke: #ffffff !important; stroke-width: 2.5px !important; }
215
  .landmark-handle.dragging { cursor: grabbing !important; r: 9 !important; fill: #38bdf8 !important; }
216
  .landmark-text {
217
+ font-family: 'JetBrains Mono', monospace; font-size: 10.5px; font-weight: 700;
218
  fill: #ffffff; paint-order: stroke; stroke: #000000; stroke-width: 3px;
219
  pointer-events: none; user-select: none;
220
  }
221
 
222
  .analysis-panel {
223
+ width: 480px; background: var(--surface-dark);
224
  border-left: 1px solid var(--surface-border);
225
+ padding: 14px; display: flex; flex-direction: column;
226
  gap: 12px; overflow-y: auto; flex-shrink: 0;
227
  }
228
 
229
  .diagnosis-banner {
230
+ background: linear-gradient(135deg, rgba(37, 99, 235, 0.18), rgba(15, 23, 42, 0.95));
231
  border: 1px solid #3b82f6;
232
+ border-radius: 8px;
233
+ padding: 10px 12px;
234
  display: flex;
235
  flex-direction: column;
236
  gap: 6px;
237
  }
238
+ .diagnosis-headline { font-size: 12px; font-weight: 700; color: #93c5fd; }
239
+ .diagnosis-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px 10px; font-size: 10.5px; }
240
  .diag-item { display: flex; flex-direction: column; }
241
+ .diag-label { font-size: 9px; color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
242
  .diag-val { font-weight: 600; color: var(--text-main); }
243
 
244
+ .analysis-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 11px; }
245
  .analysis-table th {
246
+ text-align: left; padding: 6px; font-weight: 600; font-size: 9.5px;
247
  text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);
248
  border-bottom: 1px solid var(--surface-border);
249
  }
250
+ .analysis-table td { padding: 5.5px 6px; border-bottom: 1px solid rgba(51, 65, 85, 0.35); }
251
  .metric-name { font-weight: 600; color: #e2e8f0; }
252
+ .metric-norm { color: var(--text-muted); font-size: 10px; font-family: 'JetBrains Mono', monospace; }
253
+ .metric-val { font-weight: 700; font-family: 'JetBrains Mono', monospace; }
254
+ .metric-diff { font-weight: 600; font-size: 10px; font-family: 'JetBrains Mono', monospace; }
255
 
256
+ .pill { display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 9999px; font-size: 9px; font-weight: 700; }
257
  .pill-normal { background: rgba(16, 185, 129, 0.15); color: var(--status-green); }
258
  .pill-deviated { background: rgba(244, 63, 94, 0.15); color: var(--status-red); }
259
  .pill-neutral { background: #1e293b; color: var(--text-muted); }
260
 
261
+ /* Custom Toast Notification */
262
+ #toast-msg {
263
+ position: fixed; top: 68px; right: 20px; z-index: 100;
264
+ background: #1e293b; border: 1px solid #3b82f6; color: #f8fafc;
265
+ padding: 9px 14px; border-radius: 8px; font-size: 11.5px; font-weight: 600;
266
+ display: none; box-shadow: 0 10px 25px rgba(0,0,0,0.6);
267
+ transform: translateY(-5px); transition: all 0.2s ease;
268
+ }
269
+
270
  @media print {
271
  body { background: white !important; color: black !important; height: auto !important; overflow: visible !important; }
272
+ header, .sidebar, .viewport-overlay-controls, #loupe-box, #empty-dropzone, #toast-msg { display: none !important; }
273
  .workspace { display: block !important; height: auto !important; }
274
+ .viewport { background: white !important; margin-bottom: 14px; justify-content: center; height: 420px; }
275
+ #ceph-image { max-height: 400px !important; }
276
  .analysis-panel { width: 100% !important; border: none !important; background: white !important; color: black !important; padding: 0 !important; }
277
  .diagnosis-banner { background: #f8fafc !important; border: 1px solid #94a3b8 !important; color: black !important; margin-bottom: 10px; }
278
  .diagnosis-headline { color: #1e3a8a !important; }
 
286
  </head>
287
  <body>
288
 
289
+ <div id="toast-msg">Notification</div>
290
+
291
  <header>
292
  <div class="brand">
293
  <div class="brand-icon">O</div>
294
  <div>
295
  <div class="brand-title">OrthoCeph Pro</div>
296
+ <div class="brand-subtitle">ABO Clinical Superimposition & Anatomical CVM Suite</div>
297
  </div>
298
  </div>
299
 
300
  <div class="header-actions">
301
  <div id="status-badge">
302
  <div class="indicator" id="status-ind"></div>
303
+ <span id="status-txt">Loading AI Model...</span>
304
  </div>
305
+ <button class="btn btn-secondary" id="btn-save-json" title="Save tracing, image & patient data into standalone .json">
306
  💾 Save JSON
307
  </button>
308
+ <button class="btn btn-secondary" onclick="document.getElementById('json-input').click()" title="Load previously saved .json session">
309
  📂 Load JSON
310
  </button>
311
  <input type="file" id="json-input" accept=".json,application/json" style="display:none;">
312
+ <button class="btn btn-secondary" id="btn-copy-note" title="Copy structured EMR chart note">
313
  📋 Copy Note
314
  </button>
315
+ <button class="btn btn-secondary" id="btn-export-csv" title="Download Excel CSV metrics">
316
  📊 CSV
317
  </button>
318
+ <button class="btn btn-secondary" onclick="window.print()" title="Print full ABO Ceph Report">
319
  🖨️ Print
320
  </button>
321
+ <button class="btn btn-danger" id="btn-next-patient" title="Clear current patient">
322
  🔄 Next Patient
323
  </button>
324
  </div>
325
  </header>
326
 
327
  <div class="workspace">
328
+ <!-- Left Sidebar Controls -->
329
  <aside class="sidebar">
330
  <div>
331
  <div class="section-header"><span>1. Radiograph & Patient</span></div>
 
333
  <input type="file" id="file-input" accept="image/*,.dcm,application/dicom,.json" class="input-field" style="padding: 4px;">
334
  <div class="form-group">
335
  <label>Patient Name</label>
336
+ <input type="text" id="pt-name" class="input-field" placeholder="Full name">
337
  </div>
338
  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
339
  <div class="form-group">
340
+ <label>Chart # / MRN</label>
341
+ <input type="text" id="pt-chart" class="input-field" placeholder="ID">
342
  </div>
343
  <div class="form-group">
344
+ <label>Study Date</label>
345
  <input type="date" id="pt-date" class="input-field">
346
  </div>
347
  </div>
 
356
  <div class="mode-btn" data-mode="WITS">Wits</div>
357
  <div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
358
  <div class="mode-btn" data-mode="CVM">🦴 CVM</div>
359
+ <div class="mode-btn" data-mode="SUPER">疊 T1/T2</div>
360
  <div class="mode-btn" data-mode="ALL">All</div>
361
  </div>
362
 
 
369
  </div>
370
 
371
  <div>
372
+ <div class="section-header"><span>3. Retrace & Edit Dot</span></div>
373
  <div class="card">
374
  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
375
+ <button id="btn-retrace-all" class="btn btn-secondary" title="Reset all landmarks back to AI original">
376
+ 🔄 Reset All
377
  </button>
378
+ <button id="btn-reset-single" class="btn btn-secondary" title="Reset active landmark to AI original">
379
  🎯 Reset Dot
380
  </button>
381
  </div>
382
+ <div style="font-size: 10px; color: var(--text-muted); text-align: center; margin-top: 2px;">
383
+ Selected: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot on screen to snap)
384
  </div>
385
  </div>
386
  </div>
387
 
388
  <div>
389
+ <div class="section-header"><span>4. Baccetti Cervical Maturation (CVM)</span></div>
390
  <div class="card">
391
  <div class="cvm-grid">
392
  <div class="cvm-btn" data-cvm="CS1">CS1</div>
 
396
  <div class="cvm-btn" data-cvm="CS5">CS5</div>
397
  <div class="cvm-btn" data-cvm="CS6">CS6</div>
398
  </div>
399
+ <div id="cvm-desc" style="font-size: 9.5px; color: var(--cvm-teal); font-weight: 600; text-align: center; line-height: 1.35;">
400
+ Geometric C2–C4 evaluation active. Click stage above to manually override.
401
  </div>
402
  </div>
403
  </div>
 
409
  <button id="btn-lock-t1" class="btn btn-teal">📌 Lock as T1</button>
410
  <button id="btn-clear-t1" class="btn btn-secondary">Clear T1</button>
411
  </div>
412
+ <div class="form-group" style="margin-top: 3px;">
413
+ <label>Regional Registration</label>
414
+ <select id="super-mode" class="input-field" style="padding: 4px;">
415
  <option value="CRANIAL">Cranial Base (S-N at S)</option>
416
  <option value="MAXILLARY">Maxillary (Palatal Plane at PNS)</option>
417
  <option value="MANDIBULAR">Mandibular (Symphysis & Canal)</option>
418
  </select>
419
  </div>
420
  <div id="super-status" style="font-size: 9.5px; color: var(--text-muted); text-align: center;">
421
+ No T1 baseline locked.
422
  </div>
423
  </div>
424
  </div>
425
 
426
  <div>
427
  <div class="section-header">
428
+ <span>6. Calibration & Enhancement</span>
429
  <span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 10px;">Reset</span>
430
  </div>
431
  <div class="card">
432
+ <button id="btn-cal" class="btn btn-secondary">📐 Show / Move 10mm Ruler</button>
433
+ <span id="cal-status" style="font-size: 10px; color: var(--ruler-cyan); text-align: center; font-weight: 600; font-family:'JetBrains Mono',monospace;">
434
  Scale: 10.00 px/mm
435
  </span>
436
  <div class="slider-row">
 
454
  <span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 10px; display: none;">Restore Defaults</span>
455
  </div>
456
  <div class="card">
457
+ <button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 10.5px; padding: 5px;">
458
  ⚙️ Customize ABO Norms
459
  </button>
460
  <div id="norms-drawer"></div>
 
462
  </div>
463
  </aside>
464
 
465
+ <!-- Viewport Center -->
466
  <main class="viewport" id="viewport-wrapper">
467
  <div id="loupe-box">
468
+ <canvas id="loupe-canvas" width="140" height="140"></canvas>
469
  <div id="loupe-label">S</div>
470
  </div>
471
 
472
  <div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
473
+ <div style="font-size: 42px;">🦷</div>
474
+ <div style="font-size: 15px; font-weight: 600; color: var(--text-main);">Drop Lateral Cephalogram or Saved .JSON Here</div>
475
+ <div style="font-size: 11.5px; line-height: 1.5;">Supports DICOM (.dcm), JPEG, PNG and OrthoCeph JSON records.<br>Immediate AI landmark detection with full cervical vertebral morphology.</div>
476
  </div>
477
 
478
  <div id="viewport-container">
479
+ <img id="ceph-image" src="" alt="Lateral Cephalogram">
480
  <svg id="overlay-svg"></svg>
481
  </div>
482
 
483
  <div class="viewport-overlay-controls">
484
+ <button id="btn-zoom-in" title="Zoom In">Zoom (+)</button>
485
+ <button id="btn-zoom-out" title="Zoom Out">Zoom (-)</button>
486
+ <button id="btn-zoom-reset" title="Fit to screen">Fit</button>
487
  <span style="color: var(--surface-border);">|</span>
488
+ <span class="shortcut-hint">Drag screen with <strong>Middle Click / Alt-Drag</strong> • Hold <strong>[SPACE]</strong> to peek image</span>
489
  </div>
490
  </main>
491
 
492
  <!-- Right Analysis Panel -->
493
  <aside class="analysis-panel">
494
  <div class="diagnosis-banner">
495
+ <div class="diagnosis-headline" id="diag-headline">Awaiting Lateral Cephalogram...</div>
496
  <div class="diagnosis-grid">
497
  <div class="diag-item">
498
  <span class="diag-label">Sagittal Skeletal</span>
499
  <span class="diag-val" id="diag-sagittal">-</span>
500
  </div>
501
  <div class="diag-item">
502
+ <span class="diag-label">Vertical Pattern</span>
503
  <span class="diag-val" id="diag-vertical">-</span>
504
  </div>
505
  <div class="diag-item">
506
+ <span class="diag-label">Dental Inclination</span>
507
  <span class="diag-val" id="diag-dental">-</span>
508
  </div>
509
  <div class="diag-item">
510
+ <span class="diag-label">Soft Profile & CVM</span>
511
  <span class="diag-val" id="diag-soft">-</span>
512
  </div>
513
  </div>
 
527
  </tr>
528
  </thead>
529
  <tbody id="abo-rows">
530
+ <tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 16px;">Load radiograph or JSON to view analysis...</td></tr>
531
  </tbody>
532
  </table>
533
  </div>
 
541
  <th>Norm</th>
542
  <th>Measured</th>
543
  <th>Diff</th>
544
+ <th>Interpretation</th>
545
  </tr>
546
  </thead>
547
  <tbody id="wits-rows">
548
+ <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting tracing...</td></tr>
549
  </tbody>
550
  </table>
551
  </div>
 
563
  </tr>
564
  </thead>
565
  <tbody id="holdaway-rows">
566
+ <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting tracing...</td></tr>
567
  </tbody>
568
  </table>
569
  </div>
570
 
571
  <div id="section-cvm">
572
+ <div class="section-header" style="color: #2dd4bf;">Cervical Vertebral Maturation (C2–C4 Morphology)</div>
573
  <table class="analysis-table">
574
  <thead>
575
  <tr>
576
+ <th>Vertebral Landmark</th>
577
  <th>Measured</th>
578
+ <th>Morphology & Timing</th>
579
  </tr>
580
  </thead>
581
  <tbody id="cvm-rows">
582
+ <tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 12px;">Activate CVM Focus Mode or select a maturation stage.</td></tr>
583
  </tbody>
584
  </table>
585
  </div>
 
588
 
589
  <script>
590
  // -------------------------------------------------------------
591
+ // 1. Constants, Clinical Norms & Cervical Maturation Stages
592
  // -------------------------------------------------------------
593
  const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
594
 
 
599
  };
600
 
601
  const MODE_LANDMARKS = {
602
+ ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft", "PNS", "ANS"]),
603
  WITS: new Set(["A", "B", "OP_P", "OP_A"]),
604
  HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
605
+ CVM: new Set([
606
+ "C2_INF", "C2_POST", "C2_ANT",
607
+ "C3_UL", "C3_UR", "C3_LL", "C3_LR", "C3_INF",
608
+ "C4_UL", "C4_UR", "C4_LL", "C4_LR", "C4_INF"
609
+ ]),
610
  SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog"]),
611
+ ALL: new Set([
612
+ "S", "N", "Po", "Or", "A", "B", "Pog", "Me", "Gn", "Go", "ANS", "PNS",
613
+ "UIT", "UIA", "LIT", "LIA", "Pn", "Sn", "Ls", "Li", "Pog_soft", "OP_P", "OP_A",
614
+ "C2_INF", "C2_POST", "C2_ANT",
615
+ "C3_UL", "C3_UR", "C3_LL", "C3_LR", "C3_INF",
616
+ "C4_UL", "C4_UR", "C4_LL", "C4_LR", "C4_INF"
617
+ ])
618
  };
619
 
620
  const CVM_INFO = {
621
+ CS1: "CS1 (Pre-Peak): Lower borders of C2–C4 are flat. C3 and C4 bodies are trapezoid. Mandibular growth peak is >2 years away.",
622
+ CS2: "CS2 (Pre-Peak): Concavity at the lower border of C2. C3 and C4 remain trapezoid. Peak growth within 1 year.",
623
+ CS3: "CS3 (Peak Ascending): Concavities at inferior borders of C2 & C3. C3/C4 horizontal rectangular. Peak growth begins now (Optimum timing for Class II functional orthopedics).",
624
+ CS4: "CS4 (Peak Deceleration): Concavities present at C2, C3, and C4. C3 and C4 bodies are horizontal rectangles. Peak occurred 1–2 years ago.",
625
+ CS5: "CS5 (Post-Peak): Concavities present on C2–C4; at least one body (C3 or C4) is square. Peak ended >1 year ago.",
626
+ CS6: "CS6 (Maturation Complete): Concavities prominent on C2–C4; at least one body is vertical rectangular. Craniofacial growth complete."
627
  };
628
 
629
  const DEFAULT_ABO_NORMS = [
 
643
  { id: "LL_E", name: "Lower Lip to E-Line", norm: -1.0, sd: 2.0, unit: "mm" }
644
  ];
645
 
646
+ let ABO_NORMS = JSON.parse(localStorage.getItem("custom_abo_norms_v2")) || JSON.parse(JSON.stringify(DEFAULT_ABO_NORMS));
647
 
648
  const HOLDAWAY_NORMS = [
649
  { id: "H_ANGLE", name: "H-Angle (H-Line to N'-Pog')", norm: 10.0, sd: 3.0, unit: "°" },
 
651
  { id: "NOSE_PROM", name: "Nose Prominence (Pn to H-Line)", norm: 18.0, sd: 4.0, unit: "mm" },
652
  { id: "SN_HLINE", name: "Subnasale to H-Line", norm: 5.0, sd: 2.0, unit: "mm" },
653
  { id: "LL_HLINE", name: "Lower Lip to H-Line", norm: 0.5, sd: 1.0, unit: "mm" },
654
+ { id: "CHIN_THICK", name: "Soft Chin Thickness (Pog to Pog')", norm: 11.0, sd: 2.0, unit: "mm" }
655
  ];
656
 
657
  // App State
 
669
  let showPoints = true;
670
  let showLabels = true;
671
  let spacebarPeek = false;
672
+
673
+ // Viewport Transform State (Smooth Pan/Zoom)
674
  let zoomLevel = 1.0;
675
+ let panX = 0;
676
+ let panY = 0;
677
+ let isPanning = false;
678
+ let startPanMouseX = 0, startPanMouseY = 0;
679
+
680
  let draggingLm = null;
681
  let latestMetrics = {};
682
  let latestDiagnosis = { headline: "", sagittal: "-", vertical: "-", dental: "-", soft: "-" };
 
692
  const loupeBox = document.getElementById("loupe-box");
693
  const loupeCanvas = document.getElementById("loupe-canvas");
694
  const loupeLabel = document.getElementById("loupe-label");
695
+ const toastElem = document.getElementById("toast-msg");
696
 
697
  document.getElementById("pt-date").valueAsDate = new Date();
698
  updateSectionVisibility();
699
  buildNormsEditor();
700
 
701
+ function notify(text, duration = 2800) {
702
+ toastElem.innerText = text;
703
+ toastElem.style.display = "block";
704
+ setTimeout(() => { toastElem.style.display = "none"; }, duration);
705
+ }
706
+
707
  // -------------------------------------------------------------
708
+ // 2. Custom Norms Editor
709
  // -------------------------------------------------------------
710
  function buildNormsEditor() {
711
  const drawer = document.getElementById("norms-drawer");
 
728
  const val = parseFloat(e.target.value);
729
  if (!isNaN(val)) {
730
  ABO_NORMS[i][field] = val;
731
+ localStorage.setItem("custom_abo_norms_v2", JSON.stringify(ABO_NORMS));
732
  renderAnalysis();
733
  }
734
  });
 
745
 
746
  document.getElementById("reset-norms").addEventListener("click", () => {
747
  ABO_NORMS = JSON.parse(JSON.stringify(DEFAULT_ABO_NORMS));
748
+ localStorage.removeItem("custom_abo_norms_v2");
749
  buildNormsEditor();
750
  renderAnalysis();
751
+ notify("ABO norms restored to default standards.");
752
  });
753
 
754
  // -------------------------------------------------------------
755
+ // 3. Initialize AI Model
756
  // -------------------------------------------------------------
757
  async function initModel() {
758
  try {
759
  ort.env.wasm.numThreads = 2;
760
  session = await ort.InferenceSession.create(MODEL_URL, { executionProviders: ['wasm'] });
761
  statusInd.style.backgroundColor = "var(--status-green)";
762
+ statusTxt.innerText = "AI Online";
763
  if (imgElem.src && imgElem.naturalWidth > 0 && Object.keys(coords).length === 0) {
764
  runAutoTrace();
765
  }
766
  } catch (err) {
767
  statusInd.style.backgroundColor = "var(--status-red)";
768
+ statusTxt.innerText = "AI Offline (Manual Mode)";
769
  }
770
  }
771
  initModel();
772
 
773
  // -------------------------------------------------------------
774
+ // 4. File Upload (DICOM, Standard Image, JSON)
775
  // -------------------------------------------------------------
776
  const viewportWrapper = document.getElementById("viewport-wrapper");
777
 
 
808
  if (isDicom) {
809
  const reader = new FileReader();
810
  reader.onload = (evt) => {
811
+ try {
812
+ parseAndDisplayDicom(new Uint8Array(evt.target.result));
813
+ } catch (err) {
814
+ notify("DICOM Parse Error: " + err.message);
815
+ }
816
  };
817
  reader.readAsArrayBuffer(file);
818
  } else {
 
823
  }
824
 
825
  // -------------------------------------------------------------
826
+ // 5. Robust JSON Save & Load (Fixes Blank Screen & Data Drift)
827
  // -------------------------------------------------------------
828
  document.getElementById("btn-save-json").addEventListener("click", () => {
829
  if (!coords.S) {
830
+ notify("No active cephalogram tracing to save.");
831
  return;
832
  }
833
  const ptName = document.getElementById("pt-name").value || "Patient";
 
835
  const ptDate = document.getElementById("pt-date").value || "";
836
 
837
  const payload = {
838
+ app: "OrthoCephPro",
839
+ version: "3.0",
840
  patient: { name: ptName, chart: ptChart, date: ptDate },
841
  pxPerMm,
842
  cvmStage,
 
844
  initialAiCoords,
845
  metrics: latestMetrics,
846
  diagnosis: latestDiagnosis,
847
+ imageDataUrl: imgElem.src && imgElem.src.startsWith("data:") ? imgElem.src : null
848
  };
849
 
850
  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
851
  const url = URL.createObjectURL(blob);
852
  const a = document.createElement("a");
853
  a.href = url;
854
+ a.download = `Ceph_${ptName.replace(/\s+/g, '_')}_${ptDate || 'record'}.json`;
855
  a.click();
856
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
857
+ notify("Tracing JSON record exported successfully.");
858
  });
859
 
860
  function loadJsonFile(file) {
 
867
  document.getElementById("pt-chart").value = data.patient.chart || "";
868
  if (data.patient.date) document.getElementById("pt-date").value = data.patient.date;
869
  }
870
+ if (data.pxPerMm && data.pxPerMm > 0) {
871
  pxPerMm = data.pxPerMm;
872
+ calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Loaded)`;
873
  }
874
  if (data.cvmStage) {
875
  cvmStage = data.cvmStage;
876
  highlightCvmButton(cvmStage);
877
  }
878
 
879
+ const loadedCoords = data.coords || data.landmarks || null;
880
  if (loadedCoords && loadedCoords.S) {
881
  coords = JSON.parse(JSON.stringify(loadedCoords));
882
  initialAiCoords = data.initialAiCoords
 
884
  : JSON.parse(JSON.stringify(loadedCoords));
885
  }
886
 
887
+ // Check for image or build fallback canvas
888
+ if (data.imageDataUrl && data.imageDataUrl.startsWith("data:image")) {
889
  setupImage(data.imageDataUrl, false);
890
  } else {
891
+ // If image wasn't embedded, synthesize background grid using landmark bounding box
892
+ generateFallbackCanvasFromCoords();
893
  }
894
+ notify("Session loaded successfully from JSON.");
895
  } catch (err) {
896
+ notify("Failed to parse JSON file: " + err.message);
897
  }
898
  };
899
  reader.readAsText(file);
900
  }
901
 
902
+ function generateFallbackCanvasFromCoords() {
903
+ const xs = Object.values(coords).map(p => p.x).filter(x => typeof x === 'number');
904
+ const ys = Object.values(coords).map(p => p.y).filter(y => typeof y === 'number');
905
+ const maxX = xs.length ? Math.max(...xs) + 120 : 1000;
906
+ const maxY = ys.length ? Math.max(...ys) + 120 : 1200;
907
+ const w = Math.max(800, Math.ceil(maxX));
908
+ const h = Math.max(900, Math.ceil(maxY));
909
+
910
+ const c = document.createElement("canvas");
911
+ c.width = w; c.height = h;
912
+ const ctx = c.getContext("2d");
913
+ ctx.fillStyle = "#090d16";
914
+ ctx.fillRect(0, 0, w, h);
915
+
916
+ // Anatomical orientation grid lines
917
+ ctx.strokeStyle = "#172033";
918
+ ctx.lineWidth = 1;
919
+ for (let x = 0; x < w; x += 50) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
920
+ for (let y = 0; y < h; y += 50) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
921
+
922
+ ctx.fillStyle = "#475569";
923
+ ctx.font = "14px Inter, sans-serif";
924
+ ctx.fillText("OrthoCeph Record Preview (No Background Image Stored)", 24, 36);
925
+
926
+ setupImage(c.toDataURL("image/png"), false);
927
+ }
928
+
929
  // -------------------------------------------------------------
930
+ // 6. DICOM & Canvas Setup
931
  // -------------------------------------------------------------
932
  function parseAndDisplayDicom(byteArray) {
933
  const dataSet = dicomParser.parseDicom(byteArray);
 
945
  const parts = spacingStr.split('\\').map(parseFloat);
946
  if (parts[0] > 0) {
947
  pxPerMm = 1.0 / parts[0];
948
+ calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (DICOM)`;
949
  }
950
  }
951
 
 
1006
  imgElem.onload = () => {
1007
  dropzone.style.display = "none";
1008
  container.style.display = "block";
1009
+
1010
+ const w = imgElem.naturalWidth || 1000;
1011
+ const h = imgElem.naturalHeight || 1200;
1012
+ imgElem.width = w;
1013
+ imgElem.height = h;
1014
+
1015
+ svgElem.setAttribute("viewBox", `0 0 ${w} ${h}`);
1016
+ svgElem.setAttribute("width", w);
1017
+ svgElem.setAttribute("height", h);
1018
+
1019
+ fitImageToViewport();
1020
+
1021
+ if (shouldRunAi && session) {
1022
+ runAutoTrace();
1023
+ } else {
1024
+ renderAnalysis();
1025
+ }
1026
  };
1027
  imgElem.src = srcUrl;
1028
  }
1029
 
1030
+ function fitImageToViewport() {
1031
+ if (!imgElem.naturalWidth) return;
1032
+ const vw = viewportWrapper.clientWidth;
1033
+ const vh = viewportWrapper.clientHeight;
1034
+ const iw = imgElem.naturalWidth;
1035
+ const ih = imgElem.naturalHeight;
1036
+
1037
+ const scale = Math.min((vw - 40) / iw, (vh - 40) / ih, 1.0);
1038
+ zoomLevel = Math.max(0.2, scale);
1039
+ panX = (vw - iw * zoomLevel) / 2;
1040
+ panY = (vh - ih * zoomLevel) / 2;
1041
+ updateTransform();
1042
+ }
1043
+
1044
+ function updateTransform() {
1045
+ container.style.transform = `translate(${panX}px, ${panY}px) scale(${zoomLevel})`;
1046
+ }
1047
+
1048
  // -------------------------------------------------------------
1049
+ // 7. Auto-Tracing, Anatomical CVM Heuristics & Landmark Derivation
1050
  // -------------------------------------------------------------
1051
  async function runAutoTrace() {
1052
  if (!session || !imgElem.src) return;
1053
  statusInd.style.backgroundColor = "var(--status-amber)";
1054
+ statusTxt.innerText = "Analyzing Radiograph...";
1055
 
1056
+ await new Promise(r => setTimeout(r, 30));
1057
 
1058
  const off = document.createElement("canvas");
1059
  off.width = 768; off.height = 768;
 
1094
  };
1095
  }
1096
 
1097
+ // Derive Posterior Nasal Spine (PNS) along the Palatal Plane
1098
+ if (coords.ANS && coords.Or && coords.Po) {
1099
+ const palatalVec = { x: coords.ANS.x - (coords.Po.x + (coords.Or.x - coords.Po.x) * 0.3), y: 0 };
1100
+ coords.PNS = {
1101
+ x: coords.ANS.x - Math.max(38, Math.min(65, palatalVec.x * 0.35 || 50)),
1102
+ y: coords.ANS.y + 2
1103
+ };
1104
+ } else if (coords.ANS) {
1105
+ coords.PNS = { x: coords.ANS.x - 48, y: coords.ANS.y };
1106
+ }
1107
+
1108
+ // Occlusal Plane Landmarks (OP_A anterior, OP_P posterior)
1109
  if (coords.UIT && coords.LIT) {
1110
  coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
1111
  }
1112
  if (coords.Go && coords.OP_A) {
1113
+ coords.OP_P = { x: coords.OP_A.x - (coords.OP_A.x - coords.Go.x) * 0.52, y: coords.OP_A.y - 10 };
1114
  }
1115
 
1116
+ // ANATOMICALLY SOUND C2-C4 CERVICAL VERTEBRAL TRACING
1117
+ // The Cervical Spine descends posterior to the pharynx, along the retro-mandibular trajectory
1118
+ if (coords.S && coords.Go && coords.Po) {
1119
+ // Determine spinal column trajectory
1120
+ const spineRefX = coords.Po.x - (coords.Go.x - coords.Po.x) * 0.35;
1121
+ const spineStartY = coords.Go.y - (coords.Go.y - coords.Po.y) * 0.28;
1122
+ const vWidth = Math.max(26, origW * 0.026);
1123
+ const vHeight = vWidth * 0.78;
1124
+
1125
+ // C2 (Axis) with Odontoid Base and Inferior Border
1126
+ coords.C2_ANT = { x: spineRefX + vWidth * 0.45, y: spineStartY };
1127
+ coords.C2_POST = { x: spineRefX - vWidth * 0.65, y: spineStartY - 4 };
1128
+ coords.C2_INF = { x: spineRefX - vWidth * 0.1, y: spineStartY + vHeight * 0.65 };
1129
+
1130
+ // C3 Vertebra (Corpus & concavity inflection)
1131
+ const c3Y = spineStartY + vHeight * 1.55;
1132
+ coords.C3_UL = { x: spineRefX - vWidth * 0.65, y: c3Y - vHeight * 0.45 };
1133
+ coords.C3_UR = { x: spineRefX + vWidth * 0.55, y: c3Y - vHeight * 0.35 };
1134
+ coords.C3_LL = { x: spineRefX - vWidth * 0.65, y: c3Y + vHeight * 0.5 };
1135
+ coords.C3_LR = { x: spineRefX + vWidth * 0.55, y: c3Y + vHeight * 0.45 };
1136
+ coords.C3_INF = { x: spineRefX - vWidth * 0.05, y: c3Y + vHeight * 0.35 };
1137
+
1138
+ // C4 Vertebra (Corpus & concavity inflection)
1139
+ const c4Y = c3Y + vHeight * 1.55;
1140
+ coords.C4_UL = { x: spineRefX - vWidth * 0.65, y: c4Y - vHeight * 0.45 };
1141
+ coords.C4_UR = { x: spineRefX + vWidth * 0.55, y: c4Y - vHeight * 0.35 };
1142
+ coords.C4_LL = { x: spineRefX - vWidth * 0.65, y: c4Y + vHeight * 0.5 };
1143
+ coords.C4_LR = { x: spineRefX + vWidth * 0.55, y: c4Y + vHeight * 0.45 };
1144
+ coords.C4_INF = { x: spineRefX - vWidth * 0.05, y: c4Y + vHeight * 0.35 };
1145
  }
1146
 
1147
+ // 10mm Reference Ruler in upper corner
1148
+ coords.RULER_1 = { x: origW * 0.84, y: origH * 0.1 };
1149
+ coords.RULER_2 = { x: origW * 0.84, y: origH * 0.1 + (pxPerMm * 10.0) };
1150
 
1151
  initialAiCoords = JSON.parse(JSON.stringify(coords));
 
1152
  statusInd.style.backgroundColor = "var(--status-green)";
1153
+ statusTxt.innerText = "Traced (AI Ready)";
1154
  renderAnalysis();
1155
  }
1156
 
 
1159
  if (Object.keys(initialAiCoords).length > 0) {
1160
  coords = JSON.parse(JSON.stringify(initialAiCoords));
1161
  renderAnalysis();
1162
+ notify("All points reset to AI initial positions.");
1163
  } else {
1164
  runAutoTrace();
1165
  }
 
1169
  if (selectedLm && initialAiCoords[selectedLm]) {
1170
  coords[selectedLm] = { ...initialAiCoords[selectedLm] };
1171
  renderAnalysis();
1172
+ notify(`Reset ${selectedLm} to initial position.`);
1173
  } else {
1174
+ notify("Click any landmark point first to select it.");
1175
  }
1176
  });
1177
 
1178
  // -------------------------------------------------------------
1179
+ // 8. CVM Controls & Regional Superimposition Alignment
1180
  // -------------------------------------------------------------
1181
  document.querySelectorAll(".cvm-btn").forEach(btn => {
1182
  btn.addEventListener("click", () => {
 
1191
  document.querySelectorAll(".cvm-btn").forEach(b => {
1192
  b.classList.toggle("active", b.getAttribute("data-cvm") === stage);
1193
  });
1194
+ document.getElementById("cvm-desc").innerText = CVM_INFO[stage] || "Geometric C2–C4 evaluation active.";
1195
  }
1196
 
1197
  document.getElementById("btn-lock-t1").addEventListener("click", () => {
1198
  if (!coords.S) {
1199
+ notify("Trace a baseline cephalogram first before locking T1.");
1200
  return;
1201
  }
1202
  t1Baseline = {
 
1204
  metrics: JSON.parse(JSON.stringify(latestMetrics)),
1205
  date: document.getElementById("pt-date").value || "T1"
1206
  };
1207
+ document.getElementById("super-status").innerHTML = `<span style="color:#5eead4; font-weight:700;">✅ T1 Locked (${t1Baseline.date})</span> — Now load T2 cephalogram.`;
1208
  document.getElementById("th-t1-abo").style.display = "table-cell";
1209
+ notify("Baseline T1 successfully locked.");
1210
  renderAnalysis();
1211
  });
1212
 
 
1217
  renderAnalysis();
1218
  });
1219
 
 
1220
  function getSuperimposedT1Coords() {
1221
  if (!t1Baseline || !t1Baseline.coords.S || !coords.S) return null;
1222
  const mode = document.getElementById("super-mode").value;
 
1226
  let angle1 = 0, angle2 = 0;
1227
 
1228
  if (mode === "MAXILLARY" && t1Baseline.coords.PNS && t1Baseline.coords.ANS && coords.PNS && coords.ANS) {
 
1229
  origin1 = t1Baseline.coords.PNS;
1230
  origin2 = coords.PNS;
1231
  angle1 = Math.atan2(t1Baseline.coords.ANS.y - t1Baseline.coords.PNS.y, t1Baseline.coords.ANS.x - t1Baseline.coords.PNS.x);
1232
  angle2 = Math.atan2(coords.ANS.y - coords.PNS.y, coords.ANS.x - coords.PNS.x);
1233
  } else if (mode === "MANDIBULAR" && t1Baseline.coords.Me && t1Baseline.coords.Go && coords.Me && coords.Go) {
 
1234
  origin1 = t1Baseline.coords.Me;
1235
  origin2 = coords.Me;
1236
  angle1 = Math.atan2(t1Baseline.coords.Go.y - t1Baseline.coords.Me.y, t1Baseline.coords.Go.x - t1Baseline.coords.Me.x);
1237
  angle2 = Math.atan2(coords.Go.y - coords.Me.y, coords.Go.x - coords.Me.x);
1238
  } else {
1239
+ // Cranial Base Alignment (S-N at S)
1240
  if (!t1Baseline.coords.N || !coords.N) return null;
1241
  angle1 = Math.atan2(t1Baseline.coords.N.y - s1.y, t1Baseline.coords.N.x - s1.x);
1242
  angle2 = Math.atan2(coords.N.y - s2.y, coords.N.x - s2.x);
 
1258
  }
1259
 
1260
  // -------------------------------------------------------------
1261
+ // 9. Focus Modes, Visibility & Spacebar Peek
1262
  // -------------------------------------------------------------
1263
  document.querySelectorAll(".mode-btn").forEach(btn => {
1264
  btn.addEventListener("click", () => {
 
1308
  });
1309
 
1310
  // -------------------------------------------------------------
1311
+ // 10. Interactive Canvas Pan, Zoom & Landmark Dragging
1312
  // -------------------------------------------------------------
1313
  calBtn.addEventListener("click", () => {
1314
  if (!imgElem.src) return;
1315
+ showRuler = !showRuler;
1316
+ calBtn.style.background = showRuler ? "#0891b2" : "#131c2e";
 
 
1317
  renderAnalysis();
1318
  });
1319
 
 
1325
  }
1326
 
1327
  function updateLoupe(pt, name) {
1328
+ if (!imgElem.src || !imgElem.naturalWidth) return;
1329
  loupeBox.style.display = "block";
1330
  loupeLabel.innerText = name;
1331
  const lCtx = loupeCanvas.getContext("2d");
1332
  const zoom = 3.0;
1333
+ const size = 140;
1334
  const srcSize = size / zoom;
1335
 
1336
  lCtx.clearRect(0, 0, size, size);
 
1342
  );
1343
  lCtx.filter = "none";
1344
 
1345
+ // Targeting reticle
1346
  lCtx.strokeStyle = "#38bdf8";
1347
  lCtx.lineWidth = 1.5;
1348
  lCtx.beginPath();
 
1353
  lCtx.stroke();
1354
  }
1355
 
1356
+ viewportWrapper.addEventListener("wheel", (e) => {
1357
+ if (!imgElem.src) return;
1358
+ e.preventDefault();
1359
+ const zoomFactor = e.deltaY < 0 ? 1.15 : 0.88;
1360
+ const newZoom = Math.min(Math.max(0.2, zoomLevel * zoomFactor), 4.5);
1361
+
1362
+ const rect = viewportWrapper.getBoundingClientRect();
1363
+ const mouseX = e.clientX - rect.left;
1364
+ const mouseY = e.clientY - rect.top;
1365
+
1366
+ panX = mouseX - (mouseX - panX) * (newZoom / zoomLevel);
1367
+ panY = mouseY - (mouseY - panY) * (newZoom / zoomLevel);
1368
+ zoomLevel = newZoom;
1369
+ updateTransform();
1370
+ }, { passive: false });
1371
+
1372
+ viewportWrapper.addEventListener("mousedown", (e) => {
1373
+ // Pan on middle-click or Alt-click or background drag
1374
+ if (e.button === 1 || e.altKey || e.target === viewportWrapper || e.target === imgElem) {
1375
+ isPanning = true;
1376
+ startPanMouseX = e.clientX - panX;
1377
+ startPanMouseY = e.clientY - panY;
1378
+ viewportWrapper.style.cursor = "grabbing";
1379
+ }
1380
+ });
1381
+
1382
  window.addEventListener("mousemove", (e) => {
1383
+ if (isPanning) {
1384
+ panX = e.clientX - startPanMouseX;
1385
+ panY = e.clientY - startPanMouseY;
1386
+ updateTransform();
1387
+ return;
1388
+ }
1389
+
1390
  if (!draggingLm || !coords[draggingLm]) return;
1391
  const p = getSVGCoords(e);
1392
  coords[draggingLm].x = p.x;
 
1396
  const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
1397
  if (dist > 1) {
1398
  pxPerMm = dist / 10.0;
1399
+ calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (10mm Ruler)`;
1400
  }
1401
  }
1402
 
 
1405
  });
1406
 
1407
  window.addEventListener("mouseup", () => {
1408
+ if (isPanning) {
1409
+ isPanning = false;
1410
+ viewportWrapper.style.cursor = "default";
1411
+ }
1412
  if (draggingLm) {
1413
  draggingLm = null;
1414
  loupeBox.style.display = "none";
 
1416
  }
1417
  });
1418
 
1419
+ // Viewport Zoom Buttons
1420
+ document.getElementById("btn-zoom-in").addEventListener("click", () => {
1421
+ zoomLevel = Math.min(zoomLevel * 1.25, 4.0);
1422
+ updateTransform();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1423
  });
1424
+ document.getElementById("btn-zoom-out").addEventListener("click", () => {
1425
+ zoomLevel = Math.max(zoomLevel * 0.8, 0.25);
1426
+ updateTransform();
1427
+ });
1428
+ document.getElementById("btn-zoom-reset").addEventListener("click", fitImageToViewport);
1429
 
1430
  // -------------------------------------------------------------
1431
+ // 11. Image Filters & Reset
1432
  // -------------------------------------------------------------
1433
  function applyFilters() {
1434
  const b = document.getElementById("brightness").value;
 
1451
  coords = {};
1452
  initialAiCoords = {};
1453
  latestMetrics = {};
1454
+ t1Baseline = null;
1455
  selectedLm = null;
1456
  cvmStage = "Auto";
1457
  highlightCvmButton("");
 
1463
  document.getElementById("pt-name").value = "";
1464
  document.getElementById("pt-chart").value = "";
1465
  document.getElementById("pt-date").valueAsDate = new Date();
1466
+ document.getElementById("diag-headline").innerText = "Awaiting Lateral Cephalogram...";
1467
  document.getElementById("diag-sagittal").innerText = "-";
1468
  document.getElementById("diag-vertical").innerText = "-";
1469
  document.getElementById("diag-dental").innerText = "-";
1470
  document.getElementById("diag-soft").innerText = "-";
1471
+ document.getElementById("th-t1-abo").style.display = "none";
1472
  svgElem.innerHTML = "";
1473
+ populateAboTable(ABO_NORMS, {});
1474
+ populateTable("holdaway-rows", HOLDAWAY_NORMS, {});
1475
+ populateWitsTable(null);
1476
+ populateCvmTable(null);
1477
+ notify("Workspace cleared for next patient.");
1478
  });
1479
 
1480
  // -------------------------------------------------------------
1481
+ // 12. Geometric Math, Anatomical CVM Engine & Diagnosis
1482
  // -------------------------------------------------------------
1483
  function getAngle(p1, v, p2) {
1484
  if (!p1 || !v || !p2) return null;
 
1525
  return { distMm, ao, bo };
1526
  }
1527
 
1528
+ // Full Anatomical Baccetti Assessment (C2, C3, C4)
1529
  function evaluateCvmGeometry() {
1530
  if (!coords.C3_LL || !coords.C3_LR || !coords.C3_INF || !coords.C4_LL || !coords.C4_LR || !coords.C4_INF) return null;
 
 
1531
 
1532
+ // C2 Inferior Concavity depth
1533
+ let c2Concavity = 0;
1534
+ if (coords.C2_POST && coords.C2_ANT && coords.C2_INF) {
1535
+ c2Concavity = Math.abs(getPerpDist(coords.C2_INF, coords.C2_POST, coords.C2_ANT)) || 0;
1536
+ }
1537
+
1538
+ // C3 & C4 Inferior Border Concavity depths
1539
+ const c3Concavity = Math.abs(getPerpDist(coords.C3_INF, coords.C3_LL, coords.C3_LR)) || 0;
1540
+ const c4Concavity = Math.abs(getPerpDist(coords.C4_INF, coords.C4_LL, coords.C4_LR)) || 0;
1541
+
1542
+ // C3 Corpus Dimensions & Aspect Ratio (Width vs Anterior Height)
1543
  const c3Width = Math.hypot(coords.C3_LR.x - coords.C3_LL.x, coords.C3_LR.y - coords.C3_LL.y);
1544
  const c3Height = Math.hypot(coords.C3_LL.x - coords.C3_UL.x, coords.C3_LL.y - coords.C3_UL.y);
1545
  const c3Ratio = parseFloat((c3Width / (c3Height + 1e-5)).toFixed(2));
1546
 
1547
+ // Determine vertebral geometric silhouette
1548
  let shape = "Horizontal Rectangular";
1549
  if (c3Ratio > 1.35) shape = "Trapezoid / Tapered";
1550
+ else if (c3Ratio >= 0.88 && c3Ratio <= 1.15) shape = "Square";
1551
+ else if (c3Ratio < 0.88) shape = "Vertical Rectangular";
1552
+
1553
+ // Baccetti Staging Criteria
1554
+ const concavityThreshold = 0.8; // mm threshold for perceptible concavity
1555
+ const hasC2 = c2Concavity >= concavityThreshold;
1556
+ const hasC3 = c3Concavity >= concavityThreshold;
1557
+ const hasC4 = c4Concavity >= concavityThreshold;
1558
+
1559
+ let autoStage = "CS1";
1560
+ if (!hasC2 && !hasC3 && !hasC4) autoStage = "CS1 (Pre-Peak)";
1561
+ else if (hasC2 && !hasC3 && !hasC4) autoStage = "CS2 (Pre-Peak)";
1562
+ else if (hasC2 && hasC3 && !hasC4) autoStage = "CS3 (Ascending Peak)";
1563
+ else if (hasC2 && hasC3 && hasC4 && shape === "Horizontal Rectangular") autoStage = "CS4 (Decelerating Peak)";
1564
  else if (shape === "Square") autoStage = "CS5 (Post-Peak)";
1565
  else if (shape === "Vertical Rectangular") autoStage = "CS6 (Maturation Complete)";
1566
+ else autoStage = "CS3 (Peak Timing)";
1567
 
1568
  return {
1569
+ c2Concavity,
1570
  c3Concavity,
1571
  c4Concavity,
1572
  c3Ratio,
 
1580
  }
1581
 
1582
  function updateClinicalDiagnosis(m, cvmData) {
1583
+ if (m.ANB === null || isNaN(m.ANB)) return;
1584
 
1585
  const anbN = getNormObj("ANB");
1586
  const snaN = getNormObj("SNA");
 
1626
  else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";
1627
 
1628
  const stageLabel = cvmData ? cvmData.finalStage : cvmStage;
1629
+ const softAndCvm = `${softStr} • CVM: ${stageLabel}`;
1630
+ const headline = `${skelClass} • ${vertClass} • ${dentStr}`;
1631
 
1632
  latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
1633
 
 
1639
  }
1640
 
1641
  // -------------------------------------------------------------
1642
+ // 13. High-Fidelity SVG Renderer & Measurement Calculation
1643
  // -------------------------------------------------------------
1644
  function renderAnalysis() {
1645
  svgElem.innerHTML = "";
 
1657
  svgElem.appendChild(l);
1658
  }
1659
 
1660
+ function polyline(pts, col, w = 2, fill = "none") {
1661
+ const valid = pts.filter(Boolean);
1662
+ if (valid.length < 2) return;
1663
+ const p = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
1664
+ p.setAttribute("points", valid.map(pt => `${pt.x},${pt.y}`).join(" "));
1665
+ p.setAttribute("stroke", col);
1666
+ p.setAttribute("stroke-width", w);
1667
+ p.setAttribute("fill", fill);
1668
+ p.setAttribute("stroke-linejoin", "round");
1669
+ svgElem.appendChild(p);
1670
+ }
1671
+
1672
  const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
1673
  const cvmData = evaluateCvmGeometry();
1674
 
1675
+ // 1. Draw Superimposed T1 Ghost Tracing
1676
  const t1Aligned = getSuperimposedT1Coords();
1677
  if (t1Aligned && (focusMode === "SUPER" || focusMode === "ALL" || focusMode === "ABO")) {
1678
  const drawT1Line = (a, b) => {
1679
+ line(a, b, "#000000", 4.5);
1680
  line(a, b, "#94a3b8", 2, "5,3");
1681
  };
1682
  drawT1Line(t1Aligned.S, t1Aligned.N);
 
1685
  drawT1Line(t1Aligned.Go, t1Aligned.Me);
1686
  drawT1Line(t1Aligned.UIT, t1Aligned.UIA);
1687
  drawT1Line(t1Aligned.LIT, t1Aligned.LIA);
1688
+ if (t1Aligned.ANS && t1Aligned.PNS) drawT1Line(t1Aligned.PNS, t1Aligned.ANS);
1689
  }
1690
 
1691
+ // 2. Vector Planes
1692
  if (showLines) {
1693
  const isSuper = focusMode === "SUPER";
1694
  if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
1695
+ line(coords.S, coords.N, isSuper ? "#f43f5e" : "#38bdf8", 3); // S-N Plane
1696
+ line(coords.N, coords.A, isSuper ? "#f43f5e" : "#4ade80", 2); // N-A Line
1697
+ line(coords.N, coords.B, isSuper ? "#f43f5e" : "#4ade80", 2); // N-B Line
1698
+ line(coords.Po, coords.Or, isSuper ? "#f43f5e" : "#fbbf24", 2.5); // Frankfort Horizontal
1699
+ line(coords.Go, coords.Me, isSuper ? "#f43f5e" : "#f43f5e", 3); // Mandibular Plane
1700
+ line(coords.UIT, coords.UIA, isSuper ? "#f43f5e" : "#2dd4bf", 2.5); // Upper Incisor Long Axis
1701
+ line(coords.LIT, coords.LIA, isSuper ? "#f43f5e" : "#d946ef", 2.5); // Lower Incisor Long Axis
1702
+ line(coords.Pn, coords.Pog_soft, isSuper ? "#f43f5e" : "#fb923c", 2); // Ricketts E-Line
1703
+ if (coords.PNS && coords.ANS) line(coords.PNS, coords.ANS, isSuper ? "#f43f5e" : "#a3e635", 2); // Palatal Plane
1704
  }
1705
 
1706
  if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
1707
+ line(coords.Ls, coords.Pog_soft, "#ec4899", 2.5); // Harmony Line
1708
  line(coords.N, coords.Pog_soft, "#c084fc", 1.5, "4,4");
1709
  line(coords.N, coords.Pog, "#94a3b8", 1.5, "4,4");
1710
  }
 
1713
  const dx = coords.OP_A.x - coords.OP_P.x, dy = coords.OP_A.y - coords.OP_P.y;
1714
  const extP = { x: coords.OP_P.x - dx * 0.35, y: coords.OP_P.y - dy * 0.35 };
1715
  const extA = { x: coords.OP_A.x + dx * 0.35, y: coords.OP_A.y + dy * 0.35 };
1716
+ line(extP, extA, "#a855f7", 2.5); // Functional Occlusal Plane
1717
  if (wits) {
1718
  line(coords.A, wits.ao, "#a855f7", 2, "3,3");
1719
  line(coords.B, wits.bo, "#a855f7", 2, "3,3");
1720
  }
1721
  }
1722
 
1723
+ // Anatomical C2-C4 Cervical Spine Outline
1724
  if ((focusMode === "CVM" || focusMode === "ALL") && coords.C3_UL) {
1725
+ // C2 (Axis)
1726
+ if (coords.C2_POST && coords.C2_ANT && coords.C2_INF) {
1727
+ line(coords.C2_POST, coords.C2_ANT, "#14b8a6", 2);
1728
+ line(coords.C2_POST, coords.C2_INF, "#facc15", 2);
1729
+ line(coords.C2_INF, coords.C2_ANT, "#facc15", 2);
1730
+ }
1731
+
1732
+ // C3 Vertebral Body & Concavity
1733
+ polyline([coords.C3_UL, coords.C3_UR, coords.C3_LR, coords.C3_LL], "#14b8a6", 2, "rgba(20,184,166,0.06)");
1734
  line(coords.C3_LL, coords.C3_INF, "#facc15", 2.5);
1735
  line(coords.C3_INF, coords.C3_LR, "#facc15", 2.5);
 
1736
 
1737
+ // C4 Vertebral Body & Concavity
1738
+ polyline([coords.C4_UL, coords.C4_UR, coords.C4_LR, coords.C4_LL], "#14b8a6", 2, "rgba(20,184,166,0.06)");
 
1739
  line(coords.C4_LL, coords.C4_INF, "#facc15", 2.5);
1740
  line(coords.C4_INF, coords.C4_LR, "#facc15", 2.5);
 
1741
  }
1742
  }
1743
 
1744
+ // 3. Ruler Display
1745
  if (showRuler && coords.RULER_1 && coords.RULER_2) {
1746
+ line(coords.RULER_1, coords.RULER_2, "#06b6d4", 3, "4,3");
1747
  ["RULER_1", "RULER_2"].forEach((rKey, idx) => {
1748
  const pt = coords[rKey];
1749
  const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
1750
  const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1751
  c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
1752
+ c.setAttribute("r", 7); c.setAttribute("fill", "#06b6d4");
1753
  c.setAttribute("stroke", "#0f172a"); c.setAttribute("stroke-width", 2);
1754
  c.setAttribute("class", "landmark-handle");
1755
  c.addEventListener("mousedown", (e) => {
 
1769
  });
1770
  }
1771
 
1772
+ // 4. Landmark Interactive Handles
1773
  const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
1774
 
1775
  if (showPoints) {
 
1780
  const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
1781
  const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1782
  c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
1783
+ c.setAttribute("r", selectedLm === name ? 7.5 : 5.5);
1784
 
1785
  let handleColor = "#facc15";
1786
  if (name === "Sn") handleColor = "#ec4899";
1787
+ if (name === "PNS" || name === "ANS") handleColor = "#a3e635";
1788
  if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
1789
+ if (name.startsWith("C2_") || name.startsWith("C3_") || name.startsWith("C4_")) handleColor = "#14b8a6";
1790
+ if (name.endsWith("_INF")) handleColor = "#f59e0b";
1791
  if (selectedLm === name) handleColor = "#38bdf8";
1792
 
1793
  c.setAttribute("fill", handleColor);
1794
+ c.setAttribute("stroke", "#090d16");
1795
  c.setAttribute("stroke-width", 2);
1796
  c.setAttribute("class", "landmark-handle");
1797
 
 
1808
  e.stopPropagation();
1809
  if (initialAiCoords[name]) {
1810
  coords[name] = { ...initialAiCoords[name] };
1811
+ notify(`Reset ${name} to initial prediction.`);
1812
  renderAnalysis();
1813
  }
1814
  });
 
1827
  }
1828
  }
1829
 
1830
+ // Calculate ABO Metrics
1831
  const sna = getAngle(coords.S, coords.N, coords.A);
1832
  const snb = getAngle(coords.S, coords.N, coords.B);
1833
  const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
 
1843
  const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
1844
  const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);
1845
 
1846
+ // Holdaway Metrics
1847
  const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
1848
  const skel_conv = getPerpDist(coords.A, coords.N, coords.Pog);
1849
  const nose_prom = getPerpDist(coords.Pn, coords.Ls, coords.Pog_soft);
 
1881
  let diffColor = "var(--text-muted)";
1882
  let deltaT1Html = "";
1883
 
1884
+ if (val !== null && val !== undefined && !isNaN(val)) {
1885
  measuredText = `${val.toFixed(1)}${metric.unit}`;
1886
  const rawDiff = val - metric.norm;
1887
  const isNormal = Math.abs(rawDiff) <= metric.sd;
 
1896
 
1897
  if (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[metric.id] !== undefined) {
1898
  const t1Val = t1Baseline.metrics[metric.id];
1899
+ if (t1Val !== null && !isNaN(t1Val) && val !== null && !isNaN(val)) {
1900
+ const dT1 = val - t1Val;
1901
+ deltaT1Html = `<td style="color:#5eead4; font-weight:700; font-family:'JetBrains Mono',monospace;">${dT1 > 0 ? '+' : ''}${dT1.toFixed(1)}${metric.unit}</td>`;
1902
+ } else {
1903
+ deltaT1Html = `<td>-</td>`;
1904
+ }
1905
  } else if (t1Baseline) {
1906
  deltaT1Html = `<td>-</td>`;
1907
  }
 
1930
  let diffText = "-";
1931
  let diffColor = "var(--text-muted)";
1932
 
1933
+ if (val !== null && val !== undefined && !isNaN(val)) {
1934
  measuredText = `${val.toFixed(1)}${metric.unit}`;
1935
  const rawDiff = val - metric.norm;
1936
  const isNormal = Math.abs(rawDiff) <= metric.sd;
 
1956
  function populateWitsTable(val) {
1957
  const tbody = document.getElementById("wits-rows");
1958
  tbody.innerHTML = "";
1959
+ if (val === null || val === undefined || isNaN(val)) {
1960
+ tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 10px;">Awaiting occlusal plane tracing...</td></tr>`;
1961
+ return;
1962
+ }
1963
 
1964
  const diffFromZero = val.toFixed(1);
1965
  let statusHtml = `<span class="pill pill-normal">Class I</span>`;
1966
  let diffColor = "var(--status-green)";
1967
 
1968
  if (val > 1.0) {
1969
+ statusHtml = `<span class="pill pill-deviated">Class II Jaw Base</span>`;
1970
  diffColor = "var(--status-red)";
1971
  } else if (val < -2.0) {
1972
+ statusHtml = `<span class="pill pill-deviated">Class III Jaw Base</span>`;
1973
  diffColor = "var(--status-red)";
1974
  }
1975
 
 
1986
 
1987
  function populateCvmTable(cvm) {
1988
  const tbody = document.getElementById("cvm-rows");
1989
+ if (!cvm) {
1990
+ tbody.innerHTML = `<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 10px;">Select CS1–CS6 stage or activate CVM mode.</td></tr>`;
1991
+ return;
1992
+ }
1993
  tbody.innerHTML = `
1994
  <tr>
1995
+ <td><span class="metric-name">C2 Inferior Concavity</span></td>
1996
+ <td><span class="metric-val">${cvm.c2Concavity ? cvm.c2Concavity.toFixed(1) : 0.0} mm</span></td>
1997
+ <td>${cvm.c2Concavity >= 0.8 ? '<span class="pill pill-normal">Concave (Present)</span>' : '<span class="pill pill-neutral">Flat border</span>'}</td>
1998
+ </tr>
1999
+ <tr>
2000
+ <td><span class="metric-name">C3 Inferior Concavity</span></td>
2001
  <td><span class="metric-val">${cvm.c3Concavity.toFixed(1)} mm</span></td>
2002
+ <td>${cvm.c3Concavity >= 0.8 ? '<span class="pill pill-normal">Concave (Present)</span>' : '<span class="pill pill-neutral">Flat border</span>'}</td>
2003
  </tr>
2004
  <tr>
2005
+ <td><span class="metric-name">C4 Inferior Concavity</span></td>
2006
  <td><span class="metric-val">${cvm.c4Concavity.toFixed(1)} mm</span></td>
2007
+ <td>${cvm.c4Concavity >= 0.8 ? '<span class="pill pill-normal">Concave (Present)</span>' : '<span class="pill pill-neutral">Flat border</span>'}</td>
2008
  </tr>
2009
  <tr>
2010
+ <td><span class="metric-name">C3 Aspect Ratio (W/H)</span></td>
2011
  <td><span class="metric-val">${cvm.c3Ratio}</span></td>
2012
+ <td><span style="color:#5eead4; font-weight:700;">${cvm.shape}</span></td>
2013
  </tr>
2014
  <tr>
2015
  <td><span class="metric-name">Assigned Maturation Stage</span></td>
2016
+ <td colspan="2"><span class="metric-val" style="color:#2dd4bf; font-weight:700;">${cvm.finalStage}</span></td>
2017
  </tr>
2018
  `;
2019
  }
2020
 
2021
  // -------------------------------------------------------------
2022
+ // 14. EMR Copy & CSV Export
2023
  // -------------------------------------------------------------
2024
+ document.getElementById("btn-copy-note").addEventListener("click", () => {
2025
+ if (!latestMetrics.SNA) {
2026
+ notify("Trace a radiograph first before copying notes.");
2027
+ return;
2028
+ }
2029
+ const ptName = document.getElementById("pt-name").value || "Patient";
2030
+ const m = latestMetrics;
2031
+ const note = [
2032
+ `ORTHODONTIC CEPHALOMETRIC REPORT — ${ptName}`,
2033
+ `Diagnosis: ${latestDiagnosis.headline}`,
2034
+ `• Sagittal: ${latestDiagnosis.sagittal} | SNA: ${m.SNA}°, SNB: ${m.SNB}°, ANB: ${m.ANB}°, Wits: ${m.WITS ?? '-'} mm`,
2035
+ `• Vertical: ${latestDiagnosis.vertical} | FMA: ${m.FMA}°, SN-MP: ${m.SNMP}°`,
2036
+ `• 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}°`,
2037
+ `• Soft Tissue & Maturation: ${latestDiagnosis.soft} | UL to E-Line: ${m.UL_E}mm, LL to E-Line: ${m.LL_E}mm, Holdaway H-Angle: ${m.H_ANGLE}°`
2038
+ ].join("\n");
2039
+
2040
+ // Fallback copy logic for iframes
2041
+ const ta = document.createElement("textarea");
2042
+ ta.value = note;
2043
+ document.body.appendChild(ta);
2044
+ ta.select();
2045
+ try {
2046
+ document.execCommand("copy");
2047
+ notify("EMR clinical note copied to clipboard.");
2048
+ } catch (err) {
2049
+ notify("Clipboard write failed.");
2050
+ }
2051
+ document.body.removeChild(ta);
2052
+ });
2053
+
2054
  document.getElementById("btn-export-csv").addEventListener("click", () => {
2055
  if (!latestMetrics.SNA) {
2056
+ notify("Upload and trace a cephalogram first.");
2057
  return;
2058
  }
2059
+ const ptName = document.getElementById("pt-name").value || "Unnamed";
2060
  const ptChart = document.getElementById("pt-chart").value || "N/A";
2061
  const ptDate = document.getElementById("pt-date").value || "";
2062
 
2063
+ let csv = "Patient Name,Chart ID,Date,Diagnosis,CVM Stage,Category,Parameter,Standard Norm,Measured Value,Difference,Unit,Status\n";
2064
 
2065
  const addRows = (category, list) => {
2066
  list.forEach(m => {
2067
  const val = latestMetrics[m.id];
2068
+ if (val === null || val === undefined || isNaN(val)) return;
2069
  const diff = (val - m.norm).toFixed(1);
2070
  const status = Math.abs(val - m.norm) <= m.sd ? "Normal" : (val > m.norm ? "High" : "Low");
2071
  csv += `"${ptName}","${ptChart}","${ptDate}","${latestDiagnosis.headline}","${cvmStage}","${category}","${m.name}","${m.norm} +/- ${m.sd}",${val.toFixed(1)},${diff > 0 ? '+' + diff : diff},"${m.unit}","${status}"\n`;
 
2073
  };
2074
 
2075
  addRows("ABO", ABO_NORMS);
2076
+ if (latestMetrics.WITS !== null && !isNaN(latestMetrics.WITS)) {
2077
  const w = latestMetrics.WITS;
2078
  const wStat = w > 1.0 ? "Class II" : (w < -2.0 ? "Class III" : "Class I");
2079
  csv += `"${ptName}","${ptChart}","${ptDate}","${latestDiagnosis.headline}","${cvmStage}","Wits","Wits Appraisal (AO-BO)","0.0 +/- 1.0",${w.toFixed(1)},${w.toFixed(1)},"mm","${wStat}"\n`;
 
2084
  const url = URL.createObjectURL(blob);
2085
  const a = document.createElement("a");
2086
  a.href = url;
2087
+ a.download = `Ceph_Analysis_${ptName.replace(/\s+/g, '_')}_${ptDate || 'export'}.csv`;
2088
  a.click();
2089
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
2090
+ notify("CSV spreadsheet exported.");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2091
  });
2092
  </script>
2093
  </body>