rajkhanke commited on
Commit
bf82aeb
·
verified ·
1 Parent(s): bd20939

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -379
app.py CHANGED
@@ -1,55 +1,34 @@
1
- from flask import Flask, render_template, request, jsonify, session, redirect, url_for, send_file
2
  import google.generativeai as genai
3
  import PyPDF2
4
  import os
5
  import re
6
- import io
7
  from datetime import datetime
8
- from twilio.rest import Client
9
- from reportlab.lib.pagesizes import letter
10
- from reportlab.lib import colors
11
- from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
12
- from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, ListItem, ListFlowable, Table, TableStyle
13
- from reportlab.lib.units import inch
14
- from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY
15
 
16
  app = Flask(__name__)
17
- app.secret_key = '688ed745a74bdd7ac238f5b50f4104fb87d6774b8b0a4e06e7e18ac5ed0fa31c' # Add this for session management
18
 
19
- upload_base = os.getenv('UPLOAD_DIR', 'static')
 
20
  upload_folder = os.path.join(upload_base, 'uploads')
21
- pdf_folder = os.path.join(upload_base, 'pdfs')
22
- app.config['UPLOAD_FOLDER'] = upload_folder
23
- app.config['PDF_FOLDER'] = pdf_folder
24
 
 
25
  os.makedirs(upload_folder, exist_ok=True)
26
- os.makedirs(pdf_folder, exist_ok=True)
27
-
28
- # Store patient care plans in memory (would be a database in production)
29
- if not hasattr(app, 'patient_care_plans'):
30
- app.patient_care_plans = []
31
-
32
- if not hasattr(app, 'emergency_notifications'):
33
- app.emergency_notifications = []
34
 
35
  # Gemini API Configuration
36
- genai.configure(api_key="AIzaSyCizcswP6vlKDMdB3HRAtVi2JbifOpbPvA")
 
37
  generation_config = {
38
  "temperature": 1,
39
  "top_p": 0.95,
40
  "top_k": 40,
41
  "max_output_tokens": 8192,
42
  }
 
43
  model = genai.GenerativeModel(
44
  model_name="gemini-2.0-flash",
45
  generation_config=generation_config,
46
  )
47
 
48
- # Twilio Configuration
49
- ACCOUNT_SID = 'AC490e071f8d01bf0df2f03d086c788d87'
50
- AUTH_TOKEN = '224b23b950ad5a4052aba15893fdf083'
51
- TWILIO_FROM = 'whatsapp:+14155238886'
52
- PATIENT_PHONE = 'whatsapp:+917559355282' # Hardcoded patient phone number
53
 
54
  def extract_text_from_pdf(pdf_file):
55
  try:
@@ -62,16 +41,17 @@ def extract_text_from_pdf(pdf_file):
62
  print(f"Error extracting PDF text: {e}")
63
  return ""
64
 
 
65
  def extract_care_plan_format(pdf_text):
66
  """Extract the care plan format from PDF text"""
67
  try:
68
  # Find sections and their content in the PDF using regex
69
  sections = re.findall(
70
- r'([A-Z][A-Z\s]+):(.+?)(?=\n[A-Z][A-Z\s]+:|$)',
71
  pdf_text,
72
  re.DOTALL
73
  )
74
-
75
  if sections:
76
  format_template = ""
77
  for section, content in sections:
@@ -88,279 +68,33 @@ def extract_care_plan_format(pdf_text):
88
  print(f"Error extracting format: {e}")
89
  return None
90
 
