Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,13 +12,8 @@ app = Flask(__name__, template_folder='templates')
|
|
| 12 |
|
| 13 |
auth = HTTPBasicAuth()
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
model = joblib.load('stroke_prediction_model.pkl')
|
| 18 |
-
print("Model loaded successfully.")
|
| 19 |
-
except Exception as e:
|
| 20 |
-
print(f"Error loading model: {str(e)}")
|
| 21 |
-
model = None
|
| 22 |
|
| 23 |
# Admin credentials for report access
|
| 24 |
users = {
|
|
@@ -33,7 +28,7 @@ def verify_password(username, password):
|
|
| 33 |
|
| 34 |
# Initialize SQLite database
|
| 35 |
def init_db():
|
| 36 |
-
conn = sqlite3.connect('/tmp/submissions.db')
|
| 37 |
c = conn.cursor()
|
| 38 |
c.execute('''
|
| 39 |
CREATE TABLE IF NOT EXISTS submissions (
|
|
@@ -64,18 +59,22 @@ def home():
|
|
| 64 |
|
| 65 |
@app.route('/predict', methods=['POST'])
|
| 66 |
def predict():
|
|
|
|
| 67 |
if model is None:
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
try:
|
| 71 |
-
# Get form data
|
| 72 |
data = request.json
|
| 73 |
if not data or 'input' not in data:
|
| 74 |
return jsonify({'success': False, 'error': 'Invalid input data'}), 400
|
| 75 |
input_data = data['input']
|
| 76 |
print(f"Received input data: {input_data}")
|
| 77 |
|
| 78 |
-
# Prepare data for model
|
| 79 |
features = {
|
| 80 |
'age': float(input_data.get('age', 0)),
|
| 81 |
'gender': input_data.get('gender', 'Unknown'),
|
|
@@ -90,14 +89,10 @@ def predict():
|
|
| 90 |
}
|
| 91 |
print(f"Processed features: {features}")
|
| 92 |
|
| 93 |
-
# Convert to DataFrame
|
| 94 |
df = pd.DataFrame([features])
|
| 95 |
-
|
| 96 |
-
# One-hot encode categorical variables
|
| 97 |
categorical_cols = ['gender', 'ever_married', 'Residence_type', 'work_type', 'smoking_status']
|
| 98 |
df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)
|
| 99 |
|
| 100 |
-
# Get expected columns from the model
|
| 101 |
expected_columns = model.feature_names_in_ if hasattr(model, 'feature_names_in_') else [
|
| 102 |
'age', 'hypertension', 'heart_disease', 'avg_glucose_level', 'bmi',
|
| 103 |
'gender_Male', 'gender_Other', 'ever_married_Yes', 'Residence_type_Urban',
|
|
@@ -108,17 +103,14 @@ def predict():
|
|
| 108 |
]
|
| 109 |
print(f"Expected columns: {expected_columns}")
|
| 110 |
|
| 111 |
-
# Align DataFrame with expected columns
|
| 112 |
for col in expected_columns:
|
| 113 |
if col not in df.columns:
|
| 114 |
df[col] = 0
|
| 115 |
df = df[expected_columns]
|
| 116 |
|
| 117 |
-
|
| 118 |
-
probability = model.predict_proba(df)[0][1] * 100 # Probability of stroke
|
| 119 |
risk_level = 'High' if probability > 50 else 'Moderate' if probability > 25 else 'Low'
|
| 120 |
|
| 121 |
-
# Determine contributing factors
|
| 122 |
contributing_factors = {
|
| 123 |
'age': features['age'] > 45,
|
| 124 |
'hypertension': features['hypertension'] == 1,
|
|
@@ -127,7 +119,6 @@ def predict():
|
|
| 127 |
'smoking': features['smoking_status'] in ['smokes', 'formerly smoked']
|
| 128 |
}
|
| 129 |
|
| 130 |
-
# Log submission to database
|
| 131 |
conn = sqlite3.connect('/tmp/submissions.db')
|
| 132 |
c = conn.cursor()
|
| 133 |
c.execute('''
|
|
@@ -154,7 +145,6 @@ def predict():
|
|
| 154 |
conn.commit()
|
| 155 |
conn.close()
|
| 156 |
|
| 157 |
-
# Return prediction result
|
| 158 |
return jsonify({
|
| 159 |
'success': True,
|
| 160 |
'probability': round(probability),
|
|
@@ -177,7 +167,6 @@ def admin_report():
|
|
| 177 |
if df.empty:
|
| 178 |
return "No submissions for today.", 200
|
| 179 |
|
| 180 |
-
# Prepare data for Excel
|
| 181 |
df['hypertension'] = df['hypertension'].apply(lambda x: 'Yes' if x == 1 else 'No')
|
| 182 |
df['heart_disease'] = df['heart_disease'].apply(lambda x: 'Yes' if x == 1 else 'No')
|
| 183 |
df = df[[
|
|
@@ -191,7 +180,6 @@ def admin_report():
|
|
| 191 |
'Probability (%)', 'Risk Level'
|
| 192 |
]
|
| 193 |
|
| 194 |
-
# Create Excel file in memory
|
| 195 |
output = io.BytesIO()
|
| 196 |
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
|
| 197 |
df.to_excel(writer, sheet_name='Daily Report', index=False)
|
|
@@ -201,7 +189,6 @@ def admin_report():
|
|
| 201 |
worksheet.set_column(idx, idx, max_len)
|
| 202 |
output.seek(0)
|
| 203 |
|
| 204 |
-
# Send file
|
| 205 |
return send_file(
|
| 206 |
output,
|
| 207 |
download_name=f'report_{today}.xlsx',
|
|
|
|
| 12 |
|
| 13 |
auth = HTTPBasicAuth()
|
| 14 |
|
| 15 |
+
# Global variable to hold the model (lazy-loaded)
|
| 16 |
+
model = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Admin credentials for report access
|
| 19 |
users = {
|
|
|
|
| 28 |
|
| 29 |
# Initialize SQLite database
|
| 30 |
def init_db():
|
| 31 |
+
conn = sqlite3.connect('/tmp/submissions.db')
|
| 32 |
c = conn.cursor()
|
| 33 |
c.execute('''
|
| 34 |
CREATE TABLE IF NOT EXISTS submissions (
|
|
|
|
| 59 |
|
| 60 |
@app.route('/predict', methods=['POST'])
|
| 61 |
def predict():
|
| 62 |
+
global model
|
| 63 |
if model is None:
|
| 64 |
+
try:
|
| 65 |
+
model = joblib.load('stroke_prediction_model.pkl')
|
| 66 |
+
print("Model loaded successfully during first predict request.")
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"Error loading model: {str(e)}")
|
| 69 |
+
return jsonify({'success': False, 'error': 'Model failed to load'}), 500
|
| 70 |
|
| 71 |
try:
|
|
|
|
| 72 |
data = request.json
|
| 73 |
if not data or 'input' not in data:
|
| 74 |
return jsonify({'success': False, 'error': 'Invalid input data'}), 400
|
| 75 |
input_data = data['input']
|
| 76 |
print(f"Received input data: {input_data}")
|
| 77 |
|
|
|
|
| 78 |
features = {
|
| 79 |
'age': float(input_data.get('age', 0)),
|
| 80 |
'gender': input_data.get('gender', 'Unknown'),
|
|
|
|
| 89 |
}
|
| 90 |
print(f"Processed features: {features}")
|
| 91 |
|
|
|
|
| 92 |
df = pd.DataFrame([features])
|
|
|
|
|
|
|
| 93 |
categorical_cols = ['gender', 'ever_married', 'Residence_type', 'work_type', 'smoking_status']
|
| 94 |
df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)
|
| 95 |
|
|
|
|
| 96 |
expected_columns = model.feature_names_in_ if hasattr(model, 'feature_names_in_') else [
|
| 97 |
'age', 'hypertension', 'heart_disease', 'avg_glucose_level', 'bmi',
|
| 98 |
'gender_Male', 'gender_Other', 'ever_married_Yes', 'Residence_type_Urban',
|
|
|
|
| 103 |
]
|
| 104 |
print(f"Expected columns: {expected_columns}")
|
| 105 |
|
|
|
|
| 106 |
for col in expected_columns:
|
| 107 |
if col not in df.columns:
|
| 108 |
df[col] = 0
|
| 109 |
df = df[expected_columns]
|
| 110 |
|
| 111 |
+
probability = model.predict_proba(df)[0][1] * 100
|
|
|
|
| 112 |
risk_level = 'High' if probability > 50 else 'Moderate' if probability > 25 else 'Low'
|
| 113 |
|
|
|
|
| 114 |
contributing_factors = {
|
| 115 |
'age': features['age'] > 45,
|
| 116 |
'hypertension': features['hypertension'] == 1,
|
|
|
|
| 119 |
'smoking': features['smoking_status'] in ['smokes', 'formerly smoked']
|
| 120 |
}
|
| 121 |
|
|
|
|
| 122 |
conn = sqlite3.connect('/tmp/submissions.db')
|
| 123 |
c = conn.cursor()
|
| 124 |
c.execute('''
|
|
|
|
| 145 |
conn.commit()
|
| 146 |
conn.close()
|
| 147 |
|
|
|
|
| 148 |
return jsonify({
|
| 149 |
'success': True,
|
| 150 |
'probability': round(probability),
|
|
|
|
| 167 |
if df.empty:
|
| 168 |
return "No submissions for today.", 200
|
| 169 |
|
|
|
|
| 170 |
df['hypertension'] = df['hypertension'].apply(lambda x: 'Yes' if x == 1 else 'No')
|
| 171 |
df['heart_disease'] = df['heart_disease'].apply(lambda x: 'Yes' if x == 1 else 'No')
|
| 172 |
df = df[[
|
|
|
|
| 180 |
'Probability (%)', 'Risk Level'
|
| 181 |
]
|
| 182 |
|
|
|
|
| 183 |
output = io.BytesIO()
|
| 184 |
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
|
| 185 |
df.to_excel(writer, sheet_name='Daily Report', index=False)
|
|
|
|
| 189 |
worksheet.set_column(idx, idx, max_len)
|
| 190 |
output.seek(0)
|
| 191 |
|
|
|
|
| 192 |
return send_file(
|
| 193 |
output,
|
| 194 |
download_name=f'report_{today}.xlsx',
|