Kayeaelne commited on
Commit
34eaa8b
·
verified ·
1 Parent(s): e8490ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -85
app.py CHANGED
@@ -1,92 +1,83 @@
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, medication_time, exercise_done, exercise_duration):
8
- # Convert input times (12-hour format) to datetime objects
9
- last_meal_time = datetime.datetime.strptime(last_meal_time, "%I:%M %p")
10
- medication_time = datetime.datetime.strptime(medication_time, "%I:%M %p") if medication_taken else None
11
-
12
- # Set estimated glucose impact values for different meal types
13
- meal_effects = {
14
- "Fast Carbs (Juice, Milk)": 30,
15
- "Slow Carbs (Whole Grains)": 10,
16
- "High-Protein Meal": 5,
17
- "High-Fat Meal": 5,
18
- "Balanced Meal": 15,
19
- "No Meal": 0
20
- }
21
-
22
- # Determine effect of the meal type
23
- glucose_change = meal_effects.get(meal_type, 0)
24
-
25
- # Calculate time since medication was taken
26
- if medication_taken and medication_time:
27
- time_since_medication = (datetime.datetime.now() - medication_time).total_seconds() / 3600
28
- if 1 <= time_since_medication <= 3:
29
- glucose_change -= 20 # Approximate glucose decrease due to Galvus effect
30
-
31
- # Adjust for exercise duration
32
- if exercise_done and exercise_duration:
33
- glucose_change -= min(exercise_duration // 10 * 5, 30) # Reduces 5 mg/dL per 10 min, max 30 mg/dL
34
-
35
- # Predict blood glucose levels
36
- glucose_now = blood_glucose_now + glucose_change
37
- glucose_1hr = glucose_now + glucose_change * 0.5
38
- glucose_3hr = glucose_now + glucose_change * 0.3
39
-
40
- # Determine risk levels
41
- def get_risk_label(glucose):
42
- if glucose > 180:
43
- return "⚠️ Hyperglycemia Risk"
44
- elif glucose < 70:
45
- return "⚠️ Hypoglycemia Risk"
46
- else:
47
- return "Normal"
48
-
49
- risk_now = get_risk_label(glucose_now)
50
- risk_1hr = get_risk_label(glucose_1hr)
51
- risk_3hr = get_risk_label(glucose_3hr)
52
-
53
- # Plot blood glucose trajectory
54
- time_points = [0, 1, 3] # Hours
55
- glucose_values = [glucose_now, glucose_1hr, glucose_3hr]
56
-
57
- plt.figure(figsize=(8, 6))
58
- plt.plot(time_points, glucose_values, marker='o', color='b', label="Predicted Glucose")
59
- plt.title('Blood Glucose Trajectory Over Time')
60
- plt.xlabel('Time (hours)')
61
- plt.ylabel('Blood Glucose (mg/dL)')
62
  plt.grid(True)
63
- plt.axhline(y=180, color='r', linestyle='--', label="Hyperglycemia Threshold")
64
- plt.axhline(y=70, color='g', linestyle='--', label="Hypoglycemia Threshold")
65
- plt.legend(loc="best")
66
-
67
- # Save the graph
68
- plt_file_path = "/tmp/glucose_trajectory.png"
69
- plt.savefig(plt_file_path)
70
-
71
- # Output text summary
72
- 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}"
73
-
74
- return result_text, plt_file_path
75
-
76
- # Gradio interface
77
- iface = gr.Interface(fn=predict_glucose,
78
- inputs=[
79
- gr.Number(label="Current Blood Glucose (mg/dL)"),
80
- gr.Textbox(label="Last Meal Time (e.g., 12:00 AM)"),
81
- gr.Radio(label="Meal Type", choices=[
82
- "Fast Carbs (Juice, Milk)", "Slow Carbs (Whole Grains)",
83
- "High-Protein Meal", "High-Fat Meal", "Balanced Meal", "No Meal"]),
84
- gr.Number(label="Carb Amount (grams)"),
85
- gr.Checkbox(label="Medication Taken (Galvus)"),
86
- gr.Textbox(label="Medication Time (e.g., 12:00 AM)"),
87
- gr.Checkbox(label="Exercise Done"),
88
- gr.Number(label="Exercise Duration (minutes)")
89
- ],
90
- outputs=[gr.Textbox(), gr.Image(type="filepath")])
 
 
 
 
 
 
 
 
 
 
 
91
 
 
 
92
  iface.launch()
 
1
  import gradio as gr
 
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
 
