Spaces:
Running
Running
File size: 30,663 Bytes
048f639 | 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 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 | /**
* Diabetes Health Predictor - AI Doctor Portal
* JavaScript for Dynamic Form Handling & API Integration
*/
// ========================================
// GLOBAL VARIABLES
// ========================================
let currentPredictionData = null;
let currentReportFilename = null;
let currentComparisonAnalysis = null;
let comparisonInitialized = false;
// ========================================
// DOM ELEMENTS
// ========================================
const patientForm = document.getElementById('patientForm');
const medicalForm = document.getElementById('medicalForm');
const registrationCard = document.getElementById('registrationCard');
const medicalTestCard = document.getElementById('medicalTestCard');
const resultsCard = document.getElementById('resultsCard');
const resultContainer = document.getElementById('resultContainer');
const reportModal = document.getElementById('reportModal');
const reportContent = document.getElementById('reportContent');
const reportFooter = document.getElementById('reportFooter');
const loadingOverlay = document.getElementById('loadingOverlay');
const predictBtn = document.getElementById('predictBtn');
const patientSummary = document.getElementById('patientSummary');
const reportTabPane = document.getElementById('reportTabPane');
const comparisonTabPane = document.getElementById('comparisonTabPane');
const modalTabButtons = document.querySelectorAll('.modal-tab');
const pastPredictionsSelect = document.getElementById('pastPredictionsSelect');
const comparePredictionsBtn = document.getElementById('comparePredictionsBtn');
const comparisonStatus = document.getElementById('comparisonStatus');
const currentVsNormalImg = document.getElementById('currentVsNormalImg');
const comparisonGraphImg = document.getElementById('comparisonGraphImg');
const historicalGraphCard = document.getElementById('historicalGraphCard');
const groqExplanationCard = document.getElementById('groqExplanationCard');
const groqExplanation = document.getElementById('groqExplanation');
const downloadComparisonPdfBtn = document.getElementById('downloadComparisonPdf');
const MAX_COMPARISON_SELECTION = 3;
// Store patient data
let patientData = {};
// ========================================
// FORM VALIDATION & SUBMISSION
// ========================================
// Handle Patient Registration Form Submission
patientForm.addEventListener('submit', (e) => {
e.preventDefault();
// Collect patient data
const name = document.getElementById('patientName').value.trim();
const age = document.getElementById('patientAge').value;
const sex = document.getElementById('patientSex').value;
const contact = document.getElementById('patientContact').value.trim();
const address = document.getElementById('patientAddress').value.trim();
// Validate
if (!name || !age || !sex || !contact) {
showAlert('Please fill in all required fields!', 'error');
return;
}
// Validate contact number
if (contact.length !== 10 || !/^\d+$/.test(contact)) {
showAlert('Please enter a valid 10-digit contact number!', 'error');
return;
}
// Store patient data
patientData = {
name: name,
age: parseInt(age),
sex: sex,
contact: contact,
address: address
};
// Show patient summary in medical test card
displayPatientSummary();
// Hide registration, show medical test card
registrationCard.style.display = 'none';
medicalTestCard.style.display = 'block';
medicalTestCard.scrollIntoView({ behavior: 'smooth' });
showAlert('Patient registered successfully! Please enter health details.', 'success');
});
// Display patient summary
function displayPatientSummary() {
patientSummary.innerHTML = `
<h3><i class="fas fa-user-check"></i> Patient Information</h3>
<div class="patient-summary-grid">
<div class="patient-summary-item">
<strong>Name:</strong>
<span>${patientData.name}</span>
</div>
<div class="patient-summary-item">
<strong>Age:</strong>
<span>${patientData.age} years</span>
</div>
<div class="patient-summary-item">
<strong>Sex:</strong>
<span>${patientData.sex}</span>
</div>
<div class="patient-summary-item">
<strong>Contact:</strong>
<span>${patientData.contact}</span>
</div>
</div>
`;
}
// Go back to registration
function goBackToRegistration() {
medicalTestCard.style.display = 'none';
registrationCard.style.display = 'block';
registrationCard.scrollIntoView({ behavior: 'smooth' });
}
// Handle Medical Form Submission
medicalForm.addEventListener('submit', async (e) => {
e.preventDefault();
// Collect all form data
const formData = {
// Patient Information
...patientData,
// Medical Test Parameters
pregnancies: parseFloat(document.getElementById('pregnancies').value) || 0,
glucose: parseFloat(document.getElementById('glucose').value),
bloodPressure: parseFloat(document.getElementById('bloodPressure').value),
skinThickness: parseFloat(document.getElementById('skinThickness').value) || 20,
insulin: parseFloat(document.getElementById('insulin').value) || 79,
bmi: parseFloat(document.getElementById('bmi').value),
diabetesPedigreeFunction: parseFloat(document.getElementById('diabetesPedigreeFunction').value),
};
// Validate required medical fields
if (!formData.glucose || !formData.bloodPressure || !formData.bmi || !formData.diabetesPedigreeFunction) {
showAlert('Please fill in all required medical test parameters marked with *', 'error');
return;
}
// Make prediction
await makePrediction(formData);
});
// ========================================
// API CALLS
// ========================================
/**
* Make prediction API call
*/
async function makePrediction(data) {
showLoading(true);
predictBtn.disabled = true;
try {
const response = await fetch('/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.success) {
currentPredictionData = result;
displayResults(result);
resultsCard.style.display = 'block';
resultsCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Play sound based on risk level
playPredictionSound(result.risk_level);
resetComparisonUI();
} else {
showAlert(`Prediction Error: ${result.error}`, 'error');
}
} catch (error) {
console.error('Prediction error:', error);
showAlert('Failed to connect to the server. Please try again.', 'error');
} finally {
showLoading(false);
predictBtn.disabled = false;
}
}
/**
* Generate AI doctor report
*/
async function generateReport() {
if (!currentPredictionData) {
showAlert('No prediction data available. Please run prediction first.', 'error');
return;
}
// Show modal with loading
setReportModalTab('report');
reportModal.classList.add('show');
reportContent.innerHTML = `
<div class="loading">
<i class="fas fa-spinner fa-spin"></i>
<p>Generating comprehensive medical report...</p>
<p style="font-size: 0.9rem; color: var(--text-gray); margin-top: 1rem;">
This may take a few moments
</p>
</div>
`;
reportFooter.style.display = 'none';
try {
const response = await fetch('/report', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(currentPredictionData)
});
const result = await response.json();
if (result.success) {
currentReportFilename = result.report_file;
displayReport(result.report);
if (reportFooter) {
const activeTab = document.querySelector('.modal-tab.active');
const comparisonActive = activeTab && activeTab.dataset.tab === 'comparison';
if (comparisonActive) {
reportFooter.dataset.restoreDisplay = 'flex';
reportFooter.style.display = 'none';
} else {
reportFooter.style.display = 'flex';
delete reportFooter.dataset.restoreDisplay;
}
}
} else {
reportContent.innerHTML = `
<div style="text-align: center; padding: 2rem; color: var(--danger-color);">
<i class="fas fa-exclamation-triangle" style="font-size: 3rem; margin-bottom: 1rem;"></i>
<p><strong>Report Generation Failed</strong></p>
<p>${result.error}</p>
</div>
`;
}
} catch (error) {
console.error('Report generation error:', error);
reportContent.innerHTML = `
<div style="text-align: center; padding: 2rem; color: var(--danger-color);">
<i class="fas fa-exclamation-triangle" style="font-size: 3rem; margin-bottom: 1rem;"></i>
<p><strong>Connection Error</strong></p>
<p>Failed to connect to the AI report generator.</p>
</div>
`;
}
}
/**
* Download the generated report
*/
function downloadReport() {
if (currentReportFilename) {
window.location.href = `/download_report/${currentReportFilename}`;
showAlert('Report downloaded successfully!', 'success');
} else {
showAlert('No report file available to download.', 'error');
}
}
// ========================================
// UI DISPLAY FUNCTIONS
// ========================================
/**
* Display prediction results
*/
function displayResults(data) {
const riskClass = data.risk_level === 'high' ? 'high-risk' : 'low-risk';
const icon = data.risk_level === 'high'
? '<i class="fas fa-exclamation-circle"></i>'
: '<i class="fas fa-check-circle"></i>';
resultContainer.innerHTML = `
<div class="result-badge ${riskClass}">
${icon} ${data.prediction}
</div>
<div class="confidence-badge">
Confidence: ${data.confidence}%
</div>
<div class="result-details">
<h3 style="margin-bottom: 1rem; color: var(--text-dark);">
<i class="fas fa-user"></i> Patient Information
</h3>
<div class="result-row">
<span><strong>Name:</strong></span>
<span>${data.patient_info.name}</span>
</div>
<div class="result-row">
<span><strong>Age:</strong></span>
<span>${data.patient_info.age} years</span>
</div>
<div class="result-row">
<span><strong>Sex:</strong></span>
<span>${data.patient_info.sex}</span>
</div>
<div class="result-row">
<span><strong>Contact:</strong></span>
<span>${data.patient_info.contact}</span>
</div>
</div>
<div class="result-details" style="margin-top: 1rem;">
<h3 style="margin-bottom: 1rem; color: var(--text-dark);">
<i class="fas fa-clipboard-list"></i> Medical Test Results
</h3>
${Object.entries(data.medical_data).map(([key, value]) => `
<div class="result-row">
<span><strong>${key}:</strong></span>
<span>${typeof value === 'number' ? value.toFixed(2) : value}</span>
</div>
`).join('')}
</div>
<div class="recommendation">
<strong><i class="fas fa-lightbulb"></i> Recommendation:</strong><br>
${data.recommendation}
</div>
`;
}
function resetComparisonUI() {
comparisonInitialized = false;
currentComparisonAnalysis = null;
if (pastPredictionsSelect) {
pastPredictionsSelect.innerHTML = '';
}
if (comparisonStatus) {
comparisonStatus.textContent = '';
}
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = true;
}
if (currentVsNormalImg) {
currentVsNormalImg.removeAttribute('src');
}
if (comparisonGraphImg) {
comparisonGraphImg.removeAttribute('src');
}
if (historicalGraphCard) {
historicalGraphCard.style.display = 'none';
}
if (groqExplanation) {
groqExplanation.innerHTML = '';
}
if (groqExplanationCard) {
groqExplanationCard.style.display = 'none';
}
if (downloadComparisonPdfBtn) {
downloadComparisonPdfBtn.style.display = 'none';
downloadComparisonPdfBtn.dataset.downloadUrl = '';
}
}
function updateCurrentVsNormalImage() {
if (!currentVsNormalImg) {
return;
}
const graphUrl = (currentComparisonAnalysis && currentComparisonAnalysis.current_vs_normal_graph_url)
|| currentPredictionData?.graphs?.current_vs_normal?.url
|| currentPredictionData?.current_vs_normal_graph_url;
if (graphUrl) {
currentVsNormalImg.src = appendCacheBuster(graphUrl);
} else {
currentVsNormalImg.removeAttribute('src');
}
}
async function prepareComparisonTab(forceReload = false) {
if (!comparisonTabPane) {
return;
}
if (!currentPredictionData || !currentPredictionData.firebase_id) {
resetComparisonUI();
if (comparisonStatus) {
comparisonStatus.textContent = 'Run a prediction before using trend comparison.';
}
return;
}
updateCurrentVsNormalImage();
if (!comparisonInitialized || forceReload) {
if (comparisonStatus) {
comparisonStatus.textContent = 'Loading history...';
}
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = true;
}
await populatePastPredictions(currentPredictionData.firebase_id);
comparisonInitialized = true;
} else if (comparisonStatus && !comparisonStatus.textContent) {
comparisonStatus.textContent = 'Select two or three predictions for trend analysis.';
}
if (currentComparisonAnalysis) {
renderComparisonAnalysis(currentComparisonAnalysis);
}
}
function setReportModalTab(targetTab) {
if (!modalTabButtons || modalTabButtons.length === 0) {
return;
}
modalTabButtons.forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === targetTab);
});
if (targetTab === 'comparison') {
if (reportTabPane) {
reportTabPane.style.display = 'none';
}
if (comparisonTabPane) {
comparisonTabPane.style.display = 'block';
}
if (reportFooter && !reportFooter.dataset.restoreDisplay) {
reportFooter.dataset.restoreDisplay = reportFooter.style.display || '';
}
if (reportFooter) {
reportFooter.style.display = 'none';
}
prepareComparisonTab().catch(err => console.error('Comparison prep error:', err));
} else {
if (reportTabPane) {
reportTabPane.style.display = 'block';
}
if (comparisonTabPane) {
comparisonTabPane.style.display = 'none';
}
if (reportFooter && reportFooter.dataset.restoreDisplay !== undefined) {
reportFooter.style.display = reportFooter.dataset.restoreDisplay;
delete reportFooter.dataset.restoreDisplay;
}
}
}
async function populatePastPredictions(currentPredictionId) {
if (!pastPredictionsSelect) {
return;
}
pastPredictionsSelect.innerHTML = '';
if (comparisonStatus) {
comparisonStatus.textContent = 'Loading history...';
}
try {
const response = await fetch('/patient_history?limit=25');
const data = await response.json();
if (!data.success || !Array.isArray(data.history)) {
if (comparisonStatus) {
comparisonStatus.textContent = 'Unable to load prediction history.';
}
return;
}
const filteredHistory = data.history.filter(item => item.id && item.id !== currentPredictionId);
filteredHistory.sort((a, b) => parseHistoryDate(a) - parseHistoryDate(b));
if (filteredHistory.length < 2) {
if (comparisonStatus) {
comparisonStatus.textContent = 'Need at least two past predictions to run a comparison.';
}
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = true;
}
return;
}
filteredHistory.forEach(item => {
const option = document.createElement('option');
option.value = item.id;
option.textContent = formatPredictionOption(item);
pastPredictionsSelect.appendChild(option);
});
if (comparisonStatus) {
comparisonStatus.textContent = 'Select two or three predictions for trend analysis.';
}
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = false;
}
} catch (error) {
console.error('History fetch error:', error);
if (comparisonStatus) {
comparisonStatus.textContent = 'Failed to load prediction history.';
}
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = true;
}
}
}
function parseHistoryDate(item) {
if (!item) {
return 0;
}
if (item.timestamp) {
const date = new Date(item.timestamp);
if (!Number.isNaN(date.getTime())) {
return date.getTime();
}
}
if (item.created_at) {
const created = Number(item.created_at);
if (!Number.isNaN(created)) {
return created * 1000;
}
}
if (item.date) {
const formatted = `${item.date}T${item.time || '00:00:00'}`;
const date = new Date(formatted);
if (!Number.isNaN(date.getTime())) {
return date.getTime();
}
}
return 0;
}
function formatPredictionOption(item) {
const dateValue = parseHistoryDate(item);
const dateObj = new Date(dateValue);
const hasValidDate = !Number.isNaN(dateObj.getTime());
const dateLabel = hasValidDate
? `${dateObj.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })} ${dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`
: 'Previous Visit';
const resultText = item.result || item.prediction || item.risk_level || 'Unknown Risk';
const confidenceValue = item.confidence !== undefined && item.confidence !== null
? Number(item.confidence).toFixed(1)
: null;
const confidenceText = confidenceValue ? ` (${confidenceValue}%)` : '';
return `${dateLabel} - ${resultText}${confidenceText}`;
}
function appendCacheBuster(url) {
if (!url) {
return '';
}
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}t=${Date.now()}`;
}
function formatExplanation(text) {
if (!text) {
return '<p>No explanation available.</p>';
}
return text
.split('\n')
.map(line => line.trim())
.filter(Boolean)
.map(line => `<p>${escapeHtml(line)}</p>`)
.join('');
}
function renderComparisonAnalysis(result) {
if (!result) {
if (comparisonGraphImg) {
comparisonGraphImg.removeAttribute('src');
}
if (historicalGraphCard) {
historicalGraphCard.style.display = 'none';
}
if (groqExplanation) {
groqExplanation.innerHTML = '';
}
if (groqExplanationCard) {
groqExplanationCard.style.display = 'none';
}
if (downloadComparisonPdfBtn) {
downloadComparisonPdfBtn.style.display = 'none';
downloadComparisonPdfBtn.dataset.downloadUrl = '';
}
return;
}
const comparisonGraphUrl = result.comparison_graph_url;
if (comparisonGraphImg) {
if (comparisonGraphUrl) {
comparisonGraphImg.src = appendCacheBuster(comparisonGraphUrl);
if (historicalGraphCard) {
historicalGraphCard.style.display = 'block';
}
} else {
comparisonGraphImg.removeAttribute('src');
if (historicalGraphCard) {
historicalGraphCard.style.display = 'none';
}
}
}
if (groqExplanation) {
groqExplanation.innerHTML = formatExplanation(result.explanation);
}
if (groqExplanationCard) {
groqExplanationCard.style.display = 'block';
}
if (downloadComparisonPdfBtn) {
if (result.report_download_url) {
downloadComparisonPdfBtn.dataset.downloadUrl = result.report_download_url;
downloadComparisonPdfBtn.style.display = 'inline-flex';
} else {
downloadComparisonPdfBtn.style.display = 'none';
downloadComparisonPdfBtn.dataset.downloadUrl = '';
}
}
}
async function compareWithPast() {
if (!pastPredictionsSelect || !currentPredictionData || !currentPredictionData.firebase_id) {
showAlert('Run a prediction before requesting comparisons.', 'warning');
return;
}
const selected = Array.from(pastPredictionsSelect.selectedOptions).map(option => option.value);
if (selected.length < 2 || selected.length > MAX_COMPARISON_SELECTION) {
showAlert(`Please select between 2 and ${MAX_COMPARISON_SELECTION} past predictions.`, 'warning');
return;
}
if (comparisonStatus) {
comparisonStatus.textContent = 'Generating comparison analysis...';
}
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = true;
}
try {
const response = await fetch('/prediction/analysis', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
current_prediction_id: currentPredictionData.firebase_id,
past_prediction_ids: selected
})
});
const result = await response.json();
if (!result.success) {
showAlert(`Comparison Error: ${result.error}`, 'error');
if (comparisonStatus) {
comparisonStatus.textContent = result.error || 'Comparison failed.';
}
return;
}
currentComparisonAnalysis = result;
updateCurrentVsNormalImage();
renderComparisonAnalysis(result);
if (comparisonStatus) {
comparisonStatus.textContent = 'Comparison updated successfully.';
}
} catch (error) {
console.error('Comparison analysis error:', error);
showAlert('Failed to analyze past predictions. Please try again later.', 'error');
if (comparisonStatus) {
comparisonStatus.textContent = 'Comparison failed. Try again later.';
}
} finally {
if (comparePredictionsBtn) {
comparePredictionsBtn.disabled = false;
}
}
}
function downloadComparisonReport() {
if (!downloadComparisonPdfBtn) {
return;
}
const downloadUrl = downloadComparisonPdfBtn.dataset.downloadUrl;
if (!downloadUrl) {
showAlert('Generate a comparison before downloading the report.', 'warning');
return;
}
window.location.href = downloadUrl;
showAlert('Preparing comparison report download...', 'info');
}
/**
* Display AI-generated report in modal
*/
function displayReport(reportText) {
reportContent.innerHTML = `
<div class="report-content">${escapeHtml(reportText)}</div>
`;
}
/**
* Show/hide loading overlay
*/
function showLoading(show) {
if (show) {
loadingOverlay.classList.add('show');
} else {
loadingOverlay.classList.remove('show');
}
}
/**
* Show alert message
*/
function showAlert(message, type = 'info') {
const alertColors = {
success: '#10b981',
error: '#ef4444',
warning: '#f59e0b',
info: '#3b82f6'
};
const alertDiv = document.createElement('div');
alertDiv.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: ${alertColors[type]};
color: white;
padding: 1rem 1.5rem;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
z-index: 4000;
animation: slideInRight 0.3s ease;
max-width: 400px;
font-weight: 500;
`;
alertDiv.innerHTML = `
<div style="display: flex; align-items: center; gap: 0.5rem;">
<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : 'info-circle'}"></i>
<span>${message}</span>
</div>
`;
document.body.appendChild(alertDiv);
setTimeout(() => {
alertDiv.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => alertDiv.remove(), 300);
}, 4000);
}
// ========================================
// MODAL FUNCTIONS
// ========================================
/**
* Close the report modal
*/
function closeModal() {
setReportModalTab('report');
reportModal.classList.remove('show');
}
// Close modal when clicking outside
reportModal.addEventListener('click', (e) => {
if (e.target === reportModal) {
closeModal();
}
});
// Close modal with Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && reportModal.classList.contains('show')) {
closeModal();
}
});
// ========================================
// UTILITY FUNCTIONS
// ========================================
/**
* Reset all forms
*/
function resetForms() {
if (confirm('Are you sure you want to start a new assessment?')) {
patientForm.reset();
medicalForm.reset();
registrationCard.style.display = 'block';
medicalTestCard.style.display = 'none';
resultsCard.style.display = 'none';
currentPredictionData = null;
currentReportFilename = null;
currentComparisonAnalysis = null;
comparisonInitialized = false;
patientData = {};
resetComparisonUI();
window.scrollTo({ top: 0, behavior: 'smooth' });
showAlert('Starting new patient assessment', 'info');
}
}
/**
* Start a new prediction (reset and scroll to top)
*/
function newPrediction() {
resetForms();
}
/**
* Play sound alert based on prediction result
*/
function playPredictionSound(riskLevel) {
try {
if (riskLevel === 'high') {
// Play alert sound for high risk (diabetes detected)
const alertSound = document.getElementById('alertSound');
if (alertSound) {
alertSound.volume = 0.5;
alertSound.play().catch(err => console.log('Audio play prevented:', err));
}
// Show visual alert
showAlert('⚠️ HIGH RISK DETECTED! Please consult a doctor immediately.', 'warning');
} else {
// Play success sound for low risk (safe, no diabetes)
const successSound = document.getElementById('successSound');
if (successSound) {
successSound.volume = 0.5;
successSound.play().catch(err => console.log('Audio play prevented:', err));
}
// Show visual success message
showAlert('✅ Good News! Low risk detected. Maintain healthy lifestyle.', 'success');
}
} catch (error) {
console.log('Sound playback error:', error);
}
}
/**
* Escape HTML to prevent XSS
*/
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* Validate contact number in real-time
*/
document.getElementById('patientContact').addEventListener('input', function(e) {
this.value = this.value.replace(/\D/g, '');
if (this.value.length > 10) {
this.value = this.value.slice(0, 10);
}
});
if (pastPredictionsSelect) {
pastPredictionsSelect.addEventListener('change', () => {
const selected = Array.from(pastPredictionsSelect.selectedOptions);
if (selected.length > MAX_COMPARISON_SELECTION) {
selected[selected.length - 1].selected = false;
showAlert(`You can compare up to ${MAX_COMPARISON_SELECTION} predictions at a time.`, 'warning');
}
});
}
if (modalTabButtons && modalTabButtons.length > 0) {
modalTabButtons.forEach(btn => {
btn.addEventListener('click', () => setReportModalTab(btn.dataset.tab));
});
}
if (comparePredictionsBtn) {
comparePredictionsBtn.addEventListener('click', compareWithPast);
}
if (downloadComparisonPdfBtn) {
downloadComparisonPdfBtn.addEventListener('click', downloadComparisonReport);
}
// ========================================
// ANIMATIONS FOR CSS
// ========================================
// Add slide animation styles
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOutRight {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(style);
// ========================================
// INITIALIZATION
// ========================================
console.log('🏥 Diabetes Health Predictor - AI Doctor Portal initialized');
console.log('✅ All systems ready');
|