T2LIPthedeveloper commited on
Commit
9758397
Β·
1 Parent(s): 442ca22

Implemented a complete interface for this thing

Browse files
Files changed (1) hide show
  1. app.py +218 -13
app.py CHANGED
@@ -1,7 +1,25 @@
1
  import gradio as gr
 
 
 
2
  from classification_model import classify_medicine
3
  from ocr_model import perform_ocr
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  def classify_image(image):
6
  with open(image, "rb") as f:
7
  image_bytes = f.read()
@@ -13,19 +31,206 @@ def ocr_image(image):
13
  image_bytes = f.read()
14
  return perform_ocr(image_bytes)
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  with gr.Blocks() as app:
17
- gr.Markdown("## Medicine Classification and OCR App")
18
-
19
- with gr.Tab("Classify Medicine"):
20
- image_input = gr.Image(type="filepath")
21
- classify_button = gr.Button("Classify")
22
- output_text = gr.Textbox()
23
- classify_button.click(classify_image, inputs=image_input, outputs=output_text)
24
-
25
- with gr.Tab("OCR Extraction"):
26
- image_input_ocr = gr.Image(type="filepath")
27
- ocr_button = gr.Button("Extract Text")
28
- ocr_output = gr.Textbox()
29
- ocr_button.click(ocr_image, inputs=image_input_ocr, outputs=ocr_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  app.launch()
 
1
  import gradio as gr
2
+ import datetime
3
+ import json
4
+ import os
5
  from classification_model import classify_medicine
6
  from ocr_model import perform_ocr
7
 
8
+ MEDS_FILE = "medications.json"
9
+
10
+ def load_medications():
11
+ if os.path.exists(MEDS_FILE):
12
+ try:
13
+ with open(MEDS_FILE, "r") as f:
14
+ return json.load(f)
15
+ except Exception:
16
+ return []
17
+ return []
18
+
19
+ def save_medications(meds):
20
+ with open(MEDS_FILE, "w") as f:
21
+ json.dump(meds, f)
22
+
23
  def classify_image(image):
24
  with open(image, "rb") as f:
25
  image_bytes = f.read()
 
31
  image_bytes = f.read()
32
  return perform_ocr(image_bytes)
33
 
34
+ def add_medication(name, dosage, frequency, start_date, end_date, notes):
35
+ # Convert dates to ISO strings for consistency
36
+ if isinstance(start_date, (float, int)):
37
+ start_date = datetime.datetime.fromtimestamp(start_date).date().isoformat()
38
+ elif isinstance(start_date, datetime.datetime):
39
+ start_date = start_date.date().isoformat()
40
+ elif isinstance(start_date, datetime.date):
41
+ start_date = start_date.isoformat()
42
+
43
+ if isinstance(end_date, (float, int)):
44
+ end_date = datetime.datetime.fromtimestamp(end_date).date().isoformat()
45
+ elif isinstance(end_date, datetime.datetime):
46
+ end_date = end_date.date().isoformat()
47
+ elif isinstance(end_date, datetime.date):
48
+ end_date = end_date.isoformat()
49
+
50
+ meds = load_medications()
51
+ meds.append({
52
+ "name": name,
53
+ "dosage": dosage,
54
+ "frequency": frequency,
55
+ "start_date": start_date,
56
+ "end_date": end_date,
57
+ "notes": notes
58
+ })
59
+ save_medications(meds)
60
+ return "βœ… Medication added successfully!"
61
+
62
+ def view_medications():
63
+ meds = load_medications()
64
+ if not meds:
65
+ return "No medications added."
66
+ return "\n".join([
67
+ f"{med['name']} - {med['dosage']} - {med['frequency']} ({med['start_date']} to {med['end_date']})"
68
+ for med in meds
69
+ ])
70
+
71
+ def get_today_medications():
72
+ meds = load_medications()
73
+ today = datetime.date.today()
74
+ today_name = today.strftime("%A")
75
+ today_meds = []
76
+
77
+ for med in meds:
78
+ try:
79
+ start = datetime.date.fromisoformat(med["start_date"])
80
+ end = datetime.date.fromisoformat(med["end_date"])
81
+ frequency = med["frequency"]
82
+
83
+ # Skip if today is not within the medication date range
84
+ if not (start <= today <= end):
85
+ continue
86
+
87
+ # Handle weekly medications - only show on the appropriate day
88
+ if frequency == "Weekly" and today_name != "Monday": # Assuming weekly meds are taken on Monday
89
+ continue
90
+
91
+ today_meds.append(med)
92
+ except Exception:
93
+ continue
94
+
95
+ if not today_meds:
96
+ return "No medications scheduled for today."
97
+
98
+ return "\n".join([
99
+ f"{med['name']} - {med['dosage']} - {med['frequency']}"
100
+ + (f" ({_get_time_of_day(med['frequency'])})" if _get_time_of_day(med['frequency']) else "")
101
+ for med in today_meds
102
+ ])
103
+
104
+ def _get_time_of_day(frequency):
105
+ """Helper function to return time of day based on frequency"""
106
+ if frequency == "Every morning":
107
+ return "Morning"
108
+ elif frequency == "Every evening":
109
+ return "Evening"
110
+ elif frequency == "Once daily":
111
+ return "Morning"
112
+ elif frequency == "Twice daily":
113
+ return "Morning and Evening"
114
+ elif frequency == "Three times daily":
115
+ return "Morning, Afternoon, and Evening"
116
+ elif frequency == "Four times daily":
117
+ return "Morning, Noon, Afternoon, and Night"
118
+ elif frequency == "Every 12 hours":
119
+ return "Morning and Evening"
120
+ return ""
121
+
122
+ def get_weekly_schedule():
123
+ meds = load_medications()
124
+ today = datetime.date.today()
125
+ week_meds = {(today + datetime.timedelta(days=i)).isoformat(): [] for i in range(7)}
126
+ days_of_week = [(today + datetime.timedelta(days=i)).strftime("%A") for i in range(7)]
127
+
128
+ for med in meds:
129
+ try:
130
+ start = datetime.date.fromisoformat(med["start_date"])
131
+ end = datetime.date.fromisoformat(med["end_date"])
132
+ frequency = med["frequency"]
133
+ except Exception:
134
+ continue
135
+
136
+ for i, day_str in enumerate(week_meds.keys()):
137
+ day_date = datetime.date.fromisoformat(day_str)
138
+ day_name = days_of_week[i]
139
+
140
+ # Skip if day is not within the medication date range
141
+ if not (start <= day_date <= end):
142
+ continue
143
+
144
+ # For weekly medications, only include on Mondays
145
+ if frequency == "Weekly" and day_name != "Monday":
146
+ continue
147
+
148
+ med_info = f"{med['name']} - {med['dosage']} - {med['frequency']}"
149
+ timing = _get_time_of_day(frequency)
150
+ if timing:
151
+ med_info += f" ({timing})"
152
+
153
+ week_meds[day_str].append(med_info)
154
+
155
+ # Format the output with day names for better readability
156
+ formatted_output = {}
157
+ for i, (day_str, meds_list) in enumerate(week_meds.items()):
158
+ day_name = days_of_week[i]
159
+ formatted_output[f"{day_name} ({day_str})"] = meds_list
160
+
161
+ return json.dumps(formatted_output, indent=2)
162
+
163
  with gr.Blocks() as app:
164
+ gr.Markdown("# πŸ’Š Medication Tracker")
165
+
166
+ with gr.Tabs():
167
+ with gr.Tab("πŸ“Έ Identify Medicine"):
168
+ gr.Markdown("Upload an image to identify the medicine.")
169
+ with gr.Row():
170
+ image_input = gr.Image(type="filepath")
171
+ classify_output = gr.Textbox()
172
+
173
+ classify_button = gr.Button("Classify Medicine")
174
+ classify_button.click(classify_image, inputs=image_input, outputs=classify_output)
175
+
176
+ gr.Markdown("### Add this medication to your tracker")
177
+ identified_name = gr.Textbox(label="Medication Name")
178
+ identified_dosage = gr.Textbox(label="Dosage (e.g., 500mg)")
179
+ identified_frequency = gr.Dropdown(
180
+ label="Frequency",
181
+ choices=["Once daily", "Twice daily", "Three times daily", "Four times daily",
182
+ "Every morning", "Every evening", "Every 12 hours", "Weekly", "As needed"],
183
+ value="Once daily"
184
+ )
185
+ identified_start_date = gr.DateTime(label="Start Date")
186
+ identified_end_date = gr.DateTime(label="End Date")
187
+ identified_notes = gr.Textbox(label="Additional Notes")
188
+ identified_add_button = gr.Button("Add to My Medications")
189
+ identified_add_output = gr.Textbox()
190
+
191
+ identified_add_button.click(
192
+ add_medication,
193
+ inputs=[identified_name, identified_dosage, identified_frequency,
194
+ identified_start_date, identified_end_date, identified_notes],
195
+ outputs=identified_add_output
196
+ )
197
+
198
+ with gr.Tab("πŸ” Extract Medical Label"):
199
+ gr.Markdown("Upload an image of a prescription or label to extract text.")
200
+ image_input_ocr = gr.Image(type="filepath")
201
+ ocr_button = gr.Button("Extract Text")
202
+ ocr_output = gr.Textbox()
203
+ ocr_button.click(ocr_image, inputs=image_input_ocr, outputs=ocr_output)
204
+
205
+ with gr.Tab("πŸ“ Add Medication"):
206
+ gr.Markdown("Add your medications manually.")
207
+ name = gr.Textbox(label="Medication Name")
208
+ dosage = gr.Textbox(label="Dosage (e.g., 500mg)")
209
+ frequency = gr.Dropdown(
210
+ label="Frequency",
211
+ choices=["Once daily", "Twice daily", "Three times daily", "Four times daily",
212
+ "Every morning", "Every evening", "Every 12 hours", "Weekly", "As needed"],
213
+ value="Once daily"
214
+ )
215
+ start_date = gr.DateTime(label="Start Date")
216
+ end_date = gr.DateTime(label="End Date")
217
+ notes = gr.Textbox(label="Additional Notes")
218
+ add_button = gr.Button("Add Medication")
219
+ add_output = gr.Textbox()
220
+ add_button.click(add_medication, inputs=[name, dosage, frequency, start_date, end_date, notes], outputs=add_output)
221
+
222
+ with gr.Tab("πŸ“… Medication Schedule"):
223
+ gr.Markdown("View your scheduled medications.")
224
+ today_button = gr.Button("View Today's Medications")
225
+ today_output = gr.Textbox(label="Today's Medications")
226
+ today_button.click(get_today_medications, outputs=today_output)
227
+
228
+ weekly_button = gr.Button("View Weekly Schedule")
229
+ weekly_output = gr.Textbox(label="Weekly Schedule")
230
+ weekly_button.click(get_weekly_schedule, outputs=weekly_output)
231
+
232
+ all_meds_button = gr.Button("View All Medications")
233
+ all_meds_output = gr.Textbox(label="All Medications")
234
+ all_meds_button.click(view_medications, outputs=all_meds_output)
235
 
236
  app.launch()