Repository navigation
Expand file tree
/
Copy pathbuild_web_dashboard.py
More file actions
772 lines (662 loc) · 32.6 KB
/
Copy pathbuild_web_dashboard.py
File metadata and controls
772 lines (662 loc) · 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
#!/usr/bin/env python3
"""
Build script to create a static web dashboard from the dynamic dashboard.
This reads all results data and embeds it into a static HTML file.
"""
import json
import os
import glob
import shutil
from datetime import datetime
from pathlib import Path
def load_all_results():
"""Load all results data from the results directory"""
results_dir = Path("results")
all_data = {}
if not results_dir.exists():
print("⚠️ No results directory found. Creating empty dashboard.")
return {}
# Find all model directories
for model_dir in results_dir.iterdir():
if not model_dir.is_dir() or model_dir.name.startswith('.'):
continue
model_name = model_dir.name
all_data[model_name] = {}
# Find all JSON files in this model directory
json_files = list(model_dir.glob("results_*.json"))
for json_file in json_files:
try:
with open(json_file, 'r') as f:
data = json.load(f)
# Extract timestamp from filename
filename = json_file.stem # removes .json
timestamp_match = filename.replace('results_', '')
# Parse timestamp
try:
# Handle both formats: "2025-10-03T14-37-54.407411" and "2025-10-08T18:07:30.803202"
iso_timestamp = timestamp_match
if 'T' in iso_timestamp:
date_part, time_part = iso_timestamp.split('T', 1)
time_part = time_part.replace('-', ':')
iso_timestamp = f"{date_part}T{time_part}"
timestamp = datetime.fromisoformat(iso_timestamp)
formatted_timestamp = timestamp.isoformat()
except:
formatted_timestamp = timestamp_match
# Determine test type
test_type = "Full Evaluation"
config = data.get('config', {})
limit = config.get('limit')
if limit and limit < 1000:
test_type = f"Limited Test ({int(limit)} samples)"
# Store the data
all_data[model_name][timestamp_match] = {
'id': timestamp_match,
'timestamp': formatted_timestamp,
'label': test_type,
'data': data
}
except Exception as e:
print(f"⚠️ Error loading {json_file}: {e}")
return all_data
def create_static_html(all_data):
"""Create static HTML with embedded data"""
# Read the original dashboard HTML
dashboard_path = Path("dashboard/index.html")
if not dashboard_path.exists():
print("❌ Dashboard HTML not found!")
return False
with open(dashboard_path, 'r') as f:
html_content = f.read()
# Embed the data as a JSON script tag
data_script = f"""
<script>
// Embedded results data - generated by build script
window.EMBEDDED_DATA = {json.dumps(all_data, indent=2)};
// Override the API methods to use embedded data
class StaticEvaluationDashboard {{
constructor() {{
this.data = window.EMBEDDED_DATA;
this.currentRun = null;
this.charts = {{}};
this.currentSort = {{ column: null, direction: null }};
this.tableData = [];
this.initializeEventListeners();
this.loadStaticData();
}}
loadStaticData() {{
// Populate model select
this.populateModelSelect();
// Auto-select first model and first run if available
if (Object.keys(this.data).length > 0) {{
const firstModel = Object.keys(this.data)[0];
document.getElementById('modelSelect').value = firstModel;
this.onModelChange();
// Auto-select first run
setTimeout(() => {{
const runSelect = document.getElementById('runSelect');
if (runSelect.options.length > 1) {{
runSelect.selectedIndex = 1;
this.onRunChange();
}}
}}, 100);
}}
}}
populateModelSelect() {{
const select = document.getElementById('modelSelect');
select.innerHTML = '<option value="">Select a model...</option>';
Object.keys(this.data).forEach(modelId => {{
const option = document.createElement('option');
option.value = modelId;
// Convert model ID to readable format
const displayName = modelId.replace('__', ' ').replace(/_/g, ' ')
.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(' ');
option.textContent = displayName;
select.appendChild(option);
}});
}}
async onModelChange() {{
const modelId = document.getElementById('modelSelect').value;
if (!modelId) return;
const runs = Object.values(this.data[modelId] || {{}}).map(run => ({{
id: run.id,
timestamp: run.timestamp,
label: run.label
}}));
this.populateRunSelect(runs);
}}
populateRunSelect(runs) {{
const select = document.getElementById('runSelect');
select.innerHTML = '<option value="">Select a run...</option>';
runs.forEach(run => {{
const option = document.createElement('option');
option.value = run.id;
let timestampStr = run.timestamp;
try {{
const timestamp = new Date(run.timestamp);
if (!isNaN(timestamp.getTime())) {{
timestampStr = timestamp.toLocaleString();
}}
}} catch (e) {{
console.warn('Failed to parse timestamp:', run.timestamp);
}}
option.textContent = `${{run.label}} - ${{timestampStr}}`;
select.appendChild(option);
}});
}}
async onRunChange() {{
const runId = document.getElementById('runSelect').value;
if (!runId) return;
const modelId = document.getElementById('modelSelect').value;
const runData = this.data[modelId]?.[runId]?.data;
if (!runData) {{
this.showError('Run data not found');
return;
}}
this.currentRun = {{ id: runId, data: runData }};
this.renderDashboard(runData);
}}
// Copy all other methods from the original dashboard class
renderDashboard(data) {{
document.getElementById('loading').style.display = 'none';
document.getElementById('dashboard').style.display = 'block';
this.updateMetrics(data);
this.createCharts(data);
this.populateTable(data);
}}
updateMetrics(data) {{
const results = data.results;
// Calculate overall accuracy
const accuracies = Object.values(results)
.filter(r => r['acc,none'] !== undefined)
.map(r => r['acc,none']);
const overallAccuracy = accuracies.length > 0 ? accuracies.reduce((a, b) => a + b, 0) / accuracies.length : 0;
document.getElementById('overallAccuracy').textContent = (overallAccuracy * 100).toFixed(1) + '%';
// Handle hellaswag score - may not exist in subsection tests
const hellaswagScore = results.hellaswag ? (results.hellaswag['acc,none'] * 100).toFixed(1) + '%' : 'N/A';
document.getElementById('hellaswagScore').textContent = hellaswagScore;
// Handle mmlu score - check for main mmlu task or any mmlu subsection
let mmluScore = 'N/A';
if (results.mmlu) {{
mmluScore = (results.mmlu['acc,none'] * 100).toFixed(1) + '%';
}} else {{
// Look for any MMLU subsection task
const mmluSubsection = Object.keys(results).find(key => key.startsWith('mmlu_'));
if (mmluSubsection) {{
mmluScore = (results[mmluSubsection]['acc,none'] * 100).toFixed(1) + '%';
}}
}}
document.getElementById('mmluScore').textContent = mmluScore;
// Calculate total questions - simplified display
const questionData = this.calculateQuestionBreakdown(data);
document.getElementById('totalQuestions').textContent = questionData.total.toLocaleString();
// Update subtitle based on whether it's a limited test
const isLimitedTest = data.config && data.config.limit && data.config.limit < 1000;
document.getElementById('questionsSubtitle').textContent = isLimitedTest ? 'limited test' : 'full evaluation';
// Hide the detailed breakdown from the metric card (moved to table)
document.getElementById('questionBreakdown').innerHTML = '';
// Display test duration
const duration = this.formatDuration(data);
document.getElementById('testDuration').textContent = duration.value;
document.getElementById('durationSubtitle').textContent = duration.unit;
// Extract date from run ID
const runId = this.currentRun.id;
const dateMatch = runId.match(/(\\d{{4}}-\\d{{2}}-\\d{{2}})/);
const date = dateMatch ? dateMatch[1] : 'Unknown';
document.getElementById('testDate').textContent = date;
}}
calculateQuestionBreakdown(data) {{
const config = data.config || {{}};
const limit = config.limit;
const results = data.results || {{}};
const nSamples = data['n-samples'] || {{}};
let total = 0;
let breakdownParts = [];
// Check if we have n-samples data (more accurate)
if (Object.keys(nSamples).length > 0) {{
Object.keys(nSamples).forEach(task => {{
const samples = nSamples[task];
const count = samples.effective || samples.original || 0;
if (count > 0) {{
total += count;
// Create friendly task name
const taskName = this.formatTaskName(task);
breakdownParts.push(`${{taskName}}: ${{count.toLocaleString()}}`);
}}
}});
}} else {{
// Fallback: estimate from known task sizes
if (results.hellaswag) {{
const count = (limit && limit < 1000) ? limit : 10042;
total += count;
breakdownParts.push(`HellaSwag: ${{count.toLocaleString()}}`);
}}
if (results.mmlu) {{
const count = (limit && limit < 1000) ? limit : 15908;
total += count;
breakdownParts.push(`MMLU: ${{count.toLocaleString()}}`);
}}
// Handle subsection tests
Object.keys(results).forEach(key => {{
if (key.startsWith('mmlu_') && key !== 'mmlu_humanities' && key !== 'mmlu_other' && key !== 'mmlu_stem' && key !== 'mmlu_social_sciences') {{
// This is a specific MMLU subsection - estimate 100 questions
const count = 100; // Most MMLU subsections have ~100 questions
total += count;
const taskName = this.formatTaskName(key);
breakdownParts.push(`${{taskName}}: ${{count.toLocaleString()}}`);
}}
}});
}}
return {{
total: total,
breakdown: breakdownParts.join('<br>')
}};
}}
formatTaskName(task) {{
// Convert task names to friendly format
if (task === 'hellaswag') return 'HellaSwag';
if (task === 'mmlu') return 'MMLU';
if (task.startsWith('mmlu_')) {{
const name = task.replace('mmlu_', '').split('_').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ');
return `MMLU: ${{name}}`;
}}
return task.split('_').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ');
}}
formatDuration(data) {{
// The duration is stored at the root level, not in config
const durationSeconds = parseFloat(data.total_evaluation_time_seconds || 0);
if (durationSeconds === 0) {{
return {{ value: 'N/A', unit: '' }};
}} else if (durationSeconds < 60) {{
return {{ value: durationSeconds.toFixed(0), unit: 'seconds' }};
}} else if (durationSeconds < 3600) {{
return {{ value: (durationSeconds / 60).toFixed(1), unit: 'minutes' }};
}} else {{
return {{ value: (durationSeconds / 3600).toFixed(1), unit: 'hours' }};
}}
}}
createCharts(data) {{
this.createPerformanceChart(data);
this.createMMLUBreakdownChart(data);
}}
createPerformanceChart(data) {{
const ctx = document.getElementById('performanceChart').getContext('2d');
if (this.charts.performance) {{
this.charts.performance.destroy();
}}
const results = data.results;
// Dynamically determine which tasks to show
const availableTasks = [];
const taskLabels = [];
const taskData = [];
// Prioritize main tasks
if (results.hellaswag) {{
availableTasks.push('hellaswag');
taskLabels.push('HellaSwag');
taskData.push((results.hellaswag['acc,none'] * 100).toFixed(1));
}}
if (results.mmlu) {{
availableTasks.push('mmlu');
taskLabels.push('MMLU');
taskData.push((results.mmlu['acc,none'] * 100).toFixed(1));
}}
// If no main tasks, show available subsection tasks (up to 5)
if (availableTasks.length === 0) {{
const subsectionTasks = Object.keys(results)
.filter(key => key.startsWith('mmlu_') && results[key]['acc,none'] !== undefined)
.slice(0, 5);
subsectionTasks.forEach(task => {{
availableTasks.push(task);
taskLabels.push(this.formatTaskName(task));
taskData.push((results[task]['acc,none'] * 100).toFixed(1));
}});
}}
// Generate colors based on number of tasks
const colors = this.generateColors(availableTasks.length);
this.charts.performance = new Chart(ctx, {{
type: 'bar',
data: {{
labels: taskLabels,
datasets: [{{
label: 'Accuracy (%)',
data: taskData,
backgroundColor: colors.background,
borderColor: colors.border,
borderWidth: 2
}}]
}},
options: {{
responsive: true,
maintainAspectRatio: false,
scales: {{
x: {{
ticks: {{
color: '#93a4c8',
maxRotation: 45,
minRotation: 0
}},
grid: {{
color: '#2b3d6a'
}}
}},
y: {{
beginAtZero: true,
max: 100,
ticks: {{
color: '#93a4c8',
callback: function(value) {{
return value + '%';
}}
}},
grid: {{
color: '#2b3d6a'
}}
}}
}},
plugins: {{
legend: {{
display: false
}}
}}
}}
}});
}}
createMMLUBreakdownChart(data) {{
const ctx = document.getElementById('mmluBreakdownChart').getContext('2d');
if (this.charts.mmluBreakdown) {{
this.charts.mmluBreakdown.destroy();
}}
const results = data.results;
// Find MMLU-related tasks (categories or subsections)
const mmluTasks = Object.keys(results)
.filter(key => {{
// Include category groups (mmlu_humanities, etc.) and subsections
if (key === 'mmlu') return false; // Skip the main aggregate
if (key.startsWith('mmlu_')) {{
// Check if it has an alias indicating it's a category or subsection
const alias = results[key].alias || '';
// Categories have single dash prefix, subsections have double dash
return alias.includes('-') || results[key]['acc,none'] !== undefined;
}}
return false;
}})
.map(key => ({{
name: results[key].alias ? results[key].alias.replace(/^\\s*-+\\s*/, '').replace(/_/g, ' ') : this.formatTaskName(key),
accuracy: results[key]['acc,none']
}}))
.filter(item => item.accuracy !== undefined);
// If no MMLU breakdown available, show a simple message chart
if (mmluTasks.length === 0) {{
this.charts.mmluBreakdown = new Chart(ctx, {{
type: 'doughnut',
data: {{
labels: ['No breakdown available'],
datasets: [{{
data: [1],
backgroundColor: ['#2b3d6a']
}}]
}},
options: {{
responsive: true,
maintainAspectRatio: false,
plugins: {{
legend: {{ display: false }},
tooltip: {{ enabled: false }}
}}
}}
}});
return;
}}
this.charts.mmluBreakdown = new Chart(ctx, {{
type: 'doughnut',
data: {{
labels: mmluTasks.map(s => s.name),
datasets: [{{
data: mmluTasks.map(s => (s.accuracy * 100).toFixed(1)),
backgroundColor: this.generateChartColors(mmluTasks.length)
}}]
}},
options: {{
responsive: true,
maintainAspectRatio: false,
plugins: {{
legend: {{
position: 'bottom',
labels: {{
color: '#93a4c8',
padding: 12,
usePointStyle: true,
boxWidth: 10
}}
}}
}}
}}
}});
}}
generateColors(count) {{
const palette = [
{{ bg: 'rgba(0, 229, 255, 0.85)', border: '#00e5ff' }},
{{ bg: 'rgba(255, 45, 149, 0.85)', border: '#ff2d95' }},
{{ bg: 'rgba(182, 255, 59, 0.85)', border: '#b6ff3b' }},
{{ bg: 'rgba(255, 176, 32, 0.85)', border: '#ffb020' }},
{{ bg: 'rgba(139, 108, 255, 0.85)', border: '#8b6cff' }}
];
const selected = [];
for (let i = 0; i < count; i++) {{
selected.push(palette[i % palette.length]);
}}
return {{
background: selected.map(color => color.bg),
border: selected.map(color => color.border)
}};
}}
generateChartColors(count) {{
const colors = [
'#00e5ff', '#ff2d95', '#b6ff3b', '#ffb020',
'#8b6cff', '#ff6e40', '#40c4ff', '#76ff03',
'#f50057', '#ffd740', '#7c4dff', '#18ffff'
];
return Array.from({{ length: count }}, (_, i) => colors[i % colors.length]);
}}
getAccuracyFill(accuracy) {{
if (accuracy >= 0.7) return 'linear-gradient(90deg, #00e5ff, #b6ff3b)';
if (accuracy >= 0.5) return 'linear-gradient(90deg, #8b6cff, #00e5ff)';
if (accuracy >= 0.3) return 'linear-gradient(90deg, #ffb020, #ff6e40)';
return 'linear-gradient(90deg, #ff2d95, #ff6e40)';
}}
populateTable(data) {{
// Store the data for sorting
this.tableData = [];
const nSamples = data['n-samples'] || {{}};
Object.entries(data.results).forEach(([taskKey, result]) => {{
if (result['acc,none'] === undefined) return;
// Get question count for this task
let questions = 0;
if (nSamples[taskKey]) {{
questions = nSamples[taskKey].effective || nSamples[taskKey].original || 0;
}} else {{
// Fallback estimation
if (taskKey === 'hellaswag') {{
questions = 10042;
}} else if (taskKey === 'mmlu') {{
questions = 15908;
}} else if (taskKey.startsWith('mmlu_')) {{
questions = 100; // Most MMLU subsections have ~100 questions
}}
}}
this.tableData.push({{
task: result.alias || taskKey,
taskKey: taskKey,
questions: questions,
accuracy: result['acc,none'],
error: result['acc_stderr,none'] || 0
}});
}});
this.renderTable();
}}
renderTable() {{
const tbody = document.getElementById('resultsTableBody');
tbody.innerHTML = '';
this.tableData.forEach(item => {{
const row = document.createElement('tr');
row.innerHTML = `
<td>${{item.task}}</td>
<td>${{item.questions.toLocaleString()}}</td>
<td>${{(item.accuracy * 100).toFixed(2)}}%</td>
<td>±${{(item.error * 100).toFixed(2)}}%</td>
<td>
<div class="accuracy-bar">
<div class="accuracy-fill" style="width: ${{item.accuracy * 100}}%; background: ${{this.getAccuracyFill(item.accuracy)}};"></div>
<div class="accuracy-text">${{(item.accuracy * 100).toFixed(1)}}%</div>
</div>
</td>
`;
tbody.appendChild(row);
}});
}}
handleSort(column) {{
// Determine sort direction
let direction = 'asc';
if (this.currentSort.column === column && this.currentSort.direction === 'asc') {{
direction = 'desc';
}}
// Update current sort
this.currentSort = {{ column, direction }};
// Update sort indicators
this.updateSortIndicators();
// Sort the data
this.tableData.sort((a, b) => {{
let aVal, bVal;
switch (column) {{
case 'task':
aVal = a.task.toLowerCase();
bVal = b.task.toLowerCase();
break;
case 'questions':
aVal = a.questions;
bVal = b.questions;
break;
case 'accuracy':
aVal = a.accuracy;
bVal = b.accuracy;
break;
case 'error':
aVal = a.error;
bVal = b.error;
break;
default:
return 0;
}}
if (direction === 'asc') {{
return aVal > bVal ? 1 : aVal < bVal ? -1 : 0;
}} else {{
return aVal < bVal ? 1 : aVal > bVal ? -1 : 0;
}}
}});
// Re-render the table
this.renderTable();
}}
updateSortIndicators() {{
// Reset all sort indicators
document.querySelectorAll('.sort-arrow').forEach(arrow => {{
arrow.className = 'sort-arrow';
}});
// Set active indicator
if (this.currentSort.column) {{
const activeHeader = document.querySelector(`[data-sort="${{this.currentSort.column}}"] .sort-arrow`);
if (activeHeader) {{
activeHeader.className = `sort-arrow active ${{this.currentSort.direction}}`;
}}
}}
}}
toggleComparisonMode(enabled) {{
const comparisonSection = document.getElementById('comparisonSection');
if (enabled) {{
comparisonSection.classList.add('active');
// In a real implementation, this would load comparison data
}} else {{
comparisonSection.classList.remove('active');
}}
}}
showError(message) {{
const errorDiv = document.getElementById('error');
errorDiv.textContent = message;
errorDiv.style.display = 'block';
document.getElementById('loading').style.display = 'none';
}}
initializeEventListeners() {{
document.getElementById('modelSelect').addEventListener('change', () => this.onModelChange());
document.getElementById('runSelect').addEventListener('change', () => this.onRunChange());
document.getElementById('comparisonMode').addEventListener('change', (e) => this.toggleComparisonMode(e.target.checked));
// Add sorting event listeners
document.querySelectorAll('.sortable').forEach(th => {{
th.addEventListener('click', () => this.handleSort(th.dataset.sort));
}});
}}
}}
// Initialize static dashboard when page loads
document.addEventListener('DOMContentLoaded', () => {{
new StaticEvaluationDashboard();
}});
</script>
"""
# Replace the original script section with our static version
# Find the start of the original script section
script_start_pattern = '<script>'
script_end_pattern = '</script>'
script_start_index = html_content.find(script_start_pattern)
script_end_index = html_content.rfind(script_end_pattern)
if script_start_index == -1 or script_end_index == -1:
print("❌ Could not find script section in HTML")
return False
# Replace the entire script section with our static version
new_html = html_content[:script_start_index].rstrip() + '\n\n' + data_script.lstrip('\n') + html_content[script_end_index + len(script_end_pattern):]
return new_html
def build_web_dashboard():
"""Main build function"""
print("🚀 Building static web dashboard...")
# Create dist directory
dist_dir = Path("dist")
if dist_dir.exists():
shutil.rmtree(dist_dir)
dist_dir.mkdir(exist_ok=True)
# Load all results data
print("📊 Loading results data...")
all_data = load_all_results()
if not all_data:
print("⚠️ No results data found. Creating empty dashboard.")
all_data = {}
# Create static HTML
print("📝 Generating static HTML...")
static_html = create_static_html(all_data)
if not static_html:
print("❌ Failed to generate static HTML")
return False
# Write the static HTML file
output_file = dist_dir / "index.html"
with open(output_file, 'w') as f:
f.write(static_html)
# Publish the proposal alongside the archive. This build only renders
# static files: it must never invoke models or provision AWS resources.
from part2.blueprint.build import build_blueprint
build_blueprint(dist_dir / 'part-ii')
print(f"✅ Static dashboard created: {output_file}")
print(f"📈 Embedded data for {len(all_data)} models")
# Count total runs
total_runs = sum(len(model_runs) for model_runs in all_data.values())
print(f"📊 Total runs embedded: {total_runs}")
return True
if __name__ == "__main__":
success = build_web_dashboard()
if success:
print("\n🎉 Build complete! You can now:")
print(" • Open dist/index.html in your browser")
print(" • Deploy dist/ to Netlify")
print(" • Commit and push for auto-deployment")
else:
print("\n❌ Build failed!")
exit(1)