91
- def create_care_plan_pdf(care_plan_text, patient_name="Patient"):
92
- """Generate a beautifully formatted PDF with the care plan"""
93
- buffer = io.BytesIO()
94
- doc = SimpleDocTemplate(buffer, pagesize=letter)
95
- styles = getSampleStyleSheet()
96
-
97
- # Create custom styles
98
- styles.add(ParagraphStyle(
99
- name='Title',
100
- parent=styles['Heading1'],
101
- fontSize=18,
102
- alignment=TA_CENTER,
103
- spaceAfter=20,
104
- textColor=colors.HexColor('#0d6efd')
105
- ))
106
-
107
- styles.add(ParagraphStyle(
108
- name='SectionHeading',
109
- parent=styles['Heading2'],
110
- fontSize=14,
111
- spaceAfter=6,
112
- spaceBefore=12,
113
- textColor=colors.HexColor('#0a58ca')
114
- ))
115
-
116
- styles.add(ParagraphStyle(
117
- name='BodyText',
118
- parent=styles['Normal'],
119
- fontSize=11,
120
- alignment=TA_JUSTIFY,
121
- spaceBefore=2,
122
- spaceAfter=2
123
- ))
124
-
125
- # Create story elements
126
- story = []
127
-
128
- # Add title with logo
129
- timestamp = datetime.now().strftime("%B %d, %Y")
130
- title = Paragraph(f"UPDATED CARE PLAN<br/><br/>{timestamp}", styles["Title"])
131
- story.append(title)
132
- story.append(Spacer(1, 0.25*inch))
133
-
134
- # Patient name
135
- patient_info = Paragraph(f"<b>Patient:</b> {patient_name}", styles["BodyText"])
136
- story.append(patient_info)
137
- story.append(Spacer(1, 0.15*inch))
138
-
139
- # Process care plan sections
140
- sections = care_plan_text.split("\n\n")
141
- for section in sections:
142
- if not section.strip():
143
- continue
144
-
145
- lines = section.strip().split("\n")
146
- if not lines:
147
- continue
148
-
149
- # Add section heading
150
- heading_line = lines[0].strip()
151
- if ":" in heading_line:
152
- heading = heading_line.split(":", 1)[0].strip()
153
- story.append(Paragraph(heading, styles["SectionHeading"]))
154
-
155
- # Process bullet points and content
156
- content_lines = lines[1:] if len(lines) > 1 else []
157
- bullet_items = []
158
- normal_text = ""
159
-
160
- for line in content_lines:
161
- line = line.strip()
162
- if line.startswith("-") or line.startswith("•"):
163
- bullet_text = line[1:].strip()
164
- bullet_items.append(ListItem(Paragraph(bullet_text, styles["BodyText"])))
165
- elif line: # Only add non-empty lines
166
- normal_text += line + " "
167
-
168
- # Add normal text if present
169
- if normal_text:
170
- story.append(Paragraph(normal_text, styles["BodyText"]))
171
-
172
- # Add bullet points if present
173
- if bullet_items:
174
- bullet_list = ListFlowable(
175
- bullet_items,
176
- bulletType='bullet',
177
- start=None,
178
- bulletFontName='Helvetica',
179
- bulletFontSize=11,
180
- leftIndent=20,
181
- bulletOffsetY=0
182
- )
183
- story.append(bullet_list)
184
-
185
- story.append(Spacer(1, 0.1*inch))
186
-
187
- # Add footer
188
- footer_text = """This care plan has been automatically generated based on patient feedback. Please consult with your healthcare provider before making any changes to your current treatment plan."""
189
- footer = Paragraph(f"<i>{footer_text}</i>", styles["BodyText"])
190
- story.append(Spacer(1, 0.25*inch))
191
- story.append(footer)
192
-
193
- # Build PDF
194
- doc.build(story)
195
- buffer.seek(0)
196
- return buffer
197
-
198
- def send_whatsapp_message(message, recipient=PATIENT_PHONE, pdf_data=None, pdf_name=None):
199
- """
200
- Sends a WhatsApp message using Twilio.
201
- If pdf_data is provided, it attaches the PDF to the message.
202
- """
203
- try:
204
- client = Client(ACCOUNT_SID, AUTH_TOKEN)
205
-
206
- # Check if recipient needs WhatsApp prefix
207
- if not recipient.startswith('whatsapp:'):
208
- recipient = f'whatsapp:{recipient}'
209
-
210
- message_params = {
211
- 'from_': TWILIO_FROM,
212
- 'body': message,
213
- 'to': recipient
214
- }
215
-
216
- # If we have a PDF to send, attach it
217
- if pdf_data and pdf_name:
218
- # Create a temporary file
219
- temp_pdf_path = os.path.join(app.config['PDF_FOLDER'], pdf_name)
220
- with open(temp_pdf_path, 'wb') as f:
221
- f.write(pdf_data.getvalue())
222
-
223
- # In a production environment, we would use a proper URL
224
- # For now, inform the user that the PDF would be attached
225
- message_params['body'] += "\n\nYour care plan PDF has been generated and would normally be attached here. Please check the web interface to download it."
226
-
227
- msg = client.messages.create(**message_params)
228
- return {
229
- 'success': True,
230
- 'sid': msg.sid
231
- }
232
- except Exception as e:
233
- print(f"Error sending WhatsApp message: {e}")
234
- return {
235
- 'success': False,
236
- 'error': str(e)
237
- }
238
-
239
- def determine_status(feedback, old_plan, new_plan):
240
- """
241
- Determine status of patient based on feedback and comparison of plans
242
- Returns: 'emergency', 'warning', or 'normal'
243
- """
244
- # Emergency keywords to check for severe symptoms
245
- emergency_keywords = [
246
- # Cardiovascular
247
- "severe chest pain", "heart attack", "shortness of breath",
248
- "dizziness", "loss of consciousness", "extreme pain",
249
-
250
- # Neurological
251
- "sudden weakness", "confusion", "slurred speech", "severe headache",
252
-
253
- # Respiratory
254
- "difficulty breathing", "severe shortness of breath", "wheezing", "respiratory distress",
255
-
256
- # Gastrointestinal
257
- "severe abdominal pain", "persistent vomiting", "uncontrolled bleeding",
258
-
259
- # Others
260
- "severe allergic reaction", "anaphylaxis"
261
- ]
262
-
263
- # Warning keywords for concerning but not emergency conditions
264
- warning_keywords = [
265
- "pain", "worsening", "not improving", "getting worse", "fever",
266
- "nausea", "vomiting", "rash", "diarrhea", "discomfort",
267
- "fatigue", "headache", "increase", "swelling", "irregular"
268
- ]
269
-
270
- feedback_lower = feedback.lower()
271
-
272
- # Check for emergency conditions first
273
- if any(keyword in feedback_lower for keyword in emergency_keywords):
274
- return "emergency"
275
-
276
- # Check for warning conditions
277
- if any(keyword in feedback_lower for keyword in warning_keywords):
278
- return "warning"
279
-
280
- # Compare old and new plans to detect significant changes
281
- if old_plan and new_plan:
282
- # Use Gemini to compare the plans
283
- comparison_prompt = f"""
284
- Compare these two care plans and tell me if there are significant changes
285
- that might indicate the patient's condition is deteriorating or improving.
286
- Answer only with a single word: "improved", "deteriorated", or "stable".
287
-
288
- Original care plan:
289
- {old_plan}
290
-
291
- Updated care plan:
292
- {new_plan}
293
- """
294
-
295
- try:
296
- response = model.generate_content(comparison_prompt)
297
- comparison_result = response.text.strip().lower()
298
-
299
- if "deteriorated" in comparison_result:
300
- return "warning"
301
- elif "improved" in comparison_result:
302
- return "normal"
303
- else:
304
- return "normal"
305
- except Exception as e:
306
- print(f"Error comparing plans: {e}")
307
- return "normal"
308
-
309
- return "normal"
310
 
