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