Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ scaler.pkl
instance/
shit/
*.db
.vscode/
.vscode/
dataset/sample.csv
64 changes: 62 additions & 2 deletions app/app.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from .schema.validation import UserInput
from fastapi import FastAPI, Request , Depends
from fastapi import FastAPI, Request , Depends, UploadFile
from fastapi.responses import JSONResponse, FileResponse
from fastapi.exceptions import HTTPException
from fastapi.staticfiles import StaticFiles
from typing import List, Tuple
import numpy as np
import pandas as pd
import shutil
import uuid
from sklearn.pipeline import Pipeline
import joblib
from contextlib import asynccontextmanager
Expand All @@ -13,8 +17,11 @@
# paths to the pickle files (relative to project root)
MODEL_PATH = Path(__file__).parent.parent / "models" / "estimator.pkl"
NAMES_PATH = Path(__file__).parent.parent / "models" / "names.pkl"
# Directory for user-uploaded files
UPLOAD_DIR = Path("app","uploads")
UPLOAD_DIR.mkdir(exist_ok=True)

# if pickle files are not found, this function will train the model
# if pickle files are not found, this helper will train the model
def ensure_models():
print("🔍 Checking for existing model files...")
if not MODEL_PATH.is_file() or not NAMES_PATH.is_file():
Expand All @@ -30,6 +37,24 @@ def ensure_models():
print("✅ Model and feature names loaded successfully.")
return model, names

# helper for validating the user-uploaded .csv file
def validate_csv(payload:pd.DataFrame, expected_columns:List)-> pd.DataFrame:
expected_columns = [r for r in expected_columns if r != "alert"]
if payload.columns.tolist() != expected_columns:
raise HTTPException(
status_code=422,
detail="Uploaded csv file does not match the expected column configuration"
)

try:
df = payload.astype(float)
except Exception:
raise HTTPException(
status_code=422,
detail="Value in the uploaded csv file must be numeric (float-compatible)"
)
return df

@asynccontextmanager
async def lifespan(app:FastAPI):
pipe,feat_names = ensure_models()
Expand Down Expand Up @@ -92,3 +117,38 @@ def predict_things(value:UserInput,dep:Tuple[Pipeline,np.ndarray] = Depends(get_
return JSONResponse(
status_code=201, content=msg
)

@app.post("/predict/batch",status_code=201)
def predict_things_in_batch(payload:UploadFile,dep:Tuple[Pipeline,np.ndarray] = Depends(get_things)):
pipe,feat_names = dep
feat_names:List[str] = feat_names.tolist()

# Receive and validate incoming upload
valid_exts = [".csv"]
extension = Path(payload.filename).suffix
if extension not in valid_exts:
raise HTTPException(
status_code=422, detail=f"Only `.csv` files are accepted as input, got {extension} instead"
)
df_prev = pd.read_csv(payload.file)
df: pd.DataFrame = validate_csv(df_prev,feat_names)

# Run Predictions
user_inp = df.to_numpy()
pred_label:List[float] = pipe.predict(user_inp).tolist()
pred_proba:List[List[float]] = pipe.predict_proba(user_inp).tolist()

# Postprocessing
label_map = {0: "green", 1: "orange", 2: "red", 3: "yellow"}
pred_label:List[str] = [label_map.get(r) for r in pred_label]
pred_proba = [[round(proba,3) for proba in sample] for sample in pred_proba]

# Final Output
msg = {
"message": "batch prediction successful",
"prediction": pred_label,
"probabilities": pred_proba
}
return JSONResponse(
status_code=201, content=msg
)
225 changes: 225 additions & 0 deletions app/static/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,228 @@ if (clearBtn && form) {
}
});
}

// File input display
const csvFileInput = document.getElementById('csvfile');
const fileNameDisplay = document.getElementById('fileName');
if (csvFileInput && fileNameDisplay) {
csvFileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
const file = e.target.files[0];
if (file.size > 5 * 1024 * 1024) {
showToast('File size exceeds 5MB limit. Please upload a smaller file.', 'error');
file.value = '';
fileNameDisplay.textContent = 'Choose CSV file...';
return;
}
fileNameDisplay.textContent = file.name;
}
});
}

// Batch Prediction Form
const batchForm = document.getElementById('batchForm');
const batchBtn = document.getElementById('batchPredictBtn');
const batchLoader = document.getElementById('batchLoader');

