File size: 30,010 Bytes
3543c1d
 
 
 
ed6ef13
 
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3543c1d
 
 
 
 
 
 
 
 
 
 
 
ed6ef13
3543c1d
ed6ef13
 
3543c1d
 
 
ed6ef13
 
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3543c1d
 
ed6ef13
 
 
 
 
 
 
 
 
 
 
e741c66
 
 
 
 
 
ed6ef13
e741c66
209817e
 
 
 
 
 
 
 
 
 
 
ed6ef13
3543c1d
 
 
 
ed6ef13
 
3543c1d
ed6ef13
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209817e
 
3543c1d
ed6ef13
3543c1d
ed6ef13
 
 
3543c1d
ed6ef13
 
 
 
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
209817e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed6ef13
209817e
 
ed6ef13
 
3543c1d
ed6ef13
 
 
209817e
e741c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed6ef13
e741c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed6ef13
e741c66
 
 
 
 
 
 
 
 
 
 
 
ed6ef13
e741c66
ed6ef13
e741c66
 
 
 
 
 
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209817e
 
 
 
 
3543c1d
ed6ef13
 
3543c1d
 
ed6ef13
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26dbf9
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3543c1d
 
209817e
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e741c66
 
 
 
ed6ef13
 
 
 
 
 
 
 
c26dbf9
 
 
 
 
 
 
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26dbf9
ed6ef13
 
 
 
 
 
 
 
 
c26dbf9
ed6ef13
 
 
 
e741c66
 
ed6ef13
 
 
 
e741c66
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26dbf9
e741c66
 
ed6ef13
 
c26dbf9
ed6ef13
e741c66
 
 
 
 
 
ed6ef13
 
 
 
 
 
 
 
 
 
e741c66
ed6ef13
 
 
e741c66
 
ed6ef13
 
 
 
 
 
e741c66
 
 
ed6ef13
3543c1d
209817e
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3543c1d
ed6ef13
 
3543c1d
ed6ef13
 
3543c1d
ed6ef13
 
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e741c66
 
 
 
ed6ef13
 
 
 
209817e
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26dbf9
ed6ef13
 
e741c66
 
3543c1d
ed6ef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26dbf9
ed6ef13
c26dbf9
e741c66
 
 
 
 
 
 
 
 
 
 
 
ed6ef13
 
c26dbf9
ed6ef13
 
 
 
 
 
 
 
 
 
 
3543c1d
 
 
c26dbf9
ed6ef13
 
e741c66
ed6ef13
 
e741c66
 
 
 
ed6ef13
 
c26dbf9
ed6ef13
 
 
 
 
209817e
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
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)