MedGuard AI AgentPrivacy-First Local Medical Knowledge Engine
Drop files here
or click to upload
import streamlit as st
import pandas as pd
from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.orm import Session, DeclarativeBase
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
# Download required NLTK data
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
try:
nltk.data.find('corpora/stopwords')
except LookupError:
nltk.download('stopwords')
# Database setup
class Base(DeclarativeBase):
pass
class MedicalKnowledge(Base):
__tablename__ = 'medical_knowledge'
id = Column(Integer, primary_key=True)
category = Column(String(100))
question = Column(Text)
answer = Column(Text)
engine = create_engine('sqlite:///medical_knowledge.sqlite')
Base.metadata.create_all(bind=engine)
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
# Sample medical knowledge (in production, this would be more comprehensive)
def initialize_database():
sample_data = [
{
'category': 'General Health',
'question': 'What are common symptoms of dehydration?',
'answer': 'Common symptoms of dehydration include thirst, dark urine, dry mouth, fatigue, dizziness, and decreased urine output. Severe dehydration may require immediate medical attention.'
},
{
'category': 'First Aid',
'question': 'How do you treat a minor burn?',
'answer': 'For minor burns: 1. Cool the burn with cool running water for 10-20 minutes. 2. Remove any jewelry or tight items. 3. Apply an aloe vera gel or burn ointment. 4. Cover with a sterile gauze bandage. 5. Take over-the-counter pain medication if needed.'
},
{
'category': 'Prevention',
'question': 'How can I prevent the common cold?',
'answer': 'To prevent the common cold: 1. Wash hands frequently 2. Avoid touching face 3. Stay hydrated 4. Get adequate sleep 5. Maintain a healthy diet 6. Exercise regularly 7. Avoid close contact with sick people.'
}
]
with Session(engine) as session:
# Only add if database is empty
if not session.query(MedicalKnowledge).first():
for item in sample_data:
knowledge = MedicalKnowledge(**item)
session.add(knowledge)
session.commit()
initialize_database()
# Search function
def search_knowledge_base(query):
with Session(engine) as session:
all_knowledge = session.query(MedicalKnowledge).all()
if not all_knowledge:
return None
# Prepare corpus
documents = [f"{k.question} {k.answer}" for k in all_knowledge]
vectorizer = TfidfVectorizer(stop_words='english')
tfidf_matrix = vectorizer.fit_transform(documents)
# Vectorize query
query_vector = vectorizer.transform([query])
# Calculate similarity
similarity_scores = cosine_similarity(query_vector, tfidf_matrix)[0]
# Get most relevant result
best_match_index = np.argmax(similarity_scores)
if similarity_scores[best_match_index] > 0.1: # Threshold for relevance
return all_knowledge[best_match_index]
return None
# UI
st.title("MedGuard AI")
st.subheader("Privacy-First Local Medical Knowledge Engine")
st.markdown("""
This is a privacy-focused medical knowledge assistant that processes all queries locally.
Please note that this is for informational purposes only and does not replace professional medical advice.
""")
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
# Chat input
if prompt := st.chat_input("Ask a medical question..."):
# Add user message
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.write(prompt)
# Generate and display response
with st.chat_message("assistant"):
response = search_knowledge_base(prompt)
if response:
answer = f"**Category: {response.category}**\n\n{response.answer}\n\n*Remember: This information is for educational purposes only. Always consult with a healthcare professional for medical advice.*"
else:
answer = "I apologize, but I don't have enough information to provide a reliable answer to your question. Please consult with a healthcare professional for accurate medical advice."
st.write(answer)
st.session_state.messages.append({"role": "assistant", "content": answer})
# Sidebar with disclaimer
with st.sidebar:
st.header("Important Notice")
st.markdown("""
🏥 **Medical Disclaimer**
This application provides general medical information for educational purposes only. It is not a substitute for professional medical advice, diagnosis, or treatment.
Always seek the advice of your physician or other qualified health provider with any questions you may have regarding a medical condition.
**Privacy Notice**
✓ All processing is done locally
✓ No data is sent to external servers
✓ Your queries are not stored permanently
""")
st.divider()
st.markdown("### Features")
st.markdown("""
- Privacy-first design
- Local processing
- Instant responses
- Educational resources
- Medical knowledge base
""")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?