omaralaa2004 commited on
Commit
e84de77
·
verified ·
1 Parent(s): b31a381

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -52
app.py CHANGED
@@ -7,6 +7,7 @@ import io
7
  from datetime import datetime
8
  import xlsxwriter
9
  from flask_httpauth import HTTPBasicAuth
 
10
 
11
  app = Flask(__name__, template_folder='templates')
12
  app.config['WTF_CSRF_ENABLED'] = False # Disable CSRF for testing
@@ -29,28 +30,35 @@ def verify_password(username, password):
29
 
30
  # Initialize SQLite database
31
  def init_db():
32
- conn = sqlite3.connect('/tmp/submissions.db')
33
- c = conn.cursor()
34
- c.execute('''
35
- CREATE TABLE IF NOT EXISTS submissions (
36
- id INTEGER PRIMARY KEY AUTOINCREMENT,
37
- timestamp TEXT,
38
- age REAL,
39
- gender TEXT,
40
- ever_married TEXT,
41
- residence_type TEXT,
42
- work_type TEXT,
43
- hypertension INTEGER,
44
- heart_disease INTEGER,
45
- avg_glucose_level REAL,
46
- bmi REAL,
47
- smoking_status TEXT,
48
- probability INTEGER,
49
- risk_level TEXT
50
- )
51
- ''')
52
- conn.commit()
53
- conn.close()
 
 
 
 
 
 
 
54
 
55
  init_db()
56
 
@@ -63,15 +71,24 @@ def home():
63
  def predict():
64
  global model
65
  print("Received predict request at /predict endpoint")
 
 
 
 
 
 
 
 
66
  if model is None:
67
  try:
68
- model = joblib.load('stroke_prediction_model.pkl')
69
- print("Model loaded successfully during first predict request")
70
  except Exception as e:
71
  print(f"Error loading model: {str(e)}")
72
  return jsonify({'success': False, 'error': f'Model failed to load: {str(e)}'}), 500
73
 
74
  try:
 
75
  data = request.json
76
  print(f"Received JSON data: {data}")
77
  if not data or 'input' not in data:
@@ -99,6 +116,7 @@ def predict():
99
  df = pd.DataFrame([features])
100
  categorical_cols = ['gender', 'ever_married', 'residence_type', 'work_type', 'smoking_status']
101
  df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)
 
102
 
103
  # Define expected columns based on model training
