Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,71 +2,410 @@ import gradio as gr
|
|
| 2 |
import json
|
| 3 |
from fastapi import FastAPI
|
| 4 |
import uvicorn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
if
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
is_high_risk = probability >= 50
|
| 41 |
|
| 42 |
-
return {
|
| 43 |
-
"success": True,
|
| 44 |
-
"risk_score": probability,
|
| 45 |
-
"is_high_risk": is_high_risk,
|
| 46 |
-
"risk_level": "High Risk" if is_high_risk else "Low Risk",
|
| 47 |
-
"message": "Please consult with a healthcare professional" if is_high_risk else "Keep maintaining your healthy lifestyle!"
|
| 48 |
-
}
|
| 49 |
except Exception as e:
|
| 50 |
return {
|
| 51 |
"success": False,
|
| 52 |
"error": str(e)
|
| 53 |
}
|
| 54 |
|
| 55 |
-
# Create a
|
| 56 |
-
with gr.Blocks(
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
with gr.Row():
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
|
|
|
| 65 |
with gr.Row():
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
# Symptoms
|
| 70 |
gr.Markdown("### Symptoms")
|
| 71 |
with gr.Row():
|
| 72 |
increased_thirst = gr.Checkbox(label="Increased Thirst")
|
|
@@ -77,39 +416,163 @@ with gr.Blocks(title="GlucoCheck AI API") as demo:
|
|
| 77 |
blurred_vision = gr.Checkbox(label="Blurred Vision")
|
| 78 |
weight_loss = gr.Checkbox(label="Weight Loss")
|
| 79 |
|
| 80 |
-
# Output
|
| 81 |
-
output = gr.JSON(label="Result")
|
| 82 |
-
|
| 83 |
# Predict button
|
| 84 |
-
predict_btn = gr.Button("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
# Prediction function
|
| 87 |
-
def
|
| 88 |
age_val, bmi_val, glucose_val, bp_val, insulin_val,
|
|
|
|
| 89 |
thirst, hunger, fatigue_val, vision, weight
|
| 90 |
):
|
|
|
|
| 91 |
data = {
|
| 92 |
"age": age_val,
|
| 93 |
"bmi": bmi_val,
|
| 94 |
"glucose": glucose_val,
|
| 95 |
"blood_pressure": bp_val,
|
| 96 |
"insulin": insulin_val,
|
|
|
|
|
|
|
|
|
|
| 97 |
"increased_thirst": thirst,
|
| 98 |
"increased_hunger": hunger,
|
| 99 |
"fatigue": fatigue_val,
|
| 100 |
"blurred_vision": vision,
|
| 101 |
"weight_loss": weight
|
| 102 |
}
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
|
|
|
| 105 |
predict_btn.click(
|
| 106 |
-
|
| 107 |
inputs=[
|
| 108 |
age, bmi, glucose, blood_pressure, insulin,
|
|
|
|
| 109 |
increased_thirst, increased_hunger, fatigue, blurred_vision, weight_loss
|
| 110 |
],
|
| 111 |
-
outputs=
|
|
|
|
|
|
|
|
|
|
| 112 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
# Mount Gradio app
|
| 115 |
app = gr.mount_gradio_app(app, demo, path="/")
|
|
|
|
| 2 |
import json
|
| 3 |
from fastapi import FastAPI
|
| 4 |
import uvicorn
|
| 5 |
+
import pickle
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from typing import Dict, List, Optional
|
| 9 |
+
import os
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
+
class DiabetesPredictor:
|
| 14 |
+
def __init__(self, model_path: str = "diabetes_model.pkl",
|
| 15 |
+
scaler_path: str = "scaler.pkl"):
|
| 16 |
+
"""
|
| 17 |
+
Initialize the diabetes predictor with model and scaler.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
model_path: Path to the trained model .pkl file
|
| 21 |
+
scaler_path: Path to the scaler .pkl file
|
| 22 |
+
"""
|
| 23 |
+
self.model = None
|
| 24 |
+
self.scaler = None
|
| 25 |
+
self.feature_names = None
|
| 26 |
+
|
| 27 |
+
# Try to load the model
|
| 28 |
+
try:
|
| 29 |
+
if os.path.exists(model_path):
|
| 30 |
+
with open(model_path, 'rb') as f:
|
| 31 |
+
self.model = pickle.load(f)
|
| 32 |
+
print(f"✓ Model loaded successfully from {model_path}")
|
| 33 |
+
else:
|
| 34 |
+
print(f"⚠ Warning: Model file not found at {model_path}")
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"✗ Error loading model: {e}")
|
| 37 |
|
| 38 |
+
# Try to load the scaler
|
| 39 |
+
try:
|
| 40 |
+
if os.path.exists(scaler_path):
|
| 41 |
+
with open(scaler_path, 'rb') as f:
|
| 42 |
+
self.scaler = pickle.load(f)
|
| 43 |
+
print(f"✓ Scaler loaded successfully from {scaler_path}")
|
| 44 |
+
else:
|
| 45 |
+
print(f"⚠ Warning: Scaler file not found at {scaler_path}")
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"✗ Error loading scaler: {e}")
|
| 48 |
+
|
| 49 |
+
def prepare_features(self, data: Dict) -> np.ndarray:
|
| 50 |
+
"""
|
| 51 |
+
Prepare input features for prediction.
|
| 52 |
+
Expected features in order:
|
| 53 |
+
- Pregnancies
|
| 54 |
+
- Glucose
|
| 55 |
+
- BloodPressure
|
| 56 |
+
- SkinThickness
|
| 57 |
+
- Insulin
|
| 58 |
+
- BMI
|
| 59 |
+
- DiabetesPedigreeFunction
|
| 60 |
+
- Age
|
| 61 |
+
"""
|
| 62 |
+
try:
|
| 63 |
+
# Extract features from input data
|
| 64 |
+
# If your model expects different features, modify this mapping
|
| 65 |
+
features = [
|
| 66 |
+
data.get("pregnancies", 0), # Usually needed for diabetes prediction
|
| 67 |
+
data.get("glucose", 100.0),
|
| 68 |
+
data.get("blood_pressure", 120.0),
|
| 69 |
+
data.get("skin_thickness", 20.0), # Common diabetes dataset feature
|
| 70 |
+
data.get("insulin", 15.0),
|
| 71 |
+
data.get("bmi", 25.0),
|
| 72 |
+
data.get("diabetes_pedigree", 0.5), # Common diabetes dataset feature
|
| 73 |
+
data.get("age", 30)
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
return np.array(features).reshape(1, -1)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"Error preparing features: {e}")
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
def predict(self, data: Dict) -> Dict:
|
| 82 |
+
"""
|
| 83 |
+
Make prediction using the loaded model.
|
| 84 |
+
"""
|
| 85 |
+
if self.model is None:
|
| 86 |
+
return {
|
| 87 |
+
"success": False,
|
| 88 |
+
"error": "Model not loaded. Using fallback prediction.",
|
| 89 |
+
"fallback_used": True,
|
| 90 |
+
"risk_score": self.fallback_prediction(data)
|
| 91 |
+
}
|
| 92 |
|
| 93 |
+
try:
|
| 94 |
+
# Prepare features
|
| 95 |
+
features = self.prepare_features(data)
|
| 96 |
+
if features is None:
|
| 97 |
+
raise ValueError("Could not prepare features")
|
| 98 |
+
|
| 99 |
+
# Scale features if scaler is available
|
| 100 |
+
if self.scaler is not None:
|
| 101 |
+
features = self.scaler.transform(features)
|
| 102 |
+
|
| 103 |
+
# Make prediction
|
| 104 |
+
prediction = self.model.predict(features)[0]
|
| 105 |
+
prediction_proba = self.model.predict_proba(features)[0]
|
| 106 |
+
|
| 107 |
+
# Get probability for positive class (diabetes)
|
| 108 |
+
# Assuming class 1 is diabetes
|
| 109 |
+
risk_score = float(prediction_proba[1] * 100) if len(prediction_proba) > 1 else float(prediction * 100)
|
| 110 |
+
|
| 111 |
+
is_high_risk = prediction == 1 or risk_score >= 50
|
| 112 |
+
|
| 113 |
+
return {
|
| 114 |
+
"success": True,
|
| 115 |
+
"model_used": True,
|
| 116 |
+
"prediction": int(prediction),
|
| 117 |
+
"risk_score": risk_score,
|
| 118 |
+
"is_high_risk": bool(is_high_risk),
|
| 119 |
+
"risk_level": "High Risk" if is_high_risk else "Low Risk",
|
| 120 |
+
"confidence": float(max(prediction_proba) * 100) if len(prediction_proba) > 1 else None,
|
| 121 |
+
"message": self.get_recommendation(is_high_risk, risk_score)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print(f"Prediction error: {e}")
|
| 126 |
+
return {
|
| 127 |
+
"success": False,
|
| 128 |
+
"error": str(e),
|
| 129 |
+
"fallback_used": True,
|
| 130 |
+
"risk_score": self.fallback_prediction(data)
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
def fallback_prediction(self, data: Dict) -> float:
|
| 134 |
+
"""
|
| 135 |
+
Fallback prediction logic when model fails to load.
|
| 136 |
+
This is your original logic.
|
| 137 |
+
"""
|
| 138 |
+
try:
|
| 139 |
+
age = int(data.get("age", 30))
|
| 140 |
+
bmi = float(data.get("bmi", 25.0))
|
| 141 |
+
glucose = float(data.get("glucose", 100.0))
|
| 142 |
+
|
| 143 |
+
score = 0
|
| 144 |
+
if glucose > 140:
|
| 145 |
+
score += 40
|
| 146 |
+
if bmi > 30:
|
| 147 |
+
score += 20
|
| 148 |
+
if age > 45:
|
| 149 |
+
score += 10
|
| 150 |
+
|
| 151 |
+
# Add symptoms
|
| 152 |
+
if data.get("increased_thirst"):
|
| 153 |
+
score += 10
|
| 154 |
+
if data.get("increased_hunger"):
|
| 155 |
+
score += 5
|
| 156 |
+
if data.get("fatigue"):
|
| 157 |
+
score += 5
|
| 158 |
+
if data.get("blurred_vision"):
|
| 159 |
+
score += 10
|
| 160 |
+
if data.get("weight_loss"):
|
| 161 |
+
score += 15
|
| 162 |
+
|
| 163 |
+
return min(score, 100)
|
| 164 |
+
except:
|
| 165 |
+
return 0.0
|
| 166 |
+
|
| 167 |
+
def get_recommendation(self, is_high_risk: bool, risk_score: float) -> str:
|
| 168 |
+
"""Generate recommendation based on risk level."""
|
| 169 |
+
if is_high_risk:
|
| 170 |
+
if risk_score > 80:
|
| 171 |
+
return "URGENT: Very high diabetes risk detected. Please consult a healthcare professional immediately."
|
| 172 |
+
elif risk_score > 60:
|
| 173 |
+
return "High diabetes risk detected. Schedule an appointment with your doctor soon."
|
| 174 |
+
else:
|
| 175 |
+
return "Moderate diabetes risk. Consider lifestyle changes and regular monitoring."
|
| 176 |
+
else:
|
| 177 |
+
if risk_score < 20:
|
| 178 |
+
return "Low diabetes risk. Keep maintaining your healthy lifestyle!"
|
| 179 |
+
else:
|
| 180 |
+
return "Some risk factors present. Consider preventive measures and regular check-ups."
|
| 181 |
+
|
| 182 |
+
# Initialize predictor
|
| 183 |
+
predictor = DiabetesPredictor(
|
| 184 |
+
model_path="diabetes_model.pkl",
|
| 185 |
+
scaler_path="scaler.pkl"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def calculate_diabetes_risk_api(data: dict) -> dict:
|
| 189 |
+
"""API endpoint for diabetes risk prediction using ML model."""
|
| 190 |
+
try:
|
| 191 |
+
# Use the predictor
|
| 192 |
+
result = predictor.predict(data)
|
| 193 |
|
| 194 |
+
# If model prediction failed but we have fallback, format it
|
| 195 |
+
if not result.get("success", False) and "fallback_used" in result:
|
| 196 |
+
risk_score = result.get("risk_score", 0)
|
| 197 |
+
is_high_risk = risk_score >= 50
|
| 198 |
+
|
| 199 |
+
return {
|
| 200 |
+
"success": True,
|
| 201 |
+
"model_used": False,
|
| 202 |
+
"fallback_used": True,
|
| 203 |
+
"risk_score": risk_score,
|
| 204 |
+
"is_high_risk": is_high_risk,
|
| 205 |
+
"risk_level": "High Risk" if is_high_risk else "Low Risk",
|
| 206 |
+
"message": predictor.get_recommendation(is_high_risk, risk_score)
|
| 207 |
+
}
|
| 208 |
|
| 209 |
+
return result
|
|
|
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
except Exception as e:
|
| 212 |
return {
|
| 213 |
"success": False,
|
| 214 |
"error": str(e)
|
| 215 |
}
|
| 216 |
|
| 217 |
+
# Create a comprehensive Gradio interface
|
| 218 |
+
with gr.Blocks(
|
| 219 |
+
title="GlucoCheck AI - Diabetes Prediction",
|
| 220 |
+
css="""
|
| 221 |
+
.gradio-container {
|
| 222 |
+
max-width: 900px;
|
| 223 |
+
margin: auto;
|
| 224 |
+
}
|
| 225 |
+
.header {
|
| 226 |
+
text-align: center;
|
| 227 |
+
margin-bottom: 30px;
|
| 228 |
+
}
|
| 229 |
+
.header h1 {
|
| 230 |
+
color: #2E384D;
|
| 231 |
+
font-size: 36px;
|
| 232 |
+
margin-bottom: 10px;
|
| 233 |
+
}
|
| 234 |
+
.header p {
|
| 235 |
+
color: #6B7280;
|
| 236 |
+
font-size: 16px;
|
| 237 |
+
}
|
| 238 |
+
.metric-card {
|
| 239 |
+
background: linear-gradient(135deg, #f8fafc, #f1f5f9);
|
| 240 |
+
padding: 15px;
|
| 241 |
+
border-radius: 10px;
|
| 242 |
+
border: 1px solid #e2e8f0;
|
| 243 |
+
margin-bottom: 10px;
|
| 244 |
+
}
|
| 245 |
+
.vital-metric {
|
| 246 |
+
background: linear-gradient(135deg, #fef2f2, #fef7ed);
|
| 247 |
+
padding: 20px;
|
| 248 |
+
border-radius: 12px;
|
| 249 |
+
border: 2px solid #fecaca;
|
| 250 |
+
margin-bottom: 15px;
|
| 251 |
+
}
|
| 252 |
+
.result-high-risk {
|
| 253 |
+
background: linear-gradient(135deg, #fef2f2, #fee2e2);
|
| 254 |
+
border-left: 5px solid #EF4444;
|
| 255 |
+
padding: 20px;
|
| 256 |
+
border-radius: 10px;
|
| 257 |
+
margin: 15px 0;
|
| 258 |
+
}
|
| 259 |
+
.result-low-risk {
|
| 260 |
+
background: linear-gradient(135deg, #f0fdf4, #dcfce7);
|
| 261 |
+
border-left: 5px solid #10B981;
|
| 262 |
+
padding: 20px;
|
| 263 |
+
border-radius: 10px;
|
| 264 |
+
margin: 15px 0;
|
| 265 |
+
}
|
| 266 |
+
.analyze-btn {
|
| 267 |
+
background: linear-gradient(135deg, #4361ee, #3a56d4);
|
| 268 |
+
color: white;
|
| 269 |
+
padding: 15px 30px;
|
| 270 |
+
border-radius: 12px;
|
| 271 |
+
font-weight: 600;
|
| 272 |
+
font-size: 16px;
|
| 273 |
+
border: none;
|
| 274 |
+
margin-top: 20px;
|
| 275 |
+
width: 100%;
|
| 276 |
+
}
|
| 277 |
+
.analyze-btn:hover {
|
| 278 |
+
background: linear-gradient(135deg, #3a56d4, #304bc0);
|
| 279 |
+
}
|
| 280 |
+
.disclaimer {
|
| 281 |
+
margin-top: 30px;
|
| 282 |
+
padding-top: 20px;
|
| 283 |
+
border-top: 1px solid #e2e8f0;
|
| 284 |
+
color: #6B7280;
|
| 285 |
+
font-size: 12px;
|
| 286 |
+
text-align: center;
|
| 287 |
+
}
|
| 288 |
+
.model-status {
|
| 289 |
+
padding: 10px;
|
| 290 |
+
border-radius: 8px;
|
| 291 |
+
margin: 10px 0;
|
| 292 |
+
text-align: center;
|
| 293 |
+
}
|
| 294 |
+
.model-success {
|
| 295 |
+
background: #10B98120;
|
| 296 |
+
color: #10B981;
|
| 297 |
+
border: 1px solid #10B981;
|
| 298 |
+
}
|
| 299 |
+
.model-warning {
|
| 300 |
+
background: #F59E0B20;
|
| 301 |
+
color: #F59E0B;
|
| 302 |
+
border: 1px solid #F59E0B;
|
| 303 |
+
}
|
| 304 |
+
"""
|
| 305 |
+
) as demo:
|
| 306 |
+
|
| 307 |
+
# Header
|
| 308 |
+
gr.HTML("""
|
| 309 |
+
<div class="header">
|
| 310 |
+
<h1> GlucoCheck AI - Diabetes Prediction</h1>
|
| 311 |
+
<p>Advanced ML-based diabetes risk assessment using trained models</p>
|
| 312 |
+
</div>
|
| 313 |
+
""")
|
| 314 |
+
|
| 315 |
+
# Model status display
|
| 316 |
+
model_status = gr.HTML("""
|
| 317 |
+
<div class="model-status model-success">
|
| 318 |
+
<strong>✓ ML Model Status:</strong> Ready for predictions
|
| 319 |
+
</div>
|
| 320 |
+
""") if predictor.model is not None else gr.HTML("""
|
| 321 |
+
<div class="model-status model-warning">
|
| 322 |
+
<strong>⚠ ML Model Status:</strong> Using fallback prediction logic
|
| 323 |
+
</div>
|
| 324 |
+
""")
|
| 325 |
|
| 326 |
+
gr.Markdown("### Enter Patient Information")
|
| 327 |
+
|
| 328 |
+
# Input fields in two columns
|
| 329 |
with gr.Row():
|
| 330 |
+
with gr.Column():
|
| 331 |
+
age = gr.Number(
|
| 332 |
+
label="Age (Years)",
|
| 333 |
+
value=30,
|
| 334 |
+
minimum=0,
|
| 335 |
+
maximum=120,
|
| 336 |
+
step=1,
|
| 337 |
+
elem_classes="metric-card"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
bmi = gr.Number(
|
| 341 |
+
label="BMI (kg/m²)",
|
| 342 |
+
value=25.0,
|
| 343 |
+
minimum=10,
|
| 344 |
+
maximum=60,
|
| 345 |
+
step=0.1,
|
| 346 |
+
elem_classes="metric-card"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
pregnancies = gr.Number(
|
| 350 |
+
label="Number of Pregnancies",
|
| 351 |
+
value=0,
|
| 352 |
+
minimum=0,
|
| 353 |
+
maximum=20,
|
| 354 |
+
step=1,
|
| 355 |
+
elem_classes="metric-card"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
with gr.Column():
|
| 359 |
+
glucose = gr.Number(
|
| 360 |
+
label="Glucose Level (mg/dL)",
|
| 361 |
+
value=100.0,
|
| 362 |
+
minimum=50,
|
| 363 |
+
maximum=300,
|
| 364 |
+
step=1.0,
|
| 365 |
+
elem_classes="vital-metric"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
blood_pressure = gr.Number(
|
| 369 |
+
label="Blood Pressure (mm Hg)",
|
| 370 |
+
value=120.0,
|
| 371 |
+
minimum=60,
|
| 372 |
+
maximum=200,
|
| 373 |
+
step=1.0,
|
| 374 |
+
elem_classes="metric-card"
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
insulin = gr.Number(
|
| 378 |
+
label="Insulin Level (mu U/ml)",
|
| 379 |
+
value=15.0,
|
| 380 |
+
minimum=0,
|
| 381 |
+
maximum=100,
|
| 382 |
+
step=0.1,
|
| 383 |
+
elem_classes="metric-card"
|
| 384 |
+
)
|
| 385 |
|
| 386 |
+
# Additional features that might be in your model
|
| 387 |
with gr.Row():
|
| 388 |
+
with gr.Column():
|
| 389 |
+
skin_thickness = gr.Number(
|
| 390 |
+
label="Skin Thickness (mm)",
|
| 391 |
+
value=20.0,
|
| 392 |
+
minimum=0,
|
| 393 |
+
maximum=100,
|
| 394 |
+
step=0.1,
|
| 395 |
+
elem_classes="metric-card"
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
with gr.Column():
|
| 399 |
+
diabetes_pedigree = gr.Number(
|
| 400 |
+
label="Diabetes Pedigree Function",
|
| 401 |
+
value=0.5,
|
| 402 |
+
minimum=0,
|
| 403 |
+
maximum=2.5,
|
| 404 |
+
step=0.01,
|
| 405 |
+
elem_classes="metric-card"
|
| 406 |
+
)
|
| 407 |
|
| 408 |
+
# Symptoms section
|
| 409 |
gr.Markdown("### Symptoms")
|
| 410 |
with gr.Row():
|
| 411 |
increased_thirst = gr.Checkbox(label="Increased Thirst")
|
|
|
|
| 416 |
blurred_vision = gr.Checkbox(label="Blurred Vision")
|
| 417 |
weight_loss = gr.Checkbox(label="Weight Loss")
|
| 418 |
|
|
|
|
|
|
|
|
|
|
| 419 |
# Predict button
|
| 420 |
+
predict_btn = gr.Button(" Analyze Diabetes Risk", variant="primary", elem_classes="analyze-btn")
|
| 421 |
+
|
| 422 |
+
# Output sections
|
| 423 |
+
gr.Markdown("### Prediction Results")
|
| 424 |
+
|
| 425 |
+
with gr.Row():
|
| 426 |
+
with gr.Column():
|
| 427 |
+
risk_score_output = gr.Number(label="Risk Score (%)", interactive=False)
|
| 428 |
+
risk_level_output = gr.Textbox(label="Risk Level", interactive=False)
|
| 429 |
+
model_used_output = gr.Textbox(label="Prediction Method", interactive=False)
|
| 430 |
+
|
| 431 |
+
with gr.Column():
|
| 432 |
+
result_output = gr.HTML(label="Detailed Analysis")
|
| 433 |
+
|
| 434 |
+
# Recommendations output
|
| 435 |
+
recommendations_output = gr.Textbox(
|
| 436 |
+
label="Recommendations",
|
| 437 |
+
interactive=False,
|
| 438 |
+
lines=4
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
# Raw JSON output for debugging/API
|
| 442 |
+
json_output = gr.JSON(label="Raw API Response")
|
| 443 |
|
| 444 |
# Prediction function
|
| 445 |
+
def predict_risk(
|
| 446 |
age_val, bmi_val, glucose_val, bp_val, insulin_val,
|
| 447 |
+
pregnancies_val, skin_val, pedigree_val,
|
| 448 |
thirst, hunger, fatigue_val, vision, weight
|
| 449 |
):
|
| 450 |
+
# Prepare data dictionary
|
| 451 |
data = {
|
| 452 |
"age": age_val,
|
| 453 |
"bmi": bmi_val,
|
| 454 |
"glucose": glucose_val,
|
| 455 |
"blood_pressure": bp_val,
|
| 456 |
"insulin": insulin_val,
|
| 457 |
+
"pregnancies": pregnancies_val,
|
| 458 |
+
"skin_thickness": skin_val,
|
| 459 |
+
"diabetes_pedigree": pedigree_val,
|
| 460 |
"increased_thirst": thirst,
|
| 461 |
"increased_hunger": hunger,
|
| 462 |
"fatigue": fatigue_val,
|
| 463 |
"blurred_vision": vision,
|
| 464 |
"weight_loss": weight
|
| 465 |
}
|
| 466 |
+
|
| 467 |
+
# Get prediction
|
| 468 |
+
result = calculate_diabetes_risk_api(data)
|
| 469 |
+
|
| 470 |
+
# Prepare outputs
|
| 471 |
+
if result.get("success", False):
|
| 472 |
+
risk_score = result.get("risk_score", 0)
|
| 473 |
+
risk_level = result.get("risk_level", "Unknown")
|
| 474 |
+
model_used = "ML Model" if result.get("model_used", False) else "Fallback Logic"
|
| 475 |
+
message = result.get("message", "")
|
| 476 |
+
|
| 477 |
+
# Create HTML result display
|
| 478 |
+
if result.get("is_high_risk", False):
|
| 479 |
+
result_html = f"""
|
| 480 |
+
<div class="result-high-risk">
|
| 481 |
+
<h3 style="color: #EF4444; margin-top: 0;"> HIGH RISK DETECTED</h3>
|
| 482 |
+
<p><strong>Risk Score:</strong> {risk_score:.1f}%</p>
|
| 483 |
+
<p><strong>Confidence:</strong> {result.get('confidence', 'N/A')}%</p>
|
| 484 |
+
<p><strong>Prediction:</strong> Diabetes likely present</p>
|
| 485 |
+
</div>
|
| 486 |
+
"""
|
| 487 |
+
else:
|
| 488 |
+
result_html = f"""
|
| 489 |
+
<div class="result-low-risk">
|
| 490 |
+
<h3 style="color: #10B981; margin-top: 0;"> LOW RISK</h3>
|
| 491 |
+
<p><strong>Risk Score:</strong> {risk_score:.1f}%</p>
|
| 492 |
+
<p><strong>Confidence:</strong> {result.get('confidence', 'N/A')}%</p>
|
| 493 |
+
<p><strong>Prediction:</strong> Diabetes unlikely</p>
|
| 494 |
+
</div>
|
| 495 |
+
"""
|
| 496 |
+
|
| 497 |
+
return {
|
| 498 |
+
risk_score_output: risk_score,
|
| 499 |
+
risk_level_output: risk_level,
|
| 500 |
+
model_used_output: model_used,
|
| 501 |
+
result_output: result_html,
|
| 502 |
+
recommendations_output: message,
|
| 503 |
+
json_output: result
|
| 504 |
+
}
|
| 505 |
+
else:
|
| 506 |
+
error_html = f"""
|
| 507 |
+
<div style="
|
| 508 |
+
background: #FEF2F2;
|
| 509 |
+
border-left: 5px solid #EF4444;
|
| 510 |
+
padding: 20px;
|
| 511 |
+
border-radius: 10px;
|
| 512 |
+
margin: 15px 0;
|
| 513 |
+
">
|
| 514 |
+
<h3 style="color: #EF4444; margin-top: 0;"> Error</h3>
|
| 515 |
+
<p>{result.get('error', 'Unknown error occurred')}</p>
|
| 516 |
+
</div>
|
| 517 |
+
"""
|
| 518 |
+
|
| 519 |
+
return {
|
| 520 |
+
risk_score_output: 0,
|
| 521 |
+
risk_level_output: "Error",
|
| 522 |
+
model_used_output: "Error",
|
| 523 |
+
result_output: error_html,
|
| 524 |
+
recommendations_output: "Please check your inputs and try again.",
|
| 525 |
+
json_output: result
|
| 526 |
+
}
|
| 527 |
|
| 528 |
+
# Connect predict button
|
| 529 |
predict_btn.click(
|
| 530 |
+
predict_risk,
|
| 531 |
inputs=[
|
| 532 |
age, bmi, glucose, blood_pressure, insulin,
|
| 533 |
+
pregnancies, skin_thickness, diabetes_pedigree,
|
| 534 |
increased_thirst, increased_hunger, fatigue, blurred_vision, weight_loss
|
| 535 |
],
|
| 536 |
+
outputs=[
|
| 537 |
+
risk_score_output, risk_level_output, model_used_output,
|
| 538 |
+
result_output, recommendations_output, json_output
|
| 539 |
+
]
|
| 540 |
)
|
| 541 |
+
|
| 542 |
+
# API documentation
|
| 543 |
+
gr.Markdown("### API Usage")
|
| 544 |
+
gr.Markdown("""
|
| 545 |
+
You can also use this as an API endpoint:
|
| 546 |
+
|
| 547 |
+
```bash
|
| 548 |
+
curl -X POST https://your-space.hf.space/api/predict \\
|
| 549 |
+
-H "Content-Type: application/json" \\
|
| 550 |
+
-d '{
|
| 551 |
+
"age": 45,
|
| 552 |
+
"bmi": 28.5,
|
| 553 |
+
"glucose": 150,
|
| 554 |
+
"blood_pressure": 130,
|
| 555 |
+
"insulin": 20,
|
| 556 |
+
"pregnancies": 0,
|
| 557 |
+
"skin_thickness": 25,
|
| 558 |
+
"diabetes_pedigree": 0.6,
|
| 559 |
+
"increased_thirst": true,
|
| 560 |
+
"increased_hunger": false,
|
| 561 |
+
"fatigue": true,
|
| 562 |
+
"blurred_vision": false,
|
| 563 |
+
"weight_loss": true
|
| 564 |
+
}'
|
| 565 |
+
```
|
| 566 |
+
""")
|
| 567 |
+
|
| 568 |
+
# Footer
|
| 569 |
+
gr.HTML("""
|
| 570 |
+
<div class="disclaimer">
|
| 571 |
+
<p><strong> Medical Disclaimer:</strong> This tool is for informational purposes only and is not a substitute for professional medical advice, diagnosis, or treatment.</p>
|
| 572 |
+
<p>Always seek the advice of your physician or other qualified health provider with any questions you may have regarding a medical condition.</p>
|
| 573 |
+
<p>Model file: {'Loaded' if predictor.model is not None else 'Not found'}</p>
|
| 574 |
+
</div>
|
| 575 |
+
""")
|
| 576 |
|
| 577 |
# Mount Gradio app
|
| 578 |
app = gr.mount_gradio_app(app, demo, path="/")
|