Update endpoints.py
Browse files- endpoints.py +22 -22
endpoints.py
CHANGED
@@ -13,14 +13,14 @@ import io
|
|
13 |
from datetime import datetime
|
14 |
from bson import ObjectId
|
15 |
import asyncio
|
16 |
-
from config import notifications_collection, send_push_notification
|
17 |
|
18 |
def create_router(agent, logger, patients_collection, analysis_collection, users_collection, notifications_collection):
|
19 |
router = APIRouter()
|
20 |
|
21 |
@router.get("/status")
|
22 |
async def status(current_user: dict = Depends(get_current_user)):
|
23 |
-
logger.info(f"Status endpoint accessed by {current_user['email']}")
|
24 |
return {
|
25 |
"status": "running",
|
26 |
"timestamp": datetime.utcnow().isoformat(),
|
@@ -33,7 +33,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
33 |
name: Optional[str] = Query(None),
|
34 |
current_user: dict = Depends(get_current_user)
|
35 |
):
|
36 |
-
logger.info(f"Fetching analysis results by {current_user['email']}")
|
37 |
try:
|
38 |
query = {}
|
39 |
if name:
|
@@ -57,12 +57,12 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
57 |
return enriched_results
|
58 |
|
59 |
except Exception as e:
|
60 |
-
logger.error(f"Error fetching analysis results: {e}")
|
61 |
raise HTTPException(status_code=500, detail="Failed to retrieve analysis results")
|
62 |
|
63 |
@router.get("/notifications")
|
64 |
async def get_notifications(current_user: dict = Depends(get_current_user)):
|
65 |
-
logger.info(f"Fetching notifications for {current_user['email']}")
|
66 |
try:
|
67 |
notifications = await notifications_collection.find(
|
68 |
{"recipient_email": current_user["email"]}
|
@@ -73,7 +73,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
73 |
notification["timestamp"] = notification["timestamp"].isoformat()
|
74 |
return notifications
|
75 |
except Exception as e:
|
76 |
-
logger.error(f"Error fetching notifications: {str(e)}")
|
77 |
raise HTTPException(status_code=500, detail="Failed to retrieve notifications")
|
78 |
|
79 |
@router.post("/chat-stream")
|
@@ -81,7 +81,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
81 |
request: ChatRequest,
|
82 |
current_user: dict = Depends(get_current_user)
|
83 |
):
|
84 |
-
logger.info(f"Chat stream initiated by {current_user['email']}")
|
85 |
async def token_stream():
|
86 |
try:
|
87 |
conversation = [{"role": "system", "content": agent.chat_prompt}]
|
@@ -107,7 +107,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
107 |
yield chunk + " "
|
108 |
await asyncio.sleep(0.05)
|
109 |
except Exception as e:
|
110 |
-
logger.error(f"Streaming error: {e}")
|
111 |
yield f"⚠️ Error: {e}"
|
112 |
|
113 |
return StreamingResponse(token_stream(), media_type="text/plain")
|
@@ -118,7 +118,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
118 |
language: str = Query("en-US", description="Language code for speech recognition"),
|
119 |
current_user: dict = Depends(get_current_user)
|
120 |
):
|
121 |
-
logger.info(f"Voice transcription initiated by {current_user['email']}")
|
122 |
try:
|
123 |
audio_data = await audio.read()
|
124 |
if not audio.filename.lower().endswith(('.wav', '.mp3', '.ogg', '.flac')):
|
@@ -130,7 +130,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
130 |
except HTTPException:
|
131 |
raise
|
132 |
except Exception as e:
|
133 |
-
logger.error(f"Error in voice transcription: {e}")
|
134 |
raise HTTPException(status_code=500, detail="Error processing voice input")
|
135 |
|
136 |
@router.post("/voice/synthesize")
|
@@ -138,7 +138,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
138 |
request: VoiceOutputRequest,
|
139 |
current_user: dict = Depends(get_current_user)
|
140 |
):
|
141 |
-
logger.info(f"Voice synthesis initiated by {current_user['email']}")
|
142 |
try:
|
143 |
audio_data = text_to_speech(request.text, request.language, request.slow)
|
144 |
|
@@ -154,7 +154,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
154 |
except HTTPException:
|
155 |
raise
|
156 |
except Exception as e:
|
157 |
-
logger.error(f"Error in voice synthesis: {e}")
|
158 |
raise HTTPException(status_code=500, detail="Error generating voice output")
|
159 |
|
160 |
@router.post("/voice/chat")
|
@@ -165,7 +165,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
165 |
max_new_tokens: int = Query(512, ge=50, le=1024),
|
166 |
current_user: dict = Depends(get_current_user)
|
167 |
):
|
168 |
-
logger.info(f"Voice chat initiated by {current_user['email']}")
|
169 |
try:
|
170 |
audio_data = await audio.read()
|
171 |
user_message = recognize_speech(audio_data, language)
|
@@ -188,7 +188,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
188 |
except HTTPException:
|
189 |
raise
|
190 |
except Exception as e:
|
191 |
-
logger.error(f"Error in voice chat: {e}")
|
192 |
raise HTTPException(status_code=500, detail="Error processing voice chat")
|
193 |
|
194 |
@router.post("/analyze-report")
|
@@ -199,7 +199,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
199 |
max_new_tokens: int = Form(1024),
|
200 |
current_user: dict = Depends(get_current_user)
|
201 |
):
|
202 |
-
logger.info(f"Report analysis initiated by {current_user['email']}")
|
203 |
try:
|
204 |
content_type = file.content_type
|
205 |
allowed_types = [
|
@@ -260,7 +260,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
260 |
"read": False
|
261 |
}
|
262 |
await notifications_collection.insert_one(notification)
|
263 |
-
logger.info(f"Notification created for {current_user['email']}: {notification['message']}")
|
264 |
# Send push notification
|
265 |
await send_push_notification(current_user["email"], notification["message"])
|
266 |
|
@@ -275,7 +275,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
275 |
except HTTPException:
|
276 |
raise
|
277 |
except Exception as e:
|
278 |
-
logger.error(f"Error in report analysis: {str(e)}")
|
279 |
raise HTTPException(
|
280 |
status_code=500,
|
281 |
detail=f"Failed to analyze report: {str(e)}"
|
@@ -286,7 +286,7 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
286 |
patient_id: str,
|
287 |
current_user: dict = Depends(get_current_user)
|
288 |
):
|
289 |
-
logger.info(f"Patient deletion initiated by {current_user['email']} for patient {patient_id}")
|
290 |
try:
|
291 |
patient = await patients_collection.find_one({"fhir_id": patient_id})
|
292 |
if not patient:
|
@@ -296,20 +296,20 @@ def create_router(agent, logger, patients_collection, analysis_collection, users
|
|
296 |
raise HTTPException(status_code=403, detail="Not authorized to delete this patient")
|
297 |
|
298 |
await analysis_collection.delete_many({"patient_id": patient_id})
|
299 |
-
logger.info(f"Deleted analyses for patient {patient_id}")
|
300 |
|
301 |
await notifications_collection.delete_many({"patient_id": patient_id})
|
302 |
-
logger.info(f"Deleted notifications for patient {patient_id}")
|
303 |
|
304 |
await patients_collection.delete_one({"fhir_id": patient_id})
|
305 |
-
logger.info(f"Patient {patient_id} deleted successfully")
|
306 |
|
307 |
return {"status": "success", "message": f"Patient {patient_id} and associated data deleted"}
|
308 |
|
309 |
except HTTPException:
|
310 |
raise
|
311 |
except Exception as e:
|
312 |
-
logger.error(f"Error deleting patient {patient_id}: {str(e)}")
|
313 |
raise HTTPException(status_code=500, detail=f"Failed to delete patient: {str(e)}")
|
314 |
|
315 |
return router
|
|
|
13 |
from datetime import datetime
|
14 |
from bson import ObjectId
|
15 |
import asyncio
|
16 |
+
from config import notifications_collection, send_push_notification, SECRET_KEY
|
17 |
|
18 |
def create_router(agent, logger, patients_collection, analysis_collection, users_collection, notifications_collection):
|
19 |
router = APIRouter()
|
20 |
|
21 |
@router.get("/status")
|
22 |
async def status(current_user: dict = Depends(get_current_user)):
|
23 |
+
logger.info(f"Status endpoint accessed by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
24 |
return {
|
25 |
"status": "running",
|
26 |
"timestamp": datetime.utcnow().isoformat(),
|
|
|
33 |
name: Optional[str] = Query(None),
|
34 |
current_user: dict = Depends(get_current_user)
|
35 |
):
|
36 |
+
logger.info(f"Fetching analysis results by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
37 |
try:
|
38 |
query = {}
|
39 |
if name:
|
|
|
57 |
return enriched_results
|
58 |
|
59 |
except Exception as e:
|
60 |
+
logger.error(f"Error fetching analysis results: {str(e)} at {datetime.utcnow().isoformat()}")
|
61 |
raise HTTPException(status_code=500, detail="Failed to retrieve analysis results")
|
62 |
|
63 |
@router.get("/notifications")
|
64 |
async def get_notifications(current_user: dict = Depends(get_current_user)):
|
65 |
+
logger.info(f"Fetching notifications for {current_user['email']} at {datetime.utcnow().isoformat()}")
|
66 |
try:
|
67 |
notifications = await notifications_collection.find(
|
68 |
{"recipient_email": current_user["email"]}
|
|
|
73 |
notification["timestamp"] = notification["timestamp"].isoformat()
|
74 |
return notifications
|
75 |
except Exception as e:
|
76 |
+
logger.error(f"Error fetching notifications: {str(e)} at {datetime.utcnow().isoformat()}")
|
77 |
raise HTTPException(status_code=500, detail="Failed to retrieve notifications")
|
78 |
|
79 |
@router.post("/chat-stream")
|
|
|
81 |
request: ChatRequest,
|
82 |
current_user: dict = Depends(get_current_user)
|
83 |
):
|
84 |
+
logger.info(f"Chat stream initiated by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
85 |
async def token_stream():
|
86 |
try:
|
87 |
conversation = [{"role": "system", "content": agent.chat_prompt}]
|
|
|
107 |
yield chunk + " "
|
108 |
await asyncio.sleep(0.05)
|
109 |
except Exception as e:
|
110 |
+
logger.error(f"Streaming error: {str(e)} at {datetime.utcnow().isoformat()}")
|
111 |
yield f"⚠️ Error: {e}"
|
112 |
|
113 |
return StreamingResponse(token_stream(), media_type="text/plain")
|
|
|
118 |
language: str = Query("en-US", description="Language code for speech recognition"),
|
119 |
current_user: dict = Depends(get_current_user)
|
120 |
):
|
121 |
+
logger.info(f"Voice transcription initiated by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
122 |
try:
|
123 |
audio_data = await audio.read()
|
124 |
if not audio.filename.lower().endswith(('.wav', '.mp3', '.ogg', '.flac')):
|
|
|
130 |
except HTTPException:
|
131 |
raise
|
132 |
except Exception as e:
|
133 |
+
logger.error(f"Error in voice transcription: {str(e)} at {datetime.utcnow().isoformat()}")
|
134 |
raise HTTPException(status_code=500, detail="Error processing voice input")
|
135 |
|
136 |
@router.post("/voice/synthesize")
|
|
|
138 |
request: VoiceOutputRequest,
|
139 |
current_user: dict = Depends(get_current_user)
|
140 |
):
|
141 |
+
logger.info(f"Voice synthesis initiated by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
142 |
try:
|
143 |
audio_data = text_to_speech(request.text, request.language, request.slow)
|
144 |
|
|
|
154 |
except HTTPException:
|
155 |
raise
|
156 |
except Exception as e:
|
157 |
+
logger.error(f"Error in voice synthesis: {str(e)} at {datetime.utcnow().isoformat()}")
|
158 |
raise HTTPException(status_code=500, detail="Error generating voice output")
|
159 |
|
160 |
@router.post("/voice/chat")
|
|
|
165 |
max_new_tokens: int = Query(512, ge=50, le=1024),
|
166 |
current_user: dict = Depends(get_current_user)
|
167 |
):
|
168 |
+
logger.info(f"Voice chat initiated by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
169 |
try:
|
170 |
audio_data = await audio.read()
|
171 |
user_message = recognize_speech(audio_data, language)
|
|
|
188 |
except HTTPException:
|
189 |
raise
|
190 |
except Exception as e:
|
191 |
+
logger.error(f"Error in voice chat: {str(e)} at {datetime.utcnow().isoformat()}")
|
192 |
raise HTTPException(status_code=500, detail="Error processing voice chat")
|
193 |
|
194 |
@router.post("/analyze-report")
|
|
|
199 |
max_new_tokens: int = Form(1024),
|
200 |
current_user: dict = Depends(get_current_user)
|
201 |
):
|
202 |
+
logger.info(f"Report analysis initiated by {current_user['email']} at {datetime.utcnow().isoformat()}")
|
203 |
try:
|
204 |
content_type = file.content_type
|
205 |
allowed_types = [
|
|
|
260 |
"read": False
|
261 |
}
|
262 |
await notifications_collection.insert_one(notification)
|
263 |
+
logger.info(f"Notification created for {current_user['email']} at {datetime.utcnow().isoformat()}: {notification['message']}")
|
264 |
# Send push notification
|
265 |
await send_push_notification(current_user["email"], notification["message"])
|
266 |
|
|
|
275 |
except HTTPException:
|
276 |
raise
|
277 |
except Exception as e:
|
278 |
+
logger.error(f"Error in report analysis: {str(e)} at {datetime.utcnow().isoformat()}")
|
279 |
raise HTTPException(
|
280 |
status_code=500,
|
281 |
detail=f"Failed to analyze report: {str(e)}"
|
|
|
286 |
patient_id: str,
|
287 |
current_user: dict = Depends(get_current_user)
|
288 |
):
|
289 |
+
logger.info(f"Patient deletion initiated by {current_user['email']} at {datetime.utcnow().isoformat()} for patient {patient_id}")
|
290 |
try:
|
291 |
patient = await patients_collection.find_one({"fhir_id": patient_id})
|
292 |
if not patient:
|
|
|
296 |
raise HTTPException(status_code=403, detail="Not authorized to delete this patient")
|
297 |
|
298 |
await analysis_collection.delete_many({"patient_id": patient_id})
|
299 |
+
logger.info(f"Deleted analyses for patient {patient_id} at {datetime.utcnow().isoformat()}")
|
300 |
|
301 |
await notifications_collection.delete_many({"patient_id": patient_id})
|
302 |
+
logger.info(f"Deleted notifications for patient {patient_id} at {datetime.utcnow().isoformat()}")
|
303 |
|
304 |
await patients_collection.delete_one({"fhir_id": patient_id})
|
305 |
+
logger.info(f"Patient {patient_id} deleted successfully at {datetime.utcnow().isoformat()}")
|
306 |
|
307 |
return {"status": "success", "message": f"Patient {patient_id} and associated data deleted"}
|
308 |
|
309 |
except HTTPException:
|
310 |
raise
|
311 |
except Exception as e:
|
312 |
+
logger.error(f"Error deleting patient {patient_id}: {str(e)} at {datetime.utcnow().isoformat()}")
|
313 |
raise HTTPException(status_code=500, detail=f"Failed to delete patient: {str(e)}")
|
314 |
|
315 |
return router
|