Ali2206 commited on
Commit
b207889
·
verified ·
1 Parent(s): 06eac36

Update analysis.py

Browse files
Files changed (1) hide show
  1. analysis.py +40 -3
analysis.py CHANGED
@@ -1,6 +1,6 @@
1
  from typing import Optional, Tuple, List
2
  from enum import Enum
3
- from config import agent, patients_collection, analysis_collection, alerts_collection, logger
4
  from models import RiskLevel
5
  from utils import (
6
  structure_medical_response,
@@ -26,6 +26,10 @@ class NotificationStatus(str, Enum):
26
 
27
  async def create_alert(patient_id: str, risk_data: dict):
28
  try:
 
 
 
 
29
  alert_doc = {
30
  "patient_id": patient_id,
31
  "type": "suicide_risk",
@@ -38,7 +42,7 @@ async def create_alert(patient_id: str, risk_data: dict):
38
  "type": "risk_alert",
39
  "status": "unread",
40
  "title": f"Suicide Risk: {risk_data['level'].capitalize()}",
41
- "message": f"Patient {patient_id} shows {risk_data['level']} risk factors",
42
  "icon": "⚠️",
43
  "action_url": f"/patient/{patient_id}/risk-assessment",
44
  "priority": "high" if risk_data["level"] in ["high", "severe"] else "medium"
@@ -47,10 +51,43 @@ async def create_alert(patient_id: str, risk_data: dict):
47
 
48
  await alerts_collection.insert_one(alert_doc)
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # Simplified WebSocket notification - remove Hugging Face specific code
51
  await broadcast_notification(alert_doc["notification"])
52
 
53
- logger.warning(f"⚠️ Created suicide risk alert for patient {patient_id}")
54
  return alert_doc
55
  except Exception as e:
56
  logger.error(f"Failed to create alert: {str(e)}")
 
1
  from typing import Optional, Tuple, List
2
  from enum import Enum
3
+ from config import agent, patients_collection, analysis_collection, alerts_collection, notifications_collection, users_collection, logger
4
  from models import RiskLevel
5
  from utils import (
6
  structure_medical_response,
 
26
 
27
  async def create_alert(patient_id: str, risk_data: dict):
28
  try:
29
+ # Get patient information for better notification message
30
+ patient = await patients_collection.find_one({"fhir_id": patient_id})
31
+ patient_name = patient.get("full_name", "Unknown Patient") if patient else "Unknown Patient"
32
+
33
  alert_doc = {
34
  "patient_id": patient_id,
35
  "type": "suicide_risk",
 
42
  "type": "risk_alert",
43
  "status": "unread",
44
  "title": f"Suicide Risk: {risk_data['level'].capitalize()}",
45
+ "message": f"Patient {patient_name} ({patient_id}) shows {risk_data['level']} risk factors",
46
  "icon": "⚠️",
47
  "action_url": f"/patient/{patient_id}/risk-assessment",
48
  "priority": "high" if risk_data["level"] in ["high", "severe"] else "medium"
 
51
 
52
  await alerts_collection.insert_one(alert_doc)
53
 
54
+ # Create notifications for all doctors and admins when risk is high or moderate
55
+ if risk_data["level"] in ["high", "moderate", "severe"]:
56
+ # Get all users with doctor or admin roles
57
+ doctors_and_admins = await users_collection.find({
58
+ "roles": {"$in": ["doctor", "admin"]}
59
+ }).to_list(length=None)
60
+
61
+ logger.info(f"📧 Creating notifications for {len(doctors_and_admins)} doctors/admins")
62
+
63
+ # Create individual notifications for each doctor/admin
64
+ notifications = []
65
+ for user in doctors_and_admins:
66
+ notification = {
67
+ "user_id": user["email"],
68
+ "patient_id": patient_id,
69
+ "message": f"🚨 {risk_data['level'].upper()} suicide risk detected for patient {patient_name}",
70
+ "timestamp": datetime.utcnow(),
71
+ "severity": "high" if risk_data["level"] in ["high", "severe"] else "medium",
72
+ "read": False,
73
+ "type": "suicide_risk_alert",
74
+ "risk_level": risk_data["level"],
75
+ "risk_score": risk_data["score"],
76
+ "patient_name": patient_name
77
+ }
78
+ notifications.append(notification)
79
+
80
+ if notifications:
81
+ # Insert all notifications at once
82
+ result = await notifications_collection.insert_many(notifications)
83
+ logger.info(f"✅ Created {len(result.inserted_ids)} notifications for risk alert")
84
+ else:
85
+ logger.warning("⚠️ No doctors or admins found to notify")
86
+
87
  # Simplified WebSocket notification - remove Hugging Face specific code
88
  await broadcast_notification(alert_doc["notification"])
89
 
90
+ logger.warning(f"⚠️ Created suicide risk alert for patient {patient_id} ({patient_name}) - Level: {risk_data['level']}")
91
  return alert_doc
92
  except Exception as e:
93
  logger.error(f"Failed to create alert: {str(e)}")