Spaces:
Running
Running
File size: 6,785 Bytes
c95276e |
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 |
# interface.py
import streamlit as st
import logging
from typing import Dict
from langchain_core.messages import HumanMessage
from workflow import ResearchWorkflow
from config import ResearchConfig
from langchain_core.messages import AIMessage
logger = logging.getLogger(__name__)
class ResearchInterface:
"""
Provides the Streamlit-based interface for executing the research workflow.
"""
def __init__(self) -> None:
self.workflow = ResearchWorkflow()
self._initialize_interface()
def _initialize_interface(self) -> None:
st.set_page_config(
page_title="NeuroResearch AI",
layout="wide",
initial_sidebar_state="expanded"
)
self._inject_styles()
self._build_sidebar()
self._build_main_interface()
def _inject_styles(self) -> None:
st.markdown(
"""
<style>
:root {
--primary: #2ecc71;
--secondary: #3498db;
--background: #0a0a0a;
--text: #ecf0f1;
}
.stApp {
background: var(--background);
color: var(--text);
font-family: 'Roboto', sans-serif;
}
.stTextArea textarea {
background: #1a1a1a !important;
color: var(--text) !important;
border: 2px solid var(--secondary);
border-radius: 8px;
padding: 1rem;
}
.stButton>button {
background: linear-gradient(135deg, var(--primary), var(--secondary));
border: none;
border-radius: 8px;
padding: 1rem 2rem;
transition: all 0.3s;
}
.stButton>button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(46, 204, 113, 0.3);
}
.stExpander {
background: #1a1a1a;
border: 1px solid #2a2a2a;
border-radius: 8px;
margin: 1rem 0;
}
</style>
""",
unsafe_allow_html=True
)
def _build_sidebar(self) -> None:
with st.sidebar:
st.title("π Research Database")
st.subheader("Technical Papers")
for title, short in ResearchConfig.DOCUMENT_MAP.items():
with st.expander(short):
st.markdown(f"```\n{title}\n```")
st.subheader("Analysis Metrics")
st.metric("Vector Collections", 2)
st.metric("Embedding Dimensions", ResearchConfig.EMBEDDING_DIMENSIONS)
with st.sidebar.expander("Collaboration Hub"):
st.subheader("Live Research Team")
st.write("π©π» Researcher A")
st.write("π¨π¬ Researcher B")
st.write("π€ AI Assistant")
st.subheader("Knowledge Graph")
if st.button("πΈ View Current Graph"):
self._display_knowledge_graph()
def _build_main_interface(self) -> None:
st.title("π§ NeuroResearch AI")
query = st.text_area("Research Query:", height=200, placeholder="Enter technical research question...")
domain = st.selectbox(
"Select Research Domain:",
options=[
"Biomedical Research",
"Legal Research",
"Environmental and Energy Studies",
"Competitive Programming and Theoretical Computer Science",
"Social Sciences"
],
index=0
)
if st.button("Execute Analysis", type="primary"):
self._execute_analysis(query, domain)
def _execute_analysis(self, query: str, domain: str) -> None:
try:
with st.spinner("Initializing Quantum Analysis..."):
results = self.workflow.app.stream(
{
"messages": [HumanMessage(content=query)],
"context": {"domain": domain},
"metadata": {}
},
{"recursion_limit": 100}
)
for event in results:
self._render_event(event)
st.success("β
Analysis Completed Successfully")
except Exception as e:
st.error(
f"""**Analysis Failed**
{str(e)}
Potential issues:
- Complex query structure
- Document correlation failure
- Temporal processing constraints"""
)
def _render_event(self, event: Dict) -> None:
if 'ingest' in event:
with st.container():
st.success("β
Query Ingested")
elif 'retrieve' in event:
with st.container():
docs = event['retrieve']['context'].get('documents', [])
st.info(f"π Retrieved {len(docs)} documents")
with st.expander("View Retrieved Documents", expanded=False):
for idx, doc in enumerate(docs, start=1):
st.markdown(f"**Document {idx}**")
st.code(doc.page_content, language='text')
elif 'analyze' in event:
with st.container():
content = event['analyze']['messages'][0].content
with st.expander("Technical Analysis Report", expanded=True):
st.markdown(content)
elif 'validate' in event:
with st.container():
content = event['validate']['messages'][0].content
if "VALID" in content:
st.success("β
Validation Passed")
with st.expander("View Validated Analysis", expanded=True):
st.markdown(content.split("Validation:")[0])
else:
st.warning("β οΈ Validation Issues Detected")
with st.expander("View Validation Details", expanded=True):
st.markdown(content)
elif 'enhance' in event:
with st.container():
content = event['enhance']['messages'][0].content
with st.expander("Enhanced Multi-Modal Analysis Report", expanded=True):
st.markdown(content)
def _display_knowledge_graph(self) -> None:
st.write("Knowledge Graph visualization is not implemented yet.")
class ResearchInterfaceExtended(ResearchInterface):
"""
Extended interface that includes domain adaptability, collaboration features, and graph visualization.
"""
def _build_main_interface(self) -> None:
super()._build_main_interface()
|