import streamlit as st
import os
import sys
import time
from datetime import datetime
import pandas as pd
import numpy as np
from pathlib import Path
import json
# Add backend to path
sys.path.append(os.path.join(os.path.dirname(__file__), 'backend'))
# Import backend modules
try:
from document_processor import DocumentProcessor
from vector_store import VectorStoreManager
from rag_pipeline import CognitiveTutor, TutorResponse
BACKEND_AVAILABLE = True
except ImportError as e:
print(f"Backend modules not available: {e}")
BACKEND_AVAILABLE = False
# Create mock classes for demonstration
class DocumentProcessor:
def load_pdf(self, file_path):
return [{"content": "Mock content", "metadata": {"source": file_path}}]
class VectorStoreManager:
def __init__(self):
self.initialized = False
def add_documents(self, documents):
return True
def similarity_search(self, query, k=3):
return [
{"document": "Sample document 1", "score": 0.95},
{"document": "Sample document 2", "score": 0.87}
]
class TutorResponse:
def __init__(self, answer, confidence, sources, suggested_questions):
self.answer = answer
self.confidence = confidence
self.sources = sources
self.suggested_questions = suggested_questions
class CognitiveTutor:
def __init__(self):
self.initialized = False
def process_query(self, user_id, query):
return TutorResponse(
answer=f"This is a simulated response to: '{query}'",
confidence=0.85,
sources=[{"document": "Sample source", "score": 0.9}],
suggested_questions=["What is this about?", "Can you explain more?"]
)
# Page configuration
st.set_page_config(
page_title="Cognitive AI Tutor",
page_icon="π§ ",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
""", unsafe_allow_html=True)
# Initialize session state
def init_session_state():
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'documents' not in st.session_state:
st.session_state.documents = []
if 'user_id' not in st.session_state:
st.session_state.user_id = f"user_{int(time.time())}"
if 'system_status' not in st.session_state:
st.session_state.system_status = {
"rag": "offline",
"vector_db": "offline",
"embeddings": "offline",
"document_processor": "offline"
}
if 'tutor' not in st.session_state:
try:
if BACKEND_AVAILABLE:
vector_store = VectorStoreManager()
st.session_state.tutor = CognitiveTutor(vector_store)
st.session_state.system_status["rag"] = "online"
st.session_state.system_status["vector_db"] = "online"
st.session_state.system_status["embeddings"] = "online"
st.session_state.system_status["document_processor"] = "online"
else:
st.session_state.tutor = CognitiveTutor()
st.session_state.system_status = {k: "simulated" for k in st.session_state.system_status}
except Exception as e:
st.session_state.tutor = CognitiveTutor()
st.session_state.system_status = {k: "error" for k in st.session_state.system_status}
if 'learning_stats' not in st.session_state:
st.session_state.learning_stats = {
"questions_asked": 0,
"documents_processed": 0,
"accuracy_rate": 0,
"learning_time": 0,
"concepts_learned": []
}
if 'current_tab' not in st.session_state:
st.session_state.current_tab = "Chat"
init_session_state()
# Title section
st.markdown('
π§ Cognitive AI Tutor
', unsafe_allow_html=True)
st.markdown('End-to-End RAG System with Adaptive Learning & IRT
', unsafe_allow_html=True)
# Status bar
col1, col2, col3, col4 = st.columns(4)
with col1:
status = "online" if st.session_state.system_status.get("rag") == "online" else "offline"
st.markdown(f'π€ RAG: {status.upper()}
', unsafe_allow_html=True)
with col2:
status = "online" if st.session_state.system_status.get("vector_db") == "online" else "offline"
st.markdown(f'ποΈ Vector DB: {status.upper()}
', unsafe_allow_html=True)
with col3:
status = "online" if st.session_state.system_status.get("embeddings") == "online" else "offline"
st.markdown(f'π€ Embeddings: {status.upper()}
', unsafe_allow_html=True)
with col4:
status = "online" if st.session_state.system_status.get("document_processor") == "online" else "offline"
st.markdown(f'π Processor: {status.upper()}
', unsafe_allow_html=True)
# Main layout - Use radio buttons instead of tabs for chat input compatibility
st.markdown("---")
# Create navigation
selected_tab = st.radio(
"Navigation",
["π¬ Chat Tutor", "π Document Hub", "π Analytics", "βοΈ System"],
horizontal=True,
label_visibility="collapsed"
)
# Store current tab in session state
if selected_tab != st.session_state.current_tab:
st.session_state.current_tab = selected_tab
st.rerun()
# Display selected tab content
if selected_tab == "π¬ Chat Tutor":
# Chat interface
col1, col2 = st.columns([3, 1])
with col1:
st.markdown("### π Learning Conversation")
# Chat container with custom CSS height
st.markdown('', unsafe_allow_html=True)
if not st.session_state.messages:
st.markdown("""
π€
Welcome to Cognitive AI Tutor!
Upload your study materials and start asking questions.
System Features: RAG β’ IRT β’ Adaptive Learning β’ Document Intelligence
""", unsafe_allow_html=True)
else:
for message in st.session_state.messages:
if message["role"] == "user":
st.markdown(f"""
You
{message.get('time', '')}
{message["content"]}
""", unsafe_allow_html=True)
else:
confidence = message.get('confidence', 0)
# Handle sources display
sources_html = ""
if message.get('sources') and len(message['sources']) > 0:
sources_list = ''.join([f'
β’ {src}
'
for src in message['sources'][:3]])
sources_count = len(message['sources'])
sources_html = f"""
π View Sources ({sources_count})
{sources_list}
"""
st.markdown(f"""
π€ AI Tutor
{confidence}% confidence
{message.get('time', '')}
{message["content"]}
{sources_html}
""", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
with col2:
st.markdown("### π― Learning Mode")
# Learning level
level = st.select_slider(
"Set Learning Level",
options=["Beginner", "Intermediate", "Advanced"],
value="Intermediate"
)
st.markdown("---")
# Quick questions
st.markdown("#### π‘ Try Asking")
questions = [
"Explain neural networks with an analogy",
"What is the difference between AI and ML?",
"How does gradient descent optimization work?",
"Explain transformers in natural language processing",
"What are the ethical considerations in AI?"
]
for q in questions:
if st.button(q, key=f"q_{hash(q)}", use_container_width=True):
st.session_state.messages.append({
"role": "user",
"content": q,
"time": datetime.now().strftime("%H:%M")
})
st.rerun()
st.markdown("---")
# Statistics
st.markdown("#### π Session Stats")
st.metric("Questions", st.session_state.learning_stats["questions_asked"])
st.metric("Documents", len(st.session_state.documents))
st.metric("Accuracy", f"{st.session_state.learning_stats['accuracy_rate']}%")
# Chat input - PLACED OUTSIDE ANY LAYOUT ELEMENTS
st.markdown('', unsafe_allow_html=True)
prompt = st.chat_input("Ask your AI tutor anything...", key="main_input")
st.markdown('
', unsafe_allow_html=True)
if prompt:
# Add user message
st.session_state.messages.append({
"role": "user",
"content": prompt,
"time": datetime.now().strftime("%H:%M")
})
st.session_state.learning_stats["questions_asked"] += 1
# Process with AI tutor
with st.spinner(f"π§ Processing at {level} level..."):
time.sleep(1) # Simulate processing
try:
# Get AI response
response = st.session_state.tutor.process_query(
user_id=st.session_state.user_id,
query=prompt
)
# Add AI response
st.session_state.messages.append({
"role": "assistant",
"content": response.answer,
"confidence": int(response.confidence * 100),
"sources": [str(s.get('document', ''))[:50] + '...' for s in response.sources[:2]] if response.sources else [],
"time": datetime.now().strftime("%H:%M")
})
# Update learning stats
st.session_state.learning_stats["accuracy_rate"] = min(
100, st.session_state.learning_stats["accuracy_rate"] + 2
)
except Exception as e:
st.session_state.messages.append({
"role": "assistant",
"content": f"I encountered an error: {str(e)}\n\nThis is a simulated response for demonstration.",
"confidence": 50,
"sources": [],
"time": datetime.now().strftime("%H:%M")
})
st.rerun()
elif selected_tab == "π Document Hub":
st.markdown("## π Document Management Hub")
col1, col2 = st.columns([2, 1])
with col1:
# File upload section
st.markdown("### π€ Upload Documents")
uploaded_files = st.file_uploader(
"Drag & drop or click to browse",
type=['pdf', 'txt', 'docx'],
accept_multiple_files=True,
label_visibility="collapsed"
)
if uploaded_files:
progress_bar = st.progress(0)
status_text = st.empty()
for i, file in enumerate(uploaded_files):
# Check if file already exists
file_exists = any(d.get('name') == file.name for d in st.session_state.documents)
if not file_exists:
# Save file temporarily
temp_path = f"/tmp/{file.name}"
with open(temp_path, "wb") as f:
f.write(file.getbuffer())
# Process document
try:
processor = DocumentProcessor()
documents = []
if file.name.endswith('.pdf'):
documents = processor.load_pdf(temp_path)
elif file.name.endswith('.txt'):
with open(temp_path, 'r', encoding='utf-8') as f:
content = f.read()
documents = [{"content": content, "metadata": {"source": file.name}}]
# Add to vector store
if BACKEND_AVAILABLE:
vector_store = VectorStoreManager()
docs_for_store = [
{"text": doc.get('content', '') if isinstance(doc, dict) else str(doc),
"metadata": doc.get('metadata', {}) if isinstance(doc, dict) else {}}
for doc in documents[:10] # Limit for demo
]
vector_store.add_documents(docs_for_store)
st.session_state.documents.append({
"name": file.name,
"size": f"{len(file.getvalue()) / 1024:.1f} KB",
"type": file.type,
"processed": True,
"chunks": len(documents)
})
status_text.success(f"Processed {file.name} ({len(documents)} chunks)")
except Exception as e:
st.session_state.documents.append({
"name": file.name,
"size": f"{len(file.getvalue()) / 1024:.1f} KB",
"type": file.type,
"processed": False,
"error": str(e)
})
status_text.warning(f"Added {file.name} (processing failed)")
# Clean up
if os.path.exists(temp_path):
os.remove(temp_path)
else:
status_text.info(f"{file.name} already uploaded")
progress_bar.progress((i + 1) / len(uploaded_files))
progress_bar.empty()
st.session_state.learning_stats["documents_processed"] = len([d for d in st.session_state.documents if d.get('processed', False)])
with col2:
# Document stats
st.markdown("### π Document Statistics")
if st.session_state.documents:
processed = sum(1 for d in st.session_state.documents if d.get('processed', False))
total_chunks = sum(d.get('chunks', 0) for d in st.session_state.documents)
st.metric("Total Documents", len(st.session_state.documents))
st.metric("Processed", processed)
st.metric("Total Chunks", total_chunks)
# Vector store info
st.markdown("---")
st.markdown("#### Vector Store")
store_status = "Ready" if BACKEND_AVAILABLE else "Simulated"
st.info(f"ChromaDB: {store_status}")
# Search test
if st.button("Test Search", use_container_width=True):
if BACKEND_AVAILABLE:
try:
vector_store = VectorStoreManager()
results = vector_store.similarity_search("test", k=2)
st.success(f"Search successful! Found {len(results)} results")
except Exception as e:
st.error(f"Search failed: {str(e)}")
else:
st.info("Search simulation active")
else:
st.info("No documents uploaded yet")
# Document list
if st.session_state.documents:
st.markdown("---")
st.markdown("### π Document List")
for idx, doc in enumerate(st.session_state.documents):
with st.expander(f"{'β
' if doc.get('processed', False) else 'β'} {doc['name']}"):
col1, col2, col3 = st.columns([2, 1, 1])
with col1:
st.write(f"**Type:** {doc.get('type', 'Unknown')}")
st.write(f"**Size:** {doc.get('size', 'Unknown')}")
with col2:
if doc.get('processed', False):
st.success(f"{doc.get('chunks', 0)} chunks")
else:
st.error("Not processed")
with col3:
if st.button("Remove", key=f"remove_{idx}"):
st.session_state.documents.pop(idx)
st.success(f"Removed {doc['name']}")
st.rerun()
elif selected_tab == "π Analytics":
st.markdown("## π Learning Analytics & Progress")
# Stats overview
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Questions Asked", st.session_state.learning_stats["questions_asked"])
with col2:
st.metric("Accuracy Rate", f"{st.session_state.learning_stats['accuracy_rate']}%")
with col3:
st.metric("Documents", len(st.session_state.documents))
with col4:
st.metric("Concepts Learned", len(st.session_state.learning_stats["concepts_learned"]))
# Progress charts
col1, col2 = st.columns(2)
with col1:
st.markdown("### π Learning Progress")
# Simulate progress data
dates = pd.date_range(start='2024-01-01', periods=7, freq='D')
progress_data = pd.DataFrame({
'Date': dates,
'Questions': np.random.randint(1, 10, 7),
'Accuracy': np.random.randint(70, 95, 7),
'Time (min)': np.random.randint(10, 60, 7)
})
st.line_chart(progress_data.set_index('Date')[['Questions', 'Accuracy']])
with col2:
st.markdown("### π― Skill Distribution")
skills = ['AI Fundamentals', 'ML Algorithms', 'NLP', 'Computer Vision', 'Math']
levels = np.random.randint(1, 100, 5)
skill_data = pd.DataFrame({
'Skill': skills,
'Level': levels
})
st.bar_chart(skill_data.set_index('Skill'))
# Learning path
st.markdown("### πΊοΈ Learning Path")
learning_path = [
{"stage": 1, "topic": "AI Fundamentals", "status": "completed", "progress": 100},
{"stage": 2, "topic": "Machine Learning Basics", "status": "completed", "progress": 100},
{"stage": 3, "topic": "Neural Networks", "status": "in-progress", "progress": 65},
{"stage": 4, "topic": "Deep Learning", "status": "pending", "progress": 0},
{"stage": 5, "topic": "Advanced NLP", "status": "pending", "progress": 0},
]
for item in learning_path:
col1, col2, col3 = st.columns([1, 3, 1])
with col1:
st.write(f"**Stage {item['stage']}**")
with col2:
# Use st.progress for older Streamlit compatibility
progress_value = item['progress'] / 100
st.progress(progress_value)
st.caption(item['topic'])
with col3:
status_emoji = {"completed": "β
", "in-progress": "π", "pending": "β³"}
st.write(f"{status_emoji[item['status']]} {item['status'].title()}")
elif selected_tab == "βοΈ System":
st.markdown("## βοΈ System Configuration")
col1, col2 = st.columns(2)
with col1:
st.markdown("### π§ System Settings")
# Model selection
model = st.selectbox(
"Embedding Model",
["all-MiniLM-L6-v2", "paraphrase-MiniLM-L3-v2", "multi-qa-MiniLM-L6-cos-v1"],
index=0
)
# Chunk settings
chunk_size = st.slider("Chunk Size (tokens)", 500, 2000, 1000, 100)
chunk_overlap = st.slider("Chunk Overlap (tokens)", 0, 500, 200, 50)
# IRT settings
st.markdown("---")
st.markdown("#### IRT Configuration")
irt_enabled = st.toggle("Enable Item Response Theory", value=True)
if irt_enabled:
initial_ability = st.slider("Initial Ability (ΞΈ)", -3.0, 3.0, 0.0, 0.5)
difficulty_range = st.slider("Difficulty Range (b)", -3.0, 3.0, 0.0, 0.5)
with col2:
st.markdown("### π₯οΈ System Status")
# Component status
st.markdown("#### System Components")
components = [
("Document Processor", st.session_state.system_status["document_processor"]),
("Vector Database", st.session_state.system_status["vector_db"]),
("Embedding Model", st.session_state.system_status["embeddings"]),
("RAG Pipeline", st.session_state.system_status["rag"]),
("IRT Engine", "ready" if BACKEND_AVAILABLE else "simulated")
]
for name, status in components:
col1, col2 = st.columns([2, 1])
with col1:
st.write(name)
with col2:
if status in ["online", "ready"]:
st.success("β
")
elif status == "simulated":
st.warning("β οΈ")
else:
st.error("β")
# System actions
st.markdown("---")
st.markdown("#### System Actions")
if st.button("Initialize System", use_container_width=True):
try:
if BACKEND_AVAILABLE:
vector_store = VectorStoreManager()
st.session_state.tutor = CognitiveTutor(vector_store)
st.session_state.system_status = {k: "online" for k in st.session_state.system_status}
st.success("System initialized successfully!")
else:
st.session_state.tutor = CognitiveTutor()
st.session_state.system_status = {k: "simulated" for k in st.session_state.system_status}
st.success("System initialized in simulation mode!")
except Exception as e:
st.error(f"Initialization failed: {str(e)}")
st.rerun()
if st.button("Clear All Data", use_container_width=True):
st.session_state.messages = []
st.session_state.documents = []
st.session_state.learning_stats = {
"questions_asked": 0,
"documents_processed": 0,
"accuracy_rate": 0,
"learning_time": 0,
"concepts_learned": []
}
st.success("All data cleared!")
st.rerun()
# Footer
st.markdown("---")
st.markdown(f"""
π§ Cognitive AI Tutor | End-to-End RAG System with Adaptive Learning
π Document Intelligence
π RAG Pipeline
π― IRT Adaptive Learning
ποΈ ChromaDB Vector Store
""", unsafe_allow_html=True)