Kayeaelne commited on
Commit
27ca8f1
·
verified ·
1 Parent(s): 0d48446

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -136
app.py CHANGED
@@ -1,144 +1,95 @@
1
  import gradio as gr
 
2
  import numpy as np
3
- from datetime import datetime
4
 
5
- # Function to calculate time difference in hours
6
- def time_difference(last_time):
7
- now = datetime.now()
8
- try:
9
- # Parse the input time in 12-hour format with AM/PM
10
- last_time = datetime.strptime(last_time, "%I:%M %p") # %I for 12-hour format, %p for AM/PM
11
- diff = (now - last_time).total_seconds() / 3600 # Convert to hours
12
- return max(0, diff) # Ensure non-negative
13
- except ValueError:
14
- return None # Invalid input
15
-
16
- # Blood sugar prediction function
17
- def predict_glucose(current_glucose, last_meal, meal_time, last_med, med_time, exercise, fast_carb_amount_ml, liquid_type):
18
- # Convert time inputs to hours elapsed
19
- meal_hours = time_difference(meal_time)
20
- med_hours = time_difference(med_time)
21
-
22
- # Risk scoring system
23
- risk_score_now = 0
24
- risk_score_1hr = 0
25
- risk_score_3hr = 0 # New 3-hour risk score
26
-
27
- # Meal impact
28
- if last_meal == "High Carb":
29
- risk_score_now += 2
30
- risk_score_1hr += 1
31
- risk_score_3hr -= 1 # Carbs wear off after 3 hours
32
- elif last_meal == "Protein/Fat":
33
- risk_score_now -= 1
34
- risk_score_1hr -= 1
35
- risk_score_3hr -= 1
36
- elif last_meal == "Skipped":
37
- risk_score_now -= 2
38
- risk_score_1hr -= 2
39
- risk_score_3hr -= 3 # Fasting for too long may cause hypoglycemia
40
- elif last_meal == "Fast Carb (Juice, Glucose Tablet, etc.)":
41
- # Calculate grams of fast carbs based on liquid type and amount in mL
42
- if liquid_type == "Milk":
43
- fast_carb_amount_grams = fast_carb_amount_ml * 1.03 # Milk density ~1.03g/mL
44
- else:
45
- fast_carb_amount_grams = fast_carb_amount_ml # For other liquids like juice, 1g/mL
46
-
47
- fast_carb_effect = fast_carb_amount_grams * 0.5 # Example: each unit of fast carb raises blood sugar by 5-10 mg/dL
48
- risk_score_now += fast_carb_effect
49
- risk_score_1hr += fast_carb_effect * 0.5 # Less effect after 1 hour
50
- risk_score_3hr -= fast_carb_effect * 0.5 # Glucose may drop after fast carbs wear off
51
-
52
- # Medication impact
53
- if last_med in ["Insulin", "Sulfonylurea"] and med_hours < 5:
54
- risk_score_now -= 3
55
- risk_score_1hr -= 2
56
- risk_score_3hr -= 3 # Long-acting insulin may cause delayed hypoglycemia
57
- elif last_med == "Metformin":
58
- risk_score_now -= 1
59
- risk_score_1hr -= 1
60
- risk_score_3hr -= 1
61
-
62
- # Exercise impact
63
- if exercise > 30:
64
- risk_score_now -= 2
65
- risk_score_1hr -= 1
66
- risk_score_3hr -= 2 # Delayed exercise-related hypoglycemia
67
-
68
- # Time-based adjustments
69
- if meal_hours > 4:
70
- risk_score_now -= 1
71
- risk_score_1hr -= 2
72
- risk_score_3hr -= 3
73
- if med_hours > 8:
74
- risk_score_now += 1
75
- risk_score_1hr += 2
76
- risk_score_3hr += 3
77
-
78
- # Predict glucose levels
79
- predicted_glucose_now = current_glucose + (risk_score_now * 10)
80
- predicted_glucose_1hr = predicted_glucose_now + (risk_score_1hr * 10)
81
- predicted_glucose_3hr = predicted_glucose_1hr + (risk_score_3hr * 10)
82
-
83
- # Keep within realistic limits
84
- predicted_glucose_now = max(40, min(300, predicted_glucose_now))
85
- predicted_glucose_1hr = max(40, min(300, predicted_glucose_1hr))
86
- predicted_glucose_3hr = max(40, min(300, predicted_glucose_3hr))
87
-
88
- # Determine risk level
89
- def glucose_status(glucose):
90
- if glucose < 70:
91
- return "⚠️ Hypoglycemia Risk"
92
- elif glucose > 180:
93
- return "⚠️ Hyperglycemia Risk"
94
- else:
95
- return "✅ Normal Range"
96
-
97
- status_now = glucose_status(predicted_glucose_now)
98
- status_1hr = glucose_status(predicted_glucose_1hr)
99
- status_3hr = glucose_status(predicted_glucose_3hr)
100
-
101
- return (f"**Now:** {predicted_glucose_now:.1f} mg/dL → {status_now}\n"
102
- f"**In 1 Hour:** {predicted_glucose_1hr:.1f} mg/dL → {status_1hr}\n"
103
- f"**In 3 Hours:** {predicted_glucose_3hr:.1f} mg/dL → {status_3hr}")
104
-
105
- # Define Gradio interface
106
- fast_carb_amount_input = gr.Number(label="Amount of Fast Carbs (mL)", value=0)
107
-
108
- # Create the interface components
109
- meal_input = gr.Dropdown(["Fast Carb (Juice, Glucose Tablet, etc.)", "High Carb", "Balanced", "Protein/Fat", "Skipped"], label="Last Meal Type")
110
- meal_time_input = gr.Textbox(label="Time of Last Meal (hh:mm AM/PM)", placeholder="e.g. 1:30 PM")
111
- med_input = gr.Dropdown(["None", "Metformin", "Insulin", "Sulfonylurea"], label="Last Medication Taken")
112
- med_time_input = gr.Textbox(label="Time of Last Medication (hh:mm AM/PM)", placeholder="e.g. 8:00 AM")
113
- exercise_input = gr.Number(label="Exercise in Last 2 Hours (minutes)", value=0)
114
- liquid_type_input = gr.Dropdown(["Milk", "Juice"], label="Liquid Type for Fast Carb")
115
-
116
- # Function to show/hide the fast carb amount input field
117
- def update_fast_carb_visibility(last_meal):
118
- return gr.update(visible=(last_meal == "Fast Carb (Juice, Glucose Tablet, etc.)"))
119
-
120
- # Define Gradio Interface in a Blocks context
121
- with gr.Blocks() as iface:
122
- current_glucose_input = gr.Number(label="Current Blood Glucose (mg/dL)", value=100)
123
- meal_input = gr.Dropdown(["Fast Carb (Juice, Glucose Tablet, etc.)", "High Carb", "Balanced", "Protein/Fat", "Skipped"], label="Last Meal Type")
124
- meal_time_input = gr.Textbox(label="Time of Last Meal (hh:mm AM/PM)", placeholder="e.g. 1:30 PM")
125
- med_input = gr.Dropdown(["None", "Metformin", "Insulin", "Sulfonylurea"], label="Last Medication Taken")
126
- med_time_input = gr.Textbox(label="Time of Last Medication (hh:mm AM/PM)", placeholder="e.g. 8:00 AM")
127
- exercise_input = gr.Number(label="Exercise in Last 2 Hours (minutes)", value=0)
128
- fast_carb_amount_input = gr.Number(label="Amount of Fast Carbs (mL)", value=0)
129
- liquid_type_input = gr.Dropdown(["Milk", "Juice"], label="Liquid Type for Fast Carb")
130
 
