-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
961 lines (807 loc) · 33.3 KB
/
Copy pathapp.py
File metadata and controls
961 lines (807 loc) · 33.3 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
from flask import Flask, jsonify, request, send_from_directory, send_file
from flask_cors import CORS
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams, Distance, PointStruct, Filter, FieldCondition, MatchValue
from dataclasses import dataclass
from datetime import datetime, timezone
import uuid
from fastembed import TextEmbedding
import numpy as np
import os
import logging
import bcrypt
import base64
from io import BytesIO
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.units import inch
import atexit
from dateutil import tz
LOCAL_TZ = tz.tzlocal()
from dotenv import load_dotenv
load_dotenv()
# ==================== LOGGING ====================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
# ==================== CONFIGURATION ====================
COLLECTION_NAME = "medical_events"
VECTOR_DIM = 384
# ==================== FLASK APP ====================
app = Flask(__name__, static_folder='static', static_url_path='')
app.secret_key = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
CORS(app, supports_credentials=True)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# ==================== GLOBAL STATE ====================
qdrant_client = None
embedding_model = None
groq_client = None
users_db = {}
initialization_status = {
"qdrant": False,
"embedding": False,
"collection": False,
"groq": False,
"initialized": False
}
# ==================== INITIALIZATION (RUNS ONCE) ====================
def initialize_app():
"""Initialize all components - runs ONCE on startup"""
global qdrant_client, embedding_model, groq_client, initialization_status
if initialization_status["initialized"]:
logger.info("⚠️ Already initialized, skipping...")
return True
logger.info("=" * 60)
logger.info("🩺 MEDICAL TIMELINE AI - INITIALIZATION")
logger.info("=" * 60)
# Step 1: Check environment variables
logger.info("\n📋 Step 1/5: Checking environment variables...")
required_vars = ["QDRANT_URL", "QDRANT_API_KEY", "GROQ_API_KEY"]
missing = [var for var in required_vars if not os.getenv(var)]
if missing:
logger.error(f"❌ Missing environment variables: {', '.join(missing)}")
logger.error("💡 Create a .env file with:")
for var in missing:
logger.error(f" {var}=your_value_here")
return False
for var in required_vars:
logger.info(f" ✅ {var}")
# Step 2: Initialize Qdrant client
logger.info("\n🔌 Step 2/5: Connecting to Qdrant...")
try:
qdrant_client = QdrantClient(
url=os.getenv("QDRANT_URL"),
api_key=os.getenv("QDRANT_API_KEY")
)
collections = qdrant_client.get_collections()
logger.info(f" ✅ Connected to Qdrant ({len(collections.collections)} collections found)")
initialization_status["qdrant"] = True
except Exception as e:
logger.error(f" ❌ Qdrant connection failed: {e}")
return False
# Step 3: Initialize embedding model
logger.info("\n🧠 Step 3/5: Loading embedding model...")
try:
embedding_model = TextEmbedding()
logger.info(" ✅ Embedding model loaded")
initialization_status["embedding"] = True
except Exception as e:
logger.error(f" ❌ Embedding model failed: {e}")
return False
# Step 4: Initialize Groq client
logger.info("\n🤖 Step 4/5: Initializing Groq AI...")
try:
from groq import Groq
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
# Test with a simple call
test_response = groq_client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": "Say 'ready'"}],
max_tokens=10
)
if test_response.choices:
logger.info(" ✅ Groq AI connected and working")
initialization_status["groq"] = True
else:
raise Exception("Groq returned empty response")
except Exception as e:
logger.error(f" ❌ Groq initialization failed: {e}")
logger.warning(" ⚠️ App will work but AI features disabled")
groq_client = None
# Step 5: Setup collection
logger.info(f"\n📦 Step 5/5: Setting up collection '{COLLECTION_NAME}'...")
try:
collections = qdrant_client.get_collections()
collection_names = [c.name for c in collections.collections]
if COLLECTION_NAME in collection_names:
logger.info(f" ℹ️ Collection '{COLLECTION_NAME}' already exists")
else:
qdrant_client.create_collection(
collection_name=COLLECTION_NAME,
vectors_config=VectorParams(
size=VECTOR_DIM,
distance=Distance.COSINE
)
)
logger.info(f" ✅ Collection '{COLLECTION_NAME}' created")
initialization_status["collection"] = True
except Exception as e:
logger.error(f" ❌ Collection setup failed: {e}")
return False
# Mark as fully initialized
initialization_status["initialized"] = True
logger.info("\n" + "=" * 60)
logger.info("✅ INITIALIZATION COMPLETE - SERVER READY")
logger.info("=" * 60)
logger.info(f"📍 Qdrant: {os.getenv('QDRANT_URL')}")
logger.info(f"📦 Collection: {COLLECTION_NAME}")
logger.info(f"🧠 Embedding: FastEmbed (dim={VECTOR_DIM})")
logger.info(f"🤖 AI Model: Groq Llama 3.3 70B")
logger.info("=" * 60 + "\n")
return True
# Initialize on import
if not initialize_app():
logger.error("🛑 Initialization failed - server will not start properly")
raise RuntimeError("Failed to initialize application")
# Cleanup on shutdown
def cleanup():
logger.info("🔚 Shutting down gracefully...")
atexit.register(cleanup)
# ==================== USER MANAGEMENT ====================
class User(UserMixin):
def __init__(self, id, username, email, patient_id, profile_data=None):
self.id = id
self.username = username
self.email = email
self.patient_id = patient_id
self.profile_data = profile_data or {
"age": "",
"gender": "",
"blood_type": "",
"allergies": "",
"chronic_conditions": "",
"emergency_contact": "",
"phone": "",
"address": ""
}
@login_manager.user_loader
def load_user(user_id):
user_data = users_db.get(user_id)
return user_data["user"] if user_data else None
@dataclass
class MedicalEvent:
event_id: str
patient_id: str
timestamp: str
event_type: str
modality: str
content: str
doctor_name: str = ""
hospital_name: str = ""
# ==================== STATIC FILE SERVING ====================
@app.route('/')
def index():
"""Serve main application page"""
return send_from_directory('static', 'index.html')
@app.route('/patient/<patient_id>')
def patient_view(patient_id):
"""Serve patient timeline view"""
return send_from_directory('static', 'patient_view.html')
# ==================== HEALTH CHECK ====================
@app.route("/health")
def health():
"""Health check endpoint"""
return jsonify({
"status": "healthy" if initialization_status["initialized"] else "initializing",
"components": {
"qdrant": initialization_status["qdrant"],
"embedding": initialization_status["embedding"],
"collection": initialization_status["collection"],
"groq": initialization_status["groq"]
},
"timestamp": datetime.now(timezone.utc).isoformat()
})
@app.route("/api/status")
def api_status():
"""Detailed API status"""
try:
collections = qdrant_client.get_collections()
collection_exists = COLLECTION_NAME in [c.name for c in collections.collections]
stats = None
if collection_exists:
try:
info = qdrant_client.get_collection(COLLECTION_NAME)
stats = {
"points_count": info.points_count,
"vectors_count": info.vectors_count
}
except:
pass
return jsonify({
"status": "operational",
"initialized": initialization_status["initialized"],
"qdrant": {
"connected": initialization_status["qdrant"],
"url": os.getenv("QDRANT_URL"),
"collections": len(collections.collections)
},
"collection": {
"name": COLLECTION_NAME,
"exists": collection_exists,
"stats": stats
},
"embedding": {
"loaded": initialization_status["embedding"],
"dimension": VECTOR_DIM
},
"ai": {
"provider": "Groq",
"model": "llama-3.3-70b-versatile",
"status": "connected" if initialization_status["groq"] else "disconnected"
},
"users": {
"registered": len(users_db)
}
})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
# ==================== AUTH ROUTES ====================
@app.route("/register", methods=["POST"])
def register():
try:
data = request.json
username = data.get("username")
email = data.get("email")
password = data.get("password")
if not all([username, email, password]):
return jsonify({"error": "All fields required"}), 400
for user_data in users_db.values():
if user_data["user"].email == email:
return jsonify({"error": "Email already registered"}), 400
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
user_id = str(uuid.uuid4())
# Generate human-readable patient ID
patient_id = f"MED-{user_id[:8].upper()}"
user = User(user_id, username, email, patient_id)
users_db[user_id] = {
"user": user,
"password": hashed,
"created_at": datetime.now(timezone.utc).isoformat()
}
login_user(user)
logger.info(f"👤 New user registered: {username} ({patient_id})")
return jsonify({
"status": "success",
"patient_id": patient_id,
"username": username
})
except Exception as e:
logger.error(f"Registration error: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/login", methods=["POST"])
def login():
try:
data = request.json
email = data.get("email")
password = data.get("password")
user_data = None
for ud in users_db.values():
if ud["user"].email == email:
user_data = ud
break
if not user_data:
return jsonify({"error": "Invalid credentials"}), 401
if not bcrypt.checkpw(password.encode('utf-8'), user_data["password"]):
return jsonify({"error": "Invalid credentials"}), 401
login_user(user_data["user"])
logger.info(f"🔐 User logged in: {user_data['user'].username}")
return jsonify({
"status": "success",
"patient_id": user_data["user"].patient_id,
"username": user_data["user"].username
})
except Exception as e:
logger.error(f"Login error: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/logout", methods=["POST"])
@login_required
def logout():
username = current_user.username
logout_user()
logger.info(f"👋 User logged out: {username}")
return jsonify({"status": "logged out"})
@app.route("/me")
@login_required
def get_current_user():
return jsonify({
"username": current_user.username,
"email": current_user.email,
"patient_id": current_user.patient_id,
"profile_data": current_user.profile_data
})
@app.route("/update-profile", methods=["POST"])
@login_required
def update_profile():
try:
data = request.json
profile_data = data.get("profile_data", {})
# Update user's profile data
current_user.profile_data.update(profile_data)
# Update in database
users_db[current_user.id]["user"].profile_data = current_user.profile_data
logger.info(f"📝 Profile updated for user: {current_user.username}")
return jsonify({
"status": "success",
"profile_data": current_user.profile_data
})
except Exception as e:
logger.error(f"Profile update error: {e}")
return jsonify({"error": str(e)}), 500
# ==================== DOCUMENT UPLOAD WITH OCR ====================
@app.route("/upload-document", methods=["POST"])
def upload_document():
"""Upload document with OCR text extraction"""
try:
if 'file' not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files['file']
patient_id = request.form.get('patient_id')
doctor_name = request.form.get('doctor_name', 'Unknown')
hospital_name = request.form.get('hospital_name', 'Unknown')
if not patient_id:
return jsonify({"error": "patient_id required"}), 400
logger.info(f"📄 Processing document for patient: {patient_id}")
# Read file and save it
file_content = file.read()
file_extension = os.path.splitext(file.filename)[1]
# Create uploads directory if it doesn't exist
uploads_dir = os.path.join(os.getcwd(), 'uploads')
os.makedirs(uploads_dir, exist_ok=True)
# Generate unique filename
unique_filename = f"{uuid.uuid4()}{file_extension}"
file_path = os.path.join(uploads_dir, unique_filename)
# Save file to disk
with open(file_path, 'wb') as f:
f.write(file_content)
logger.info(f"📁 File saved to: {file_path}")
# Get manual notes if provided
extracted_text = f"Document: {file.filename}"
additional_notes = request.form.get('notes', '')
if additional_notes:
extracted_text += f"\n\nNotes: {additional_notes}"
# Create event with extracted text
doc_date = datetime.now(timezone.utc).isoformat()
event = create_medical_event(
extracted_text,
patient_id,
"document",
doc_date,
doctor_name=doctor_name,
hospital_name=hospital_name
)
vector = list(embedding_model.embed(event.content))[0].tolist()
qdrant_client.upsert(
collection_name=COLLECTION_NAME,
points=[PointStruct(
id=event.event_id,
vector=vector,
payload={
"patient_id": event.patient_id,
"timestamp": event.timestamp,
"event_type": event.event_type,
"modality": "document",
"content": event.content,
"filename": file.filename,
"file_path": unique_filename, # Store relative path
"file_extension": file_extension,
"doctor_name": event.doctor_name,
"hospital_name": event.hospital_name
}
)]
)
logger.info(f"✅ Document stored: {event.event_id[:8]}...")
return jsonify({
"status": "success",
"event_id": event.event_id,
"extracted_text": extracted_text,
"filename": file.filename,
"file_path": unique_filename,
"document_type": "document",
"note": "Document stored. You can download it anytime from your timeline."
})
except Exception as e:
logger.error(f"Document upload error: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/download-document/<filename>")
def download_document(filename):
"""Download uploaded document"""
try:
uploads_dir = os.path.join(os.getcwd(), 'uploads')
file_path = os.path.join(uploads_dir, filename)
if not os.path.exists(file_path):
return jsonify({"error": "File not found"}), 404
# Get original filename from Qdrant if possible
try:
results = qdrant_client.scroll(
collection_name=COLLECTION_NAME,
scroll_filter=Filter(must=[
FieldCondition(key="file_path", match=MatchValue(value=filename))
]),
limit=1,
with_payload=True
)
if results[0]:
original_filename = results[0][0].payload.get("filename", filename)
else:
original_filename = filename
except:
original_filename = filename
logger.info(f"📥 Downloading document: {original_filename}")
return send_file(
file_path,
as_attachment=True,
download_name=original_filename
)
except Exception as e:
logger.error(f"Document download error: {e}")
return jsonify({"error": str(e)}), 500
# ==================== DATA INGESTION ====================
@app.route("/ingest", methods=["POST"])
def ingest():
try:
data = request.json
required = ["content", "patient_id", "event_type"]
for field in required:
if not data.get(field):
return jsonify({"error": f"Missing: {field}"}), 400
doctor_name = data.get("doctor_name", "Unknown")
hospital_name = data.get("hospital_name", "Unknown")
event = create_medical_event(
data["content"],
data["patient_id"],
data["event_type"],
data.get("timestamp"),
doctor_name,
hospital_name
)
vector = list(embedding_model.embed(event.content))[0].tolist()
qdrant_client.upsert(
collection_name=COLLECTION_NAME,
points=[PointStruct(
id=event.event_id,
vector=vector,
payload={
"patient_id": event.patient_id,
"timestamp": event.timestamp,
"event_type": event.event_type,
"modality": "text",
"content": event.content,
"doctor_name": event.doctor_name,
"hospital_name": event.hospital_name
}
)]
)
logger.info(f"📝 Event ingested: {event.event_id[:8]}... ({event.event_type})")
return jsonify({"status": "stored", "event_id": event.event_id})
except Exception as e:
logger.error(f"Ingest error: {e}")
return jsonify({"error": str(e)}), 500
# ==================== TIMELINE & ANALYSIS ====================
@app.route("/timeline-summary", methods=["POST"])
def timeline_summary():
try:
patient_id = request.json.get("patient_id")
if not patient_id:
return jsonify({"error": "Missing patient_id"}), 400
points = fetch_timeline_events(patient_id)
if not points:
return jsonify({"error": "No events found"}), 404
timeline = build_patient_timeline(points)
if len(points) == 1:
return jsonify({
"timeline": timeline,
"timeline_insights": {
"activity_rate": 0,
"activity_level": "N/A",
"activity_description": "Only one event recorded",
"longest_gap_days": 0,
"continuity": "N/A",
"continuity_description": "Need more events for analysis",
"completeness": 100 if timeline[0]["doctor_name"] != "Unknown" else 0,
"event_breakdown": {timeline[0]["event_type"]: 100},
"unique_hospitals": 1 if timeline[0]["hospital_name"] != "Unknown" else 0,
"unique_doctors": 1 if timeline[0]["doctor_name"] != "Unknown" else 0,
"total_days": 1,
"total_events": 1
},
"overall_summary": "Only one event recorded. Add more medical events to see detailed timeline analysis.",
"data_quality": compute_data_quality(timeline)
})
insights = compute_timeline_insights(timeline)
summary = ai_explain(build_overview_prompt(timeline))
logger.info(f"📊 Timeline generated for {patient_id}: {len(points)} events")
return jsonify({
"timeline": timeline,
"timeline_insights": insights,
"overall_summary": summary,
"data_quality": compute_data_quality(timeline)
})
except Exception as e:
logger.error(f"Timeline error: {e}")
return jsonify({"error": str(e)}), 500
# ==================== PDF EXPORT ====================
@app.route("/export-pdf", methods=["POST"])
def export_pdf():
try:
patient_id = request.json.get("patient_id")
if not patient_id:
return jsonify({"error": "patient_id required"}), 400
points = fetch_timeline_events(patient_id)
if not points:
return jsonify({"error": "No events found"}), 404
timeline = build_patient_timeline(points)
buffer = BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter)
story = []
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
'Title',
parent=styles['Heading1'],
fontSize=24,
textColor=colors.HexColor('#1e40af'),
spaceAfter=20
)
# Get hospital name if available
hospital_name = timeline[0].get('hospital_name', 'General Hospital') if timeline else 'General Hospital'
story.append(Paragraph("Medical Timeline Report", title_style))
story.append(Paragraph(f"Hospital: {hospital_name}", styles['Normal']))
story.append(Paragraph(f"Patient ID: {patient_id}", styles['Normal']))
story.append(Paragraph(f"Generated: {datetime.now().strftime('%B %d, %Y at %I:%M %p')}", styles['Normal']))
story.append(Spacer(1, 0.4*inch))
table_data = [['Date', 'Type', 'Details']]
for e in timeline:
utc_time = datetime.fromisoformat(e['timestamp'])
local_time = utc_time.astimezone(LOCAL_TZ)
date = local_time.strftime('%b %d, %Y %I:%M %p')
table_data.append([
Paragraph(date, styles['Normal']),
Paragraph(e['event_type'], styles['Normal']),
Paragraph(e['content'][:200] + ('...' if len(e['content']) > 200 else ''), styles['Normal'])
])
table = Table(table_data, colWidths=[1.5*inch, 1.5*inch, 4*inch])
table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,0), colors.HexColor('#1e40af')),
('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke),
('ALIGN', (0,0), (-1,-1), 'LEFT'),
('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
('FONTSIZE', (0,0), (-1,0), 11),
('BOTTOMPADDING', (0,0), (-1,0), 12),
('GRID', (0,0), (-1,-1), 1, colors.black),
('VALIGN', (0,0), (-1,-1), 'TOP')
]))
story.append(table)
doc.build(story)
buffer.seek(0)
logger.info(f"📄 PDF exported for {patient_id}")
return send_file(
buffer,
mimetype='application/pdf',
as_attachment=True,
download_name=f'medical_timeline_{patient_id}_{datetime.now().strftime("%Y%m%d")}.pdf'
)
except Exception as e:
logger.error(f"PDF export error: {e}")
return jsonify({"error": str(e)}), 500
# ==================== HELPER FUNCTIONS ====================
def create_medical_event(content, patient_id, event_type, timestamp=None, doctor_name="", hospital_name=""):
log_time_utc = (
datetime.fromisoformat(timestamp).astimezone(timezone.utc)
if timestamp
else datetime.now(timezone.utc)
)
return MedicalEvent(
event_id=str(uuid.uuid4()),
patient_id=patient_id,
timestamp=log_time_utc.isoformat(),
event_type=event_type,
modality="text",
content=content,
doctor_name=doctor_name,
hospital_name=hospital_name
)
def fetch_timeline_events(patient_id):
try:
results = qdrant_client.scroll(
collection_name=COLLECTION_NAME,
scroll_filter=Filter(must=[
FieldCondition(key="patient_id", match=MatchValue(value=patient_id))
]),
limit=100,
with_payload=True
)
points = results[0]
return sorted(points, key=lambda p: datetime.fromisoformat(p.payload["timestamp"]))
except Exception as e:
logger.error(f"Fetch timeline error: {e}")
return []
def build_patient_timeline(points):
timeline = []
for p in sorted(points, key=lambda x: datetime.fromisoformat(x.payload["timestamp"])):
utc_time = datetime.fromisoformat(p.payload["timestamp"])
local_time = utc_time.astimezone(LOCAL_TZ)
timeline.append({
"timestamp": utc_time.isoformat(),
"local_time": local_time.isoformat(),
"event_type": p.payload["event_type"],
"content": p.payload["content"],
"doctor_name": p.payload.get("doctor_name", "Unknown"),
"hospital_name": p.payload.get("hospital_name", "Unknown"),
"filename": p.payload.get("filename"),
"file_path": p.payload.get("file_path"),
"file_extension": p.payload.get("file_extension"),
"timestamp_type": "log_time"
})
return timeline
def compute_timeline_insights(timeline):
"""Calculate meaningful timeline metrics"""
if not timeline:
return None
# Sort by timestamp
sorted_timeline = sorted(timeline, key=lambda x: datetime.fromisoformat(x["timestamp"]))
# Calculate time span
first_date = datetime.fromisoformat(sorted_timeline[0]["timestamp"])
last_date = datetime.fromisoformat(sorted_timeline[-1]["timestamp"])
total_days = (last_date - first_date).days + 1
# Calculate activity rate (events per month)
months = max(total_days / 30, 1) # At least 1 month
activity_rate = len(timeline) / months
# Find longest gap between events
max_gap_days = 0
for i in range(1, len(sorted_timeline)):
prev_date = datetime.fromisoformat(sorted_timeline[i-1]["timestamp"])
curr_date = datetime.fromisoformat(sorted_timeline[i]["timestamp"])
gap = (curr_date - prev_date).days
max_gap_days = max(max_gap_days, gap)
# Event type breakdown (percentages)
event_types = {}
for event in timeline:
event_type = event["event_type"]
event_types[event_type] = event_types.get(event_type, 0) + 1
event_breakdown = {
event_type: round((count / len(timeline)) * 100, 1)
for event_type, count in event_types.items()
}
# Unique care providers
hospitals = set(e["hospital_name"] for e in timeline if e["hospital_name"] != "Unknown")
doctors = set(e["doctor_name"] for e in timeline if e["doctor_name"] != "Unknown")
# Data completeness (percentage of events with doctor/hospital info)
complete_events = sum(1 for e in timeline
if e["doctor_name"] != "Unknown" and e["hospital_name"] != "Unknown")
completeness = round((complete_events / len(timeline)) * 100, 1) if timeline else 0
# Activity level assessment
if activity_rate >= 3:
activity_level = "High"
activity_desc = "Frequent medical visits"
elif activity_rate >= 1:
activity_level = "Moderate"
activity_desc = "Regular checkups"
else:
activity_level = "Low"
activity_desc = "Infrequent visits"
# Continuity assessment (based on gaps)
if max_gap_days <= 14:
continuity = "Excellent"
continuity_desc = "No significant gaps in care"
elif max_gap_days <= 60:
continuity = "Good"
continuity_desc = "Minor gaps between visits"
elif max_gap_days <= 180:
continuity = "Fair"
continuity_desc = "Some gaps in care history"
else:
continuity = "Poor"
continuity_desc = "Large gaps in documentation"
return {
"activity_rate": round(activity_rate, 1),
"activity_level": activity_level,
"activity_description": activity_desc,
"longest_gap_days": max_gap_days,
"continuity": continuity,
"continuity_description": continuity_desc,
"completeness": completeness,
"event_breakdown": event_breakdown,
"unique_hospitals": len(hospitals),
"unique_doctors": len(doctors),
"total_days": total_days,
"total_events": len(timeline)
}
def compute_data_quality(timeline):
count = len(timeline)
if count == 0:
return {"label": "No Data", "description": "No medical records available"}
times = [datetime.fromisoformat(e["timestamp"]) for e in timeline]
span = (max(times) - min(times)).days + 1
avg_len = sum(len(e["content"]) for e in timeline) / count
if count >= 6 and span >= 7 and avg_len >= 40:
return {"label": "Rich", "description": "Sufficient records for comprehensive analysis"}
if count >= 3 and span >= 2:
return {"label": "Moderate", "description": "Some continuity present, insights may be limited"}
return {"label": "Sparse", "description": "Limited data, interpretation constrained"}
def human_time(iso_ts):
if not iso_ts:
return "unknown time"
dt = datetime.fromisoformat(iso_ts)
local_dt = dt.astimezone(LOCAL_TZ)
return local_dt.strftime("%b %d, %Y at %I:%M %p")
def build_overview_prompt(timeline):
entries = "\n".join([
(
f"- Event was logged on {human_time(e.get('timestamp'))}."
f"\n Type: {e['event_type']}"
f"\n Details: {e['content']}"
)
for e in timeline
])
return f"""
You are a medical timeline summarization assistant.
IMPORTANT CONTEXT:
- All times refer to documentation (log) time unless explicitly stated as "occurred on".
- Logged times may differ from actual medical event dates.
- Do NOT output raw timestamps or ISO date strings.
STRICT RULES:
- Do NOT infer exact onset times
- Do NOT assume events occurred at log time
- Use clear, human-readable time references only
Timeline:
{entries}
Write a clear, professional medical summary suitable for clinicians.
"""
def ai_explain(prompt):
"""AI explanation using Groq"""
try:
if not groq_client:
logger.warning("Groq client not initialized")
return "AI analysis unavailable. Groq API not configured."
response = groq_client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": prompt}],
max_tokens=2048,
temperature=0.7
)
if response.choices and response.choices[0].message.content:
return response.choices[0].message.content
else:
return "AI returned empty response. Timeline data is still accessible."
except Exception as e:
error_msg = str(e).lower()
if "rate limit" in error_msg or "quota" in error_msg:
logger.error(f"Groq rate limit: {e}")
return "⚠️ AI rate limit reached. Timeline data is available below."
elif "auth" in error_msg or "invalid" in error_msg:
logger.error(f"Groq auth failed: {e}")
return "⚠️ AI authentication failed. Check GROQ_API_KEY."
else:
logger.error(f"Groq error: {e}")
return "⚠️ AI analysis temporarily unavailable. Timeline data is still visible below."
# ==================== ERROR HANDLERS ====================
@app.errorhandler(404)
def not_found(error):
return jsonify({"error": "Endpoint not found"}), 404
@app.errorhandler(500)
def internal_error(error):
logger.error(f"Internal server error: {error}")
return jsonify({"error": "Internal server error"}), 500
# ==================== MAIN ====================
if __name__ == "__main__":
logger.info("🚀 Starting development server...")
logger.info("📍 Access at: http://localhost:5000")
logger.info("💡 Press Ctrl+C to stop")
app.run(debug=True, host='0.0.0.0', port=5000)