AmrGaberr commited on
Commit
f3bcc00
·
verified ·
1 Parent(s): 3b55629

Update UI2/calculator.js

Browse files
Files changed (1) hide show
  1. UI2/calculator.js +480 -480
UI2/calculator.js CHANGED
@@ -1,481 +1,481 @@
1
- document.addEventListener('DOMContentLoaded', () => {
2
- const form = document.getElementById("predictionForm");
3
- const resultContainer = document.getElementById("result-container");
4
-
5
- if (resultContainer) {
6
- resultContainer.style.display = 'none';
7
- }
8
-
9
- // Validation helper
10
- const validateField = (input) => {
11
- const value = input.value.trim();
12
- const min = parseFloat(input.min);
13
- const max = parseFloat(input.max);
14
- if (!value) return false;
15
- if (input.type === 'number') {
16
- const numValue = parseFloat(value);
17
- return !isNaN(numValue) && numValue >= min && numValue <= max;
18
- }
19
- return true;
20
- };
21
-
22
- // Add validation feedback
23
- const addValidationFeedback = (input) => {
24
- const validateInput = () => {
25
- const formGroup = input.closest('.form-group');
26
- const value = input.value.trim();
27
- const isValid = value !== '' && validateField(input);
28
-
29
- formGroup.classList.remove('error', 'success');
30
- formGroup.classList.add(isValid ? 'success' : 'error');
31
-
32
- const existingMessage = formGroup.querySelector('.validation-message');
33
- if (existingMessage) existingMessage.remove();
34
-
35
- const message = document.createElement('div');
36
- message.className = `validation-message ${isValid ? 'success' : 'error'}`;
37
- message.textContent = value === '' ? 'This field is required' :
38
- (isValid ? 'Valid input' : 'Please check the value');
39
- formGroup.appendChild(message);
40
-
41
- return isValid;
42
- };
43
-
44
- input.addEventListener('input', validateInput);
45
- input.addEventListener('blur', validateInput);
46
- };
47
-
48
- document.querySelectorAll('input, select').forEach(addValidationFeedback);
49
-
50
- // Animate counter
51
- function animateCounter(element, target) {
52
- let start = 0;
53
- const duration = 1000;
54
- const stepTime = Math.abs(Math.floor(duration / target));
55
- const timer = setInterval(() => {
56
- start++;
57
- element.textContent = start + '%';
58
- if (start >= target) clearInterval(timer);
59
- }, stepTime);
60
- }
61
-
62
- // Update gauge SVG
63
- function updateGauge(elementId, percent, textId, tooltipId, tooltipMessages) {
64
- const gauge = document.querySelector(elementId);
65
- const text = document.querySelector(textId);
66
- const tooltip = document.querySelector(tooltipId);
67
- const radius = elementId.includes('radial') ? 40 : 54;
68
- const circumference = 2 * Math.PI * radius;
69
- const offset = circumference - (percent / 100) * circumference;
70
- gauge.style.strokeDasharray = `${circumference} ${circumference}`;
71
- gauge.style.strokeDashoffset = offset;
72
- if (text) text.textContent = `${Math.round(percent)}%`;
73
-
74
- if (tooltip && tooltipMessages) {
75
- if (percent >= 75) {
76
- tooltip.textContent = tooltipMessages.high;
77
- } else if (percent >= 50) {
78
- tooltip.textContent = tooltipMessages.medium;
79
- } else {
80
- tooltip.textContent = tooltipMessages.low;
81
- }
82
- }
83
- }
84
-
85
- // Mapping of recommendation keywords to professional resources
86
- const resourceLinks = {
87
- 'training': {
88
- url: 'https://www.acsm.org/docs/default-source/files-for-resource-library/acsms-guidelines-for-exercise-testing-and-prescription-(10th-ed.).pdf',
89
- source: 'American College of Sports Medicine'
90
- },
91
- 'intensity': {
92
- url: 'https://www.mayoclinic.org/healthy-lifestyle/fitness/in-depth/exercise-intensity/art-20046887',
93
- source: 'Mayo Clinic'
94
- },
95
- 'recovery': {
96
- url: 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5592286/',
97
- source: 'PubMed - Sports Medicine Journal'
98
- },
99
- 'rest': {
100
- url: 'https://www.sleepfoundation.org/physical-activity/athletic-performance-and-sleep',
101
- source: 'Sleep Foundation'
102
- },
103
- 'injury': {
104
- url: 'https://orthoinfo.aaos.org/en/diseases--conditions/sports-injuries/',
105
- source: 'American Academy of Orthopaedic Surgeons'
106
- },
107
- 'prevention': {
108
- url: 'https://www.nata.org/professional-interests/safe-sports-environments/injury-prevention',
109
- source: 'National Athletic Trainers\' Association'
110
- }
111
- };
112
-
113
- // Enhanced recommendation processing
114
- function enhanceRecommendations(recommendations, factorData, featureImportance) {
115
- const categories = {
116
- 'Training Adjustments': [],
117
- 'Recovery Strategies': [],
118
- 'Injury Prevention': []
119
- };
120
-
121
- recommendations.forEach((rec, index) => {
122
- let category = 'Injury Prevention';
123
- if (rec.toLowerCase().includes('training') || rec.toLowerCase().includes('intensity')) {
124
- category = 'Training Adjustments';
125
- } else if (rec.toLowerCase().includes('recovery') || rec.toLowerCase().includes('rest')) {
126
- category = 'Recovery Strategies';
127
- }
128
-
129
- const priority = calculatePriority(rec, factorData, featureImportance);
130
-
131
- // Find the most relevant resource link
132
- let resource = { url: 'https://www.healthline.com/health/sports-injuries', source: 'Healthline' };
133
- for (const [keyword, link] of Object.entries(resourceLinks)) {
134
- if (rec.toLowerCase().includes(keyword)) {
135
- resource = link;
136
- break;
137
- }
138
- }
139
-
140
- categories[category].push({
141
- id: `rec-${index}`,
142
- text: rec,
143
- priority: priority,
144
- details: generateDetails(rec, factorData),
145
- completed: false,
146
- resourceUrl: resource.url,
147
- resourceSource: resource.source
148
- });
149
- });
150
-
151
- Object.keys(categories).forEach(category => {
152
- categories[category].sort((a, b) => b.priority - a.priority);
153
- });
154
-
155
- return categories;
156
- }
157
-
158
- function calculatePriority(recommendation, factorData, featureImportance) {
159
- let priority = 0.5;
160
- const keywords = {
161
- 'Training_Load_Score': ['training', 'intensity'],
162
- 'Fatigue_Level': ['fatigue', 'rest'],
163
- 'Recovery_Time_Between_Sessions': ['recovery', 'rest'],
164
- 'Previous_Injury_Count': ['injury', 'prevention']
165
- };
166
-
167
- Object.keys(keywords).forEach(key => {
168
- if (keywords[key].some(kw => recommendation.toLowerCase().includes(kw))) {
169
- const impact = (factorData[key] || 0) * (featureImportance[key] || 0);
170
- priority = Math.max(priority, impact);
171
- }
172
- });
173
-
174
- return Math.min(1, Math.max(0, priority));
175
- }
176
-
177
- function generateDetails(recommendation, factorData) {
178
- if (recommendation.toLowerCase().includes('training') && factorData.High_Intensity_Training_Hours > 10) {
179
- return `Reduce high-intensity sessions by 1-2 hours/week to lower training load.`;
180
- } else if (recommendation.toLowerCase().includes('recovery') && factorData.Recovery_Time_Between_Sessions < 12) {
181
- return `Increase rest periods to at least 12 hours between sessions.`;
182
- } else if (recommendation.toLowerCase().includes('injury') && factorData.Previous_Injury_Count > 2) {
183
- return `Consult a physiotherapist to address recurring injury risks.`;
184
- }
185
- return `Follow this recommendation consistently for optimal results.`;
186
- }
187
-
188
- function loadCompletedRecommendations() {
189
- const stored = localStorage.getItem('completedRecommendations');
190
- return stored ? JSON.parse(stored) : {};
191
- }
192
-
193
- function saveCompletedRecommendations(completed) {
194
- localStorage.setItem('completedRecommendations', JSON.stringify(completed));
195
- }
196
-
197
- if (form) {
198
- form.addEventListener("submit", async (e) => {
199
- e.preventDefault();
200
-
201
- document.querySelectorAll('.validation-message').forEach(msg => msg.remove());
202
- document.querySelectorAll('.form-group').forEach(group => group.classList.remove('error'));
203
-
204
- const inputs = form.querySelectorAll('input, select');
205
- let isValid = true;
206
-
207
- inputs.forEach(input => {
208
- const value = input.value.trim();
209
- const formGroup = input.closest('.form-group');
210
-
211
- if (value === '') {
212
- isValid = false;
213
- formGroup.classList.add('error');
214
- const message = document.createElement('div');
215
- message.className = 'validation-message error';
216
- message.innerHTML = `<strong>Required:</strong> Please fill out this field`;
217
- formGroup.appendChild(message);
218
-
219
- input.classList.add('shake');
220
- setTimeout(() => input.classList.remove('shake'), 500);
221
-
222
- input.style.borderColor = '#ef4444';
223
- input.style.boxShadow = '0 0 10px rgba(239, 68, 68, 0.3)';
224
- }
225
- });
226
-
227
- if (!isValid) {
228
- const firstError = form.querySelector('.form-group.error');
229
- if (firstError) {
230
- firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
231
- }
232
- return;
233
- }
234
-
235
- const rawData = Object.fromEntries(new FormData(form).entries());
236
- const formData = new FormData(form);
237
- const data = Object.fromEntries(formData.entries());
238
-
239
- const genderMap = { "Male": 0, "Female": 1 };
240
- const experienceMap = {
241
- "Beginner": 0,
242
- "Intermediate": 1,
243
- "Advanced": 2,
244
- "Professional": 3
245
- };
246
- const injuryTypeMap = {
247
- "None": 0,
248
- "Sprain": 1,
249
- "Ligament Tear": 2,
250
- "Tendonitis": 3,
251
- "Strain": 4,
252
- "Fracture": 5
253
- };
254
- const sportTypeMap = {
255
- "Football": 0,
256
- "Basketball": 1,
257
- "Swimming": 2,
258
- "Running": 3,
259
- "Tennis": 4,
260
- "Volleyball": 5
261
- };
262
-
263
- data.Gender = genderMap[data.Gender] ?? 0;
264
- data.Experience_Level = experienceMap[data.Experience_Level] ?? 0;
265
- data.Previous_Injury_Type = injuryTypeMap[data.Previous_Injury_Type] ?? 0;
266
- data.Sport_Type = sportTypeMap[data.Sport_Type] ?? 0;
267
-
268
- Object.keys(data).forEach(key => {
269
- data[key] = isNaN(data[key]) ? 0 : parseFloat(data[key]);
270
- });
271
-
272
- const outlierWarnings = [];
273
- if (data.Age < 18 && data.Total_Weekly_Training_Hours > 40) {
274
- outlierWarnings.push('Unusual training hours for age under 18. Consider reducing to prevent burnout.');
275
- }
276
- if (data.Sprint_Speed > 10 && data.Age > 50) {
277
- outlierWarnings.push('Sprint speed seems high for age over 50. Please verify this value.');
278
- }
279
- if (data.Fatigue_Level > 8 && data.Recovery_Time_Between_Sessions < 12) {
280
- outlierWarnings.push('High fatigue with low recovery time may skew results. Consider adjusting inputs.');
281
- }
282
- if (outlierWarnings.length > 0) {
283
- const warningDiv = document.createElement('div');
284
- warningDiv.style.color = '#facc15';
285
- warningDiv.style.marginBottom = '20px';
286
- warningDiv.innerHTML = `<strong>Warning:</strong><ul>${outlierWarnings.map(w => `<li>${w}</li>`).join('')}</ul>`;
287
- form.appendChild(warningDiv);
288
- }
289
-
290
- try {
291
- console.log('Sending prediction request to server:', data);
292
- const response = await fetch("http://127.0.0.1:8000/predict", {
293
- method: "POST",
294
- headers: { "Content-Type": "application/json" },
295
- body: JSON.stringify(data),
296
- });
297
- if (!response.ok) throw new Error("Prediction failed");
298
-
299
- const result = await response.json();
300
- console.log('Received prediction result:', result);
301
-
302
- const {
303
- predicted_risk_level,
304
- injury_likelihood_percent,
305
- model_class_probability,
306
- recommendations,
307
- feature_importance
308
- } = result;
309
-
310
- if (!predicted_risk_level || typeof injury_likelihood_percent !== 'number' || !Array.isArray(recommendations)) {
311
- throw new Error("Invalid API response format");
312
- }
313
-
314
- const trainingLoad = Math.min(100, Math.max(0, (parseFloat(data.Training_Load_Score) / 100) * 100));
315
- const recoveryStatus = Math.min(100, Math.max(0, (parseFloat(data.Recovery_Time_Between_Sessions) / 48) * 100));
316
- const injuryImpact = Math.min(100, Math.max(0, (parseFloat(data.Previous_Injury_Count) / 10) * 100));
317
- const recoveryPerTraining = data.Total_Weekly_Training_Hours > 0
318
- ? Math.min(100, Math.max(0, (parseFloat(data.Recovery_Time_Between_Sessions) / parseFloat(data.Total_Weekly_Training_Hours)) * 100))
319
- : 0;
320
- const totalWeeklyHours = Math.min(100, Math.max(0, (parseFloat(data.Total_Weekly_Training_Hours) / 50) * 100));
321
- const fatigueLevel = Math.min(100, Math.max(0, (parseFloat(data.Fatigue_Level) / 10) * 100));
322
- const highIntensityHours = Math.min(100, Math.max(0, (parseFloat(data.High_Intensity_Training_Hours) / 20) * 100));
323
- const experienceLevel = Math.min(100, Math.max(0, (data.Experience_Level / 3) * 100));
324
-
325
- const defaultFeatureImportance = {
326
- Training_Load_Score: 0.22,
327
- Recovery_Per_Training: 0.18,
328
- Total_Weekly_Training_Hours: 0.16,
329
- Fatigue_Level: 0.14,
330
- Recovery_Time_Between_Sessions: 0.12,
331
- High_Intensity_Training_Hours: 0.10
332
- };
333
- const finalFeatureImportance = feature_importance || defaultFeatureImportance;
334
-
335
- const enhancedRecommendations = enhanceRecommendations(recommendations, {
336
- Training_Load_Score: trainingLoad,
337
- Recovery_Per_Training: recoveryPerTraining,
338
- Total_Weekly_Training_Hours: totalWeeklyHours,
339
- Fatigue_Level: fatigueLevel,
340
- Recovery_Time_Between_Sessions: recoveryStatus,
341
- High_Intensity_Training_Hours: highIntensityHours,
342
- Previous_Injury_Count: injuryImpact
343
- }, finalFeatureImportance);
344
-
345
- const fullReportData = {
346
- predicted_risk_level,
347
- injury_likelihood_percent,
348
- model_class_probability,
349
- recommendations: enhancedRecommendations,
350
- feature_importance: finalFeatureImportance,
351
- factorData: {
352
- Training_Load_Score: trainingLoad,
353
- Recovery_Per_Training: recoveryPerTraining,
354
- Total_Weekly_Training_Hours: totalWeeklyHours,
355
- Fatigue_Level: fatigueLevel,
356
- Recovery_Time_Between_Sessions: recoveryStatus,
357
- High_Intensity_Training_Hours: highIntensityHours,
358
- Experience_Level: experienceLevel,
359
- Intensity_Ratio: data.High_Intensity_Training_Hours > 0
360
- ? Math.min(100, Math.max(0, (parseFloat(data.High_Intensity_Training_Hours) / parseFloat(data.Total_Weekly_Training_Hours)) * 100))
361
- : 0,
362
- Endurance_Score: Math.min(100, Math.max(0, (parseFloat(data.Endurance_Score) / 10) * 100)),
363
- Sprint_Speed: Math.min(100, Math.max(0, (parseFloat(data.Sprint_Speed) / 20) * 100)),
364
- Agility_Score: Math.min(100, Math.max(0, (parseFloat(data.Agility_Score) / 10) * 100)),
365
- Flexibility_Score: Math.min(100, Math.max(0, (parseFloat(data.Flexibility_Score) / 10) * 100)),
366
- Age: Math.min(100, Math.max(0, (parseFloat(data.Age) / 80) * 100)),
367
- Strength_Training_Frequency: Math.min(100, Math.max(0, (parseFloat(data.Strength_Training_Frequency) / 7) * 100)),
368
- Sport_Type: Math.min(100, Math.max(0, data.Sport_Type * 20)),
369
- Gender: data.Gender * 100,
370
- Previous_Injury_Count: injuryImpact,
371
- Previous_Injury_Type: Math.min(100, Math.max(0, data.Previous_Injury_Type * 20))
372
- },
373
- profile: {
374
- age: rawData.Age,
375
- gender: rawData.Gender,
376
- sport: rawData.Sport_Type
377
- },
378
- timestamp: new Date().toISOString(),
379
- version: '1.1.0'
380
- };
381
-
382
- console.log('Storing prediction data in localStorage:', fullReportData);
383
- localStorage.setItem('predictionData', JSON.stringify(fullReportData));
384
-
385
- document.getElementById('risk-level').textContent = predicted_risk_level;
386
- document.getElementById('likelihood-percent').textContent = `${Math.round(injury_likelihood_percent)}%`;
387
- updateGauge('.summary-gauge .gauge-value', injury_likelihood_percent, '.summary-gauge .gauge-text', null, null);
388
-
389
- updateGauge('#training-load-gauge', trainingLoad, '#training-load-text', '#training-load-tooltip', {
390
- high: 'High training load may significantly increase injury risk.',
391
- medium: 'Moderate training load; monitor closely.',
392
- low: 'Low training load; risk appears minimal.'
393
- });
394
- updateGauge('#recovery-gauge', recoveryStatus, '#recovery-text', '#recovery-tooltip', {
395
- high: 'Excellent recovery time; low risk from this factor.',
396
- medium: 'Moderate recovery; consider increasing rest.',
397
- low: 'Insufficient recovery may elevate injury risk.'
398
- });
399
- updateGauge('#injury-history-gauge', injuryImpact, '#injury-history-text', '#injury-history-tooltip', {
400
- high: 'Significant injury history; high risk of recurrence.',
401
- medium: 'Moderate injury history; take preventive measures.',
402
- low: 'Minimal injury history; low risk from this factor.'
403
- });
404
-
405
- const recommendationListEl = document.querySelector('.recommendation-list');
406
- const completedRecs = loadCompletedRecommendations();
407
- recommendationListEl.innerHTML = Object.keys(enhancedRecommendations).map(category => `
408
- <div class="recommendation-category">
409
- <h5 class="category-title">${category}</h5>
410
- ${enhancedRecommendations[category].map(rec => `
411
- <li class="recommendation-item expandable ${completedRecs[rec.id] ? 'completed' : ''}">
412
- <input type="checkbox" class="rec-checkbox" data-id="${rec.id}" ${completedRecs[rec.id] ? 'checked' : ''}>
413
- <span class="priority-indicator" style="color: ${rec.priority > 0.7 ? '#ef4444' : rec.priority > 0.4 ? '#facc15' : '#22c55e'}">
414
- ${rec.priority > 0.7 ? '🛑' : rec.priority > 0.4 ? '⚠️' : '✅'}
415
- </span>
416
- <span class="recommendation-summary">${rec.text}</span>
417
- <span class="tooltip-icon">ℹ️
418
- <span class="tooltip-text">${rec.details}</span>
419
- </span>
420
- <div class="recommendation-detail">${rec.details}</div>
421
- <button class="learn-more-btn" data-url="${rec.resourceUrl}" title="Source: ${rec.resourceSource}">Learn More</button>
422
- </li>
423
- `).join('')}
424
- </div>
425
- `).join('');
426
-
427
- document.querySelectorAll('.rec-checkbox').forEach(checkbox => {
428
- checkbox.addEventListener('change', () => {
429
- const recId = checkbox.dataset.id;
430
- const completedRecs = loadCompletedRecommendations();
431
- completedRecs[recId] = checkbox.checked;
432
- saveCompletedRecommendations(completedRecs);
433
- checkbox.closest('.recommendation-item').classList.toggle('completed', checkbox.checked);
434
- });
435
- });
436
-
437
- document.querySelectorAll('.recommendation-item.expandable').forEach(item => {
438
- item.addEventListener('click', (e) => {
439
- if (e.target.classList.contains('rec-checkbox') || e.target.classList.contains('learn-more-btn')) return;
440
- const detail = item.querySelector('.recommendation-detail');
441
- if (detail.style.display === "none" || detail.style.display === "") {
442
- detail.style.display = "block";
443
- detail.style.maxHeight = detail.scrollHeight + "px";
444
- } else {
445
- detail.style.display = "none";
446
- detail.style.maxHeight = "0";
447
- }
448
- });
449
- });
450
-
451
- document.querySelectorAll('.learn-more-btn').forEach(btn => {
452
- btn.addEventListener('click', () => {
453
- const url = btn.dataset.url;
454
- window.open(url, '_blank');
455
- });
456
- });
457
-
458
- resultContainer.style.display = 'block';
459
- resultContainer.classList.remove("hidden");
460
- setTimeout(() => {
461
- resultContainer.classList.add("visible");
462
- }, 100);
463
- resultContainer.scrollIntoView({ behavior: "smooth" });
464
-
465
- const reportActions = document.createElement('div');
466
- reportActions.className = 'report-actions';
467
- reportActions.innerHTML = `
468
- <button onclick="window.location.href='report.html'" class="action-button">
469
- View Detailed Analysis
470
- </button>
471
- `;
472
- resultContainer.appendChild(reportActions);
473
- } catch (err) {
474
- console.error('Prediction error:', err.message);
475
- const resultOutput = document.createElement('div');
476
- resultOutput.innerHTML = `<p style="color: red;">Error: ${err.message}. Please ensure the prediction server is running and try again.</p>`;
477
- form.appendChild(resultOutput);
478
- }
479
- });
480
- }
481
  });
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const form = document.getElementById("predictionForm");
3
+ const resultContainer = document.getElementById("result-container");
4
+
5
+ if (resultContainer) {
6
+ resultContainer.style.display = 'none';
7
+ }
8
+
9
+ // Validation helper
10
+ const validateField = (input) => {
11
+ const value = input.value.trim();
12
+ const min = parseFloat(input.min);
13
+ const max = parseFloat(input.max);
14
+ if (!value) return false;
15
+ if (input.type === 'number') {
16
+ const numValue = parseFloat(value);
17
+ return !isNaN(numValue) && numValue >= min && numValue <= max;
18
+ }
19
+ return true;
20
+ };
21
+
22
+ // Add validation feedback
23
+ const addValidationFeedback = (input) => {
24
+ const validateInput = () => {
25
+ const formGroup = input.closest('.form-group');
26
+ const value = input.value.trim();
27
+ const isValid = value !== '' && validateField(input);
28
+
29
+ formGroup.classList.remove('error', 'success');
30
+ formGroup.classList.add(isValid ? 'success' : 'error');
31
+
32
+ const existingMessage = formGroup.querySelector('.validation-message');
33
+ if (existingMessage) existingMessage.remove();
34
+
35
+ const message = document.createElement('div');
36
+ message.className = `validation-message ${isValid ? 'success' : 'error'}`;
37
+ message.textContent = value === '' ? 'This field is required' :
38
+ (isValid ? 'Valid input' : 'Please check the value');
39
+ formGroup.appendChild(message);
40
+
41
+ return isValid;
42
+ };
43
+
44
+ input.addEventListener('input', validateInput);
45
+ input.addEventListener('blur', validateInput);
46
+ };
47
+
48
+ document.querySelectorAll('input, select').forEach(addValidationFeedback);
49
+
50
+ // Animate counter
51
+ function animateCounter(element, target) {
52
+ let start = 0;
53
+ const duration = 1000;
54
+ const stepTime = Math.abs(Math.floor(duration / target));
55
+ const timer = setInterval(() => {
56
+ start++;
57
+ element.textContent = start + '%';
58
+ if (start >= target) clearInterval(timer);
59
+ }, stepTime);
60
+ }
61
+
62
+ // Update gauge SVG
63
+ function updateGauge(elementId, percent, textId, tooltipId, tooltipMessages) {
64
+ const gauge = document.querySelector(elementId);
65
+ const text = document.querySelector(textId);
66
+ const tooltip = document.querySelector(tooltipId);
67
+ const radius = elementId.includes('radial') ? 40 : 54;
68
+ const circumference = 2 * Math.PI * radius;
69
+ const offset = circumference - (percent / 100) * circumference;
70
+ gauge.style.strokeDasharray = `${circumference} ${circumference}`;
71
+ gauge.style.strokeDashoffset = offset;
72
+ if (text) text.textContent = `${Math.round(percent)}%`;
73
+
74
+ if (tooltip && tooltipMessages) {
75
+ if (percent >= 75) {
76
+ tooltip.textContent = tooltipMessages.high;
77
+ } else if (percent >= 50) {
78
+ tooltip.textContent = tooltipMessages.medium;
79
+ } else {
80
+ tooltip.textContent = tooltipMessages.low;
81
+ }
82
+ }
83
+ }
84
+
85
+ // Mapping of recommendation keywords to professional resources
86
+ const resourceLinks = {
87
+ 'training': {
88
+ url: 'https://www.acsm.org/docs/default-source/files-for-resource-library/acsms-guidelines-for-exercise-testing-and-prescription-(10th-ed.).pdf',
89
+ source: 'American College of Sports Medicine'
90
+ },
91
+ 'intensity': {
92
+ url: 'https://www.mayoclinic.org/healthy-lifestyle/fitness/in-depth/exercise-intensity/art-20046887',
93
+ source: 'Mayo Clinic'
94
+ },
95
+ 'recovery': {
96
+ url: 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5592286/',
97
+ source: 'PubMed - Sports Medicine Journal'
98
+ },
99
+ 'rest': {
100
+ url: 'https://www.sleepfoundation.org/physical-activity/athletic-performance-and-sleep',
101
+ source: 'Sleep Foundation'
102
+ },
103
+ 'injury': {
104
+ url: 'https://orthoinfo.aaos.org/en/diseases--conditions/sports-injuries/',
105
+ source: 'American Academy of Orthopaedic Surgeons'
106
+ },
107
+ 'prevention': {
108
+ url: 'https://www.nata.org/professional-interests/safe-sports-environments/injury-prevention',
109
+ source: 'National Athletic Trainers\' Association'
110
+ }
111
+ };
112
+
113
+ // Enhanced recommendation processing
114
+ function enhanceRecommendations(recommendations, factorData, featureImportance) {
115
+ const categories = {
116
+ 'Training Adjustments': [],
117
+ 'Recovery Strategies': [],
118
+ 'Injury Prevention': []
119
+ };
120
+
121
+ recommendations.forEach((rec, index) => {
122
+ let category = 'Injury Prevention';
123
+ if (rec.toLowerCase().includes('training') || rec.toLowerCase().includes('intensity')) {
124
+ category = 'Training Adjustments';
125
+ } else if (rec.toLowerCase().includes('recovery') || rec.toLowerCase().includes('rest')) {
126
+ category = 'Recovery Strategies';
127
+ }
128
+
129
+ const priority = calculatePriority(rec, factorData, featureImportance);
130
+
131
+ // Find the most relevant resource link
132
+ let resource = { url: 'https://www.healthline.com/health/sports-injuries', source: 'Healthline' };
133
+ for (const [keyword, link] of Object.entries(resourceLinks)) {
134
+ if (rec.toLowerCase().includes(keyword)) {
135
+ resource = link;
136
+ break;
137
+ }
138
+ }
139
+
140
+ categories[category].push({
141
+ id: `rec-${index}`,
142
+ text: rec,
143
+ priority: priority,
144
+ details: generateDetails(rec, factorData),
145
+ completed: false,
146
+ resourceUrl: resource.url,
147
+ resourceSource: resource.source
148
+ });
149
+ });
150
+
151
+ Object.keys(categories).forEach(category => {
152
+ categories[category].sort((a, b) => b.priority - a.priority);
153
+ });
154
+
155
+ return categories;
156
+ }
157
+
158
+ function calculatePriority(recommendation, factorData, featureImportance) {
159
+ let priority = 0.5;
160
+ const keywords = {
161
+ 'Training_Load_Score': ['training', 'intensity'],
162
+ 'Fatigue_Level': ['fatigue', 'rest'],
163
+ 'Recovery_Time_Between_Sessions': ['recovery', 'rest'],
164
+ 'Previous_Injury_Count': ['injury', 'prevention']
165
+ };
166
+
167
+ Object.keys(keywords).forEach(key => {
168
+ if (keywords[key].some(kw => recommendation.toLowerCase().includes(kw))) {
169
+ const impact = (factorData[key] || 0) * (featureImportance[key] || 0);
170
+ priority = Math.max(priority, impact);
171
+ }
172
+ });
173
+
174
+ return Math.min(1, Math.max(0, priority));
175
+ }
176
+
177
+ function generateDetails(recommendation, factorData) {
178
+ if (recommendation.toLowerCase().includes('training') && factorData.High_Intensity_Training_Hours > 10) {
179
+ return `Reduce high-intensity sessions by 1-2 hours/week to lower training load.`;
180
+ } else if (recommendation.toLowerCase().includes('recovery') && factorData.Recovery_Time_Between_Sessions < 12) {
181
+ return `Increase rest periods to at least 12 hours between sessions.`;
182
+ } else if (recommendation.toLowerCase().includes('injury') && factorData.Previous_Injury_Count > 2) {
183
+ return `Consult a physiotherapist to address recurring injury risks.`;
184
+ }
185
+ return `Follow this recommendation consistently for optimal results.`;
186
+ }
187
+
188
+ function loadCompletedRecommendations() {
189
+ const stored = localStorage.getItem('completedRecommendations');
190
+ return stored ? JSON.parse(stored) : {};
191
+ }
192
+
193
+ function saveCompletedRecommendations(completed) {
194
+ localStorage.setItem('completedRecommendations', JSON.stringify(completed));
195
+ }
196
+
197
+ if (form) {
198
+ form.addEventListener("submit", async (e) => {
199
+ e.preventDefault();
200
+
201
+ document.querySelectorAll('.validation-message').forEach(msg => msg.remove());
202
+ document.querySelectorAll('.form-group').forEach(group => group.classList.remove('error'));
203
+
204
+ const inputs = form.querySelectorAll('input, select');
205
+ let isValid = true;
206
+
207
+ inputs.forEach(input => {
208
+ const value = input.value.trim();
209
+ const formGroup = input.closest('.form-group');
210
+
211
+ if (value === '') {
212
+ isValid = false;
213
+ formGroup.classList.add('error');
214
+ const message = document.createElement('div');
215
+ message.className = 'validation-message error';
216
+ message.innerHTML = `<strong>Required:</strong> Please fill out this field`;
217
+ formGroup.appendChild(message);
218
+
219
+ input.classList.add('shake');
220
+ setTimeout(() => input.classList.remove('shake'), 500);
221
+
222
+ input.style.borderColor = '#ef4444';
223
+ input.style.boxShadow = '0 0 10px rgba(239, 68, 68, 0.3)';
224
+ }
225
+ });
226
+
227
+ if (!isValid) {
228
+ const firstError = form.querySelector('.form-group.error');
229
+ if (firstError) {
230
+ firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
231
+ }
232
+ return;
233
+ }
234
+
235
+ const rawData = Object.fromEntries(new FormData(form).entries());
236
+ const formData = new FormData(form);
237
+ const data = Object.fromEntries(formData.entries());
238
+
239
+ const genderMap = { "Male": 0, "Female": 1 };
240
+ const experienceMap = {
241
+ "Beginner": 0,
242
+ "Intermediate": 1,
243
+ "Advanced": 2,
244
+ "Professional": 3
245
+ };
246
+ const injuryTypeMap = {
247
+ "None": 0,
248
+ "Sprain": 1,
249
+ "Ligament Tear": 2,
250
+ "Tendonitis": 3,
251
+ "Strain": 4,
252
+ "Fracture": 5
253
+ };
254
+ const sportTypeMap = {
255
+ "Football": 0,
256
+ "Basketball": 1,
257
+ "Swimming": 2,
258
+ "Running": 3,
259
+ "Tennis": 4,
260
+ "Volleyball": 5
261
+ };
262
+
263
+ data.Gender = genderMap[data.Gender] ?? 0;
264
+ data.Experience_Level = experienceMap[data.Experience_Level] ?? 0;
265
+ data.Previous_Injury_Type = injuryTypeMap[data.Previous_Injury_Type] ?? 0;
266
+ data.Sport_Type = sportTypeMap[data.Sport_Type] ?? 0;
267
+
268
+ Object.keys(data).forEach(key => {
269
+ data[key] = isNaN(data[key]) ? 0 : parseFloat(data[key]);
270
+ });
271
+
272
+ const outlierWarnings = [];
273
+ if (data.Age < 18 && data.Total_Weekly_Training_Hours > 40) {
274
+ outlierWarnings.push('Unusual training hours for age under 18. Consider reducing to prevent burnout.');
275
+ }
276
+ if (data.Sprint_Speed > 10 && data.Age > 50) {
277
+ outlierWarnings.push('Sprint speed seems high for age over 50. Please verify this value.');
278
+ }
279
+ if (data.Fatigue_Level > 8 && data.Recovery_Time_Between_Sessions < 12) {
280
+ outlierWarnings.push('High fatigue with low recovery time may skew results. Consider adjusting inputs.');
281
+ }
282
+ if (outlierWarnings.length > 0) {
283
+ const warningDiv = document.createElement('div');
284
+ warningDiv.style.color = '#facc15';
285
+ warningDiv.style.marginBottom = '20px';
286
+ warningDiv.innerHTML = `<strong>Warning:</strong><ul>${outlierWarnings.map(w => `<li>${w}</li>`).join('')}</ul>`;
287
+ form.appendChild(warningDiv);
288
+ }
289
+
290
+ try {
291
+ console.log('Sending prediction request to server:', data);
292
+ const response = await fetch("http://0.0.0.0:7860/predict", {
293
+ method: "POST",
294
+ headers: { "Content-Type": "application/json" },
295
+ body: JSON.stringify(data),
296
+ });
297
+ if (!response.ok) throw new Error("Prediction failed");
298
+
299
+ const result = await response.json();
300
+ console.log('Received prediction result:', result);
301
+
302
+ const {
303
+ predicted_risk_level,
304
+ injury_likelihood_percent,
305
+ model_class_probability,
306
+ recommendations,
307
+ feature_importance
308
+ } = result;
309
+
310
+ if (!predicted_risk_level || typeof injury_likelihood_percent !== 'number' || !Array.isArray(recommendations)) {
311
+ throw new Error("Invalid API response format");
312
+ }
313
+
314
+ const trainingLoad = Math.min(100, Math.max(0, (parseFloat(data.Training_Load_Score) / 100) * 100));
315
+ const recoveryStatus = Math.min(100, Math.max(0, (parseFloat(data.Recovery_Time_Between_Sessions) / 48) * 100));
316
+ const injuryImpact = Math.min(100, Math.max(0, (parseFloat(data.Previous_Injury_Count) / 10) * 100));
317
+ const recoveryPerTraining = data.Total_Weekly_Training_Hours > 0
318
+ ? Math.min(100, Math.max(0, (parseFloat(data.Recovery_Time_Between_Sessions) / parseFloat(data.Total_Weekly_Training_Hours)) * 100))
319
+ : 0;
320
+ const totalWeeklyHours = Math.min(100, Math.max(0, (parseFloat(data.Total_Weekly_Training_Hours) / 50) * 100));
321
+ const fatigueLevel = Math.min(100, Math.max(0, (parseFloat(data.Fatigue_Level) / 10) * 100));
322
+ const highIntensityHours = Math.min(100, Math.max(0, (parseFloat(data.High_Intensity_Training_Hours) / 20) * 100));
323
+ const experienceLevel = Math.min(100, Math.max(0, (data.Experience_Level / 3) * 100));
324
+
325
+ const defaultFeatureImportance = {
326
+ Training_Load_Score: 0.22,
327
+ Recovery_Per_Training: 0.18,
328
+ Total_Weekly_Training_Hours: 0.16,
329
+ Fatigue_Level: 0.14,
330
+ Recovery_Time_Between_Sessions: 0.12,
331
+ High_Intensity_Training_Hours: 0.10
332
+ };
333
+ const finalFeatureImportance = feature_importance || defaultFeatureImportance;
334
+
335
+ const enhancedRecommendations = enhanceRecommendations(recommendations, {
336
+ Training_Load_Score: trainingLoad,
337
+ Recovery_Per_Training: recoveryPerTraining,
338
+ Total_Weekly_Training_Hours: totalWeeklyHours,
339
+ Fatigue_Level: fatigueLevel,
340
+ Recovery_Time_Between_Sessions: recoveryStatus,
341
+ High_Intensity_Training_Hours: highIntensityHours,
342
+ Previous_Injury_Count: injuryImpact
343
+ }, finalFeatureImportance);
344
+
345
+ const fullReportData = {
346
+ predicted_risk_level,
347
+ injury_likelihood_percent,
348
+ model_class_probability,
349
+ recommendations: enhancedRecommendations,
350
+ feature_importance: finalFeatureImportance,
351
+ factorData: {
352
+ Training_Load_Score: trainingLoad,
353
+ Recovery_Per_Training: recoveryPerTraining,
354
+ Total_Weekly_Training_Hours: totalWeeklyHours,
355
+ Fatigue_Level: fatigueLevel,
356
+ Recovery_Time_Between_Sessions: recoveryStatus,
357
+ High_Intensity_Training_Hours: highIntensityHours,
358
+ Experience_Level: experienceLevel,
359
+ Intensity_Ratio: data.High_Intensity_Training_Hours > 0
360
+ ? Math.min(100, Math.max(0, (parseFloat(data.High_Intensity_Training_Hours) / parseFloat(data.Total_Weekly_Training_Hours)) * 100))
361
+ : 0,
362
+ Endurance_Score: Math.min(100, Math.max(0, (parseFloat(data.Endurance_Score) / 10) * 100)),
363
+ Sprint_Speed: Math.min(100, Math.max(0, (parseFloat(data.Sprint_Speed) / 20) * 100)),
364
+ Agility_Score: Math.min(100, Math.max(0, (parseFloat(data.Agility_Score) / 10) * 100)),
365
+ Flexibility_Score: Math.min(100, Math.max(0, (parseFloat(data.Flexibility_Score) / 10) * 100)),
366
+ Age: Math.min(100, Math.max(0, (parseFloat(data.Age) / 80) * 100)),
367
+ Strength_Training_Frequency: Math.min(100, Math.max(0, (parseFloat(data.Strength_Training_Frequency) / 7) * 100)),
368
+ Sport_Type: Math.min(100, Math.max(0, data.Sport_Type * 20)),
369
+ Gender: data.Gender * 100,
370
+ Previous_Injury_Count: injuryImpact,
371
+ Previous_Injury_Type: Math.min(100, Math.max(0, data.Previous_Injury_Type * 20))
372
+ },
373
+ profile: {
374
+ age: rawData.Age,
375
+ gender: rawData.Gender,
376
+ sport: rawData.Sport_Type
377
+ },
378
+ timestamp: new Date().toISOString(),
379
+ version: '1.1.0'
380
+ };
381
+
382
+ console.log('Storing prediction data in localStorage:', fullReportData);
383
+ localStorage.setItem('predictionData', JSON.stringify(fullReportData));
384
+
385
+ document.getElementById('risk-level').textContent = predicted_risk_level;
386
+ document.getElementById('likelihood-percent').textContent = `${Math.round(injury_likelihood_percent)}%`;
387
+ updateGauge('.summary-gauge .gauge-value', injury_likelihood_percent, '.summary-gauge .gauge-text', null, null);
388
+
389
+ updateGauge('#training-load-gauge', trainingLoad, '#training-load-text', '#training-load-tooltip', {
390
+ high: 'High training load may significantly increase injury risk.',
391
+ medium: 'Moderate training load; monitor closely.',
392
+ low: 'Low training load; risk appears minimal.'
393
+ });
394
+ updateGauge('#recovery-gauge', recoveryStatus, '#recovery-text', '#recovery-tooltip', {
395
+ high: 'Excellent recovery time; low risk from this factor.',
396
+ medium: 'Moderate recovery; consider increasing rest.',
397
+ low: 'Insufficient recovery may elevate injury risk.'
398
+ });
399
+ updateGauge('#injury-history-gauge', injuryImpact, '#injury-history-text', '#injury-history-tooltip', {
400
+ high: 'Significant injury history; high risk of recurrence.',
401
+ medium: 'Moderate injury history; take preventive measures.',
402
+ low: 'Minimal injury history; low risk from this factor.'
403
+ });
404
+
405
+ const recommendationListEl = document.querySelector('.recommendation-list');
406
+ const completedRecs = loadCompletedRecommendations();
407
+ recommendationListEl.innerHTML = Object.keys(enhancedRecommendations).map(category => `
408
+ <div class="recommendation-category">
409
+ <h5 class="category-title">${category}</h5>
410
+ ${enhancedRecommendations[category].map(rec => `
411
+ <li class="recommendation-item expandable ${completedRecs[rec.id] ? 'completed' : ''}">
412
+ <input type="checkbox" class="rec-checkbox" data-id="${rec.id}" ${completedRecs[rec.id] ? 'checked' : ''}>
413
+ <span class="priority-indicator" style="color: ${rec.priority > 0.7 ? '#ef4444' : rec.priority > 0.4 ? '#facc15' : '#22c55e'}">
414
+ ${rec.priority > 0.7 ? '🛑' : rec.priority > 0.4 ? '⚠️' : '✅'}
415
+ </span>
416
+ <span class="recommendation-summary">${rec.text}</span>
417
+ <span class="tooltip-icon">ℹ️
418
+ <span class="tooltip-text">${rec.details}</span>
419
+ </span>
420
+ <div class="recommendation-detail">${rec.details}</div>
421
+ <button class="learn-more-btn" data-url="${rec.resourceUrl}" title="Source: ${rec.resourceSource}">Learn More</button>
422
+ </li>
423
+ `).join('')}
424
+ </div>
425
+ `).join('');
426
+
427
+ document.querySelectorAll('.rec-checkbox').forEach(checkbox => {
428
+ checkbox.addEventListener('change', () => {
429
+ const recId = checkbox.dataset.id;
430
+ const completedRecs = loadCompletedRecommendations();
431
+ completedRecs[recId] = checkbox.checked;
432
+ saveCompletedRecommendations(completedRecs);
433
+ checkbox.closest('.recommendation-item').classList.toggle('completed', checkbox.checked);
434
+ });
435
+ });
436
+
437
+ document.querySelectorAll('.recommendation-item.expandable').forEach(item => {
438
+ item.addEventListener('click', (e) => {
439
+ if (e.target.classList.contains('rec-checkbox') || e.target.classList.contains('learn-more-btn')) return;
440
+ const detail = item.querySelector('.recommendation-detail');
441
+ if (detail.style.display === "none" || detail.style.display === "") {
442
+ detail.style.display = "block";
443
+ detail.style.maxHeight = detail.scrollHeight + "px";
444
+ } else {
445
+ detail.style.display = "none";
446
+ detail.style.maxHeight = "0";
447
+ }
448
+ });
449
+ });
450
+
451
+ document.querySelectorAll('.learn-more-btn').forEach(btn => {
452
+ btn.addEventListener('click', () => {
453
+ const url = btn.dataset.url;
454
+ window.open(url, '_blank');
455
+ });
456
+ });
457
+
458
+ resultContainer.style.display = 'block';
459
+ resultContainer.classList.remove("hidden");
460
+ setTimeout(() => {
461
+ resultContainer.classList.add("visible");
462
+ }, 100);
463
+ resultContainer.scrollIntoView({ behavior: "smooth" });
464
+
465
+ const reportActions = document.createElement('div');
466
+ reportActions.className = 'report-actions';
467
+ reportActions.innerHTML = `
468
+ <button onclick="window.location.href='report.html'" class="action-button">
469
+ View Detailed Analysis
470
+ </button>
471
+ `;
472
+ resultContainer.appendChild(reportActions);
473
+ } catch (err) {
474
+ console.error('Prediction error:', err.message);
475
+ const resultOutput = document.createElement('div');
476
+ resultOutput.innerHTML = `<p style="color: red;">Error: ${err.message}. Please ensure the prediction server is running and try again.</p>`;
477
+ form.appendChild(resultOutput);
478
+ }
479
+ });
480
+ }
481
  });