311
  @app.route('/')
312
  def index():
313
  return render_template('index.html')
314
 
 
315
  @app.route('/switch_role', methods=['POST'])
316
  def switch_role():
317
  role = request.form.get('role')
318
  session['role'] = role
319
  return jsonify({'success': True, 'role': role})
320
 
 
321
  @app.route('/doctor_dashboard')
322
  def doctor_dashboard():
323
  if session.get('role') != 'doctor':
324
  return redirect('/')
325
  return render_template('doctor_dashboard.html')
326
 
327
- @app.route('/download_pdf/<filename>')
328
- def download_pdf(filename):
329
- try:
330
- return send_file(
331
- os.path.join(app.config['PDF_FOLDER'], filename),
332
- as_attachment=True,
333
- download_name=filename
334
- )
335
- except Exception as e:
336
- return jsonify({'success': False, 'error': str(e)})
337
-
338
- @app.route('/get_care_plan_details/<plan_id>')
339
- def get_care_plan_details(plan_id):
340
- try:
341
- care_plans = getattr(app, 'patient_care_plans', [])
342
- plan = next((p for p in care_plans if p.get('id') == plan_id), None)
343
-
344
- if not plan:
345
- return jsonify({'success': False, 'error': 'Care plan not found'})
346
-
347
- return jsonify({
348
- 'success': True,
349
- 'plan': plan
350
- })
351
- except Exception as e:
352
- return jsonify({'success': False, 'error': str(e)})
353
 
354
  @app.route('/submit_feedback', methods=['POST'])
355
  def submit_feedback():
356
  try:
357
  feedback = request.form.get('feedback', '')
