try to fix the response parser , fingers crossed
Browse files- utils/oneclick.py +33 -41
- utils/responseparser.py +38 -18
utils/oneclick.py
CHANGED
@@ -91,63 +91,55 @@ def generate_discharge_paper_one_click(
|
|
91 |
|
92 |
logger.info(f"Found {len(extractor.patients)} patients in the data")
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
98 |
for i in range(len(extractor.patients)):
|
99 |
extractor.set_patient_by_index(i)
|
100 |
patient_data = extractor.get_patient_dict()
|
101 |
-
|
102 |
patient_id_from_data = str(patient_data.get('id', '')).strip().lower()
|
103 |
-
first_name_from_data = str(patient_data.get('first_name', '')).strip().lower()
|
104 |
-
last_name_from_data = str(patient_data.get('last_name', '')).strip().lower()
|
105 |
-
|
106 |
-
all_patient_ids.append(patient_id_from_data)
|
107 |
-
all_patient_names.append(f"{first_name_from_data} {last_name_from_data}".strip())
|
108 |
-
|
109 |
-
patient_id_input = str(patient_id).strip().lower()
|
110 |
-
first_name_input = str(first_name).strip().lower()
|
111 |
-
last_name_input = str(last_name).strip().lower()
|
112 |
-
|
113 |
-
logger.debug(f"Patient {i}: ID={patient_id_from_data}, Name={first_name_from_data} {last_name_from_data}")
|
114 |
-
logger.debug(f"Comparing - Input: ID={patient_id_input}, First={first_name_input}, Last={last_name_input}")
|
115 |
|
116 |
-
# Match logic: ID takes precedence, then first/last name
|
117 |
-
matches = False
|
118 |
if patient_id_input and patient_id_from_data == patient_id_input:
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
|
|
|
|
|
|
|
|
|
|
132 |
search_criteria = f"ID: {patient_id or 'N/A'}, First: {first_name or 'N/A'}, Last: {last_name or 'N/A'}"
|
|
|
|
|
|
|
133 |
logger.warning(f"No patients matched criteria: {search_criteria}")
|
134 |
-
logger.info(f"Available patient IDs: {all_patient_ids}")
|
135 |
-
logger.info(f"Available patient names: {all_patient_names}")
|
136 |
return None, (f"No patients found matching criteria: {search_criteria}\n"
|
137 |
f"Available IDs: {', '.join(all_patient_ids)}\n"
|
138 |
f"Available Names: {', '.join(all_patient_names)}"), None, None, None
|
|
|
|
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
basic_summary = format_discharge_summary(patient_data)
|
144 |
-
ai_summary, verified_summary = generate_ai_discharge_summary(patient_data, client)
|
145 |
|
146 |
if not ai_summary or not verified_summary:
|
147 |
return None, "Failed to generate or verify AI summary", basic_summary, None, None
|
148 |
|
149 |
pdf_gen = PDFGenerator()
|
150 |
-
filename = f"discharge_{
|
151 |
pdf_path = pdf_gen.generate_pdf_from_text(ai_summary, filename)
|
152 |
|
153 |
if pdf_path:
|
@@ -157,7 +149,7 @@ def generate_discharge_paper_one_click(
|
|
157 |
except Exception as e:
|
158 |
logger.error(f"Error in one-click discharge generation: {str(e)}", exc_info=True)
|
159 |
return None, f"Error generating discharge summary: {str(e)}", None, None, None
|
160 |
-
|
161 |
def format_discharge_summary(patient_data: dict) -> str:
|
162 |
"""Format patient data into a discharge summary text."""
|
163 |
patient_data.setdefault('id', 'Unknown')
|
|
|
91 |
|
92 |
logger.info(f"Found {len(extractor.patients)} patients in the data")
|
93 |
|
94 |
+
matching_patient = None
|
95 |
+
patient_id_input = str(patient_id).strip().lower()
|
96 |
+
first_name_input = str(first_name).strip().lower()
|
97 |
+
last_name_input = str(last_name).strip().lower()
|
98 |
+
|
99 |
for i in range(len(extractor.patients)):
|
100 |
extractor.set_patient_by_index(i)
|
101 |
patient_data = extractor.get_patient_dict()
|
102 |
+
logger.debug(f"Processing patient {i}: {patient_data}") # Add debug log
|
103 |
patient_id_from_data = str(patient_data.get('id', '')).strip().lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
|
|
|
|
105 |
if patient_id_input and patient_id_from_data == patient_id_input:
|
106 |
+
matching_patient = patient_data
|
107 |
+
logger.info(f"Exact match found for patient ID: {patient_id_from_data}")
|
108 |
+
break
|
109 |
+
|
110 |
+
if not matching_patient and (first_name_input or last_name_input):
|
111 |
+
for i in range(len(extractor.patients)):
|
112 |
+
extractor.set_patient_by_index(i)
|
113 |
+
patient_data = extractor.get_patient_dict()
|
114 |
+
first_name_from_data = str(patient_data.get('first_name', '')).strip().lower()
|
115 |
+
last_name_from_data = str(patient_data.get('last_name', '')).strip().lower()
|
116 |
+
|
117 |
+
if (first_name_input == first_name_from_data and
|
118 |
+
last_name_input == last_name_from_data):
|
119 |
+
matching_patient = patient_data
|
120 |
+
logger.info(f"Match found by name: {first_name_from_data} {last_name_from_data}")
|
121 |
+
break
|
122 |
+
|
123 |
+
if not matching_patient:
|
124 |
search_criteria = f"ID: {patient_id or 'N/A'}, First: {first_name or 'N/A'}, Last: {last_name or 'N/A'}"
|
125 |
+
all_patient_ids = [str(p.get('id', '')) for p in extractor.get_all_patients()]
|
126 |
+
all_patient_names = [f"{p.get('first_name', '')} {p.get('last_name', '')}".strip()
|
127 |
+
for p in extractor.get_all_patients()]
|
128 |
logger.warning(f"No patients matched criteria: {search_criteria}")
|
|
|
|
|
129 |
return None, (f"No patients found matching criteria: {search_criteria}\n"
|
130 |
f"Available IDs: {', '.join(all_patient_ids)}\n"
|
131 |
f"Available Names: {', '.join(all_patient_names)}"), None, None, None
|
132 |
+
|
133 |
+
logger.info(f"Selected patient data: {matching_patient}")
|
134 |
|
135 |
+
basic_summary = format_discharge_summary(matching_patient)
|
136 |
+
ai_summary, verified_summary = generate_ai_discharge_summary(matching_patient, client)
|
|
|
|
|
|
|
137 |
|
138 |
if not ai_summary or not verified_summary:
|
139 |
return None, "Failed to generate or verify AI summary", basic_summary, None, None
|
140 |
|
141 |
pdf_gen = PDFGenerator()
|
142 |
+
filename = f"discharge_{matching_patient.get('id', 'unknown')}_{matching_patient.get('last_name', 'patient')}.pdf"
|
143 |
pdf_path = pdf_gen.generate_pdf_from_text(ai_summary, filename)
|
144 |
|
145 |
if pdf_path:
|
|
|
149 |
except Exception as e:
|
150 |
logger.error(f"Error in one-click discharge generation: {str(e)}", exc_info=True)
|
151 |
return None, f"Error generating discharge summary: {str(e)}", None, None, None
|
152 |
+
|
153 |
def format_discharge_summary(patient_data: dict) -> str:
|
154 |
"""Format patient data into a discharge summary text."""
|
155 |
patient_data.setdefault('id', 'Unknown')
|
utils/responseparser.py
CHANGED
@@ -256,32 +256,52 @@ class PatientDataExtractor:
|
|
256 |
def get_patient_dict(self) -> Dict[str, str]:
|
257 |
"""Return a dictionary of patient data mapped to discharge form fields."""
|
258 |
data = self.get_all_patient_data()
|
|
|
|
|
259 |
latest_encounter = data["encounters"][-1] if data["encounters"] else {}
|
|
|
|
|
|
|
|
|
260 |
latest_condition = data["conditions"][-1] if data["conditions"] else {}
|
261 |
-
|
|
|
|
|
|
|
|
|
|
|
262 |
return {
|
263 |
-
"id": data
|
264 |
-
"first_name": data
|
265 |
-
"last_name": data
|
266 |
-
"
|
267 |
-
"
|
268 |
-
"
|
269 |
-
"
|
270 |
-
"
|
271 |
-
"
|
272 |
-
"
|
273 |
-
"
|
274 |
-
"
|
|
|
|
|
|
|
|
|
|
|
275 |
"doctor_last_name": "",
|
276 |
-
"hospital_name": "",
|
277 |
"doctor_address": "",
|
278 |
"doctor_city": "",
|
279 |
"doctor_state": "",
|
280 |
"doctor_zip": "",
|
281 |
-
"
|
282 |
-
"
|
283 |
-
"
|
284 |
-
"
|
|
|
|
|
|
|
|
|
285 |
}
|
286 |
|
287 |
def get_all_patient_data(self) -> Dict[str, Union[str, List, Dict]]:
|
|
|
256 |
def get_patient_dict(self) -> Dict[str, str]:
|
257 |
"""Return a dictionary of patient data mapped to discharge form fields."""
|
258 |
data = self.get_all_patient_data()
|
259 |
+
|
260 |
+
# Get the latest encounter for admission/discharge dates
|
261 |
latest_encounter = data["encounters"][-1] if data["encounters"] else {}
|
262 |
+
admission_date = latest_encounter.get("start", "")
|
263 |
+
discharge_date = latest_encounter.get("end", "")
|
264 |
+
|
265 |
+
# Get the latest condition for diagnosis
|
266 |
latest_condition = data["conditions"][-1] if data["conditions"] else {}
|
267 |
+
diagnosis = latest_condition.get("description", "")
|
268 |
+
|
269 |
+
# Format medications as a string
|
270 |
+
medications_str = "; ".join([m["description"] for m in data["medications"] if m["description"]]) or "None specified"
|
271 |
+
|
272 |
+
# Safely extract fields with defaults to avoid KeyError
|
273 |
return {
|
274 |
+
"id": data.get("id", "Unknown"),
|
275 |
+
"first_name": data.get("first_name", ""),
|
276 |
+
"last_name": data.get("last_name", ""),
|
277 |
+
"name_prefix": data.get("name_prefix", ""), # Safely handle missing name_prefix
|
278 |
+
"dob": data.get("dob", "Unknown"),
|
279 |
+
"age": data.get("age", "Unknown"),
|
280 |
+
"sex": data.get("gender", "Unknown"),
|
281 |
+
"address": data.get("address_line", "Unknown"),
|
282 |
+
"city": data.get("city", "Unknown"),
|
283 |
+
"state": data.get("state", "Unknown"),
|
284 |
+
"zip_code": data.get("zip_code", "Unknown"),
|
285 |
+
"phone": data.get("phone", "Unknown"),
|
286 |
+
"admission_date": admission_date,
|
287 |
+
"discharge_date": discharge_date,
|
288 |
+
"diagnosis": diagnosis,
|
289 |
+
"medications": medications_str,
|
290 |
+
"doctor_first_name": "", # Could be extracted from Practitioner resource if linked
|
291 |
"doctor_last_name": "",
|
292 |
+
"hospital_name": "", # Could be extracted from Organization resource if linked
|
293 |
"doctor_address": "",
|
294 |
"doctor_city": "",
|
295 |
"doctor_state": "",
|
296 |
"doctor_zip": "",
|
297 |
+
"middle_initial": "",
|
298 |
+
"referral_source": "",
|
299 |
+
"admission_method": "",
|
300 |
+
"discharge_reason": "",
|
301 |
+
"date_of_death": "",
|
302 |
+
"procedures": "",
|
303 |
+
"preparer_name": "",
|
304 |
+
"preparer_job_title": ""
|
305 |
}
|
306 |
|
307 |
def get_all_patient_data(self) -> Dict[str, Union[str, List, Dict]]:
|