add new version with inference client and fixes to datamodel
Browse files- app.py +8 -8
- notes.py +221 -0
- templates/oneclick.html +10 -3
- utils/oneclick.py +102 -30
app.py
CHANGED
@@ -10,14 +10,12 @@ logger = logging.getLogger(__name__)
|
|
10 |
|
11 |
app = Flask(__name__)
|
12 |
|
13 |
-
# Configuration from environment variables
|
14 |
CLIENT_ID = os.getenv("MELDRX_CLIENT_ID", "04bdc9f9a23d488a868b93d594ee5a4a")
|
15 |
CLIENT_SECRET = os.getenv("MELDRX_CLIENT_SECRET", None)
|
16 |
WORKSPACE_ID = os.getenv("MELDRX_WORKSPACE_ID", "09ed4f76-b5ac-42bf-92d5-496933203dbe")
|
17 |
SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
|
18 |
REDIRECT_URI = f"{SPACE_URL}/auth/callback"
|
19 |
|
20 |
-
# Initialize MeldRx API
|
21 |
meldrx_api = MeldRxAPI(
|
22 |
client_id=CLIENT_ID,
|
23 |
client_secret=CLIENT_SECRET,
|
@@ -66,21 +64,23 @@ def one_click():
|
|
66 |
last_name = request.form.get('last_name', '').strip()
|
67 |
action = request.form.get('action', '')
|
68 |
|
69 |
-
pdf_path, status,
|
70 |
meldrx_api, patient_id, first_name, last_name
|
71 |
)
|
72 |
|
73 |
-
if action == "Display Summary"
|
74 |
return render_template('oneclick.html',
|
75 |
-
status=status,
|
76 |
-
|
|
|
77 |
elif action == "Generate PDF" and pdf_path:
|
78 |
return send_file(pdf_path,
|
79 |
as_attachment=True,
|
80 |
download_name=f"discharge_summary_{patient_id or 'patient'}.pdf")
|
81 |
return render_template('oneclick.html',
|
82 |
-
status=status,
|
83 |
-
|
|
|
84 |
|
85 |
return render_template('oneclick.html')
|
86 |
|
|
|
10 |
|
11 |
app = Flask(__name__)
|
12 |
|
|
|
13 |
CLIENT_ID = os.getenv("MELDRX_CLIENT_ID", "04bdc9f9a23d488a868b93d594ee5a4a")
|
14 |
CLIENT_SECRET = os.getenv("MELDRX_CLIENT_SECRET", None)
|
15 |
WORKSPACE_ID = os.getenv("MELDRX_WORKSPACE_ID", "09ed4f76-b5ac-42bf-92d5-496933203dbe")
|
16 |
SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
|
17 |
REDIRECT_URI = f"{SPACE_URL}/auth/callback"
|
18 |
|
|
|
19 |
meldrx_api = MeldRxAPI(
|
20 |
client_id=CLIENT_ID,
|
21 |
client_secret=CLIENT_SECRET,
|
|
|
64 |
last_name = request.form.get('last_name', '').strip()
|
65 |
action = request.form.get('action', '')
|
66 |
|
67 |
+
pdf_path, status, basic_summary, ai_summary = generate_discharge_paper_one_click(
|
68 |
meldrx_api, patient_id, first_name, last_name
|
69 |
)
|
70 |
|
71 |
+
if action == "Display Summary":
|
72 |
return render_template('oneclick.html',
|
73 |
+
status=status,
|
74 |
+
basic_summary=basic_summary.replace('\n', '<br>') if basic_summary else None,
|
75 |
+
ai_summary=ai_summary.replace('\n', '<br>') if ai_summary else None)
|
76 |
elif action == "Generate PDF" and pdf_path:
|
77 |
return send_file(pdf_path,
|
78 |
as_attachment=True,
|
79 |
download_name=f"discharge_summary_{patient_id or 'patient'}.pdf")
|
80 |
return render_template('oneclick.html',
|
81 |
+
status=status,
|
82 |
+
basic_summary=basic_summary.replace('\n', '<br>') if basic_summary else None,
|
83 |
+
ai_summary=ai_summary.replace('\n', '<br>') if ai_summary else None)
|
84 |
|
85 |
return render_template('oneclick.html')
|
86 |
|
notes.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
from flask import Flask, render_template, request, send_file, redirect, url_for
|
3 |
+
import os
|
4 |
+
import logging
|
5 |
+
from utils.meldrx import MeldRxAPI
|
6 |
+
from utils.oneclick import generate_discharge_paper_one_click
|
7 |
+
|
8 |
+
logging.basicConfig(level=logging.INFO)
|
9 |
+
logger = logging.getLogger(__name__)
|
10 |
+
|
11 |
+
app = Flask(__name__)
|
12 |
+
|
13 |
+
# Configuration from environment variables
|
14 |
+
CLIENT_ID = os.getenv("MELDRX_CLIENT_ID", "04bdc9f9a23d488a868b93d594ee5a4a")
|
15 |
+
CLIENT_SECRET = os.getenv("MELDRX_CLIENT_SECRET", None)
|
16 |
+
WORKSPACE_ID = os.getenv("MELDRX_WORKSPACE_ID", "09ed4f76-b5ac-42bf-92d5-496933203dbe")
|
17 |
+
SPACE_URL = os.getenv("SPACE_URL", "https://multitransformer-tonic-discharge-guard.hf.space")
|
18 |
+
REDIRECT_URI = f"{SPACE_URL}/auth/callback"
|
19 |
+
|
20 |
+
# Initialize MeldRx API
|
21 |
+
meldrx_api = MeldRxAPI(
|
22 |
+
client_id=CLIENT_ID,
|
23 |
+
client_secret=CLIENT_SECRET,
|
24 |
+
workspace_id=WORKSPACE_ID,
|
25 |
+
redirect_uri=REDIRECT_URI
|
26 |
+
)
|
27 |
+
|
28 |
+
@app.route('/')
|
29 |
+
def index():
|
30 |
+
return render_template('index.html')
|
31 |
+
|
32 |
+
@app.route('/auth', methods=['GET', 'POST'])
|
33 |
+
def auth():
|
34 |
+
if request.method == 'POST':
|
35 |
+
auth_code = request.form.get('auth_code')
|
36 |
+
if auth_code and meldrx_api.authenticate_with_code(auth_code):
|
37 |
+
return redirect(url_for('dashboard'))
|
38 |
+
return render_template('auth.html', auth_url=meldrx_api.get_authorization_url(), auth_result="Authentication failed")
|
39 |
+
return render_template('auth.html', auth_url=meldrx_api.get_authorization_url())
|
40 |
+
|
41 |
+
@app.route('/auth/callback', methods=['GET'])
|
42 |
+
def auth_callback():
|
43 |
+
auth_code = request.args.get('code')
|
44 |
+
if auth_code and meldrx_api.authenticate_with_code(auth_code):
|
45 |
+
return redirect(url_for('dashboard'))
|
46 |
+
return render_template('auth.html', auth_url=meldrx_api.get_authorization_url(), auth_result="Callback failed")
|
47 |
+
|
48 |
+
@app.route('/dashboard', methods=['GET'])
|
49 |
+
def dashboard():
|
50 |
+
if not meldrx_api.access_token:
|
51 |
+
return redirect(url_for('auth'))
|
52 |
+
patients_data = meldrx_api.get_patients()
|
53 |
+
if not patients_data or "entry" not in patients_data:
|
54 |
+
return render_template('dashboard.html', error="Failed to fetch patient data")
|
55 |
+
patients = [entry['resource'] for entry in patients_data.get('entry', [])]
|
56 |
+
return render_template('dashboard.html', patients=patients, authenticated=True)
|
57 |
+
|
58 |
+
@app.route('/oneclick', methods=['GET', 'POST'])
|
59 |
+
def one_click():
|
60 |
+
if not meldrx_api.access_token:
|
61 |
+
return redirect(url_for('auth'))
|
62 |
+
|
63 |
+
if request.method == 'POST':
|
64 |
+
patient_id = request.form.get('patient_id', '').strip()
|
65 |
+
first_name = request.form.get('first_name', '').strip()
|
66 |
+
last_name = request.form.get('last_name', '').strip()
|
67 |
+
action = request.form.get('action', '')
|
68 |
+
|
69 |
+
pdf_path, status, display_summary = generate_discharge_paper_one_click(
|
70 |
+
meldrx_api, patient_id, first_name, last_name
|
71 |
+
)
|
72 |
+
|
73 |
+
if action == "Display Summary" and display_summary:
|
74 |
+
return render_template('oneclick.html',
|
75 |
+
status=status,
|
76 |
+
summary=display_summary.replace('\n', '<br>'))
|
77 |
+
elif action == "Generate PDF" and pdf_path:
|
78 |
+
return send_file(pdf_path,
|
79 |
+
as_attachment=True,
|
80 |
+
download_name=f"discharge_summary_{patient_id or 'patient'}.pdf")
|
81 |
+
return render_template('oneclick.html',
|
82 |
+
status=status,
|
83 |
+
summary=display_summary.replace('\n', '<br>') if display_summary else None)
|
84 |
+
|
85 |
+
return render_template('oneclick.html')
|
86 |
+
|
87 |
+
if __name__ == '__main__':
|
88 |
+
port = int(os.getenv("PORT", 7860))
|
89 |
+
app.run(debug=False, host='0.0.0.0', port=port)
|
90 |
+
|
91 |
+
|
92 |
+
# utils/oneclick.py
|
93 |
+
from typing import Tuple, Optional
|
94 |
+
from .meldrx import MeldRxAPI
|
95 |
+
from .responseparser import PatientDataExtractor
|
96 |
+
from .pdfutils import PDFGenerator
|
97 |
+
import logging
|
98 |
+
import json
|
99 |
+
|
100 |
+
logger = logging.getLogger(__name__)
|
101 |
+
|
102 |
+
def generate_discharge_paper_one_click(
|
103 |
+
api: MeldRxAPI,
|
104 |
+
patient_id: str = "",
|
105 |
+
first_name: str = "",
|
106 |
+
last_name: str = ""
|
107 |
+
) -> Tuple[Optional[str], str, Optional[str]]:
|
108 |
+
"""
|
109 |
+
Generate a discharge summary PDF and upload it to MeldRx patient data.
|
110 |
+
|
111 |
+
Args:
|
112 |
+
api: Initialized MeldRxAPI instance
|
113 |
+
patient_id: Optional patient ID filter
|
114 |
+
first_name: Optional first name filter
|
115 |
+
last_name: Optional last name filter
|
116 |
+
|
117 |
+
Returns:
|
118 |
+
Tuple of (pdf_path, status_message, display_summary)
|
119 |
+
"""
|
120 |
+
try:
|
121 |
+
# Get patient data from MeldRx API
|
122 |
+
patients_data = api.get_patients()
|
123 |
+
if not patients_data or "entry" not in patients_data:
|
124 |
+
return None, "Failed to fetch patient data", None
|
125 |
+
|
126 |
+
# Create PatientDataExtractor instance
|
127 |
+
extractor = PatientDataExtractor(patients_data, "json")
|
128 |
+
|
129 |
+
# Filter patients based on input
|
130 |
+
matching_patients = []
|
131 |
+
matching_indices = []
|
132 |
+
for i in range(len(extractor.patients)):
|
133 |
+
extractor.set_patient_by_index(i)
|
134 |
+
patient_data = extractor.get_patient_dict()
|
135 |
+
|
136 |
+
if (not patient_id or patient_data["id"] == patient_id) and \
|
137 |
+
(not first_name or patient_data["first_name"].lower() == first_name.lower()) and \
|
138 |
+
(not last_name or patient_data["last_name"].lower() == last_name.lower()):
|
139 |
+
matching_patients.append(patient_data)
|
140 |
+
matching_indices.append(i)
|
141 |
+
|
142 |
+
if not matching_patients:
|
143 |
+
return None, "No matching patients found", None
|
144 |
+
|
145 |
+
# Use the first matching patient
|
146 |
+
patient_data = matching_patients[0]
|
147 |
+
patient_index = matching_indices[0]
|
148 |
+
extractor.set_patient_by_index(patient_index)
|
149 |
+
|
150 |
+
# Format the discharge summary text
|
151 |
+
summary_text = format_discharge_summary(patient_data)
|
152 |
+
|
153 |
+
# Generate PDF
|
154 |
+
pdf_gen = PDFGenerator()
|
155 |
+
filename = f"discharge_{patient_data['id'] or 'summary'}_{patient_data['last_name']}.pdf"
|
156 |
+
pdf_path = pdf_gen.generate_pdf_from_text(summary_text, filename)
|
157 |
+
|
158 |
+
# Prepare and upload discharge summary to MeldRx
|
159 |
+
if pdf_path:
|
160 |
+
# Convert summary to escaped JSON
|
161 |
+
discharge_summary_json = json.dumps(summary_text)
|
162 |
+
|
163 |
+
# Get the original patient resource
|
164 |
+
patient_resource = extractor.patients[patient_index]
|
165 |
+
|
166 |
+
# Add discharge_summary as an extension
|
167 |
+
if "extension" not in patient_resource:
|
168 |
+
patient_resource["extension"] = []
|
169 |
+
|
170 |
+
patient_resource["extension"].append({
|
171 |
+
"url": "http://example.com/fhir/StructureDefinition/discharge-summary",
|
172 |
+
"valueString": discharge_summary_json
|
173 |
+
})
|
174 |
+
|
175 |
+
# Update the patient in MeldRx
|
176 |
+
update_success = api.update_fhir_patient(patient_data["id"], patient_resource)
|
177 |
+
|
178 |
+
status_message = "Discharge summary generated and uploaded successfully" if update_success \
|
179 |
+
else "Discharge summary generated but failed to upload to MeldRx"
|
180 |
+
|
181 |
+
return pdf_path, status_message, summary_text
|
182 |
+
|
183 |
+
return None, "Failed to generate PDF", summary_text
|
184 |
+
|
185 |
+
except Exception as e:
|
186 |
+
logger.error(f"Error in one-click discharge generation: {str(e)}")
|
187 |
+
return None, f"Error: {str(e)}", None
|
188 |
+
|
189 |
+
def format_discharge_summary(patient_data: dict) -> str:
|
190 |
+
"""Format patient data into a discharge summary text."""
|
191 |
+
summary = [
|
192 |
+
"DISCHARGE SUMMARY",
|
193 |
+
"",
|
194 |
+
"PATIENT INFORMATION",
|
195 |
+
f"Name: {patient_data['name_prefix']} {patient_data['first_name']} {patient_data['last_name']}",
|
196 |
+
f"Date of Birth: {patient_data['dob']}",
|
197 |
+
f"Age: {patient_data['age']}",
|
198 |
+
f"Gender: {patient_data['sex']}",
|
199 |
+
f"Patient ID: {patient_data['id']}",
|
200 |
+
"",
|
201 |
+
"CONTACT INFORMATION",
|
202 |
+
f"Address: {patient_data['address']}",
|
203 |
+
f"City: {patient_data['city']}, {patient_data['state']} {patient_data['zip_code']}",
|
204 |
+
f"Phone: {patient_data['phone']}",
|
205 |
+
"",
|
206 |
+
"ADMISSION INFORMATION",
|
207 |
+
f"Admission Date: {patient_data['admission_date']}",
|
208 |
+
f"Discharge Date: {patient_data['discharge_date']}",
|
209 |
+
f"Diagnosis: {patient_data['diagnosis']}",
|
210 |
+
"",
|
211 |
+
"MEDICATIONS",
|
212 |
+
f"{patient_data['medications']}",
|
213 |
+
"",
|
214 |
+
"PHYSICIAN INFORMATION",
|
215 |
+
f"Physician: Dr. {patient_data['doctor_first_name']} {patient_data['doctor_last_name']}",
|
216 |
+
f"Hospital: {patient_data['hospital_name']}",
|
217 |
+
f"Address: {patient_data['doctor_address']}",
|
218 |
+
f"City: {patient_data['doctor_city']}, {patient_data['doctor_state']} {patient_data['doctor_zip']}",
|
219 |
+
]
|
220 |
+
|
221 |
+
return "\n".join(line for line in summary if line.strip() or line == "")
|
templates/oneclick.html
CHANGED
@@ -13,10 +13,17 @@
|
|
13 |
<div class="status-message">{{ status }}</div>
|
14 |
{% endif %}
|
15 |
|
16 |
-
{% if
|
17 |
<div class="summary-container">
|
18 |
-
<h3>Discharge Summary Preview</h3>
|
19 |
-
<div class="summary-content">{{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
</div>
|
21 |
{% endif %}
|
22 |
|
|
|
13 |
<div class="status-message">{{ status }}</div>
|
14 |
{% endif %}
|
15 |
|
16 |
+
{% if basic_summary %}
|
17 |
<div class="summary-container">
|
18 |
+
<h3>Basic Discharge Summary Preview</h3>
|
19 |
+
<div class="summary-content">{{ basic_summary | safe }}</div>
|
20 |
+
</div>
|
21 |
+
{% endif %}
|
22 |
+
|
23 |
+
{% if ai_summary %}
|
24 |
+
<div class="summary-container">
|
25 |
+
<h3>AI-Generated Discharge Summary Preview</h3>
|
26 |
+
<div class="summary-content">{{ ai_summary | safe }}</div>
|
27 |
</div>
|
28 |
{% endif %}
|
29 |
|
utils/oneclick.py
CHANGED
@@ -1,80 +1,152 @@
|
|
1 |
# utils/oneclick.py
|
2 |
-
from typing import Tuple, Optional
|
3 |
from .meldrx import MeldRxAPI
|
4 |
from .responseparser import PatientDataExtractor
|
5 |
from .pdfutils import PDFGenerator
|
6 |
import logging
|
|
|
7 |
|
8 |
logger = logging.getLogger(__name__)
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
def generate_discharge_paper_one_click(
|
11 |
api: MeldRxAPI,
|
12 |
patient_id: str = "",
|
13 |
first_name: str = "",
|
14 |
last_name: str = ""
|
15 |
-
) -> Tuple[Optional[str], str, Optional[str]]:
|
16 |
"""
|
17 |
Generate a discharge summary PDF with one click using MeldRx API data.
|
18 |
|
19 |
-
Args:
|
20 |
-
api: Initialized MeldRxAPI instance
|
21 |
-
patient_id: Optional patient ID filter
|
22 |
-
first_name: Optional first name filter
|
23 |
-
last_name: Optional last name filter
|
24 |
-
|
25 |
Returns:
|
26 |
-
Tuple of (pdf_path, status_message,
|
27 |
"""
|
28 |
try:
|
29 |
-
# Get patient data from MeldRx API
|
30 |
patients_data = api.get_patients()
|
31 |
if not patients_data or "entry" not in patients_data:
|
32 |
-
return None, "Failed to fetch patient data", None
|
33 |
|
34 |
-
# Create PatientDataExtractor instance
|
35 |
extractor = PatientDataExtractor(patients_data, "json")
|
36 |
|
37 |
-
|
|
|
|
|
38 |
matching_patients = []
|
39 |
for i in range(len(extractor.patients)):
|
40 |
extractor.set_patient_by_index(i)
|
41 |
patient_data = extractor.get_patient_dict()
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
46 |
matching_patients.append(patient_data)
|
47 |
|
48 |
if not matching_patients:
|
49 |
-
return None, "No matching patients found", None
|
50 |
|
51 |
-
# Use the first matching patient
|
52 |
patient_data = matching_patients[0]
|
53 |
-
extractor.set_patient_by_index(0)
|
54 |
|
55 |
-
#
|
56 |
-
|
|
|
57 |
|
58 |
-
|
|
|
|
|
59 |
pdf_gen = PDFGenerator()
|
60 |
-
filename = f"discharge_{patient_data
|
61 |
-
pdf_path = pdf_gen.generate_pdf_from_text(
|
62 |
|
63 |
if pdf_path:
|
64 |
-
return pdf_path, "Discharge summary generated successfully",
|
65 |
-
return None, "Failed to generate PDF",
|
66 |
|
67 |
except Exception as e:
|
68 |
-
logger.error(f"Error in one-click discharge generation: {str(e)}")
|
69 |
-
return None, f"Error: {str(e)}", None
|
70 |
|
71 |
def format_discharge_summary(patient_data: dict) -> str:
|
72 |
"""Format patient data into a discharge summary text."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
summary = [
|
74 |
"DISCHARGE SUMMARY",
|
75 |
"",
|
76 |
"PATIENT INFORMATION",
|
77 |
-
f"Name: {patient_data['name_prefix']} {patient_data['first_name']} {patient_data['last_name']}",
|
78 |
f"Date of Birth: {patient_data['dob']}",
|
79 |
f"Age: {patient_data['age']}",
|
80 |
f"Gender: {patient_data['sex']}",
|
@@ -94,7 +166,7 @@ def format_discharge_summary(patient_data: dict) -> str:
|
|
94 |
f"{patient_data['medications']}",
|
95 |
"",
|
96 |
"PHYSICIAN INFORMATION",
|
97 |
-
f"Physician: Dr. {patient_data['doctor_first_name']} {patient_data['doctor_last_name']}",
|
98 |
f"Hospital: {patient_data['hospital_name']}",
|
99 |
f"Address: {patient_data['doctor_address']}",
|
100 |
f"City: {patient_data['doctor_city']}, {patient_data['doctor_state']} {patient_data['doctor_zip']}",
|
|
|
1 |
# utils/oneclick.py
|
2 |
+
from typing import Tuple, Optional, Dict
|
3 |
from .meldrx import MeldRxAPI
|
4 |
from .responseparser import PatientDataExtractor
|
5 |
from .pdfutils import PDFGenerator
|
6 |
import logging
|
7 |
+
from huggingface_hub import InferenceClient
|
8 |
|
9 |
logger = logging.getLogger(__name__)
|
10 |
|
11 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
12 |
+
if not HF_TOKEN:
|
13 |
+
raise ValueError("HF_TOKEN environment variable not set.")
|
14 |
+
client = InferenceClient(api_key=HF_TOKEN)client = InferenceClient() # Initialize the xAI client (adjust initialization as needed)
|
15 |
+
MODEL_NAME = "meta-llama/Llama-3.3-70B-Instruct"
|
16 |
+
|
17 |
+
def generate_ai_discharge_summary(patient_dict: Dict[str, str]) -> Optional[str]:
|
18 |
+
"""Generate a discharge summary using AI based on extracted patient data."""
|
19 |
+
try:
|
20 |
+
# Use the formatted summary as input
|
21 |
+
formatted_summary = format_discharge_summary(patient_dict)
|
22 |
+
|
23 |
+
logger.info("Generating AI discharge summary with patient info: %s", formatted_summary)
|
24 |
+
|
25 |
+
messages = [
|
26 |
+
{
|
27 |
+
"role": "assistant",
|
28 |
+
"content": (
|
29 |
+
"You are a senior medical practitioner tasked with creating discharge summaries. "
|
30 |
+
"Generate a complete discharge summary based on the provided patient information."
|
31 |
+
)
|
32 |
+
},
|
33 |
+
{"role": "user", "content": formatted_summary}
|
34 |
+
]
|
35 |
+
|
36 |
+
stream = client.chat.completions.create(
|
37 |
+
model=MODEL_NAME,
|
38 |
+
messages=messages,
|
39 |
+
temperature=0.4,
|
40 |
+
max_tokens=3584,
|
41 |
+
top_p=0.7,
|
42 |
+
stream=True
|
43 |
+
)
|
44 |
+
|
45 |
+
discharge_summary = ""
|
46 |
+
for chunk in stream:
|
47 |
+
content = chunk.choices[0].delta.content
|
48 |
+
if content:
|
49 |
+
discharge_summary += content
|
50 |
+
|
51 |
+
logger.info("AI discharge summary generated successfully")
|
52 |
+
return discharge_summary.strip()
|
53 |
+
|
54 |
+
except Exception as e:
|
55 |
+
logger.error(f"Error generating AI discharge summary: {str(e)}", exc_info=True)
|
56 |
+
return None
|
57 |
+
|
58 |
def generate_discharge_paper_one_click(
|
59 |
api: MeldRxAPI,
|
60 |
patient_id: str = "",
|
61 |
first_name: str = "",
|
62 |
last_name: str = ""
|
63 |
+
) -> Tuple[Optional[str], str, Optional[str], Optional[str]]:
|
64 |
"""
|
65 |
Generate a discharge summary PDF with one click using MeldRx API data.
|
66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
Returns:
|
68 |
+
Tuple of (pdf_path, status_message, basic_summary, ai_summary)
|
69 |
"""
|
70 |
try:
|
|
|
71 |
patients_data = api.get_patients()
|
72 |
if not patients_data or "entry" not in patients_data:
|
73 |
+
return None, "Failed to fetch patient data from MeldRx API", None, None
|
74 |
|
|
|
75 |
extractor = PatientDataExtractor(patients_data, "json")
|
76 |
|
77 |
+
if not extractor.patients:
|
78 |
+
return None, "No patients found in the data", None, None
|
79 |
+
|
80 |
matching_patients = []
|
81 |
for i in range(len(extractor.patients)):
|
82 |
extractor.set_patient_by_index(i)
|
83 |
patient_data = extractor.get_patient_dict()
|
84 |
|
85 |
+
patient_data.setdefault('id', 'unknown')
|
86 |
+
patient_data.setdefault('first_name', '')
|
87 |
+
patient_data.setdefault('last_name', '')
|
88 |
+
|
89 |
+
if (not patient_id or patient_data.get("id", "") == patient_id) and \
|
90 |
+
(not first_name or patient_data.get("first_name", "").lower() == first_name.lower()) and \
|
91 |
+
(not last_name or patient_data.get("last_name", "").lower() == last_name.lower()):
|
92 |
matching_patients.append(patient_data)
|
93 |
|
94 |
if not matching_patients:
|
95 |
+
return None, "No matching patients found with the provided criteria", None, None
|
96 |
|
|
|
97 |
patient_data = matching_patients[0]
|
98 |
+
extractor.set_patient_by_index(0)
|
99 |
|
100 |
+
# Generate both basic and AI summaries
|
101 |
+
basic_summary = format_discharge_summary(patient_data)
|
102 |
+
ai_summary = generate_ai_discharge_summary(patient_data)
|
103 |
|
104 |
+
if not ai_summary:
|
105 |
+
return None, "Failed to generate AI summary", basic_summary, None
|
106 |
+
|
107 |
pdf_gen = PDFGenerator()
|
108 |
+
filename = f"discharge_{patient_data.get('id', 'unknown')}_{patient_data.get('last_name', 'patient')}.pdf"
|
109 |
+
pdf_path = pdf_gen.generate_pdf_from_text(ai_summary, filename)
|
110 |
|
111 |
if pdf_path:
|
112 |
+
return pdf_path, "Discharge summary generated successfully", basic_summary, ai_summary
|
113 |
+
return None, "Failed to generate PDF file", basic_summary, ai_summary
|
114 |
|
115 |
except Exception as e:
|
116 |
+
logger.error(f"Error in one-click discharge generation: {str(e)}", exc_info=True)
|
117 |
+
return None, f"Error generating discharge summary: {str(e)}", None, None
|
118 |
|
119 |
def format_discharge_summary(patient_data: dict) -> str:
|
120 |
"""Format patient data into a discharge summary text."""
|
121 |
+
patient_data.setdefault('name_prefix', '')
|
122 |
+
patient_data.setdefault('first_name', '')
|
123 |
+
patient_data.setdefault('last_name', '')
|
124 |
+
patient_data.setdefault('dob', 'Unknown')
|
125 |
+
patient_data.setdefault('age', 'Unknown')
|
126 |
+
patient_data.setdefault('sex', 'Unknown')
|
127 |
+
patient_data.setdefault('id', 'Unknown')
|
128 |
+
patient_data.setdefault('address', 'Unknown')
|
129 |
+
patient_data.setdefault('city', 'Unknown')
|
130 |
+
patient_data.setdefault('state', 'Unknown')
|
131 |
+
patient_data.setdefault('zip_code', 'Unknown')
|
132 |
+
patient_data.setdefault('phone', 'Unknown')
|
133 |
+
patient_data.setdefault('admission_date', 'Unknown')
|
134 |
+
patient_data.setdefault('discharge_date', 'Unknown')
|
135 |
+
patient_data.setdefault('diagnosis', 'Unknown')
|
136 |
+
patient_data.setdefault('medications', 'None specified')
|
137 |
+
patient_data.setdefault('doctor_first_name', 'Unknown')
|
138 |
+
patient_data.setdefault('doctor_last_name', 'Unknown')
|
139 |
+
patient_data.setdefault('hospital_name', 'Unknown')
|
140 |
+
patient_data.setdefault('doctor_address', 'Unknown')
|
141 |
+
patient_data.setdefault('doctor_city', 'Unknown')
|
142 |
+
patient_data.setdefault('doctor_state', 'Unknown')
|
143 |
+
patient_data.setdefault('doctor_zip', 'Unknown')
|
144 |
+
|
145 |
summary = [
|
146 |
"DISCHARGE SUMMARY",
|
147 |
"",
|
148 |
"PATIENT INFORMATION",
|
149 |
+
f"Name: {patient_data['name_prefix']} {patient_data['first_name']} {patient_data['last_name']}".strip(),
|
150 |
f"Date of Birth: {patient_data['dob']}",
|
151 |
f"Age: {patient_data['age']}",
|
152 |
f"Gender: {patient_data['sex']}",
|
|
|
166 |
f"{patient_data['medications']}",
|
167 |
"",
|
168 |
"PHYSICIAN INFORMATION",
|
169 |
+
f"Physician: Dr. {patient_data['doctor_first_name']} {patient_data['doctor_last_name']}".strip(),
|
170 |
f"Hospital: {patient_data['hospital_name']}",
|
171 |
f"Address: {patient_data['doctor_address']}",
|
172 |
f"City: {patient_data['doctor_city']}, {patient_data['doctor_state']} {patient_data['doctor_zip']}",
|