File size: 2,731 Bytes
268b40a | 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 | import chromadb
import pandas as pd
from datasets import load_dataset
import json
print("Setting up ChromaDB...")
# Create a local persistent database folder called patient_db
client = chromadb.PersistentClient(path="./patient_db")
# Create a collection to store the clinical notes
collection = client.get_or_create_collection(
name="clinical_notes",
metadata={"hnsw:space": "cosine"}
)
print("Loading dataset...")
dataset = load_dataset("AGBonnet/augmented-clinical-notes", split="train[:200]")
df = dataset.to_pandas()
print("Storing notes into ChromaDB...")
success = 0
skipped = 0
for i, row in df.iterrows():
try:
# Parse the summary JSON for metadata
summary = json.loads(row["summary"]) if isinstance(row["summary"], str) else row["summary"]
# Pull useful metadata fields safely
patient_info = summary.get("patient information", {})
age = patient_info.get("age", "Unknown")
sex = patient_info.get("sex", "Unknown")
visit_motivation = summary.get("visit motivation", "Unknown")
# Store the full note as the document
# Store metadata alongside it for filtering later
collection.add(
documents=[row["full_note"]],
metadatas=[{
"idx": str(row["idx"]),
"age": str(age),
"sex": str(sex),
"visit_motivation": str(visit_motivation)[:200] # cap length
}],
ids=[str(row["idx"])]
)
success += 1
except Exception as e:
skipped += 1
continue
print(f"\nβ
Successfully stored: {success} notes")
print(f"β οΈ Skipped: {skipped} rows")
print(f"\nTotal notes in ChromaDB: {collection.count()}")
# ββ Retrieval Function βββββββββββββββββββββββββββββββββββββββββββ
def retrieve_similar_notes(query: str, n_results: int = 3):
"""
Given a transcript or query, find the most similar
clinical notes stored in ChromaDB
"""
results = collection.query(
query_texts=[query],
n_results=n_results
)
notes = results["documents"][0]
metadatas = results["metadatas"][0]
print(f"\nπ Top {n_results} similar notes retrieved:")
for i, (note, meta) in enumerate(zip(notes, metadatas)):
print(f"\n[{i+1}] Age: {meta['age']} | Sex: {meta['sex']}")
print(f" Visit: {meta['visit_motivation'][:100]}")
print(f" Note preview: {note[:150]}...")
return notes, metadatas
# Test the retrieval
if __name__ == "__main__":
test_query = "Patient has neck pain and difficulty walking"
retrieve_similar_notes(test_query) |