parass13 commited on
Commit
104a413
·
verified ·
1 Parent(s): 85bdbf2

Update components/predict.py

Browse files
Files changed (1) hide show
  1. components/predict.py +36 -12
components/predict.py CHANGED
@@ -1,20 +1,44 @@
1
- import gradio as gr
 
2
  import pickle
3
  import numpy as np
4
  from utils.db import log_prediction
5
- from components.auth import user_session
6
 
7
- model = pickle.load(open("model.pkl", "rb"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- def predict(pregnancies, glucose, blood_pressure, insulin, bmi, age):
10
- if not user_session["email"]:
11
- return "❌ Please log in first."
12
 
13
- data = [pregnancies, glucose, blood_pressure, insulin, bmi, age]
14
- data_np = np.array(data).reshape(1, -1)
 
 
 
 
 
15
 
16
- prediction = model.predict(data_np)[0]
17
- result = "✅ Diabetic" if prediction == 1 else "🟢 Not Diabetic"
 
 
18
 
19
- log_prediction(data, int(prediction), user_session["email"])
20
- return result
 
1
+ # components/predict.py
2
+
3
  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. Please run the 'create_dummy_model.py' script first.")
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 on the 'Login / Signup' tab before making a prediction."
21
+
22
+ # Validate inputs
23
+ if any(v is None for v in [pregnancies, glucose, blood_pressure, insulin, bmi, age]):
24
+ return "❌ Please fill in all the fields."
25
 
26
+ # Prepare the data for the model
27
+ input_data = [pregnancies, glucose, blood_pressure, insulin, bmi, age]
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 the prediction to the database in the background
39
+ log_prediction(input_data, result_text, user_state["email"])
40
+
41
+ return final_result
42
 
43
+ except Exception as e:
44
+ return f"An error occurred during prediction: {e}"