if (batchForm && batchBtn) {
batchForm.addEventListener('submit', async (e) => {
e.preventDefault();

const fileInput = document.getElementById('csvfile');
if (!fileInput || !fileInput.files.length) {
showToast('Please select a CSV file', 'error');
return;
}

const formData = new FormData();
formData.append('payload', fileInput.files[0]);

const btnText = batchBtn.querySelector('.btn-text');
batchBtn.disabled = true;
if (btnText) {
btnText.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Processing...';
}
if (batchLoader) {
batchLoader.style.display = 'inline-block';
}

try {
const response = await fetch('/predict/batch', {
method: 'POST',
body: formData
});

const data = await response.json();

if (response.ok) {
showToast('Batch prediction successful!', 'success');
displayBatchResults(data);
} else if (response.status === 422) {
if (data.detail) {
showToast(data.detail, 'error');
} else if (Array.isArray(data.detail)) {
data.detail.forEach(err => {
const field = err.loc ? err.loc[err.loc.length - 1] : 'validation';
showToast(`Validation Error (${field}): ${err.msg}`, 'error');
});
} else {
showToast('Validation Error', 'error');
}
} else {
showToast(data.message || 'An error occurred', 'error');
}
} catch (error) {
showToast('Network error or server down', 'error');
} finally {
batchBtn.disabled = false;
if (btnText) {
btnText.innerHTML = '<i class="fas fa-bolt"></i> Run Batch Prediction';
}
if (batchLoader) {
batchLoader.style.display = 'none';
}
}
});
}

function displayBatchResults(data) {
const container = document.getElementById('batch-result-container');
if (!container) return;

const predictions = data.prediction;
const probabilities = data.probabilities;
const count = predictions.length;

const counts = { green: 0, orange: 0, red: 0, yellow: 0 };
predictions.forEach(p => {
if (counts[p] !== undefined) counts[p]++;
});

let tableRows = '';
const predictionDetails = { green: [], orange: [], red: [], yellow: [] };
predictions.forEach((pred, i) => {
const probs = probabilities[i];
const maxProb = Math.max(...probs) * 100;
predictionDetails[pred].push(i + 1);
tableRows += `
<tr>
<td>${i + 1}</td>
<td class="alert-cell ${pred}">${pred.toUpperCase()}</td>
<td>${maxProb.toFixed(1)}%</td>
</tr>
`;
});

container.innerHTML = `
<div class="chart-container" style="display: block;">
<canvas id="batchPieChart"></canvas>
</div>
<div class="batch-summary">
<div class="batch-stat">
<div class="batch-stat-value">${count}</div>
<div class="batch-stat-label">Total Predictions</div>
</div>
<div class="batch-stat">
<div class="batch-stat-value" style="color: var(--green);">${counts.green}</div>
<div class="batch-stat-label">Green</div>
</div>
<div class="batch-stat">
<div class="batch-stat-value" style="color: var(--orange);">${counts.orange}</div>
<div class="batch-stat-label">Orange</div>
</div>
<div class="batch-stat">
<div class="batch-stat-value" style="color: var(--red);">${counts.red}</div>
<div class="batch-stat-label">Red</div>
</div>
<div class="batch-stat">
<div class="batch-stat-value" style="color: var(--yellow);">${counts.yellow}</div>
<div class="batch-stat-label">Yellow</div>
</div>
</div>
<table class="batch-results-table">
<thead>
<tr>
<th>#</th>
<th>Alert</th>
<th>Confidence</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
`;

const ctx = document.getElementById('batchPieChart');
if (ctx) {
new Chart(ctx, {
type: 'pie',
data: {
labels: ['Green', 'Orange', 'Red', 'Yellow'],
datasets: [{
data: [counts.green, counts.orange, counts.red, counts.yellow],
backgroundColor: ['#22c55e', '#f97316', '#ef4444', '#eab308'],
borderColor: ['#22c55e', '#f97316', '#ef4444', '#eab308'],
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: '#8b949e'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw || 0;
const predictionList = predictionDetails[label.toLowerCase()];
return `${label}: ${value} predictions`;
},
afterLabel: function(context) {
const label = context.label || '';
const predictionList = predictionDetails[label.toLowerCase()];
if (predictionList && predictionList.length > 0) {
return `Rows: ${predictionList.join(', ')}`;
}
return '';
}
}
}
}
}
});
}
}

// Clear batch button
const clearBatchBtn = document.getElementById('clearBatchBtn');
if (clearBatchBtn && batchForm) {
clearBatchBtn.addEventListener('click', () => {
const fileInput = document.getElementById('csvfile');
if (fileInput) fileInput.value = '';

const fileNameDisplay = document.getElementById('fileName');
if (fileNameDisplay) fileNameDisplay.textContent = 'Choose CSV file...';

const batchContainer = document.getElementById('batch-result-container');
if (batchContainer) {
batchContainer.innerHTML = `
<div class="empty-result">
<div class="empty-icon">
<i class="fas fa-file-csv"></i>
</div>
<p class="empty-text">Upload a CSV file and click "Run Batch Prediction"</p>
</div>
<div class="chart-container" style="display: none;">
<canvas id="batchPieChart"></canvas>
</div>
`;
}
});
}
Loading
Loading