Spaces:
Sleeping
Sleeping
Update api/routes.py
Browse files- api/routes.py +63 -70
api/routes.py
CHANGED
|
@@ -136,89 +136,82 @@ async def list_patients(current_user: dict = Depends(get_current_user)):
|
|
| 136 |
|
| 137 |
@router.post("/ehr/fetch-from-api")
|
| 138 |
async def fetch_and_store_patients_from_fhir():
|
| 139 |
-
|
| 140 |
-
|
|
|
|
| 141 |
|
| 142 |
try:
|
| 143 |
-
async with httpx.AsyncClient() as client:
|
| 144 |
-
|
| 145 |
-
patient_res = await client.get(fhir_patients_url)
|
| 146 |
-
if patient_res.status_code != 200:
|
| 147 |
-
raise HTTPException(status_code=502, detail="Failed to fetch patients")
|
| 148 |
-
patient_entries = patient_res.json().get("entry", [])
|
| 149 |
-
|
| 150 |
-
# Fetch encounters
|
| 151 |
-
encounter_res = await client.get(fhir_encounters_url)
|
| 152 |
-
if encounter_res.status_code != 200:
|
| 153 |
-
raise HTTPException(status_code=502, detail="Failed to fetch encounters")
|
| 154 |
-
encounter_entries = encounter_res.json().get("entry", [])
|
| 155 |
-
|
| 156 |
-
# Parse encounter notes grouped by patient ID
|
| 157 |
-
patient_notes = {}
|
| 158 |
-
for entry in encounter_entries:
|
| 159 |
-
resource = entry.get("resource", {})
|
| 160 |
-
ref = resource.get("subject", {}).get("reference") # e.g., "Patient/abc123"
|
| 161 |
-
if not ref or "note" not in resource:
|
| 162 |
-
continue
|
| 163 |
-
|
| 164 |
-
patient_id = ref.split("/")[-1]
|
| 165 |
-
notes_texts = [n.get("text") for n in resource.get("note", []) if n.get("text")]
|
| 166 |
-
if notes_texts:
|
| 167 |
-
patient_notes.setdefault(patient_id, []).extend(notes_texts)
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
resource = entry.get("resource", {})
|
| 172 |
-
fhir_id = resource.get("id")
|
| 173 |
-
name_info = resource.get("name", [{}])[0]
|
| 174 |
-
address_info = resource.get("address", [{}])[0]
|
| 175 |
|
| 176 |
-
|
| 177 |
-
family = name_info.get("family", "")
|
| 178 |
-
full_name = f"{given} {family}".strip()
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
gender = resource.get("gender")
|
| 181 |
birth_date = resource.get("birthDate")
|
| 182 |
-
address = address_info.get("line", [""])[0]
|
| 183 |
-
city = address_info.get("city", "")
|
| 184 |
-
state = address_info.get("state", "")
|
| 185 |
-
zip_code = address_info.get("postalCode", "")
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
continue
|
| 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 |
except Exception as e:
|
| 221 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
| 222 |
@router.get("/ehr/fhir-patients")
|
| 223 |
async def list_fhir_patients():
|
| 224 |
cursor = patients_collection.find({"fhir_id": {"$exists": True}})
|
|
|
|
| 136 |
|
| 137 |
@router.post("/ehr/fetch-from-api")
|
| 138 |
async def fetch_and_store_patients_from_fhir():
|
| 139 |
+
base_url = "https://hapi.fhir.org/baseR4"
|
| 140 |
+
patient_url = f"{base_url}/Patient?_count=50"
|
| 141 |
+
valid_patients = []
|
| 142 |
|
| 143 |
try:
|
| 144 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 145 |
+
patient_response = await client.get(patient_url)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
if patient_response.status_code != 200:
|
| 148 |
+
raise HTTPException(status_code=502, detail="Failed to fetch patients")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
patients_data = patient_response.json().get("entry", [])
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
for p_entry in patients_data:
|
| 153 |
+
resource = p_entry.get("resource", {})
|
| 154 |
+
fhir_id = resource.get("id")
|
| 155 |
+
name = resource.get("name", [{}])[0]
|
| 156 |
+
full_name = f"{name.get('given', [''])[0]} {name.get('family', '')}".strip()
|
| 157 |
gender = resource.get("gender")
|
| 158 |
birth_date = resource.get("birthDate")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
+
address_data = resource.get("address", [{}])[0]
|
| 161 |
+
address = address_data.get("line", [""])[0]
|
| 162 |
+
city = address_data.get("city", "")
|
| 163 |
+
state = address_data.get("state", "")
|
| 164 |
+
zip_code = address_data.get("postalCode", "")
|
| 165 |
+
|
| 166 |
+
# Skip incomplete patients
|
| 167 |
+
if not (fhir_id and full_name and gender and birth_date and address and city and state and zip_code):
|
| 168 |
continue
|
| 169 |
|
| 170 |
+
# Fetch encounters for this patient
|
| 171 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 172 |
+
encounter_response = await client.get(f"{base_url}/Encounter?subject=Patient/{fhir_id}")
|
| 173 |
+
|
| 174 |
+
if encounter_response.status_code != 200:
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
encounter_entries = encounter_response.json().get("entry", [])
|
| 178 |
+
notes = []
|
| 179 |
+
|
| 180 |
+
for enc in encounter_entries:
|
| 181 |
+
enc_resource = enc.get("resource", {})
|
| 182 |
+
for n in enc_resource.get("note", []):
|
| 183 |
+
if n.get("text"):
|
| 184 |
+
notes.append(n["text"])
|
| 185 |
+
|
| 186 |
+
if not notes:
|
| 187 |
+
continue # ✅ Skip if no notes
|
| 188 |
+
|
| 189 |
+
valid_patients.append({
|
| 190 |
+
"fhir_id": fhir_id,
|
| 191 |
+
"full_name": full_name,
|
| 192 |
+
"gender": gender,
|
| 193 |
+
"date_of_birth": birth_date,
|
| 194 |
+
"address": address,
|
| 195 |
+
"city": city,
|
| 196 |
+
"state": state,
|
| 197 |
+
"zip": zip_code,
|
| 198 |
+
"notes": notes,
|
| 199 |
+
"created_at": datetime.utcnow()
|
| 200 |
+
})
|
| 201 |
+
|
| 202 |
+
if not valid_patients:
|
| 203 |
+
return {"message": "No patients with complete info and notes were found."}
|
| 204 |
+
|
| 205 |
+
result = await patients_collection.insert_many(valid_patients)
|
| 206 |
+
return {
|
| 207 |
+
"message": "Imported patients with notes",
|
| 208 |
+
"count": len(result.inserted_ids)
|
| 209 |
+
}
|
| 210 |
|
| 211 |
except Exception as e:
|
| 212 |
raise HTTPException(status_code=500, detail=str(e))
|
| 213 |
+
|
| 214 |
+
|
| 215 |
@router.get("/ehr/fhir-patients")
|
| 216 |
async def list_fhir_patients():
|
| 217 |
cursor = patients_collection.find({"fhir_id": {"$exists": True}})
|