varshakolanu commited on
Commit
7b9794c
·
verified ·
1 Parent(s): 90d0ff7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -28
app.py CHANGED
@@ -23,31 +23,49 @@ sf = Salesforce(username=sf_username, password=sf_password, security_token=sf_se
23
  twilio_client = twilio.rest.Client(twilio_sid, twilio_auth_token)
24
 
25
  def get_patient_data(patient_id):
26
- query = f"SELECT Name, Phone__c, Email__c, DateOfBirth__c, ConsentGiven__c, Height__c, Weight__c, EmergencyContactName__c, EmergencyContactNumber__c FROM Patient__c WHERE Id = '{patient_id}' LIMIT 1"
27
- result = sf.query(query)
28
- return result['records'][0] if result['totalSize'] > 0 else {}
 
 
 
29
 
30
  def get_appointments(patient_id):
31
- query = f"SELECT Name, DateTime__c, Status__c, Provider__c FROM Appointment__c WHERE Patient__c = '{patient_id}' AND Status__c = 'Confirmed'"
32
- result = sf.query(query)
33
- return result['records'] if result['totalSize'] > 0 else []
 
 
 
34
 
35
  def get_doctors():
36
- query = "SELECT Name, Doctor_Name__c, AvailableTimings__c FROM Doctor__c"
37
- result = sf.query(query)
38
- return result['records'] if result['totalSize'] > 0 else []
 
 
 
39
 
40
  def send_followup_message(phone, message):
41
  if phone and message:
42
- twilio_client.messages.create(
43
- body=message,
44
- from_=twilio_phone,
45
- to=f"+{phone}"
46
- )
 
 
 
 
47
 
48
  def dashboard_tab(patient_id):
49
  patient = get_patient_data(patient_id)
 
 
 
50
  appointments = get_appointments(patient_id)
 
 
51
 
52
  welcome_text = f"Welcome back, {patient.get('Name', 'Guest')}!"
53
  next_appointment = appointments[0]['DateTime__c'] if appointments else "None scheduled"
@@ -71,23 +89,31 @@ def dashboard_tab(patient_id):
71
 
72
  return gr.Column([
73
  gr.Markdown(f"# {welcome_text}\nHere's an overview of your healthcare journey"),
74
- gr.Row([gr.Column([gr.Markdown("### Next Appointment"), gr.Markdown(f"Dec 15, 2024\n2:30 PM - Dr. Smith")]),
75
  gr.Column([gr.Markdown("### Pending Forms"), gr.Markdown(f"{len(pending_forms)} - {', '.join(pending_forms)}")]),
76
- gr.Column([gr.Markdown("### Health Score"), gr.Markdown("85/100\nExcellent progress")]),
77
  gr.Column([gr.Markdown("### Notifications"), gr.Markdown("\n".join(notifications))])]),
78
  gr.Row([gr.Column(tasks), gr.Column(recent_activity)])
79
  ])
80
 
81
  def appointments_tab(patient_id):
82
  patient = get_patient_data(patient_id)
 
 
 
83
  appointments = get_appointments(patient_id)
 
 
 
84
  doctors = get_doctors()
 
 
85
 
86
  def schedule_appointment(provider, appt_type, date, time_slot, reason, instructions):
87
  if not provider or not appt_type or not date or not time_slot:
88
  return "Please fill all required fields."
89
  doctor = next((d for d in doctors if d['Doctor_Name__c'] == provider), None)
90
- if not doctor or not check_availability(doctor['AvailableTimings__c'], date, time_slot):
91
  return "Selected doctor or time slot unavailable."
92
  appt_data = {
93
  'Name': f"Appointment_{datetime.now().strftime('%Y%m%d%H%M%S')}",
@@ -98,19 +124,22 @@ def appointments_tab(patient_id):
98
  'Reason__c': reason,
99
  'SpecialInstructions__c': instructions
100
  }
101
- sf.Appointment__c.create(appt_data)
102
- send_followup_message(patient.get('Phone__c'), f"Appointment booked: {date} {time_slot} with {provider}")
103
- return "Appointment scheduled successfully!"
 
 
 
104
 
105
  def check_availability(timings, date, time_slot):
106
  # Placeholder: Parse timings to check availability
107
- return True # Implement real logic based on AvailableTimings__c
108
 
109
  with gr.Column():
110
  gr.Markdown("# Appointments\nManage your healthcare appointments and schedule new visits")
111
  gr.Markdown("### Upcoming Appointments")
112
  for appt in appointments:
113
- gr.Markdown(f"- {appt['Name']}\n {appt['DateTime__c']}\n Status: Confirmed")
114
  with gr.Row():
115
  with gr.Column():
116
  gr.Markdown("### Quick Actions")
@@ -123,7 +152,7 @@ def appointments_tab(patient_id):
123
  gr.Markdown("- Initial Consultation\n Dr. Michael Johnson\n Oct 15, 2024 2:00 PM\n [Complete] [View Notes]")
124
  with gr.Row():
125
  with gr.Column():
126
- provider = gr.Dropdown(choices=[d['Doctor_Name__c'] for d in doctors] or ["None"], label="Select Provider")
127
  appt_type = gr.Dropdown(choices=["Routine Check-up", "Follow-up", "Consultation", "Urgent Care"], label="Appointment Type")
128
  date = gr.DatePicker(label="Preferred Date")
129
  time_slot = gr.Dropdown(choices=["9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM"], label="Available Time Slots")
@@ -136,6 +165,9 @@ def appointments_tab(patient_id):
136
 
137
  def health_records_tab(patient_id):
138
  patient = get_patient_data(patient_id)
 
 
 
139
  return gr.Column([
140
  gr.Markdown("# Health Records"),
141
  gr.Markdown(f"- Name: {patient.get('Name', 'N/A')}\n- Date of Birth: {patient.get('DateOfBirth__c', 'N/A')}\n- Height: {patient.get('Height__c', 'Not filled')}\n- Weight: {patient.get('Weight__c', 'Not filled')}\n- Emergency Contact: {patient.get('EmergencyContactName__c', 'Not filled')}"),
@@ -144,23 +176,33 @@ def health_records_tab(patient_id):
144
 
145
  def follow_up_tab(patient_id):
146
  patient = get_patient_data(patient_id)
 
 
 
147
  if patient.get('ConsentGiven__c'):
148
- send_followup_message(patient.get('Phone__c'), f"Thank you for registering, {patient.get('Name')}! Daily follow-up will begin tomorrow.")
149
  return gr.Column([
150
  gr.Markdown("# Follow-up"),
151
  gr.Markdown("Automated follow-up messages will be sent daily.")
152
  ])
153
 
154
  with gr.Blocks(title="HealthPortal - Patient Care System") as demo:
 
 
 
 
 
 
 
155
  gr.Markdown("# HealthPortal\nPatient Care System")
156
  with gr.Tabs():
157
  with gr.TabItem("Dashboard"):
158
- dashboard_tab(gr.State(value="a0b1c2d3-e4f5-4g6h-7i8j-9k0l1m2n3o4p")) # Placeholder patient_id
159
  with gr.TabItem("Appointments"):
160
- appointments_tab(gr.State(value="a0b1c2d3-e4f5-4g6h-7i8j-9k0l1m2n3o4p"))
161
  with gr.TabItem("Health Records"):
162
- health_records_tab(gr.State(value="a0b1c2d3-e4f5-4g6h-7i8j-9k0l1m2n3o4p"))
163
  with gr.TabItem("Follow-up"):
164
- follow_up_tab(gr.State(value="a0b1c2d3-e4f5-4g6h-7i8j-9k0l1m2n3o4p"))
165
 
166
  demo.launch()
 
23
  twilio_client = twilio.rest.Client(twilio_sid, twilio_auth_token)
24
 
25
  def get_patient_data(patient_id):
26
+ try:
27
+ query = f"SELECT Name, Phone__c, Email__c, DateOfBirth__c, ConsentGiven__c, Height__c, Weight__c, EmergencyContactName__c, EmergencyContactNumber__c FROM Patient__c WHERE Id = '{patient_id}' LIMIT 1"
28
+ result = sf.query(query)
29
+ return result['records'][0] if result['totalSize'] > 0 else {}
30
+ except Exception as e:
31
+ return {"error": str(e)}
32
 
33
  def get_appointments(patient_id):
34
+ try:
35
+ query = f"SELECT Name, DateTime__c, Status__c, Provider__c FROM Appointment__c WHERE Patient__c = '{patient_id}' AND Status__c = 'Confirmed'"
36
+ result = sf.query(query)
37
+ return result['records'] if result['totalSize'] > 0 else []
38
+ except Exception as e:
39
+ return [{"error": str(e)}]
40
 
41
  def get_doctors():
42
+ try:
43
+ query = "SELECT Name, Doctor_Name__c, AvailabilitySchedule__c FROM Doctor__c"
44
+ result = sf.query(query)
45
+ return result['records'] if result['totalSize'] > 0 else []
46
+ except Exception as e:
47
+ return [{"error": str(e)}]
48
 
49
  def send_followup_message(phone, message):
50
  if phone and message:
51
+ try:
52
+ twilio_client.messages.create(
53
+ body=message,
54
+ from_=twilio_phone,
55
+ to=f"+{phone}"
56
+ )
57
+ except Exception as e:
58
+ return f"Failed to send message: {str(e)}"
59
+ return "Message sent successfully"
60
 
61
  def dashboard_tab(patient_id):
62
  patient = get_patient_data(patient_id)
63
+ if "error" in patient:
64
+ return gr.Markdown(f"# Error\n{patient['error']}\nPlease log in again or contact support.")
65
+
66
  appointments = get_appointments(patient_id)
67
+ if any("error" in appt for appt in appointments):
68
+ return gr.Markdown(f"# Error\n{next(appt['error'] for appt in appointments if 'error' in appt)}\nPlease try again later.")
69
 
70
  welcome_text = f"Welcome back, {patient.get('Name', 'Guest')}!"
71
  next_appointment = appointments[0]['DateTime__c'] if appointments else "None scheduled"
 
89
 
90
  return gr.Column([
91
  gr.Markdown(f"# {welcome_text}\nHere's an overview of your healthcare journey"),
92
+ gr.Row([gr.Column([gr.Markdown("### Next Appointment"), gr.Markdown(f"{next_appointment}")]),
93
  gr.Column([gr.Markdown("### Pending Forms"), gr.Markdown(f"{len(pending_forms)} - {', '.join(pending_forms)}")]),
94
+ gr.Column([gr.Markdown("### Health Score"), gr.Markdown(f"{health_score}/100\nExcellent progress")]),
95
  gr.Column([gr.Markdown("### Notifications"), gr.Markdown("\n".join(notifications))])]),
96
  gr.Row([gr.Column(tasks), gr.Column(recent_activity)])
97
  ])
98
 
99
  def appointments_tab(patient_id):
100
  patient = get_patient_data(patient_id)
101
+ if "error" in patient:
102
+ return gr.Markdown(f"# Error\n{patient['error']}\nPlease log in again or contact support.")
103
+
104
  appointments = get_appointments(patient_id)
105
+ if any("error" in appt for appt in appointments):
106
+ return gr.Markdown(f"# Error\n{next(appt['error'] for appt in appointments if 'error' in appt)}\nPlease try again later.")
107
+
108
  doctors = get_doctors()
109
+ if any("error" in doc for doc in doctors):
110
+ return gr.Markdown(f"# Error\n{next(doc['error'] for doc in doctors if 'error' in doc)}\nPlease try again later.")
111
 
112
  def schedule_appointment(provider, appt_type, date, time_slot, reason, instructions):
113
  if not provider or not appt_type or not date or not time_slot:
114
  return "Please fill all required fields."
115
  doctor = next((d for d in doctors if d['Doctor_Name__c'] == provider), None)
116
+ if not doctor or not check_availability(doctor.get('AvailabilitySchedule__c', ''), date, time_slot):
117
  return "Selected doctor or time slot unavailable."
118
  appt_data = {
119
  'Name': f"Appointment_{datetime.now().strftime('%Y%m%d%H%M%S')}",
 
124
  'Reason__c': reason,
125
  'SpecialInstructions__c': instructions
126
  }
127
+ try:
128
+ sf.Appointment__c.create(appt_data)
129
+ send_followup_message(patient.get('Phone__c'), f"Appointment booked: {date} {time_slot} with {provider}")
130
+ return "Appointment scheduled successfully!"
131
+ except Exception as e:
132
+ return f"Failed to schedule appointment: {str(e)}"
133
 
134
  def check_availability(timings, date, time_slot):
135
  # Placeholder: Parse timings to check availability
136
+ return True # Implement real logic based on AvailabilitySchedule__c
137
 
138
  with gr.Column():
139
  gr.Markdown("# Appointments\nManage your healthcare appointments and schedule new visits")
140
  gr.Markdown("### Upcoming Appointments")
141
  for appt in appointments:
142
+ gr.Markdown(f"- {appt.get('Name', 'N/A')}\n {appt.get('DateTime__c', 'N/A')}\n Status: {appt.get('Status__c', 'N/A')}")
143
  with gr.Row():
144
  with gr.Column():
145
  gr.Markdown("### Quick Actions")
 
152
  gr.Markdown("- Initial Consultation\n Dr. Michael Johnson\n Oct 15, 2024 2:00 PM\n [Complete] [View Notes]")
153
  with gr.Row():
154
  with gr.Column():
155
+ provider = gr.Dropdown(choices=[d['Doctor_Name__c'] for d in doctors if 'Doctor_Name__c' in d] or ["None"], label="Select Provider")
156
  appt_type = gr.Dropdown(choices=["Routine Check-up", "Follow-up", "Consultation", "Urgent Care"], label="Appointment Type")
157
  date = gr.DatePicker(label="Preferred Date")
158
  time_slot = gr.Dropdown(choices=["9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM"], label="Available Time Slots")
 
165
 
166
  def health_records_tab(patient_id):
167
  patient = get_patient_data(patient_id)
168
+ if "error" in patient:
169
+ return gr.Markdown(f"# Error\n{patient['error']}\nPlease log in again or contact support.")
170
+
171
  return gr.Column([
172
  gr.Markdown("# Health Records"),
173
  gr.Markdown(f"- Name: {patient.get('Name', 'N/A')}\n- Date of Birth: {patient.get('DateOfBirth__c', 'N/A')}\n- Height: {patient.get('Height__c', 'Not filled')}\n- Weight: {patient.get('Weight__c', 'Not filled')}\n- Emergency Contact: {patient.get('EmergencyContactName__c', 'Not filled')}"),
 
176
 
177
  def follow_up_tab(patient_id):
178
  patient = get_patient_data(patient_id)
179
+ if "error" in patient:
180
+ return gr.Markdown(f"# Error\n{patient['error']}\nPlease log in again or contact support.")
181
+
182
  if patient.get('ConsentGiven__c'):
183
+ send_followup_message(patient.get('Phone__c'), f"Thank you for registering, {patient.get('Name', 'Patient')}! Daily follow-up will begin tomorrow.")
184
  return gr.Column([
185
  gr.Markdown("# Follow-up"),
186
  gr.Markdown("Automated follow-up messages will be sent daily.")
187
  ])
188
 
189
  with gr.Blocks(title="HealthPortal - Patient Care System") as demo:
190
+ # Get patient_id from URL parameter
191
+ patient_id = gr.State(value=None)
192
+ demo.load(
193
+ fn=lambda: gr.update(value=gr.inputs.Textbox(default="a0b1c2d3-e4f5-4g6h-7i8j-9k0l1m2n3o4p")), # Default placeholder
194
+ inputs=None,
195
+ outputs=patient_id
196
+ )
197
  gr.Markdown("# HealthPortal\nPatient Care System")
198
  with gr.Tabs():
199
  with gr.TabItem("Dashboard"):
200
+ dashboard_tab(patient_id)
201
  with gr.TabItem("Appointments"):
202
+ appointments_tab(patient_id)
203
  with gr.TabItem("Health Records"):
204
+ health_records_tab(patient_id)
205
  with gr.TabItem("Follow-up"):
206
+ follow_up_tab(patient_id)
207
 
208
  demo.launch()