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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ======================================================================================
|
2 |
+
# 1. SETUP: Patch SQLite and Import Libraries
|
3 |
+
# ======================================================================================
|
4 |
+
# This MUST be the first import to ensure ChromaDB uses the correct SQLite version
|
5 |
+
import sys
|
6 |
+
import os
|
7 |
+
os.environ['PYSQLITE3_BUNDLED'] = '1'
|
8 |
+
__import__('pysqlite3')
|
9 |
+
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
|
10 |
+
|
11 |
+
# Standard and third-party libraries
|
12 |
+
import json
|
13 |
+
import pandas as pd
|
14 |
+
from typing import List, Union
|
15 |
+
|
16 |
+
import chromadb
|
17 |
+
|
18 |
+
import gradio as gr
|
19 |
+
from pydantic import BaseModel, ValidationError
|
20 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
21 |
+
|
22 |
+
# LangChain imports
|
23 |
+
from langchain_openai.chat_models import ChatOpenAI
|
24 |
+
from langchain_community.vectorstores import Chroma
|
25 |
+
from langchain.prompts import ChatPromptTemplate
|
26 |
+
from langchain.schema.runnable import RunnablePassthrough
|
27 |
+
from langchain.schema.output_parser import StrOutputParser
|
28 |
+
from langchain.output_parsers import PydanticOutputParser
|
29 |
+
from langchain_community.embeddings import SentenceTransformerEmbeddings
|
30 |
+
|
31 |
+
# ======================================================================================
|
32 |
+
# 2. CONSTANTS AND CONFIGURATION
|
33 |
+
# ======================================================================================
|
34 |
+
DB_DIR = "./chroma_db"
|
35 |
+
COLLECTION_NAME = "clinical_examples"
|
36 |
+
EMBEDDING_MODEL_NAME = "pritamdeka/S-Biomed-Roberta-snli-multinli-stsb"
|
37 |
+
RERANKER_MODEL_NAME = 'cross-encoder/ms-marco-MiniLM-L-6-v2'
|
38 |
+
DATASET_URL = "https://huggingface.co/datasets/DanFed/patient_encounters1_notes_preprocessed/raw/main/patient_encounters1_notes_preprocessed.csv"
|
39 |
+
|
40 |
+
|
41 |
+
# ======================================================================================
|
42 |
+
# 3. DATABASE SETUP: One-time data loading and embedding
|
43 |
+
# ======================================================================================
|
44 |
+
def setup_database(client: chromadb.Client):
|
45 |
+
"""
|
46 |
+
Loads data, generates embeddings, and populates the ChromaDB collection
|
47 |
+
only if it's empty.
|
48 |
+
"""
|
49 |
+
collection = client.get_or_create_collection(name=COLLECTION_NAME)
|
50 |
+
|
51 |
+
if collection.count() > 0:
|
52 |
+
print(f"Collection '{COLLECTION_NAME}' already exists with {collection.count()} documents. Skipping setup.")
|
53 |
+
return
|
54 |
+
|
55 |
+
print(f"Collection '{COLLECTION_NAME}' is empty. Starting data population...")
|
56 |
+
|
57 |
+
# Load dataset
|
58 |
+
df = pd.read_csv(DATASET_URL)
|
59 |
+
df.drop(['index', 'ENCOUNTER_ID', 'CLINICAL_NOTES', 'BIRTHDATE', 'FIRST',
|
60 |
+
'START', 'STOP', 'PATIENT_ID', 'ENCOUNTERCLASS', 'CODE', 'DESCRIPTION',
|
61 |
+
'BASE_ENCOUNTER_COST', 'TOTAL_CLAIM_COST', 'PAYER_COVERAGE',
|
62 |
+
'REASONCODE', 'REASONDESCRIPTION', 'PATIENT_AGE',
|
63 |
+
'DESCRIPTION_OBSERVATIONS', 'DESCRIPTION_CONDITIONS',
|
64 |
+
'DESCRIPTION_MEDICATIONS', 'DESCRIPTION_PROCEDURES', 'AGE_GROUP'], axis=1, inplace=True)
|
65 |
+
|
66 |
+
# Create example strings
|
67 |
+
def create_examples(row):
|
68 |
+
return f"Message: \n\n{row['ENCOUNTER_PROMPT'].strip()}\n\nResult: \n\n{row['COND_MED_PRO_STRUCTURED'].strip()}"
|
69 |
+
df['EXAMPLES'] = df.apply(create_examples, axis=1)
|
70 |
+
|
71 |
+
# Generate embeddings
|
72 |
+
model = SentenceTransformer(EMBEDDING_MODEL_NAME)
|
73 |
+
examples = df["EXAMPLES"].tolist()
|
74 |
+
embeddings = model.encode(
|
75 |
+
examples,
|
76 |
+
batch_size=32,
|
77 |
+
show_progress_bar=True,
|
78 |
+
convert_to_numpy=True
|
79 |
+
)
|
80 |
+
|
81 |
+
# Add to collection
|
82 |
+
collection.add(
|
83 |
+
documents=df["EXAMPLES"].tolist(),
|
84 |
+
embeddings=embeddings.tolist(),
|
85 |
+
ids=[str(i) for i in range(len(df["EXAMPLES"]))]
|
86 |
+
)
|
87 |
+
print(f"Successfully added {len(df['EXAMPLES'])} documents to the '{COLLECTION_NAME}' collection.")
|
88 |
+
|
89 |
+
|
90 |
+
# ======================================================================================
|
91 |
+
# 4. APPLICATION GLOBALS AND AI COMPONENTS
|
92 |
+
# ======================================================================================
|
93 |
+
# Pydantic schema for structured output
|
94 |
+
class ClinicalExtraction(BaseModel):
|
95 |
+
conditions: List[str]
|
96 |
+
medications: List[str]
|
97 |
+
procedures: List[str]
|
98 |
+
|
99 |
+
# Parser and format instructions
|
100 |
+
parser = PydanticOutputParser(pydantic_object=ClinicalExtraction)
|
101 |
+
format_instructions = parser.get_format_instructions().replace("{", "{{").replace("}", "}}")
|
102 |
+
|
103 |
+
# Global variables for AI components
|
104 |
+
LANGCHAIN_LLM = None
|
105 |
+
FINAL_PROMPT = None
|
106 |
+
FINAL_CHAIN = None
|
107 |
+
VECTOR_STORE = None
|
108 |
+
RERANKER = CrossEncoder(RERANKER_MODEL_NAME)
|
109 |
+
|
110 |
+
def initialize_ai_components(api_key: str):
|
111 |
+
"""Initializes all AI components needed for the RAG pipeline."""
|
112 |
+
global LANGCHAIN_LLM, FINAL_PROMPT, FINAL_CHAIN
|
113 |
+
if not api_key:
|
114 |
+
raise gr.Error("OpenAI API Key is required!")
|
115 |
+
|
116 |
+
# LLM
|
117 |
+
LANGCHAIN_LLM = ChatOpenAI(openai_api_key=api_key, temperature=0.2)
|
118 |
+
|
119 |
+
# Prompt Template
|
120 |
+
FINAL_PROMPT = ChatPromptTemplate.from_template(
|
121 |
+
f"""You are a clinical information extractor.
|
122 |
+
Extract EXACTLY this JSON format and nothing else:
|
123 |
+
|
124 |
+
{format_instructions}
|
125 |
+
|
126 |
+
CONTEXT (examples):
|
127 |
+
|
128 |
+
{{context}}
|
129 |
+
|
130 |
+
INPUT MESSAGE (clinical note + surrounding metadata):
|
131 |
+
|
132 |
+
{{input}}
|
133 |
+
|
134 |
+
Result:"""
|
135 |
+
)
|
136 |
+
|
137 |
+
# RAG Chain
|
138 |
+
FINAL_CHAIN = (
|
139 |
+
{"context": RunnablePassthrough(), "input": RunnablePassthrough()}
|
140 |
+
| FINAL_PROMPT
|
141 |
+
| LANGCHAIN_LLM
|
142 |
+
| StrOutputParser()
|
143 |
+
)
|
144 |
+
return "<p style='color:green;'>AI components initialized successfully!</p>"
|
145 |
+
|
146 |
+
# ======================================================================================
|
147 |
+
# 5. RAG PIPELINE
|
148 |
+
# ======================================================================================
|
149 |
+
def format_docs(docs):
|
150 |
+
"""Join doc.page_content with blank lines."""
|
151 |
+
return "\n\n".join(d.page_content for d in docs)
|
152 |
+
|
153 |
+
def generate_rag_response(input_text: str) -> Union[dict, str]:
|
154 |
+
"""
|
155 |
+
Performs retrieval, reranking, generation, and validation.
|
156 |
+
"""
|
157 |
+
if not FINAL_CHAIN or not VECTOR_STORE:
|
158 |
+
return "Error: AI components not initialized. Please set your API key."
|
159 |
+
|
160 |
+
# Initial embedding retrieval (top 20)
|
161 |
+
retriever = VECTOR_STORE.as_retriever(search_kwargs={"k": 20})
|
162 |
+
candidates = retriever.get_relevant_documents(input_text)
|
163 |
+
|
164 |
+
# Cross-encoder rerank -> top 5
|
165 |
+
pairs = [(input_text, d.page_content) for d in candidates]
|
166 |
+
scores = RERANKER.predict(pairs)
|
167 |
+
sorted_docs = [d for _, d in sorted(zip(scores, candidates), reverse=True)]
|
168 |
+
top_docs = sorted_docs[:5]
|
169 |
+
|
170 |
+
# Build context and invoke chain
|
171 |
+
context = format_docs(top_docs)
|
172 |
+
raw_output = FINAL_CHAIN.invoke({"context": context, "input": input_text})
|
173 |
+
|
174 |
+
# Parse and validate the output
|
175 |
+
try:
|
176 |
+
parsed = parser.parse(raw_output)
|
177 |
+
return parsed.dict()
|
178 |
+
except ValidationError as e:
|
179 |
+
return f"Schema validation failed: {e}. Raw output was: {raw_output}"
|
180 |
+
|
181 |
+
# ======================================================================================
|
182 |
+
# 6. GRADIO UI
|
183 |
+
# ======================================================================================
|
184 |
+
def create_gradio_ui():
|
185 |
+
"""Defines and returns the Gradio UI blocks."""
|
186 |
+
with gr.Blocks(title="Clinical Information Extractor") as demo:
|
187 |
+
gr.Markdown("# Clinical Information Extractor with RAG and Reranking")
|
188 |
+
|
189 |
+
with gr.Accordion("API Key Configuration", open=True):
|
190 |
+
key_box = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...")
|
191 |
+
key_btn = gr.Button("Set API Key")
|
192 |
+
key_status = gr.Markdown("")
|
193 |
+
key_btn.click(initialize_ai_components, inputs=[key_box], outputs=[key_status])
|
194 |
+
|
195 |
+
gr.Markdown("---")
|
196 |
+
gr.Markdown("## Enter Clinical Note and Metadata")
|
197 |
+
|
198 |
+
with gr.Row():
|
199 |
+
age_group_input = gr.Textbox(label="Age Group", placeholder="e.g., middle adulthood")
|
200 |
+
visit_type_input = gr.Textbox(label="Visit Type", placeholder="e.g., ambulatory")
|
201 |
+
description_input = gr.Textbox(label="Description", placeholder="e.g., encounter for check up (procedure)")
|
202 |
+
note_input = gr.Textbox(label="Clinical Note", placeholder="Type the clinical note here...", lines=5)
|
203 |
+
|
204 |
+
chatbot = gr.Chatbot(label="Extraction History", height=400)
|
205 |
+
send_btn = gr.Button("➡️ Extract Information")
|
206 |
+
|
207 |
+
def chat_interface(age, visit, desc, note, history):
|
208 |
+
history = history or []
|
209 |
+
|
210 |
+
# Build full input with metadata
|
211 |
+
metadata_parts = []
|
212 |
+
if age: metadata_parts.append(f"Age group: {age}")
|
213 |
+
if visit: metadata_parts.append(f"Visit type: {visit}")
|
214 |
+
if desc: metadata_parts.append(f"Description: {desc}")
|
215 |
+
metadata_str = " | ".join(metadata_parts)
|
216 |
+
|
217 |
+
full_input = f"{metadata_str}\n\nClinical Note:\n{note}" if metadata_str else note
|
218 |
+
user_display = f"**Metadata**: {metadata_str}\n\n**Note**: {note}"
|
219 |
+
|
220 |
+
# Get response from RAG pipeline
|
221 |
+
response = generate_rag_response(full_input)
|
222 |
+
|
223 |
+
# Format bot response
|
224 |
+
if isinstance(response, dict):
|
225 |
+
bot_response = f"```json\n{json.dumps(response, indent=2)}\n```"
|
226 |
+
else:
|
227 |
+
bot_response = str(response)
|
228 |
+
|
229 |
+
history.append((user_display, bot_response))
|
230 |
+
return history, "" # Return updated history and clear the input textbox
|
231 |
+
|
232 |
+
send_btn.click(
|
233 |
+
fn=chat_interface,
|
234 |
+
inputs=[age_group_input, visit_type_input, description_input, note_input, chatbot],
|
235 |
+
outputs=[chatbot, note_input]
|
236 |
+
)
|
237 |
+
note_input.submit(
|
238 |
+
fn=chat_interface,
|
239 |
+
inputs=[age_group_input, visit_type_input, description_input, note_input, chatbot],
|
240 |
+
outputs=[chatbot, note_input]
|
241 |
+
)
|
242 |
+
return demo
|
243 |
+
|
244 |
+
# ======================================================================================
|
245 |
+
# 7. MAIN EXECUTION
|
246 |
+
# ======================================================================================
|
247 |
+
def main():
|
248 |
+
"""
|
249 |
+
Main function to set up the database, initialize components, and launch the UI.
|
250 |
+
"""
|
251 |
+
global VECTOR_STORE
|
252 |
+
|
253 |
+
# 1. Setup ChromaDB client
|
254 |
+
client = chromadb.PersistentClient(path=DB_DIR)
|
255 |
+
|
256 |
+
# 2. Populate the database if needed
|
257 |
+
setup_database(client)
|
258 |
+
|
259 |
+
# 3. Initialize the LangChain vector store wrapper
|
260 |
+
embeddings = SentenceTransformerEmbeddings(model_name=EMBEDDING_MODEL_NAME)
|
261 |
+
VECTOR_STORE = Chroma(
|
262 |
+
client=client,
|
263 |
+
collection_name=COLLECTION_NAME,
|
264 |
+
embedding_function=embeddings,
|
265 |
+
)
|
266 |
+
print(f"Vector store initialized with {VECTOR_STORE._collection.count()} documents.")
|
267 |
+
|
268 |
+
# 4. Create and launch the Gradio UI
|
269 |
+
demo = create_gradio_ui()
|
270 |
+
print("Launching Clinical IE Demo...")
|
271 |
+
demo.launch(server_name="0.0.0.0")
|
272 |
+
|
273 |
+
if __name__ == "__main__":
|
274 |
+
main()
|