pranit144 commited on
Commit
fd11474
·
verified ·
1 Parent(s): 1e5f303

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -212
app.py CHANGED
@@ -1,213 +1,213 @@
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
-
68
- @app.route('/')
69
- def index():
70
- return render_template('index.html')
71
-
72
-
73
- @app.route('/switch_role', methods=['POST'])
74
- def switch_role():
75
- role = request.form.get('role')
76
- session['role'] = role
77
- return jsonify({'success': True, 'role': role})
78
-
79
-
80
- @app.route('/doctor_dashboard')
81
- def doctor_dashboard():
82
- if session.get('role') != 'doctor':
83
- return redirect('/')
84
- return render_template('doctor_dashboard.html')
85
-
86
-
87
- @app.route('/submit_feedback', methods=['POST'])
88
- def submit_feedback():
89
- try:
90
- feedback = request.form.get('feedback', '')
91
- care_plan_text = ""
92
- care_plan_format = None
93
-
94
- if 'care_plan_pdf' in request.files:
95
- pdf_file = request.files['care_plan_pdf']
96
- if pdf_file.filename != '':
97
- care_plan_text = extract_text_from_pdf(pdf_file)
98
- care_plan_format = extract_care_plan_format(care_plan_text)
99
-
100
- # If no format is found in the PDF, use a default format
101
- if not care_plan_format:
102
- care_plan_format = """
103
- ASSESSMENT:
104
- [Assessment details]
105
-
106
- DAILY CARE PLAN:
107
- Morning:
108
- - [Morning activities]
109
-
110
- Afternoon:
111
- - [Afternoon activities]
112
-
113
- Evening:
114
- - [Evening activities]
115
-
116
- MEDICATIONS:
117
- - [Medication details]
118
-
119
- ADDITIONAL RECOMMENDATIONS:
120
- - [Recommendations]
121
-
122
- FOLLOW-UP:
123
- [Follow-up details]
124
- """
125
-
126
- # Define emergency keywords to check for severe symptoms
127
- emergency_keywords = [
128
- # Cardiovascular
129
- "severe chest pain", "heart attack", "shortness of breath",
130
- "dizziness", "loss of consciousness", "extreme pain",
131
-
132
- # Neurological
133
- "sudden weakness", "confusion", "slurred speech", "severe headache",
134
-
135
- # Respiratory
136
- "difficulty breathing", "severe shortness of breath", "wheezing", "respiratory distress",
137
-
138
- # Gastrointestinal
139
- "severe abdominal pain", "persistent vomiting", "uncontrolled bleeding",
140
-
141
- # Others
142
- "severe allergic reaction", "anaphylaxis"
143
- ]
144
-
145
- feedback_lower = feedback.lower()
146
- is_emergency = any(keyword in feedback_lower for keyword in emergency_keywords)
147
-
148
- if is_emergency:
149
- # Store emergency notification
150
- emergency_data = {
151
- 'patient_feedback': feedback,
152
- 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
153
- 'status': 'urgent'
154
- }
155
- # In a real application, you would store this in a database
156
- # For now, we'll use a global variable (not recommended for production)
157
- if not hasattr(app, 'emergency_notifications'):
158
- app.emergency_notifications = []
159
- app.emergency_notifications.append(emergency_data)
160
-
161
- # If emergency symptoms are detected, instruct immediate emergency response
162
- emergency_message = (
163
- "Emergency symptoms detected. Please call emergency services immediately at 104/108/109/112."
164
- )
165
- return jsonify({
166
- 'success': True,
167
- 'updated_plan': emergency_message
168
- })
169
-
170
- # Prepare a prompt for Gemini AI for a perfect, attractively formatted day care plan.
171
- prompt = f"""
172
- Patient Care Plan Update Request:
173
- Current Symptoms and Feedback: {feedback}
174
- Current Care Plan (extracted from PDF): {care_plan_text}
175
-
176
- Based on the patient's feedback and current care plan, please provide an updated, perfect daily care plan in the exact following format:
177
-
178
- {care_plan_format}
179
-
180
- Please ensure the following:
181
- - The response is well-structured with clear section headings.
182
- - Use bullet points for list items without including any asterisk (*) symbols.
183
- - Format the text attractively and professionally.
184
- - Remove any extraneous symbols.
185
- """
186
- # Get response from Gemini AI
187
- response = model.generate_content(prompt)
188
- # Remove any asterisk symbols from the response text
189
- updated_plan = response.text.replace("*", "")
190
-
191
- return jsonify({
192
- 'success': True,
193
- 'updated_plan': updated_plan
194
- })
195
-
196
- except Exception as e:
197
- return jsonify({
198
- 'success': False,
199
- 'error': str(e)
200
- })
201
-
202
-
203
- @app.route('/get_emergency_notifications')
204
- def get_emergency_notifications():
205
- if session.get('role') != 'doctor':
206
- return jsonify({'success': False, 'error': 'Unauthorized'})
207
-
208
- notifications = getattr(app, 'emergency_notifications', [])
209
- return jsonify({'success': True, 'notifications': notifications})
210
-
211
-
212
- if __name__ == '__main__':
213
  app.run(debug=True, port=5001)
 
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="AIzaSyCizcswP6vlKDMdB3HRAtVi2JbifOpbPvA")
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
+
68
+ @app.route('/')
69
+ def index():
70
+ return render_template('index.html')
71
+
72
+
73
+ @app.route('/switch_role', methods=['POST'])
74
+ def switch_role():
75
+ role = request.form.get('role')
76
+ session['role'] = role
77
+ return jsonify({'success': True, 'role': role})
78
+
79
+
80
+ @app.route('/doctor_dashboard')
81
+ def doctor_dashboard():
82
+ if session.get('role') != 'doctor':
83
+ return redirect('/')
84
+ return render_template('doctor_dashboard.html')
85
+
86
+
87
+ @app.route('/submit_feedback', methods=['POST'])
88
+ def submit_feedback():
89
+ try:
90
+ feedback = request.form.get('feedback', '')
91
+ care_plan_text = ""
92
+ care_plan_format = None
93
+
94
+ if 'care_plan_pdf' in request.files:
95
+ pdf_file = request.files['care_plan_pdf']
96
+ if pdf_file.filename != '':
97
+ care_plan_text = extract_text_from_pdf(pdf_file)
98
+ care_plan_format = extract_care_plan_format(care_plan_text)
99
+
100
+ # If no format is found in the PDF, use a default format
101
+ if not care_plan_format:
102
+ care_plan_format = """
103
+ ASSESSMENT:
104
+ [Assessment details]
105
+
106
+ DAILY CARE PLAN:
107
+ Morning:
108
+ - [Morning activities]
109
+
110
+ Afternoon:
111
+ - [Afternoon activities]
112
+
113
+ Evening:
114
+ - [Evening activities]
115
+
116
+ MEDICATIONS:
117
+ - [Medication details]
118
+
119
+ ADDITIONAL RECOMMENDATIONS:
120
+ - [Recommendations]
121
+
122
+ FOLLOW-UP:
123
+ [Follow-up details]
124
+ """
125
+
126
+ # Define emergency keywords to check for severe symptoms
127
+ emergency_keywords = [
128
+ # Cardiovascular
129
+ "severe chest pain", "heart attack", "shortness of breath",
130
+ "dizziness", "loss of consciousness", "extreme pain",
131
+
132
+ # Neurological
133
+ "sudden weakness", "confusion", "slurred speech", "severe headache",
134
+
135
+ # Respiratory
136
+ "difficulty breathing", "severe shortness of breath", "wheezing", "respiratory distress",
137
+
138
+ # Gastrointestinal
139
+ "severe abdominal pain", "persistent vomiting", "uncontrolled bleeding",
140
+
141
+ # Others
142
+ "severe allergic reaction", "anaphylaxis"
143
+ ]
144
+
145
+ feedback_lower = feedback.lower()
146
+ is_emergency = any(keyword in feedback_lower for keyword in emergency_keywords)
147
+
148
+ if is_emergency:
149
+ # Store emergency notification
150
+ emergency_data = {
151
+ 'patient_feedback': feedback,
152
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
153
+ 'status': 'urgent'
154
+ }
155
+ # In a real application, you would store this in a database
156
+ # For now, we'll use a global variable (not recommended for production)
157
+ if not hasattr(app, 'emergency_notifications'):
158
+ app.emergency_notifications = []
159
+ app.emergency_notifications.append(emergency_data)
160
+
161
+ # If emergency symptoms are detected, instruct immediate emergency response
162
+ emergency_message = (
163
+ "Emergency symptoms detected. Please call emergency services immediately at 104/108/109/112."
164
+ )
165
+ return jsonify({
166
+ 'success': True,
167
+ 'updated_plan': emergency_message
168
+ })
169
+
170
+ # Prepare a prompt for Gemini AI for a perfect, attractively formatted day care plan.
171
+ prompt = f"""
172
+ Patient Care Plan Update Request:
173
+ Current Symptoms and Feedback: {feedback}
174
+ Current Care Plan (extracted from PDF): {care_plan_text}
175
+
176
+ Based on the patient's feedback and current care plan, please provide an updated, perfect daily care plan in the exact following format:
177
+
178
+ {care_plan_format}
179
+
180
+ Please ensure the following:
181
+ - The response is well-structured with clear section headings.
182
+ - Use bullet points for list items without including any asterisk (*) symbols.
183
+ - Format the text attractively and professionally.
184
+ - Remove any extraneous symbols.
185
+ """
186
+ # Get response from Gemini AI
187
+ response = model.generate_content(prompt)
188
+ # Remove any asterisk symbols from the response text
189
+ updated_plan = response.text.replace("*", "")
190
+
191
+ return jsonify({
192
+ 'success': True,
193
+ 'updated_plan': updated_plan
194
+ })
195
+
196
+ except Exception as e:
197
+ return jsonify({
198
+ 'success': False,
199
+ 'error': str(e)
200
+ })
201
+
202
+
203
+ @app.route('/get_emergency_notifications')
204
+ def get_emergency_notifications():
205
+ if session.get('role') != 'doctor':
206
+ return jsonify({'success': False, 'error': 'Unauthorized'})
207
+
208
+ notifications = getattr(app, 'emergency_notifications', [])
209
+ return jsonify({'success': True, 'notifications': notifications})
210
+
211
+
212
+ if __name__ == '__main__':
213
  app.run(debug=True, port=5001)