358
- patient_name = request.form.get('patient_name', 'Patient')
359
- patient_phone = PATIENT_PHONE # Use the hardcoded phone number
360
-
361
  care_plan_text = ""
362
  care_plan_format = None
363
-
364
  if 'care_plan_pdf' in request.files:
365
  pdf_file = request.files['care_plan_pdf']
366
  if pdf_file.filename != '':
@@ -371,38 +105,53 @@ def submit_feedback():
371
  if not care_plan_format:
372
  care_plan_format = """
373
  ASSESSMENT:
374
- - Assessment details
375
-
376
  DAILY CARE PLAN:
377
- - Morning activities
378
- - Afternoon activities
379
- - Evening activities
380
-
 
 
381
  MEDICATIONS:
382
- - Medication details
383
-
384
  ADDITIONAL RECOMMENDATIONS:
385
- - Recommendations
386
-
387
  FOLLOW-UP:
388
- - Follow-up details
389
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
 
391
- # Determine if this is an emergency situation
392
- status = determine_status(feedback, care_plan_text, None)
393
- is_emergency = (status == "emergency")
394
 
395
  if is_emergency:
396
  # Store emergency notification
397
  emergency_data = {
398
- 'id': datetime.now().strftime("%Y%m%d%H%M%S"),
399
- 'patient_name': patient_name,
400
- 'patient_phone': patient_phone,
401
  'patient_feedback': feedback,
402
  'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
403
- 'status': 'emergency'
404
  }
405
-
 
406
  if not hasattr(app, 'emergency_notifications'):
407
  app.emergency_notifications = []
408
  app.emergency_notifications.append(emergency_data)
@@ -411,118 +160,49 @@ FOLLOW-UP:
411
  emergency_message = (
412
  "Emergency symptoms detected. Please call emergency services immediately at 104/108/109/112."
413
  )
414
-
415
- # Send emergency message to patient
416
- send_whatsapp_message(
417
- message=emergency_message,
418
- recipient=patient_phone
419
- )
420
-
421
  return jsonify({
422
  'success': True,
423
- 'is_emergency': True,
424
- 'status': 'emergency',
425
  'updated_plan': emergency_message
426
  })
427
 
428
- # Prepare a prompt for Gemini AI
429
  prompt = f"""
430
  Patient Care Plan Update Request:
431
- Patient Name: {patient_name}
432
  Current Symptoms and Feedback: {feedback}
433
  Current Care Plan (extracted from PDF): {care_plan_text}
434
-
435
- Based on the patient's feedback and current care plan, please provide an updated, comprehensive daily care plan in the exact following format:
436
  {care_plan_format}
437
-
438
  Please ensure the following:
