Spaces:
Sleeping
Sleeping
Download app.py from codedawakening/cognitive-ai-tutor: direct link, hf CLI and curl.
- Browser
- Download file 30 kB
-
https://huggingface.co/spaces/codedawakening/cognitive-ai-tutor/resolve/main/app.py
- Command line
-
hf download hf://spaces/codedawakening/cognitive-ai-tutor/app.py
-
curl -L -o app.py https://huggingface.co/spaces/codedawakening/cognitive-ai-tutor/resolve/main/app.py
30 kB
| 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(""" | |
| <style> | |
| /* Main styles */ | |
| .main-header { | |
| font-size: 3.5rem; | |
| background: linear-gradient(90deg, #667eea 0%, #764ba2 50%, #ec4899 100%); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| font-weight: 800; | |
| text-align: center; | |
| margin-bottom: 0.5rem; | |
| animation: fadeIn 1s ease-in; | |
| } | |
| @keyframes fadeIn { | |
| from { opacity: 0; transform: translateY(-20px); } | |
| to { opacity: 1; transform: translateY(0); } | |
| } | |
| .subtitle { | |
| text-align: center; | |
| color: #6b7280; | |
| font-size: 1.2rem; | |
| margin-bottom: 2rem; | |
| font-weight: 300; | |
| } | |
| /* Cards */ | |
| .feature-card { | |
| background: white; | |
| border-radius: 16px; | |
| padding: 1.5rem; | |
| border: 1px solid #e5e7eb; | |
| box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); | |
| transition: all 0.3s ease; | |
| height: 100%; | |
| } | |
| .feature-card:hover { | |
| transform: translateY(-5px); | |
| box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); | |
| } | |
| /* Status indicators */ | |
| .status-indicator { | |
| display: inline-flex; | |
| align-items: center; | |
| gap: 0.5rem; | |
| padding: 0.5rem 1rem; | |
| border-radius: 9999px; | |
| font-weight: 500; | |
| font-size: 0.875rem; | |
| } | |
| .status-online { | |
| background: linear-gradient(135deg, #10b981, #059669); | |
| color: white; | |
| } | |
| .status-offline { | |
| background: #ef4444; | |
| color: white; | |
| } | |
| .status-warning { | |
| background: #f59e0b; | |
| color: white; | |
| } | |
| /* Chat messages */ | |
| .message-user { | |
| background: linear-gradient(135deg, #667eea, #764ba2); | |
| color: white; | |
| padding: 1rem 1.25rem; | |
| border-radius: 1.5rem 1.5rem 0.5rem 1.5rem; | |
| margin-left: auto; | |
| margin-bottom: 1rem; | |
| max-width: 80%; | |
| animation: slideInRight 0.3s ease; | |
| } | |
| .message-ai { | |
| background: white; | |
| color: #1f2937; | |
| padding: 1rem 1.25rem; | |
| border-radius: 1.5rem 1.5rem 1.5rem 0.5rem; | |
| margin-right: auto; | |
| margin-bottom: 1rem; | |
| max-width: 80%; | |
| border: 1px solid #e5e7eb; | |
| box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); | |
| animation: slideInLeft 0.3s ease; | |
| } | |
| @keyframes slideInRight { | |
| from { transform: translateX(20px); opacity: 0; } | |
| to { transform: translateX(0); opacity: 1; } | |
| } | |
| @keyframes slideInLeft { | |
| from { transform: translateX(-20px); opacity: 0; } | |
| to { transform: translateX(0); opacity: 1; } | |
| } | |
| /* Progress bars */ | |
| .progress-container { | |
| background: #f3f4f6; | |
| border-radius: 9999px; | |
| height: 0.5rem; | |
| overflow: hidden; | |
| } | |
| .progress-bar { | |
| background: linear-gradient(90deg, #667eea, #764ba2); | |
| height: 100%; | |
| border-radius: 9999px; | |
| transition: width 0.5s ease; | |
| } | |
| /* Buttons */ | |
| .stButton > button { | |
| background: linear-gradient(135deg, #667eea, #764ba2); | |
| color: white; | |
| border: none; | |
| border-radius: 0.75rem; | |
| padding: 0.75rem 1.5rem; | |
| font-weight: 600; | |
| transition: all 0.3s ease; | |
| } | |
| .stButton > button:hover { | |
| transform: translateY(-2px); | |
| box-shadow: 0 10px 25px -5px rgba(102, 126, 234, 0.4); | |
| } | |
| /* Chat container */ | |
| .chat-container { | |
| height: 500px; | |
| overflow-y: auto; | |
| padding: 1rem; | |
| border: 1px solid #e5e7eb; | |
| border-radius: 0.75rem; | |
| background: #fafafa; | |
| margin-bottom: 1rem; | |
| } | |
| /* Chat input wrapper */ | |
| .chat-input-wrapper { | |
| position: sticky; | |
| bottom: 0; | |
| background: white; | |
| padding: 1rem; | |
| border-top: 1px solid #e5e7eb; | |
| z-index: 100; | |
| } | |
| </style> | |
| """, 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('<h1 class="main-header">π§ Cognitive AI Tutor</h1>', unsafe_allow_html=True) | |
| st.markdown('<p class="subtitle">End-to-End RAG System with Adaptive Learning & IRT</p>', 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'<div class="status-indicator status-{status}">π€ RAG: {status.upper()}</div>', unsafe_allow_html=True) | |
| with col2: | |
| status = "online" if st.session_state.system_status.get("vector_db") == "online" else "offline" | |
| st.markdown(f'<div class="status-indicator status-{status}">ποΈ Vector DB: {status.upper()}</div>', unsafe_allow_html=True) | |
| with col3: | |
| status = "online" if st.session_state.system_status.get("embeddings") == "online" else "offline" | |
| st.markdown(f'<div class="status-indicator status-{status}">π€ Embeddings: {status.upper()}</div>', unsafe_allow_html=True) | |
| with col4: | |
| status = "online" if st.session_state.system_status.get("document_processor") == "online" else "offline" | |
| st.markdown(f'<div class="status-indicator status-{status}">π Processor: {status.upper()}</div>', 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('<div class="chat-container">', unsafe_allow_html=True) | |
| if not st.session_state.messages: | |
| st.markdown(""" | |
| <div style="text-align: center; padding: 3rem; color: #6b7280;"> | |
| <div style="font-size: 4rem; margin-bottom: 1rem;">π€</div> | |
| <h3 style="color: #374151;">Welcome to Cognitive AI Tutor!</h3> | |
| <p>Upload your study materials and start asking questions.</p> | |
| <p style="font-size: 0.9rem; margin-top: 1rem;"> | |
| <strong>System Features:</strong> RAG β’ IRT β’ Adaptive Learning β’ Document Intelligence | |
| </p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| else: | |
| for message in st.session_state.messages: | |
| if message["role"] == "user": | |
| st.markdown(f""" | |
| <div class="message-user"> | |
| <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;"> | |
| <strong>You</strong> | |
| <small style="opacity: 0.8;">{message.get('time', '')}</small> | |
| </div> | |
| <div>{message["content"]}</div> | |
| </div> | |
| """, 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'<div style="padding: 0.25rem 0; color: #6b7280;">β’ {src}</div>' | |
| for src in message['sources'][:3]]) | |
| sources_count = len(message['sources']) | |
| sources_html = f""" | |
| <div style="margin-top: 1rem; padding-top: 0.75rem; border-top: 1px solid #e5e7eb;"> | |
| <details style="cursor: pointer;"> | |
| <summary style="color: #667eea; font-weight: 500;"> | |
| <span style="margin-right: 5px;">π</span> View Sources ({sources_count}) | |
| </summary> | |
| <div style="margin-top: 0.5rem; font-size: 0.875rem;"> | |
| {sources_list} | |
| </div> | |
| </details> | |
| </div> | |
| """ | |
| st.markdown(f""" | |
| <div class="message-ai"> | |
| <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;"> | |
| <div style="display: flex; align-items: center; gap: 0.5rem;"> | |
| <strong>π€ AI Tutor</strong> | |
| <small style="background: #10b98120; color: #10b981; padding: 0.125rem 0.5rem; border-radius: 9999px;"> | |
| {confidence}% confidence | |
| </small> | |
| </div> | |
| <small style="opacity: 0.8;">{message.get('time', '')}</small> | |
| </div> | |
| <div>{message["content"]}</div> | |
| {sources_html} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown('</div>', 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('<div class="chat-input-wrapper">', unsafe_allow_html=True) | |
| prompt = st.chat_input("Ask your AI tutor anything...", key="main_input") | |
| st.markdown('</div>', 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""" | |
| <div style="text-align: center; color: #6b7280; padding: 2rem 0;"> | |
| <div style="font-size: 0.9rem; margin-bottom: 0.5rem;"> | |
| <strong>π§ Cognitive AI Tutor</strong> | End-to-End RAG System with Adaptive Learning | |
| </div> | |
| <div style="font-size: 0.8rem; display: flex; justify-content: center; gap: 2rem; margin-bottom: 0.5rem;"> | |
| <span>π Document Intelligence</span> | |
| <span>π RAG Pipeline</span> | |
| <span>π― IRT Adaptive Learning</span> | |
| <span>ποΈ ChromaDB Vector Store</span> | |
| </div> | |
| <div style="font-size: 0.75rem;"> | |
| Build: v2.0 | Status: Operational | User: {st.session_state.user_id} | | |
| <a href="https://huggingface.co/spaces/codedawakening/cognitive-ai-tutor" target="_blank" style="color: #667eea; text-decoration: none;"> | |
| View on Hugging Face | |
| </a> | |
| </div> | |
| </div> | |
| """, unsafe_allow_html=True) |