131
- # Event to show/hide the fast carb input field
132
- meal_input.change(fn=update_fast_carb_visibility, inputs=meal_input, outputs=fast_carb_amount_input)
 
133
 
134
- output = gr.Textbox()
 
135
 
136
- # Call the prediction function on form submission
137
- gr.Button("Predict").click(
138
- fn=predict_glucose,
139
- inputs=[current_glucose_input, meal_input, meal_time_input, med_input, med_time_input, exercise_input, fast_carb_amount_input, liquid_type_input],
140
- outputs=output
141
- )
 
 
 
 
 
142
 
143
- # Launch the interface
144
  iface.launch()
 
1
  import gradio as gr
2
+ import datetime
3
  import numpy as np
4
+ import matplotlib.pyplot as plt
5
 
6
+ # Function to calculate predicted blood glucose based on inputs
7
+ def predict_glucose(blood_glucose_now, last_meal_time, meal_type, carb_amount, medication_taken, exercise_done):
8
+ # Convert input time (12-hour format) to 24-hour for calculation
9
+ last_meal_time = datetime.datetime.strptime(last_meal_time, "%I:%M %p").time()
10
+
11
+ # Assuming standard carb impact for milk (fast carbs)
12
+ fast_carb_effect = 30 # Approximate rise in glucose from 120 ml of milk
13
+ slow_carb_effect = 10 # Approximate rise for slow carbs
14
+
15
+ # Medication effects (Metformin)
16
+ metformin_effect = -20 # Approximate glucose decrease over time after Metformin intake (hours)
17
+
18
+ # Estimate the current blood glucose change based on meal type
19
+ if meal_type == "Milk (Fast Carb)":
20
+ glucose_change = fast_carb_effect
21
+ else:
22
+ glucose_change = slow_carb_effect
23
+
24
+ # Time-based adjustments for Metformin action
25
+ if medication_taken:
26
+ # Assuming Metformin starts working after 2-4 hours (gradually lowering glucose)
27
+ time_since_medication = (datetime.datetime.now() - datetime.datetime.combine(datetime.date.today(), last_meal_time)).seconds / 3600
28
+ if time_since_medication >= 2:
29
+ glucose_change += metformin_effect
30
+
31
+ # Adjust for exercise
32
+ if exercise_done:
33
+ glucose_change -= 10 # Decrease glucose due to physical activity
34
+
35
+ # Predict future glucose levels (after 1 hour and 3 hours)
36
+ glucose_now = blood_glucose_now + glucose_change
37
+ glucose_1hr = glucose_now + glucose_change * 0.5 # Prediction after 1 hour
38
+ glucose_3hr = glucose_now + glucose_change * 0.3 # Prediction after 3 hours
39
+
40
+ # Determine risk
41
+ if glucose_now > 180:
42
+ risk_now = "⚠️ Hyperglycemia Risk"
43
+ elif glucose_now < 70:
44
+ risk_now = "⚠️ Hypoglycemia Risk"
45
+ else:
46
+ risk_now = "Normal"
47
+
48
+ if glucose_1hr > 180:
49
+ risk_1hr = "⚠️ Hyperglycemia Risk"
50
+ elif glucose_1hr < 70:
51
+ risk_1hr = "⚠️ Hypoglycemia Risk"
52
+ else:
53
+ risk_1hr = "Normal"
54
+
55
+ if glucose_3hr > 180:
56
+ risk_3hr = "⚠️ Hyperglycemia Risk"
57
+ elif glucose_3hr < 70:
58
+ risk_3hr = "⚠️ Hypoglycemia Risk"
59
+ else:
60
+ risk_3hr = "Normal"
61
+
62
+ # Blood glucose trajectory (graph generation)
63
+ time_points = [0, 1, 3] # Time in hours: Now, 1 hour, and 3 hours
64
+ glucose_values = [glucose_now, glucose_1hr, glucose_3hr]
65
+
66
+ plt.figure(figsize=(8, 6))
67
+ plt.plot(time_points, glucose_values, marker='o', color='b', label="Predicted Glucose")
68
+ plt.title('Blood Glucose Trajectory Over Time')
69
+ plt.xlabel('Time (hours)')
70
+ plt.ylabel('Blood Glucose (mg/dL)')
71
+ plt.grid(True)
72
+ plt.axhline(y=180, color='r', linestyle='--', label="Hyperglycemia Threshold")
73
+ plt.axhline(y=70, color='g', linestyle='--', label="Hypoglycemia Threshold")
74
+ plt.legend(loc="best")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ # Save the graph as an image
77
+ plt_file_path = "/tmp/glucose_trajectory.png"
78
+ plt.savefig(plt_file_path)
79
 
80
+ # Return the predicted values and trajectory image
81
+ result_text = f"Now: {glucose_now:.1f} mg/dL → {risk_now}\nIn 1 Hour: {glucose_1hr:.1f} mg/dL → {risk_1hr}\nIn 3 Hours: {glucose_3hr:.1f} mg/dL → {risk_3hr}"
82
 
83
+ return result_text, plt_file_path
84
+
85
+ # Gradio interface
86
+ iface = gr.Interface(fn=predict_glucose,
87
+ inputs=[gr.Number(label="Current Blood Glucose (mg/dL)"),
88
+ gr.Textbox(label="Last Meal Time (e.g., 12:00 AM)"),
89
+ gr.Radio(label="Meal Type", choices=["Milk (Fast Carb)", "Slow Carbs"]),
90
+ gr.Number(label="Carb Amount (grams)"),
91
+ gr.Checkbox(label="Medication Taken (Metformin)"),
92
+ gr.Checkbox(label="Exercise Done")],
93
+ outputs=[gr.Textbox(), gr.Image(type="file")])
94
 
 
95
  iface.launch()