pranit144 commited on
Commit
5874435
·
verified ·
1 Parent(s): 5672f98

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +209 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ app.config['UPLOAD_FOLDER'] = 'uploads'
10
+ app.secret_key = '688ed745a74bdd7ac238f5b50f4104fb87d6774b8b0a4e06e7e18ac5ed0fa31c' # Add this for session management
11
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
12
+
13
+ # Gemini API Configuration
14
+ genai.configure(api_key="AIzaSyA3joMQMnael_heUCwpNvoRznCUiU3avf4")
15
+
16
+ generation_config = {
17
+ "temperature": 1,
18
+ "top_p": 0.95,
19
+ "top_k": 40,
20
+ "max_output_tokens": 8192,
21
+ }
22
+
23
+ model = genai.GenerativeModel(
24
+ model_name="gemini-2.0-flash-exp",
25
+ generation_config=generation_config,
26
+ )
27
+
28
+
29
+ def extract_text_from_pdf(pdf_file):
30
+ try:
31
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
32
+ text = ""
33
+ for page in pdf_reader.pages:
34
+ text += page.extract_text()
35
+ return text.strip()
36
+ except Exception as e:
37
+ print(f"Error extracting PDF text: {e}")
38
+ return ""
39
+
40
+
41
+ def extract_care_plan_format(pdf_text):
42
+ """Extract the care plan format from PDF text"""
43
+ try:
44
+ # Find sections and their content in the PDF using regex
45
+ sections = re.findall(
46
+ r'([A-Z][A-Z\s]+)[:|\n]((?:(?!\n[A-Z][A-Z\s]+[:|\n]).)*)',
47
+ pdf_text,
48
+ re.DOTALL
49
+ )
50
+
51
+ if sections:
52
+ format_template = ""
53
+ for section, content in sections:
54
+ format_template += f"{section.strip()}:\n"
55
+ # Extract bullet points if they exist and remove any asterisks
56
+ bullets = re.findall(r'[-•*]\s*(.*?)(?=[-•*]|\n|$)', content)
57
+ if bullets:
58
+ for bullet in bullets:
59
+ format_template += f"- {bullet.strip()}\n"
60
+ format_template += "\n"
61
+ return format_template
62
+ return None
63
+ except Exception as e:
64
+ print(f"Error extracting format: {e}")
65
+ return None
66
+
67
+ @app.route('/')
68
+ def index():
69
+ return render_template('index.html')
70
+
71
+ @app.route('/switch_role', methods=['POST'])
72
+ def switch_role():
73
+ role = request.form.get('role')
74
+ session['role'] = role
75
+ return jsonify({'success': True, 'role': role})
76
+
77
+ @app.route('/doctor_dashboard')
78
+ def doctor_dashboard():
79
+ if session.get('role') != 'doctor':
80
+ return redirect('/')
81
+ return render_template('doctor_dashboard.html')
82
+
83
+ @app.route('/submit_feedback', methods=['POST'])
84
+ def submit_feedback():
85
+ try:
86
+ feedback = request.form.get('feedback', '')
87
+ care_plan_text = ""
88
+ care_plan_format = None
89
+
90
+ if 'care_plan_pdf' in request.files:
91
+ pdf_file = request.files['care_plan_pdf']
92
+ if pdf_file.filename != '':
93
+ care_plan_text = extract_text_from_pdf(pdf_file)
94
+ care_plan_format = extract_care_plan_format(care_plan_text)
95
+
96
+ # If no format is found in the PDF, use a default format
97
+ if not care_plan_format:
98
+ care_plan_format = """
99
+ ASSESSMENT:
100
+ [Assessment details]
101
+
102
+ DAILY CARE PLAN:
103
+ Morning:
104
+ - [Morning activities]
105
+
106
+ Afternoon:
107
+ - [Afternoon activities]
108
+
109
+ Evening:
110
+ - [Evening activities]
111
+
112
+ MEDICATIONS:
113
+ - [Medication details]
114
+
115
+ ADDITIONAL RECOMMENDATIONS:
116
+ - [Recommendations]
117
+
118
+ FOLLOW-UP:
119
+ [Follow-up details]
120
+ """
121
+
122
+ # Define emergency keywords to check for severe symptoms
123
+ emergency_keywords = [
124
+ # Cardiovascular
125
+ "severe chest pain", "heart attack", "shortness of breath",
126
+ "dizziness", "loss of consciousness", "extreme pain",
127
+
128
+ # Neurological
129
+ "sudden weakness", "confusion", "slurred speech", "severe headache",
130
+
131
+ # Respiratory
132
+ "difficulty breathing", "severe shortness of breath", "wheezing", "respiratory distress",
133
+
134
+ # Gastrointestinal
135
+ "severe abdominal pain", "persistent vomiting", "uncontrolled bleeding",
136
+
137
+ # Others
138
+ "severe allergic reaction", "anaphylaxis"
139
+ ]
140
+
141
+ feedback_lower = feedback.lower()
142
+ is_emergency = any(keyword in feedback_lower for keyword in emergency_keywords)
143
+
144
+ if is_emergency:
145
+ # Store emergency notification
146
+ emergency_data = {
147
+ 'patient_feedback': feedback,
148
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
149
+ 'status': 'urgent'
150
+ }
151
+ # In a real application, you would store this in a database
152
+ # For now, we'll use a global variable (not recommended for production)
153
+ if not hasattr(app, 'emergency_notifications'):
154
+ app.emergency_notifications = []
155
+ app.emergency_notifications.append(emergency_data)
156
+
157
+ # If emergency symptoms are detected, instruct immediate emergency response
158
+ emergency_message = (
159
+ "Emergency symptoms detected. Please call emergency services immediately at 104/108/109/112."
160
+ )
161
+ return jsonify({
162
+ 'success': True,
163
+ 'updated_plan': emergency_message
164
+ })
165
+
166
+ # Prepare a prompt for Gemini AI for a perfect, attractively formatted day care plan.
167
+ prompt = f"""
168
+ Patient Care Plan Update Request:
169
+ Current Symptoms and Feedback: {feedback}
170
+ Current Care Plan (extracted from PDF): {care_plan_text}
171
+
172
+ Based on the patient's feedback and current care plan, please provide an updated, perfect daily care plan in the exact following format:
173
+
174
+ {care_plan_format}
175
+
176
+ Please ensure the following:
177
+ - The response is well-structured with clear section headings.
178
+ - Use bullet points for list items without including any asterisk (*) symbols.
179
+ - Format the text attractively and professionally.
180
+ - Remove any extraneous symbols.
181
+ """
182
+ # Get response from Gemini AI
183
+ response = model.generate_content(prompt)
184
+ # Remove any asterisk symbols from the response text
185
+ updated_plan = response.text.replace("*", "")
186
+
187
+ return jsonify({
188
+ 'success': True,
189
+ 'updated_plan': updated_plan
190
+ })
191
+
192
+ except Exception as e:
193
+ return jsonify({
194
+ 'success': False,
195
+ 'error': str(e)
196
+ })
197
+
198
+
199
+ @app.route('/get_emergency_notifications')
200
+ def get_emergency_notifications():
201
+ if session.get('role') != 'doctor':
202
+ return jsonify({'success': False, 'error': 'Unauthorized'})
203
+
204
+ notifications = getattr(app, 'emergency_notifications', [])
205
+ return jsonify({'success': True, 'notifications': notifications})
206
+
207
+
208
+ if __name__ == '__main__':
209
+ app.run(debug=True, port=5001)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Flask==3.0.2
2
+ google-generativeai==0.3.2
3
+ PyPDF2==3.0.1