104
  expected_columns = model.feature_names_in_ if hasattr(model, 'feature_names_in_') else [
@@ -116,10 +134,12 @@ def predict():
116
  if col not in df.columns:
117
  df[col] = 0
118
  df = df[expected_columns]
 
119
 
120
  # Make prediction
121
  probability = model.predict_proba(df)[0][1] * 100
122
  risk_prediction = "Stroke Risk" if probability > 50 else "No Stroke Risk"
 
123
 
124
  # Determine contributing factors
125
  contributing_factors = {
@@ -128,35 +148,43 @@ def predict():
128
  'heartDisease': features['heart_disease'] == 1,
129
  'smoking': features['smoking_status'] in ['smokes', 'formerly smoked']
130
  }
 
131
 
132
- # Store in database
133
- conn = sqlite3.connect('/tmp/submissions.db')
134
- c = conn.cursor()
135
- c.execute('''
136
- INSERT INTO submissions (
137
- timestamp, age, gender, ever_married, residence_type, work_type,
138
- hypertension, heart_disease, avg_glucose_level, bmi, smoking_status,
139
- probability, risk_level
140
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
141
- ''', (
142
- datetime.now().isoformat(),
143
- features['age'],
144
- features['gender'],
145
- features['ever_married'],
146
- features['residence_type'],
147
- features['work_type'],
148
- features['hypertension'],
149
- features['heart_disease'],
150
- features['avg_glucose_level'],
151
- features['bmi'],
152
- features['smoking_status'],
153
- round(probability),
154
- risk_prediction
155
- ))
156
- conn.commit()
157
- conn.close()
158
-
159
- print(f"Prediction success: probability={probability}%, prediction={risk_prediction}")
 
 
 
 
 
 
 
160
  return jsonify({
161
  'success': True,
162
  'prediction': risk_prediction,
 
7
  from datetime import datetime
8
  import xlsxwriter
9
  from flask_httpauth import HTTPBasicAuth
10
+ import os
11
 
12
  app = Flask(__name__, template_folder='templates')
13
  app.config['WTF_CSRF_ENABLED'] = False # Disable CSRF for testing
 
30
 
31
  # Initialize SQLite database
32
  def init_db():
33
+ db_path = '/tmp/submissions.db'
34
+ print(f"Initializing database at {db_path}")
35
+ try:
36
+ conn = sqlite3.connect(db_path)
37
+ c = conn.cursor()
38
+ c.execute('''
39
+ CREATE TABLE IF NOT EXISTS submissions (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ timestamp TEXT,
42
+ age REAL,
43
+ gender TEXT,
44
+ ever_married TEXT,
45
+ residence_type TEXT,
46
+ work_type TEXT,
47
+ hypertension INTEGER,
48
+ heart_disease INTEGER,
49
+ avg_glucose_level REAL,
50
+ bmi REAL,
51
+ smoking_status TEXT,
52
+ probability INTEGER,
53
+ risk_level TEXT
54
+ )
55
+ ''')
56
+ conn.commit()
57
+ print("Database initialized successfully")
58
+ except Exception as e:
59
+ print(f"Error initializing database: {str(e)}")
60
+ finally:
61
+ conn.close()
62
 
63
  init_db()
64
 
 
71
  def predict():
72
  global model
73
  print("Received predict request at /predict endpoint")
74
+
75
+ # Check model file existence
76
+ model_path = 'stroke_prediction_model.pkl'
77
+ if not os.path.exists(model_path):
78
+ print(f"Model file not found at {model_path}")
79
+ return jsonify({'success': False, 'error': f'Model file not found at {model_path}'}), 500
80
+
81
+ # Load model if not already loaded
82
  if model is None:
83
  try:
84
+ model = joblib.load(model_path)
85
+ print("Model loaded successfully")
86
  except Exception as e:
87
  print(f"Error loading model: {str(e)}")
88
  return jsonify({'success': False, 'error': f'Model failed to load: {str(e)}'}), 500
89
 
90
  try:
91
+ # Parse incoming data
92
  data = request.json
93
  print(f"Received JSON data: {data}")
94
  if not data or 'input' not in data:
 
116
  df = pd.DataFrame([features])
117
  categorical_cols = ['gender', 'ever_married', 'residence_type', 'work_type', 'smoking_status']
118
  df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)
119
+ print(f"DataFrame after get_dummies: {df.columns.tolist()}")
120
 
121
  # Define expected columns based on model training
122
  expected_columns = model.feature_names_in_ if hasattr(model, 'feature_names_in_') else [
 
134
  if col not in df.columns:
135
  df[col] = 0
136
  df = df[expected_columns]
137
+ print(f"Aligned DataFrame columns: {df.columns.tolist()}")
138
 
139
  # Make prediction
140
  probability = model.predict_proba(df)[0][1] * 100
141
  risk_prediction = "Stroke Risk" if probability > 50 else "No Stroke Risk"
142
+ print(f"Prediction result: probability={probability}%, prediction={risk_prediction}")
143
 
144
  # Determine contributing factors
145
  contributing_factors = {
 
148
  'heartDisease': features['heart_disease'] == 1,
149
  'smoking': features['smoking_status'] in ['smokes', 'formerly smoked']
150
  }
151
+ print(f"Contributing factors: {contributing_factors}")
152
 
153
+ # Temporarily comment out database write to isolate the issue
154
+ """
155
+ try:
156
+ conn = sqlite3.connect('/tmp/submissions.db')
157
+ c = conn.cursor()
158
+ c.execute('''
159
+ INSERT INTO submissions (
160
+ timestamp, age, gender, ever_married, residence_type, work_type,
161
+ hypertension, heart_disease, avg_glucose_level, bmi, smuggling_status,
162
+ probability, risk_level
163
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
164
+ ''', (
165
+ datetime.now().isoformat(),
166
+ features['age'],
167
+ features['gender'],
168
+ features['ever_married'],
169
+ features['residence_type'],
170
+ features['work_type'],
171
+ features['hypertension'],
172
+ features['heart_disease'],
173
+ features['avg_glucose_level'],
174
+ features['bmi'],
175
+ features['smoking_status'],
176
+ round(probability),
177
+ risk_prediction
178
+ ))
179
+ conn.commit()
180
+ print("Data successfully written to database")
181
+ except Exception as db_error:
182
+ print(f"Database write error: {str(db_error)}")
183
+ finally:
184
+ conn.close()
185
+ """
186
+
187
+ # Return prediction result
188
  return jsonify({
189
  'success': True,
190
  'prediction': risk_prediction,