5
+ # Function to simulate blood glucose changes over time
6
+ def predict_glucose(current_glucose, meal_type, meal_time, galvus_dose, exercise_duration, fast_carbs_ml, prediction_time=3):
7
+ # Constants for glucose reduction effects
8
+ post_meal_reduction = 63.6 # mg/dL (avg reduction for Vildagliptin in 2 hours)
9
+ fasting_reduction = 27.7 # mg/dL (avg reduction over 6-12 hours)
10
+
11
+ # Adjust for fast carbs (milk, juice, etc.)
12
+ carb_effect = fast_carbs_ml * 1.5 # Approximate glucose rise per mL of fast carbs
13
+
14
+ # Calculate blood glucose over time considering meal type, Galvus dose, and exercise
15
+ if meal_type == 'High-carb':
16
+ glucose_after_meal = current_glucose + carb_effect
17
+ else:
18
+ glucose_after_meal = current_glucose
19
+
20
+ # Simulate blood glucose levels over 1 hour and 3 hours
21
+ glucose_1hr = glucose_after_meal - post_meal_reduction + carb_effect * 0.5 # Adjust for carb effect
22
+ glucose_3hr = glucose_1hr - fasting_reduction
23
+
24
+ # Apply Galvus pharmacokinetic effects
25
+ if galvus_dose > 0:
26
+ glucose_3hr -= fasting_reduction # Galvus effect after 3 hours
27
+
28
+ # Exercise effect on glucose (hypothetical value, may vary based on intensity)
29
+ glucose_3hr -= exercise_duration * 2 # Exercise reduces glucose by 2 mg/dL per minute
30
+
31
+ # Plotting the graph of glucose prediction over time
32
+ time_points = [0, 1, 3] # Time: 0 hours, 1 hour, 3 hours
33
+ glucose_values = [current_glucose, glucose_1hr, glucose_3hr]
34
+
35
+ plt.plot(time_points, glucose_values, marker='o', color='b')
36
+ plt.title("Blood Glucose Prediction Over Time")
37
+ plt.xlabel("Time (Hours)")
38
+ plt.ylabel("Blood Glucose (mg/dL)")
39
+ plt.xticks([0, 1, 2, 3])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  plt.grid(True)
41
+ plt.tight_layout()
42
+
43
+ # Save the graph as a file to show it in Gradio
44
+ plt.savefig('/tmp/blood_glucose_prediction.png')
45
+ plt.close()
46
+
47
+ # Return glucose predictions and the image file path
48
+ return glucose_1hr, glucose_3hr, '/tmp/blood_glucose_prediction.png'
49
+
50
+ # Gradio Interface
51
+ def build_interface():
52
+ with gr.Blocks() as iface:
53
+ gr.Markdown("# Blood Glucose Prediction Model (With Vildagliptin Effects)")
54
+
55
+ # Inputs for current glucose, meal info, medication dose, exercise, fast carbs
56
+ with gr.Row():
57
+ current_glucose = gr.Number(label="Current Blood Glucose (mg/dL)", value=150)
58
+ meal_type = gr.Radio(choices=["Normal", "High-carb"], label="Meal Type", value="Normal")
59
+ meal_time = gr.Number(label="Last Meal Time (in hours)", value=2)
60
+ galvus_dose = gr.Number(label="Galvus Dose (mg)", value=50)
61
+ exercise_duration = gr.Number(label="Exercise Duration (min)", value=0)
62
+ fast_carbs_ml = gr.Number(label="Fast Carbs (mL)", value=0)
63
+
64
+ # Output predictions and graph
65
+ glucose_1hr_output = gr.Textbox(label="Predicted Glucose Level in 1 Hour (mg/dL)")
66
+ glucose_3hr_output = gr.Textbox(label="Predicted Glucose Level in 3 Hours (mg/dL)")
67
+ glucose_graph = gr.Image(label="Blood Glucose Prediction Graph")
68
+
69
+ # Button to trigger prediction
70
+ predict_button = gr.Button("Predict Blood Glucose")
71
+
72
+ # Set button action
73
+ predict_button.click(
74
+ predict_glucose,
75
+ inputs=[current_glucose, meal_type, meal_time, galvus_dose, exercise_duration, fast_carbs_ml],
76
+ outputs=[glucose_1hr_output, glucose_3hr_output, glucose_graph]
77
+ )
78
+
79
+ return iface
80
 
81
+ # Build and launch the Gradio interface
82
+ iface = build_interface()
83
  iface.launch()