-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclinical_qa_system.py
More file actions
229 lines (180 loc) · 8.67 KB
/
clinical_qa_system.py
File metadata and controls
229 lines (180 loc) · 8.67 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
221
222
223
224
225
226
227
228
229
# clinical_qa_system.py
from neo4j import GraphDatabase
import json
import numpy as np
from typing import List, Dict
import re
class ClinicalQASystem:
def __init__(self, uri, user, password):
self.driver = GraphDatabase.driver(uri, auth=(user, password))
# Load article data for retrieval
with open('data/pubmed_entities_extracted.json', 'r') as f:
self.articles = json.load(f)
# Create article index by PMID
self.article_index = {a['pmid']: a for a in self.articles}
def close(self):
self.driver.close()
def extract_entities_from_question(self, question: str) -> Dict:
"""Extract medical entities from question"""
question_lower = question.lower()
# Common disease keywords
diseases = ['diabetes', 'cancer', 'hypertension', 'stroke', 'alzheimer',
'infection', 'tumor', 'obesity', 'heart failure', 'parkinson']
# Common drug keywords
drugs = ['insulin', 'metformin', 'aspirin', 'chemotherapy', 'immunotherapy',
'statin', 'antibiotic', 'antiviral']
found_diseases = [d for d in diseases if d in question_lower]
found_drugs = [d for d in drugs if d in question_lower]
return {
'diseases': found_diseases,
'drugs': found_drugs
}
def retrieve_relevant_articles(self, question: str, top_k: int = 5) -> List[Dict]:
"""Retrieve relevant articles from knowledge graph"""
entities = self.extract_entities_from_question(question)
with self.driver.session() as session:
# Build query based on detected entities
if entities['diseases'] and entities['drugs']:
# Question involves both disease and drug
disease = entities['diseases'][0]
drug = entities['drugs'][0]
query = """
MATCH (a:Article)-[:MENTIONS_DISEASE]->(d:Disease {name: $disease})
MATCH (a)-[:MENTIONS_DRUG]->(dr:Drug {name: $drug})
RETURN a.pmid as pmid, a.title as title, a.abstract as abstract
LIMIT $top_k
"""
result = session.run(query, disease=disease, drug=drug, top_k=top_k)
elif entities['diseases']:
# Question about disease only
disease = entities['diseases'][0]
query = """
MATCH (a:Article)-[:MENTIONS_DISEASE]->(d:Disease {name: $disease})
RETURN a.pmid as pmid, a.title as title, a.abstract as abstract
ORDER BY a.year DESC
LIMIT $top_k
"""
result = session.run(query, disease=disease, top_k=top_k)
elif entities['drugs']:
# Question about drug only
drug = entities['drugs'][0]
query = """
MATCH (a:Article)-[:MENTIONS_DRUG]->(dr:Drug {name: $drug})
RETURN a.pmid as pmid, a.title as title, a.abstract as abstract
ORDER BY a.year DESC
LIMIT $top_k
"""
result = session.run(query, drug=drug, top_k=top_k)
else:
# No specific entities detected - return recent articles
return []
articles = [dict(record) for record in result]
return articles
def generate_answer(self, question: str, articles: List[Dict]) -> str:
"""Generate answer based on retrieved articles"""
if not articles:
return "I don't have enough information to answer this question based on the available literature."
# Simple answer generation (would use LLM in production)
entities = self.extract_entities_from_question(question)
answer_parts = []
answer_parts.append(f"Based on {len(articles)} relevant scientific articles:\n")
# Summarize findings
if entities['diseases'] and entities['drugs']:
disease = entities['diseases'][0]
drug = entities['drugs'][0]
answer_parts.append(f"\nRegarding {drug} for {disease}:")
answer_parts.append(f"- Found {len(articles)} articles discussing this combination")
elif entities['diseases']:
disease = entities['diseases'][0]
answer_parts.append(f"\nRegarding {disease}:")
elif entities['drugs']:
drug = entities['drugs'][0]
answer_parts.append(f"\nRegarding {drug}:")
# Add article references
answer_parts.append("\n\nKey findings from recent literature:")
for i, article in enumerate(articles[:3], 1):
title_short = article['title'][:100] + "..." if len(article['title']) > 100 else article['title']
answer_parts.append(f"{i}. {title_short} (PMID: {article['pmid']})")
return "\n".join(answer_parts)
def answer_question(self, question: str) -> Dict:
"""Main Q&A pipeline"""
# Step 1: Retrieve relevant articles
articles = self.retrieve_relevant_articles(question, top_k=5)
# Step 2: Generate answer
answer = self.generate_answer(question, articles)
# Step 3: Get additional context from graph
entities = self.extract_entities_from_question(question)
graph_context = self.get_graph_context(entities)
return {
'question': question,
'answer': answer,
'supporting_articles': articles,
'graph_context': graph_context
}
def get_graph_context(self, entities: Dict) -> Dict:
"""Get additional context from knowledge graph"""
context = {}
with self.driver.session() as session:
if entities['diseases']:
disease = entities['diseases'][0]
# Get treatment count
query = """
MATCH (dr:Drug)-[r:TREATS]->(d:Disease {name: $disease})
RETURN count(dr) as treatment_count
"""
result = session.run(query, disease=disease)
record = result.single()
context['treatments_available'] = record['treatment_count'] if record else 0
# Get associated genes count
query = """
MATCH (g:Gene)-[r:ASSOCIATED_WITH]->(d:Disease {name: $disease})
RETURN count(g) as gene_count
"""
result = session.run(query, disease=disease)
record = result.single()
context['associated_genes'] = record['gene_count'] if record else 0
if entities['drugs']:
drug = entities['drugs'][0]
# Get diseases treated
query = """
MATCH (dr:Drug {name: $drug})-[r:TREATS]->(d:Disease)
RETURN count(d) as disease_count
"""
result = session.run(query, drug=drug)
record = result.single()
context['diseases_treated'] = record['disease_count'] if record else 0
return context
def run_qa_examples():
"""Run example clinical questions"""
URI = "neo4j://127.0.0.1:7687"
USER = "neo4j"
PASSWORD = "MedicalLiterature"
qa = ClinicalQASystem(URI, USER, PASSWORD)
print("="*80)
print("CLINICAL QUESTION ANSWERING SYSTEM - EXAMPLES")
print("="*80)
# Example questions
questions = [
"What is the role of insulin in diabetes treatment?",
"How does metformin work for diabetes?",
"What are the treatment options for hypertension?",
"What genes are associated with cancer?",
"Is chemotherapy effective for cancer treatment?"
]
for i, question in enumerate(questions, 1):
print(f"\n{'='*80}")
print(f"QUESTION {i}: {question}")
print(f"{'='*80}")
result = qa.answer_question(question)
print(f"\n{result['answer']}")
if result['graph_context']:
print(f"\nKnowledge Graph Context:")
for key, value in result['graph_context'].items():
print(f" - {key.replace('_', ' ').title()}: {value}")
print(f"\nRetrieved {len(result['supporting_articles'])} supporting articles")
qa.close()
print(f"\n{'='*80}")
print("✓ Q&A examples complete!")
print("="*80)
if __name__ == "__main__":
run_qa_examples()