Update components/predict.py
Browse files- components/predict.py +15 -23
components/predict.py
CHANGED
|
@@ -4,41 +4,33 @@ import pickle
|
|
| 4 |
import numpy as np
|
| 5 |
from utils.db import log_prediction
|
| 6 |
|
| 7 |
-
# Load the machine learning model from the file
|
| 8 |
try:
|
| 9 |
model = pickle.load(open("model.pkl", "rb"))
|
| 10 |
except FileNotFoundError:
|
| 11 |
-
raise RuntimeError("The 'model.pkl' file was not found.
|
| 12 |
-
|
| 13 |
|
| 14 |
def predict(pregnancies, glucose, blood_pressure, insulin, bmi, age, user_state):
|
| 15 |
-
"""
|
| 16 |
-
Performs diabetes prediction based on user input.
|
| 17 |
-
"""
|
| 18 |
-
# First, check if the user is logged in by checking the user_state
|
| 19 |
if not user_state.get("logged_in"):
|
| 20 |
-
return "❌ Please log in
|
| 21 |
-
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
| 28 |
data_np = np.array(input_data).reshape(1, -1)
|
| 29 |
-
|
| 30 |
-
# Make the prediction
|
| 31 |
try:
|
| 32 |
prediction = model.predict(data_np)[0]
|
| 33 |
result_text = "Diabetic" if prediction == 1 else "Not Diabetic"
|
| 34 |
-
|
| 35 |
-
# Format the result with an emoji
|
| 36 |
final_result = f"✅ Result: {result_text}"
|
| 37 |
-
|
| 38 |
-
# Log
|
| 39 |
-
|
|
|
|
| 40 |
|
| 41 |
return final_result
|
| 42 |
-
|
| 43 |
except Exception as e:
|
| 44 |
return f"An error occurred during prediction: {e}"
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
from utils.db import log_prediction
|
| 6 |
|
|
|
|
| 7 |
try:
|
| 8 |
model = pickle.load(open("model.pkl", "rb"))
|
| 9 |
except FileNotFoundError:
|
| 10 |
+
raise RuntimeError("The 'model.pkl' file was not found.")
|
|
|
|
| 11 |
|
| 12 |
def predict(pregnancies, glucose, blood_pressure, insulin, bmi, age, user_state):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
if not user_state.get("logged_in"):
|
| 14 |
+
return "❌ Please log in first."
|
| 15 |
+
|
| 16 |
+
# If pregnancies field is hidden (None), default to 0 for the model
|
| 17 |
+
pregnancies_value = pregnancies if pregnancies is not None else 0
|
| 18 |
+
|
| 19 |
+
if any(v is None for v in [glucose, blood_pressure, insulin, bmi, age]):
|
| 20 |
+
return "❌ Please fill in all the non-optional fields."
|
| 21 |
+
|
| 22 |
+
input_data = [pregnancies_value, glucose, blood_pressure, insulin, bmi, age]
|
| 23 |
data_np = np.array(input_data).reshape(1, -1)
|
| 24 |
+
|
|
|
|
| 25 |
try:
|
| 26 |
prediction = model.predict(data_np)[0]
|
| 27 |
result_text = "Diabetic" if prediction == 1 else "Not Diabetic"
|
|
|
|
|
|
|
| 28 |
final_result = f"✅ Result: {result_text}"
|
| 29 |
+
|
| 30 |
+
# Log prediction if user ID exists
|
| 31 |
+
if user_state.get("id"):
|
| 32 |
+
log_prediction(input_data, result_text, user_state["id"])
|
| 33 |
|
| 34 |
return final_result
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
return f"An error occurred during prediction: {e}"
|