439
- 1. The response is well-structured with clear section headings.
440
- 2. Use bullet points for list items without including any asterisk (*) symbols.
441
- 3. Format the text attractively and professionally.
442
- 4. Remove any extraneous symbols.
443
- 5. Be specific and detailed with recommendations.
444
  """
445
-
446
  # Get response from Gemini AI
447
  response = model.generate_content(prompt)
448
-
449
  # Remove any asterisk symbols from the response text
450
  updated_plan = response.text.replace("*", "")
451
-
452
- # Determine status based on feedback and plan comparison
453
- status = determine_status(feedback, care_plan_text, updated_plan)
454
-
455
- # Generate PDF
456
- pdf_buffer = create_care_plan_pdf(updated_plan, patient_name)
457
-
458
- # Save the PDF to file system with a unique name
459
- timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
460
- safe_name = re.sub(r'[^a-zA-Z0-9]', '_', patient_name)
461
- pdf_filename = f"care_plan_{safe_name}_{timestamp}.pdf"
462
- pdf_path = os.path.join(app.config['PDF_FOLDER'], pdf_filename)
463
-
464
- with open(pdf_path, 'wb') as f:
465
- f.write(pdf_buffer.getvalue())
466
-
467
- # Reset the buffer pointer for potential reuse
468
- pdf_buffer.seek(0)
469
-
470
- # Store care plan data
471
- care_plan_data = {
472
- 'id': timestamp,
473
- 'patient_name': patient_name,
474
- 'original_plan': care_plan_text,
475
- 'updated_plan': updated_plan,
476
- 'feedback': feedback,
477
- 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
478
- 'pdf_filename': pdf_filename,
479
- 'status': status
480
- }
481
-
482
- if not hasattr(app, 'patient_care_plans'):
483
- app.patient_care_plans = []
484
- app.patient_care_plans.append(care_plan_data)
485
-
486
- # Send WhatsApp message with PDF
487
- message_result = send_whatsapp_message(
488
- message=f"Hello {patient_name}, your updated care plan is ready based on your feedback. Please review it and contact your healthcare provider if you have any questions.",
489
- recipient=patient_phone,
490
- pdf_data=pdf_buffer,
491
- pdf_name=pdf_filename
492
- )
493
-
494
  return jsonify({
495
  'success': True,
496
- 'updated_plan': updated_plan,
497
- 'pdf_filename': pdf_filename,
498
- 'message_sent': message_result['success'] if message_result else False,
499
- 'is_emergency': False,
500
- 'status': status
501
  })
502
-
503
  except Exception as e:
504
- import traceback
505
- traceback.print_exc()
506
  return jsonify({
507
  'success': False,
508
  'error': str(e)
509
  })
510
 
 
511
  @app.route('/get_emergency_notifications')
512
  def get_emergency_notifications():
513
  if session.get('role') != 'doctor':
514
  return jsonify({'success': False, 'error': 'Unauthorized'})
515
-
516
  notifications = getattr(app, 'emergency_notifications', [])
517
  return jsonify({'success': True, 'notifications': notifications})
518
 
519
- @app.route('/get_patient_care_plans')
520
- def get_patient_care_plans():
521
- if session.get('role') != 'doctor':
522
- return jsonify({'success': False, 'error': 'Unauthorized'})
523
-
524
- care_plans = getattr(app, 'patient_care_plans', [])
525
- return jsonify({'success': True, 'care_plans': care_plans})
526
 
527
  if __name__ == '__main__':
528
  app.run(debug=True)
 
1
+ from flask import Flask, render_template, request, jsonify, session, redirect
2
  import google.generativeai as genai
3
  import PyPDF2
4
  import os
5
  import re
 
6
  from datetime import datetime
 
 
 
 
 
 
 
7
 
8
  app = Flask(__name__)
 
9
 
10
+ app.secret_key = '688ed745a74bdd7ac238f5b50f4104fb87d6774b8b0a4e06e7e18ac5ed0fa31c' # Add this for session management
11
+ upload_base = os.getenv('UPLOAD_DIR')
12
  upload_folder = os.path.join(upload_base, 'uploads')
 
 
 
13
 
14
+ app.config['UPLOAD_FOLDER'] = upload_folder
15
  os.makedirs(upload_folder, exist_ok=True)
 
 
 
 
 
 
 
 
16
 
17
  # Gemini API Configuration
18
+ genai.configure(api_key="AIzaSyD54ejbjVIVa-F3aD_Urnp8m1EFLUGR__I")
19
+
20
  generation_config = {
21
  "temperature": 1,
22
  "top_p": 0.95,
23
  "top_k": 40,
24
  "max_output_tokens": 8192,
25
  }
26
+
27
  model = genai.GenerativeModel(
28
  model_name="gemini-2.0-flash",
29
  generation_config=generation_config,
30
  )
31
 
 
 
 
 
 
32
 
33
  def extract_text_from_pdf(pdf_file):
34
  try:
 
41
  print(f"Error extracting PDF text: {e}")
42
  return ""
43
 
44
+
45
  def extract_care_plan_format(pdf_text):
46
  """Extract the care plan format from PDF text"""
47
  try:
48
  # Find sections and their content in the PDF using regex
49
  sections = re.findall(
50
+ r'([A-Z][A-Z\s]+)[:|\n]((?:(?!\n[A-Z][A-Z\s]+[:|\n]).)*)',
51
  pdf_text,
52
  re.DOTALL
53
  )
54
+
55
  if sections:
56
  format_template = ""
57
  for section, content in sections:
 
68
  print(f"Error extracting format: {e}")
69
  return None
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  @app.route('/')
73
  def index():
74
  return render_template('index.html')
75
 
76
+
77
  @app.route('/switch_role', methods=['POST'])
78
  def switch_role():
79
  role = request.form.get('role')
80
  session['role'] = role
81
  return jsonify({'success': True, 'role': role})
82
 
83
+
84
  @app.route('/doctor_dashboard')
85
  def doctor_dashboard():
86
  if session.get('role') != 'doctor':
87
  return redirect('/')
88
  return render_template('doctor_dashboard.html')
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  @app.route('/submit_feedback', methods=['POST'])
92
  def submit_feedback():
93
  try:
94
  feedback = request.form.get('feedback', '')
 
 
 
95
  care_plan_text = ""
96
  care_plan_format = None
97
+
98
  if 'care_plan_pdf' in request.files:
99
  pdf_file = request.files['care_plan_pdf']
100
  if pdf_file.filename != '':
 
105
  if not care_plan_format:
106
  care_plan_format = """
