Spaces:
Sleeping
Sleeping
File size: 8,244 Bytes
cd38846 | 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 | const API_URL = '/predict';
const WINDOW_SIZE = 30;
// Initialize the UI
document.addEventListener('DOMContentLoaded', function() {
initializeInputs();
setupEventListeners();
});
function initializeInputs() {
const container = document.getElementById('dataInputs');
container.innerHTML = '';
for (let i = 0; i < WINDOW_SIZE; i++) {
const item = document.createElement('div');
item.className = 'data-input-item';
const label = document.createElement('label');
label.textContent = `Day ${i + 1}`;
const input = document.createElement('input');
input.type = 'number';
input.step = '0.01';
input.min = '0';
input.placeholder = '0';
input.id = `input-${i}`;
input.addEventListener('input', validateInputs);
item.appendChild(label);
item.appendChild(input);
container.appendChild(item);
}
updateInputCount();
}
function setupEventListeners() {
document.getElementById('predictBtn').addEventListener('click', makePrediction);
document.getElementById('loadSampleBtn').addEventListener('click', loadSampleData);
document.getElementById('clearBtn').addEventListener('click', clearAll);
document.getElementById('csvFile').addEventListener('change', handleCSVUpload);
}
function validateInputs() {
const inputs = document.querySelectorAll('#dataInputs input');
let filledCount = 0;
inputs.forEach(input => {
if (input.value && input.value.trim() !== '') {
filledCount++;
}
});
updateInputCount(filledCount);
const predictBtn = document.getElementById('predictBtn');
predictBtn.disabled = filledCount !== WINDOW_SIZE;
}
function updateInputCount(count = null) {
if (count === null) {
const inputs = document.querySelectorAll('#dataInputs input');
count = Array.from(inputs).filter(input => input.value && input.value.trim() !== '').length;
}
const countElement = document.getElementById('inputCount');
countElement.textContent = count;
countElement.style.color = count === WINDOW_SIZE ? '#28a745' : count > 0 ? '#ffc107' : '#666';
}
function getInputValues() {
const inputs = document.querySelectorAll('#dataInputs input');
const values = [];
inputs.forEach(input => {
const value = parseFloat(input.value);
if (isNaN(value)) {
throw new Error('Please fill all 30 fields with valid numbers');
}
values.push(value);
});
if (values.length !== WINDOW_SIZE) {
throw new Error('Please fill all 30 fields');
}
return values;
}
async function makePrediction() {
const predictBtn = document.getElementById('predictBtn');
const predictBtnText = document.getElementById('predictBtnText');
const loadingSpinner = document.getElementById('loadingSpinner');
const resultSection = document.getElementById('resultSection');
const errorSection = document.getElementById('errorSection');
// Hide previous results/errors
resultSection.style.display = 'none';
errorSection.style.display = 'none';
try {
// Get and validate input values
const values = getInputValues();
// Show loading state
predictBtn.disabled = true;
predictBtnText.textContent = 'Predicting...';
loadingSpinner.style.display = 'inline-block';
// Make API call
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
new_cases: values
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to get prediction');
}
const data = await response.json();
// Display result
document.getElementById('predictedValue').textContent = Math.round(data.predicted_cases).toLocaleString();
document.getElementById('resultMessage').textContent = data.message;
resultSection.style.display = 'block';
// Scroll to result
resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
} catch (error) {
// Display error
document.getElementById('errorMessage').textContent = error.message;
errorSection.style.display = 'block';
errorSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
} finally {
// Reset button state
predictBtn.disabled = false;
predictBtnText.textContent = 'Make Prediction';
loadingSpinner.style.display = 'none';
}
}
function loadSampleData() {
// Generate sample data (trending upward)
const inputs = document.querySelectorAll('#dataInputs input');
let baseValue = 100;
inputs.forEach((input, index) => {
// Create a trend with some variation
const value = baseValue + (index * 5) + Math.random() * 20;
input.value = Math.round(value);
});
validateInputs();
}
function clearAll() {
const inputs = document.querySelectorAll('#dataInputs input');
inputs.forEach(input => {
input.value = '';
});
validateInputs();
document.getElementById('resultSection').style.display = 'none';
document.getElementById('errorSection').style.display = 'none';
}
function handleCSVUpload(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const text = e.target.result;
const lines = text.split('\n');
// Try to find the new_cases column
let newCasesIndex = -1;
let dataStartIndex = 0;
// Check if first line is header
const header = lines[0].toLowerCase();
if (header.includes('new_cases') || header.includes('new cases')) {
const headers = lines[0].split(',');
newCasesIndex = headers.findIndex(h =>
h.toLowerCase().includes('new') && h.toLowerCase().includes('case')
);
dataStartIndex = 1;
}
if (newCasesIndex === -1) {
// Assume first column is new_cases
newCasesIndex = 0;
}
const values = [];
for (let i = dataStartIndex; i < lines.length && values.length < WINDOW_SIZE; i++) {
if (lines[i].trim() === '') continue;
const columns = lines[i].split(',');
const value = parseFloat(columns[newCasesIndex]);
if (!isNaN(value)) {
values.push(value);
}
}
if (values.length < WINDOW_SIZE) {
throw new Error(`CSV file must contain at least ${WINDOW_SIZE} valid values. Found ${values.length}.`);
}
// Take the last 30 values
const last30Values = values.slice(-WINDOW_SIZE);
// Fill inputs
const inputs = document.querySelectorAll('#dataInputs input');
last30Values.forEach((value, index) => {
if (inputs[index]) {
inputs[index].value = value;
}
});
validateInputs();
// Show success message
alert(`Successfully loaded ${WINDOW_SIZE} values from CSV file!`);
} catch (error) {
alert('Error reading CSV file: ' + error.message);
}
};
reader.readAsText(file);
// Reset file input
event.target.value = '';
}
|