ontograph / app.py
TYehan's picture
Upload app.py
72f40a8 verified
raw
history blame
10.3 kB
import streamlit as st
from rdflib import Graph, Namespace, URIRef, Literal
from typing import Dict, List, Optional
from langgraph.graph import StateGraph
from langchain.prompts import ChatPromptTemplate
import json
from dotenv import load_dotenv
import os
from dataclasses import dataclass
from langchain_community.chat_models import ChatOllama
from langchain_groq import ChatGroq
import logging
from analyzers import DrugInteractionAnalyzer
import base64
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler()
]
)
# Validating API key
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
logging.error("GROQ_API_KEY not found in environment variables. Please add it to your .env file.")
raise ValueError("GROQ_API_KEY not found in environment variables. Please add it to your .env file.")
@dataclass
class GraphState:
"""State type for the graph."""
input: str
query: Optional[str] = None
ontology_results: Optional[str] = None
response: Optional[str] = None
class OntologyAgent:
def __init__(self, owl_file_path: str):
"""Initialize the OntologyAgent with an OWL file."""
self.g = Graph()
try:
self.g.parse(owl_file_path, format="xml")
self.ns = Namespace("http://www.example.org/DrugInteraction.owl#")
logging.info(f"Ontology loaded successfully from {owl_file_path}")
except Exception as e:
logging.error(f"Failed to load ontology file: {e}")
raise ValueError(f"Failed to load ontology file: {e}")
def create_agent_graph(owl_file_path: str) -> StateGraph:
"""Create a processing graph for drug interaction analysis using separate agents."""
analyzer = DrugInteractionAnalyzer(owl_file_path)
def user_input_node(state: GraphState) -> Dict[str, str]:
logging.info("Processing user input.")
return {"query": state.input}
def ontology_query_node(state: GraphState) -> Dict[str, str]:
try:
logging.info("Executing ontology queries.")
drug_names = [d.strip() for d in state.input.split(",")]
results = analyzer.analyze_drugs(drug_names)
logging.info(f"Ontology query results: {results}")
return {"ontology_results": json.dumps(results, indent=2)}
except Exception as e:
logging.warning(f"Ontology query failed: {e}")
return {"ontology_results": json.dumps({"error": str(e)})}
def llm_processing_node(state: GraphState) -> Dict[str, str]:
template = """
Based on the drug interaction analysis results:
{ontology_results}
Please provide a comprehensive summary of:
1. Direct interactions between the drugs
2. Potential conflicts
3. Similar drug alternatives
4. Recommended alternatives if conflicts exist
If no results were found, please indicate this clearly.
Format the response in a clear, structured manner.
"""
prompt = ChatPromptTemplate.from_template(template)
try:
llm = ChatGroq(
model_name="llama3-groq-70b-8192-tool-use-preview",
api_key=GROQ_API_KEY,
temperature=0.7
)
logging.info("LLM initialized successfully.")
except Exception as e:
logging.error(f"Error initializing LLM: {e}")
return {"response": f"Error initializing LLM: {str(e)}"}
chain = prompt | llm
try:
response = chain.invoke({
"ontology_results": state.ontology_results
})
logging.info("LLM processing completed successfully.")
return {"response": response.content}
except Exception as e:
logging.error(f"Error processing results with LLM: {e}")
return {"response": f"Error processing results: {str(e)}"}
workflow = StateGraph(GraphState)
workflow.add_node("input_processor", user_input_node)
workflow.add_node("ontology_query", ontology_query_node)
workflow.add_node("llm_processing", llm_processing_node)
workflow.add_edge("input_processor", "ontology_query")
workflow.add_edge("ontology_query", "llm_processing")
workflow.set_entry_point("input_processor")
logging.info("Agent graph created and configured successfully.")
return workflow.compile()
def main():
st.set_page_config(page_title="OntoGraph", page_icon="💊", layout="wide")
st.markdown("<h1 style='text-align: center;'>OntoGraph - Drug Interaction Analysis System 🧬</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: #c9f9fa;'>This application uses a combination of ontology-based reasoning and language models to analyze drug interactions.</p>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: #faffb7;'>Analyze potential interactions between different drugs</p>", unsafe_allow_html=True)
st.markdown("""
<style>
.centered {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
</style>
<div class="centered">
""", unsafe_allow_html=True)
def get_base64_image(img_path):
with open(img_path, "rb") as f:
encoded = base64.b64encode(f.read()).decode()
return f"data:image/webp;base64,{encoded}"
# Generate the image URL
image_url = get_base64_image("img/header-image.webp")
# Load custom CSS with the embedded image
st.markdown(f"""
<style>
.parallax {{
background-image: url("{image_url}");
min-height: 200px;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}}
</style>
""", unsafe_allow_html=True)
st.markdown('<div class="parallax"></div>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
col1, col2, col3 = st.columns([3, 1, 7])
with col3:
st.markdown("<h2 style='text-align: left; color: #d46c6c;'>Instructions</h2>", unsafe_allow_html=True)
st.markdown("<p style='text-align: left; color: white;'>1. Enter the drug names separated by commas. <br> 2. Click on the 'Analyze' button. <br> 3. Wait for the analysis to complete. <br> 4. View the results below.</p>", unsafe_allow_html=True)
st.markdown("<div class='divider'></div>", unsafe_allow_html=True)
st.markdown("<hr>", unsafe_allow_html=True)
st.markdown('<h3 class="big-font">Enter drug names separated by commas (e.g., Aspirin, Warfarin):</h3>', unsafe_allow_html=True)
user_input = st.text_input("", value="", key="drug_input")
st.markdown('<style>div[data-testid="stTextInput"] input { font-size: 16px;}</style>', unsafe_allow_html=True)
if st.button("Analyze"):
if not user_input.strip():
st.warning("Please enter at least one drug name.")
return
owl_file_path = os.path.join("ontology", "DrugInteraction.owl")
if not os.path.exists(owl_file_path):
logging.error(f"Ontology file not found: {owl_file_path}")
st.error(f"Ontology file not found: {owl_file_path}")
return
try:
with st.spinner("Analyzing drug interactions..."):
agent_graph = create_agent_graph(owl_file_path)
result = agent_graph.invoke(GraphState(input=user_input))
st.subheader("Analysis Results:")
st.markdown(result["response"])
logging.info("Analysis completed and results displayed.")
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
st.error(f"An error occurred: {str(e)}")
with col1:
st.markdown("<h4 style='text-align: center; color: #5ac5c9;'>Comprehensive Drug Analysis</h4>", unsafe_allow_html=True)
# st.markdown("<img src='https://cdn.dribbble.com/users/228367/screenshots/4603754/chemistryset_dribbble.gif' alt='reaction' width='100%'/>", unsafe_allow_html=True)
st.markdown("<div class='divider'></div>", unsafe_allow_html=True)
image_base64 = get_base64_image("img/reaction.gif")
st.markdown(f"<img src='{image_base64}' width='100%'/>", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.write("""
- Drug interaction detection
- Conflict identification
- Similar drug suggestions
- Alternative medication recommendations
""")
st.markdown("<hr>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: #faffb7;'></p>", unsafe_allow_html=True)
st.write("""
<div style='text-align: center;'>
<p style='text-align: left; color: #d46c6c;'>Disclaimer: </p><p style='text-align: left; color: #707377;'>This application is intended for informational purposes only and does not replace professional medical advice, diagnosis, or treatment. The analysis provided is based on the data available in the ontology and may not account for all possible drug interactions. Users are strongly advised to consult a licensed healthcare provider before making any decisions based on the analysis results. The creators of this application are not responsible for any decisions made or actions taken based on the information provided.</p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()