107
  ASSESSMENT:
108
+ [Assessment details]
 
109
  DAILY CARE PLAN:
110
+ Morning:
111
+ - [Morning activities]
112
+ Afternoon:
113
+ - [Afternoon activities]
114
+ Evening:
115
+ - [Evening activities]
116
  MEDICATIONS:
117
+ - [Medication details]
 
118
  ADDITIONAL RECOMMENDATIONS:
119
+ - [Recommendations]
 
120
  FOLLOW-UP:
121
+ [Follow-up details]
122
+ """
123
+
124
+ # Define emergency keywords to check for severe symptoms
125
+ emergency_keywords = [
126
+ # Cardiovascular
127
+ "severe chest pain", "heart attack", "shortness of breath",
128
+ "dizziness", "loss of consciousness", "extreme pain",
129
+
130
+ # Neurological
131
+ "sudden weakness", "confusion", "slurred speech", "severe headache",
132
+
133
+ # Respiratory
134
+ "difficulty breathing", "severe shortness of breath", "wheezing", "respiratory distress",
135
+
136
+ # Gastrointestinal
137
+ "severe abdominal pain", "persistent vomiting", "uncontrolled bleeding",
138
+
139
+ # Others
140
+ "severe allergic reaction", "anaphylaxis"
141
+ ]
142
 
143
+ feedback_lower = feedback.lower()
144
+ is_emergency = any(keyword in feedback_lower for keyword in emergency_keywords)
 
145
 
146
  if is_emergency:
147
  # Store emergency notification
148
  emergency_data = {
 
 
 
149
  'patient_feedback': feedback,
150
  'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
151
+ 'status': 'urgent'
152
  }
153
+ # In a real application, you would store this in a database
154
+ # For now, we'll use a global variable (not recommended for production)
155
  if not hasattr(app, 'emergency_notifications'):
156
  app.emergency_notifications = []
157
  app.emergency_notifications.append(emergency_data)
 
160
  emergency_message = (
161
  "Emergency symptoms detected. Please call emergency services immediately at 104/108/109/112."
162
  )
 
 
 
 
 
 
 
163
  return jsonify({
164
  'success': True,
 
 
165
  'updated_plan': emergency_message
166
  })
167
 
168
+ # Prepare a prompt for Gemini AI for a perfect, attractively formatted day care plan.
169
  prompt = f"""
170
  Patient Care Plan Update Request:
 
171
  Current Symptoms and Feedback: {feedback}
172
  Current Care Plan (extracted from PDF): {care_plan_text}
173
+ Based on the patient's feedback and current care plan, please provide an updated, perfect daily care plan in the exact following format:
 
174
  {care_plan_format}
 
175
  Please ensure the following:
176
+ - The response is well-structured with clear section headings.
177
+ - Use bullet points for list items without including any asterisk (*) symbols.
178
+ - Format the text attractively and professionally.
179
+ - Remove any extraneous symbols.
 
180
  """
 
181
  # Get response from Gemini AI
182
  response = model.generate_content(prompt)
 
183
  # Remove any asterisk symbols from the response text
184
  updated_plan = response.text.replace("*", "")
185
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  return jsonify({
187
  'success': True,
188
+ 'updated_plan': updated_plan
 
 
 
 
189
  })
190
+
191
  except Exception as e:
 
 
192
  return jsonify({
193
  'success': False,
194
  'error': str(e)
195
  })
196
 
197
+
198
  @app.route('/get_emergency_notifications')
199
  def get_emergency_notifications():
200
  if session.get('role') != 'doctor':
201
  return jsonify({'success': False, 'error': 'Unauthorized'})
202
+
203
  notifications = getattr(app, 'emergency_notifications', [])
204
  return jsonify({'success': True, 'notifications': notifications})
205
 
 
 
 
 
 
 
 
206
 
207
  if __name__ == '__main__':
208
  app.run(debug=True)