-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q_and_A_medical_dignosis_RAG_streamlit.py
174 lines (150 loc) · 6.28 KB
/
Q_and_A_medical_dignosis_RAG_streamlit.py
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
import streamlit as st
import sys
import os
import pandas as pd
from datetime import datetime
import requests
import json
import chromadb
from Covid19_RAG_Implementation import (
setup_ollama,
setup_chroma,
medical_qa,
process_metadata,
clean_dataset,
preprocess_text,
store_documents
)
def initialize_system():
"""Initialize the RAG system with ChromaDB and Ollama"""
try:
with st.spinner('Loading the medical research system...'):
# Check if collection already exists in session state
if 'collection' not in st.session_state:
# Process data
st.info("Processing metadata...")
df = process_metadata()
if df is None:
st.error("Failed to load dataset. Check if data files exist.")
return False
st.info("Cleaning dataset...")
df_cleaned = clean_dataset(df)
documents, metadata = preprocess_text(df_cleaned)
st.info("Setting up ChromaDB...")
try:
collection = setup_chroma()
if collection is not None:
st.info("Storing documents in ChromaDB...")
store_documents(collection, documents, metadata)
st.session_state.collection = collection
st.success("Database setup complete!")
return True
else:
st.error("ChromaDB setup failed")
return False
except Exception as e:
st.error(f"ChromaDB Error: {str(e)}")
return False
return True # If collection already exists
except Exception as e:
st.error(f"Initialization Error: {str(e)}")
return False
def init_ollama():
"""Initialize Ollama if not already done"""
try:
if 'ollama_query' not in st.session_state:
with st.spinner('Setting up the AI model...'):
st.info("Connecting to Ollama...")
ollama_query = setup_ollama("llama2")
if ollama_query is not None:
st.session_state.ollama_query = ollama_query
st.success("AI Model connected successfully!")
return True
else:
st.error("Failed to connect to Ollama. Make sure Ollama is running.")
return False
return True
except Exception as e:
st.error(f"Ollama Error: {str(e)}")
return False
def main():
st.title("Medical Research Question Answering System")
#updated main description
st.markdown(""" ### 🏥 AI Medical Research Assistant
This AI system analyzes medical research papers to answer questions about medical topics,
diagnosis with particular expertise in respiratory diseases and infections.
Ask a question about:
- General medical conditions and treatments
- Research Findings and clinical studies
- Medical procedures and protocols
- Disease symptoms and diagnoses
- And more.......
While the system can handle general medical queries, it has extensive knowledge about respiratory health
from specialized research papers in this field. The system will search through research papers to provide relevant answers with citations.
""")
# Initialize system components
system_ready = initialize_system()
ollama_ready = init_ollama()
if not system_ready or not ollama_ready:
st.error("System initialization failed. Please check the logs above and try again.")
return
# Input section
query = st.text_area(
"Enter your medical research question:",
height=100,
placeholder="""Example:
"What are the main symptoms of respiratory infections?"
"What research exist on asthma management"
"What are common complications of viral infections"""
)
if st.button("Get Answer"):
if not query:
st.warning("Please enter a question.")
return
with st.spinner("Searching through research papers..."):
try:
response = medical_qa(
query,
st.session_state.collection,
st.session_state.ollama_query
)
if response and isinstance(response, dict):
# Display answer
st.markdown("### Answer")
st.write(response["answer"])
# Display sources
st.markdown("### 📚Research Sources")
for source in response["sources"]: # Fixed: 'sources' instead of 'source'
st.markdown(f"""
📚Title: **{source['title']}
** 📅 Published: {source['publish_time']}
""")
else:
st.error("Failed to get a valid response from the system.")
except Exception as e:
st.error(f"An error occurred: {str(e)}")
# Sidebar information
with st.sidebar:
st.markdown("### About- AI-Medical Research Question-Answering System")
st.markdown("""
This advanced medical research assistant uses:
- AI-powered analysis of medical literature
- Comprehensive medical research database
- Specialized focus on respiratory medicine
- Real-time research paper analysis
#### 🎯 Research Coverage
- Primary focus: Respiratory diseases
- Secondary: General medical topics
- Research papers from peer-reviewed journals
#### 💡 Tips for Best Results
1. Be specific in your questions
2. Include relevant medical terms
3. Specify the aspect you're most interested in
4. Wait for thorough analysis of sources
""")
# System status indicators
st.markdown("### System Status")
st.markdown("✅ Database: Connected" if system_ready else "❌ Database: Not Connected")
st.markdown("✅ AI Model: Ready" if ollama_ready else "❌ AI Model: Not Ready")
if __name__ == "__main__":
main()