-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdashboard.py
More file actions
2383 lines (2091 loc) · 123 KB
/
dashboard.py
File metadata and controls
2383 lines (2091 loc) · 123 KB
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import hashlib
from typing import Any, Dict
import requests
import streamlit as st
import streamlit.components.v1 as components
import plotly.graph_objects as go
# Import pandas with error handling
try:
import pandas as pd
PANDAS_AVAILABLE = True
except ImportError:
pd = None
PANDAS_AVAILABLE = False
st.warning("⚠️ pandas is not installed. Some features may not work correctly.")
# Import floating chat widget
try:
from frontend.components.floating_chat import render_floating_chat
FLOATING_CHAT_AVAILABLE = True
except ImportError:
FLOATING_CHAT_AVAILABLE = False
# Import floating community panel
try:
from frontend.components.floating_community_panel import render_floating_community_panel
FLOATING_COMMUNITY_AVAILABLE = True
except ImportError:
FLOATING_COMMUNITY_AVAILABLE = False
# Import chat history service
try:
from backend.services.chat_history import ChatHistory
CHAT_HISTORY_AVAILABLE = True
except ImportError:
CHAT_HISTORY_AVAILABLE = False
ChatHistory = None
API_BASE = os.getenv("STILLME_API_BASE", "http://localhost:8000")
STILLME_API_KEY = os.getenv("STILLME_API_KEY", "")
def get_api_headers() -> Dict[str, str]:
"""
Get headers for API requests, including API key if available.
Returns:
Dictionary with headers including X-API-Key if STILLME_API_KEY is set
"""
headers = {
"Content-Type": "application/json"
}
if STILLME_API_KEY:
headers["X-API-Key"] = STILLME_API_KEY
return headers
def _format_timestamp_gmt7(timestamp_str: str) -> str:
"""
Convert UTC timestamp to GMT+7 format for display
Args:
timestamp_str: ISO format UTC timestamp string
Returns:
Formatted timestamp string in GMT+7 (e.g., "Nov 22 2025 08:33:12")
"""
if not timestamp_str:
return "N/A"
try:
from datetime import datetime, timezone, timedelta
# Parse UTC timestamp
if isinstance(timestamp_str, str):
if timestamp_str.endswith('Z'):
timestamp_str = timestamp_str[:-1] + '+00:00'
dt_utc = datetime.fromisoformat(timestamp_str.replace('Z', '+00:00'))
# Convert UTC to GMT+7 (Vietnam timezone)
gmt7 = timezone(timedelta(hours=7))
dt_local = dt_utc.astimezone(gmt7)
return dt_local.strftime("%b %d %Y %H:%M:%S")
else:
return str(timestamp_str)
except Exception:
# Fallback: return first 19 chars if conversion fails
return timestamp_str[:19] if isinstance(timestamp_str, str) and len(timestamp_str) > 19 else str(timestamp_str)
def display_local_time(utc_time_str: str, label: str = "Next run"):
"""
Display UTC time converted to user's local timezone.
Args:
utc_time_str: ISO format UTC time string
label: Label text to display before the time
"""
if not utc_time_str:
st.caption(f"{label}: Not scheduled")
return
# Create HTML that includes both label and time in one component
element_id = f"local_time_label_{abs(hash(utc_time_str)) % 1000000}"
escaped_utc_time = utc_time_str.replace('"', '\\"').replace("'", "\\'")
html = f"""
<div style="font-size: 0.88rem; color: rgb(250, 250, 250);">
<span>{label}: </span>
<span id="{element_id}" style="display: inline-block;"></span>
</div>
<script>
(function() {{
const utcTime = "{escaped_utc_time}";
const element = document.getElementById("{element_id}");
if (!utcTime || utcTime === "None" || utcTime === "null" || utcTime === "") {{
element.textContent = "Not scheduled";
return;
}}
try {{
// Parse UTC time (assume it's UTC if no timezone specified)
let utcDate;
if (utcTime.includes('Z')) {{
utcDate = new Date(utcTime);
}} else {{
// If no Z, assume UTC and add Z
utcDate = new Date(utcTime + 'Z');
}}
// Check if date is valid
if (isNaN(utcDate.getTime())) {{
element.textContent = utcTime;
return;
}}
// Format to local time with timezone
const options = {{
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short',
hour12: false
}};
const localTimeStr = utcDate.toLocaleString('en-US', options);
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
// Format: MM/DD/YYYY, HH:MM:SS (Timezone)
// Remove comma and format nicely
const formatted = localTimeStr.replace(',', '') + ' (' + timezone + ')';
element.textContent = formatted;
}} catch (e) {{
console.error('Error converting UTC time:', e);
element.textContent = utcTime;
}}
}})();
</script>
"""
components.html(html, height=30)
def get_json(path: str, default: Dict[str, Any] | None = None, timeout: int = 10) -> Dict[str, Any]:
"""
Fetch JSON from API endpoint.
Returns default dict if request fails.
Does NOT raise exceptions - gracefully handles errors.
Args:
path: API endpoint path
default: Default value to return on error
timeout: Request timeout in seconds (default: 10s)
"""
url = f"{API_BASE}{path}"
try:
r = requests.get(url, timeout=timeout)
r.raise_for_status()
result = r.json()
# Ensure result is never None - return empty dict if None
if result is None:
return default or {}
return result
except requests.exceptions.ConnectionError as e:
# Connection failed - backend may be down
import logging
logging.error(f"Connection error fetching {url}: {e}")
return default or {}
except requests.exceptions.Timeout as e:
# Request timed out
import logging
logging.error(f"Timeout fetching {url}: {e}")
return default or {}
except requests.exceptions.HTTPError as e:
# HTTP error (4xx, 5xx)
import logging
try:
status_code = r.status_code
except Exception:
status_code = "unknown"
logging.error(f"HTTP error fetching {url}: Status {status_code} - {e}")
# Special handling for 502 Bad Gateway
if status_code == 502:
logging.error(f"502 Bad Gateway - Backend service may be down, restarting, or crashed. URL: {url}")
return default or {}
except requests.exceptions.RequestException as e:
# Other request errors
import logging
logging.error(f"Request error fetching {url}: {e}")
return default or {}
except Exception as e:
# Unexpected errors
import logging
logging.error(f"Unexpected error fetching {url}: {e}")
return default or {}
def page_overview():
# Ensure time module is available (avoid UnboundLocalError from shadowing)
import time as time_module
status = get_json("/api/status", {})
rag_stats = get_json("/api/rag/stats", {}).get("stats", {})
accuracy = get_json("/api/learning/accuracy_metrics", {}).get("metrics", {})
# Get scheduler status (with longer timeout - backend may be busy during learning cycle)
try:
scheduler_status = get_json("/api/learning/scheduler/status", {}, timeout=90)
except requests.exceptions.Timeout:
# Backend may be busy processing learning cycle - this is OK
scheduler_status = {}
# Display logo and title
col_logo, col_title = st.columns([1, 4])
with col_logo:
try:
st.image("assets/logo.png", width=80)
except Exception:
st.markdown("🧠") # Fallback emoji
with col_title:
st.markdown("# StillMe")
st.caption("Learning AI system with RAG foundation")
st.markdown("---")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Current Stage", status.get("stage", "Unknown"))
with col2:
st.metric("System Age (days)", status.get("system_age_days", 0))
with col3:
st.metric("Next Milestone", status.get("milestone_sessions", 100))
with col4:
st.metric(
"Progress",
f"{status.get('sessions_completed', 0)}/{status.get('milestone_sessions', 100)}",
)
st.markdown("### Evolution Progress")
req = [100, 500, 1000, 5000]
labels = ["Infant", "Child", "Adolescent", "Adult"]
current = [
min(status.get("sessions_completed", 0), req[0]),
0,
0,
0,
]
fig = go.Figure()
fig.add_bar(name="Required Sessions", x=labels, y=req, marker_color="#8a8f98")
fig.add_bar(name="Current Progress", x=labels, y=current, marker_color="#46b3ff")
fig.update_layout(barmode="group", height=360, margin=dict(l=0, r=0, t=10, b=0))
st.plotly_chart(fig, width='stretch')
st.markdown("### Vector DB Stats")
c1, c2, c3 = st.columns(3)
with c1:
st.metric("Total Documents", rag_stats.get("total_documents", 0))
with c2:
st.metric("Knowledge Docs", rag_stats.get("knowledge_documents", 0))
with c3:
st.metric("Conversation Docs", rag_stats.get("conversation_documents", 0))
st.markdown("### Learning Performance")
st.caption("📊 **Accuracy Score**: Measures how accurate StillMe's answers are compared to expected answers. Target: 80% accuracy.")
avg_acc = accuracy.get("average_accuracy", 0.0)
gauge = go.Figure(
go.Indicator(
mode="gauge+number+delta",
value=max(0.0, min(1.0, float(avg_acc))) * 100.0,
number={"suffix": "%"},
gauge={"axis": {"range": [0, 100]}},
delta={"reference": 80},
title={"text": "Answer Accuracy (%)"},
)
)
gauge.update_layout(height=320, margin=dict(l=0, r=0, t=10, b=0))
st.plotly_chart(gauge, width='stretch')
# Phase 3: Time-based Learning Analytics
st.markdown("### 📈 Learning Metrics (Time-based Analytics)")
try:
# Get today's metrics
today_metrics = get_json("/api/learning/metrics/daily", {}, timeout=10)
if today_metrics and today_metrics.get("metrics"):
metrics = today_metrics["metrics"]
col_m1, col_m2, col_m3, col_m4 = st.columns(4)
with col_m1:
st.metric("📥 Entries Fetched", metrics.get("total_entries_fetched", 0))
with col_m2:
st.metric("✅ Entries Added", metrics.get("total_entries_added", 0))
with col_m3:
st.metric("🚫 Entries Filtered", metrics.get("total_entries_filtered", 0))
with col_m4:
filter_rate = metrics.get("filter_rate", 0.0)
st.metric("📊 Filter Rate", f"{filter_rate}%")
# Show filter reasons if available
filter_reasons = metrics.get("filter_reasons", {})
if filter_reasons:
with st.expander("🔍 Filter Reasons Breakdown", expanded=False):
for reason, count in filter_reasons.items():
st.write(f"**{reason}**: {count}")
# Show sources breakdown if available
sources = metrics.get("sources", {})
if sources:
with st.expander("📚 Sources Breakdown", expanded=False):
for source, count in sources.items():
st.write(f"**{source.replace('_', ' ').title()}**: {count}")
# Show learning cycles for today
cycles = metrics.get("cycles", [])
if cycles:
st.caption(f"📅 Today ({today_metrics.get('date', 'N/A')}): {metrics.get('total_cycles', 0)} learning cycle(s)")
else:
st.info("📊 No learning metrics available for today yet. Metrics will appear after the first learning cycle completes.")
# Get summary metrics
summary = get_json("/api/learning/metrics/summary", {}, timeout=10)
if summary and summary.get("summary"):
summary_data = summary["summary"]
if summary_data.get("total_cycles", 0) > 0:
with st.expander("📊 Overall Learning Summary", expanded=False):
col_s1, col_s2, col_s3 = st.columns(3)
with col_s1:
st.metric("Total Cycles", summary_data.get("total_cycles", 0))
with col_s2:
st.metric("Total Fetched", summary_data.get("total_entries_fetched", 0))
with col_s3:
st.metric("Total Added", summary_data.get("total_entries_added", 0))
st.caption(f"Filter Rate: {summary_data.get('filter_rate', 0.0)}% | Add Rate: {summary_data.get('add_rate', 0.0)}%")
except Exception as e:
st.caption(f"💡 Learning metrics will be available after the first learning cycle completes. (Error: {str(e)})")
st.markdown("---")
# Auto-Learning Status Section
st.subheader("🤖 Auto-Learning Status")
# Show API_BASE for debugging (can be removed in production)
with st.expander("🔧 Debug Info", expanded=False):
st.code(f"API_BASE: {API_BASE}", language="text")
st.caption("💡 Verify this matches your backend URL on Railway")
# Test backend connection
col_test1, col_test2 = st.columns(2)
with col_test1:
if st.button("🔍 Test Backend Connection", width='stretch'):
try:
test_r = requests.get(f"{API_BASE}/health", timeout=5)
if test_r.status_code == 200:
st.success(f"✅ Backend reachable: {test_r.status_code}")
st.json(test_r.json())
else:
st.error(f"❌ Backend returned: {test_r.status_code}")
except Exception as test_e:
st.error(f"❌ Connection failed: {test_e}")
with col_test2:
if st.button("📤 Test Chat Endpoint", width='stretch'):
with st.spinner("Testing chat endpoint (this may take 30-60 seconds if model is loading)..."):
try:
test_r = requests.post(
f"{API_BASE}/api/chat/smart_router",
json={"message": "test", "user_id": "test", "use_rag": False, "context_limit": 1},
timeout=120 # Increased to 120s to handle model loading
)
if test_r.status_code == 200:
st.success(f"✅ Chat endpoint reachable: {test_r.status_code}")
response_data = test_r.json()
if "response" in response_data:
st.caption(f"Response preview: {response_data['response'][:100]}...")
else:
st.error(f"❌ Chat endpoint returned: {test_r.status_code}")
try:
st.json(test_r.json())
except Exception:
st.code(test_r.text[:200])
except requests.exceptions.Timeout:
st.warning("⏱️ **Timeout after 2 minutes** - This usually means:")
st.markdown("""
- **Embedding model is still loading** (first request can take 2-3 minutes)
- **AI API is slow** (DeepSeek/OpenAI may be experiencing delays)
- **Backend is processing** but needs more time
**Solutions:**
1. Wait 1-2 minutes and try again (model may be cached now)
2. Check backend logs for model loading progress
3. Try actual chat (it has 5-minute timeout, more forgiving)
""")
except Exception as test_e:
st.error(f"❌ Chat endpoint failed: {test_e}")
if "timeout" in str(test_e).lower():
st.info("💡 **Tip:** Chat endpoint is working but slow. Try sending an actual message - it has a longer timeout (5 minutes).")
# Show environment info
st.markdown("---")
st.caption("**Environment Variables:**")
st.code(f"STILLME_API_BASE: {os.getenv('STILLME_API_BASE', 'NOT SET')}", language="text")
st.code(f"STILLME_API_KEY: {'SET (length: ' + str(len(STILLME_API_KEY)) + ')' if STILLME_API_KEY else 'NOT SET'}", language="text")
if API_BASE == "http://localhost:8000":
st.warning("⚠️ **WARNING:** API_BASE is still `localhost:8000`! This means `STILLME_API_BASE` environment variable is NOT set in Railway dashboard service. You need to set it to your backend URL (e.g., `https://stillme-backend-production-xxxx.up.railway.app`)")
if not STILLME_API_KEY:
st.error("❌ **CRITICAL:** `STILLME_API_KEY` is NOT set! Protected endpoints (scheduler start/stop, database reset, knowledge injection) will fail with 401 Unauthorized. Set `STILLME_API_KEY` in Railway dashboard service variables (must match backend `STILLME_API_KEY`).")
# Get scheduler status with longer timeout (backend may be busy during learning cycle)
# Use try-except to handle timeout gracefully and show progress if job is running
try:
scheduler_status = get_json("/api/learning/scheduler/status", {}, timeout=90)
except requests.exceptions.Timeout:
# Backend may be busy processing learning cycle - check if job is running
if st.session_state.get("learning_job_started"):
# Job is running - this is expected, don't show error
st.info("⏳ Backend is processing learning cycle. Showing job progress below...")
scheduler_status = {} # Empty to trigger job status display
else:
# No job running but timeout - backend may be busy or slow
st.warning("⏳ Backend is taking longer than usual to respond. This may indicate a learning cycle is running.")
st.info("💡 **Tip:** If you just clicked 'Run Now', the learning cycle is likely starting. Progress will appear below.")
scheduler_status = {}
# Debug: Show what we received and test connection
if not scheduler_status or scheduler_status == {}:
# Don't show error if we know a job is running (timeout is expected)
if not st.session_state.get("learning_job_started"):
st.warning("⚠️ **Warning:** Could not fetch scheduler status from backend.")
st.info("💡 **Tip:** If you just clicked 'Run Now', the learning cycle is starting. Wait a moment and refresh.")
# Try to provide more specific error info (only if not a known job)
if not st.session_state.get("learning_job_started"):
try:
test_url = f"{API_BASE}/api/status"
test_r = requests.get(test_url, timeout=10) # Quick check for backend availability
if test_r.status_code == 200:
st.info("💡 Backend is reachable. Scheduler status may be temporarily unavailable during learning cycle.")
elif test_r.status_code == 502:
st.error("❌ **502 Bad Gateway** - Backend service is not responding.")
st.markdown("""
**502 Bad Gateway means the backend service is down or crashed.**
**Immediate Actions:**
1. Go to Railway Dashboard → Service "stillme-backend"
2. Check **"Deployments"** tab → See if service is running
3. Check **"Logs"** tab → Look for errors or crashes
4. If service is stopped → Click **"Redeploy"** or **"Restart"**
5. If service is building → Wait for deployment to complete
**Common Causes:**
- Backend crashed during initialization
- Backend is restarting after code change
- Backend ran out of memory (check Railway resource limits)
- Database connection issues
""")
elif test_r.status_code == 503:
st.error(f"❌ **503 Service Unavailable** - Backend returned status code 503 for `/api/status`")
st.markdown("""
**503 Service Unavailable means the backend is temporarily unavailable.**
**Possible Causes:**
- Backend is restarting or cold starting
- Backend is under heavy load
- Backend is initializing services (database, ChromaDB, etc.)
**Actions:**
1. Wait 30-60 seconds and refresh the page
2. Check Railway Dashboard → Service "stillme-backend" → Logs
3. If persists, restart the backend service
""")
else:
st.error(f"❌ Backend returned status code {test_r.status_code} for `/api/status`")
except requests.exceptions.ConnectionError:
st.error(f"❌ **Cannot connect to backend at:** `{API_BASE}`")
st.markdown("""
**Possible causes:**
1. Backend service is not running on Railway
2. Environment variable `STILLME_API_BASE` is not set in dashboard service
3. Backend URL has changed
4. Network/firewall issue
**Solution:**
- Check Railway dashboard → Service "stillme-backend" → Ensure it's running
- Check Railway dashboard → Service "dashboard" → Variables → Verify `STILLME_API_BASE` is set
- Restart dashboard service if needed
""")
except Exception as e:
st.warning(f"Error testing connection: {e}")
st.json({"error": "Empty response from /api/learning/scheduler/status", "api_base": API_BASE})
return
if scheduler_status.get("status") == "ok":
is_running = scheduler_status.get("is_running", False)
interval_hours = scheduler_status.get("interval_hours", 4)
next_run = scheduler_status.get("next_run_time")
col_status, col_info = st.columns([1, 2])
with col_status:
if is_running:
st.success(f"🟢 **Running** (every {interval_hours}h)")
else:
st.warning("🟡 **Stopped**")
with col_info:
if next_run:
display_local_time(next_run, "Next run")
else:
st.caption("Next run: Not scheduled")
# Display source statistics for transparency
source_stats = scheduler_status.get("source_statistics", {})
if source_stats and not source_stats.get("error"):
st.markdown("### 📊 Learning Source Statistics")
# RSS Statistics
if "rss" in source_stats:
rss_data = source_stats["rss"]
rss_stats = rss_data.get("stats") or {} # Get stats from nested structure, handle None case
# Debug: Log what we're getting (only in debug mode)
import logging
logger = logging.getLogger(__name__)
if rss_stats:
logger.debug(f"RSS stats from API: {rss_stats}")
else:
logger.warning(f"RSS stats is None or empty! rss_data: {rss_data}")
# Get feeds_count from rss_data (top level) or from stats (fallback)
feeds_count = rss_data.get("feeds_count", rss_stats.get("feeds_count", 0)) if rss_stats else rss_data.get("feeds_count", 0)
successful_feeds = rss_stats.get("successful_feeds", 0) if rss_stats else 0
failed_feeds = rss_stats.get("failed_feeds", 0) if rss_stats else 0
status = rss_stats.get("status", "unknown") if rss_stats else "unknown"
last_error = rss_stats.get("last_error") if rss_stats else None
failure_rate = rss_stats.get("failure_rate", 0) if rss_stats else 0
# Show warning if stats show 0/0 but feeds_count > 0 (likely no fetch cycle has run yet)
last_fetch_timestamp = rss_stats.get("last_fetch_timestamp") if rss_stats else None
if feeds_count > 0 and successful_feeds == 0 and failed_feeds == 0:
if not last_fetch_timestamp:
st.info("ℹ️ **No fetch cycle has run yet.** RSS stats will appear after the first learning cycle completes.")
else:
# Debug: Show raw data if there's a mismatch (0/0 when we expect failures)
with st.expander("🔍 Debug: RSS Stats Data", expanded=False):
st.json({
"rss_data": rss_data,
"rss_stats": rss_stats,
"feeds_count": feeds_count,
"successful_feeds": successful_feeds,
"failed_feeds": failed_feeds,
"status": status,
"last_fetch_timestamp": last_fetch_timestamp
})
st.caption("⚠️ If backend logs show failures but this shows 0/0, there may be a timing issue or stats not being updated correctly.")
col_rss1, col_rss2, col_rss3, col_rss4 = st.columns(4)
with col_rss1:
st.metric("📡 RSS Feeds", feeds_count)
with col_rss2:
st.metric("✅ Successful", successful_feeds)
with col_rss3:
st.metric("❌ Failed", failed_feeds)
with col_rss4:
status_icon = "🟢" if status == "ok" else "🔴"
st.metric("Status", f"{status_icon} {status.upper()}")
# Show errors if any
if failed_feeds > 0:
with st.expander("⚠️ RSS Feed Errors", expanded=False):
if last_error:
st.error(f"**Last Error:** {last_error}")
st.caption(f"💡 {failed_feeds} feed(s) failed (failure rate: {failure_rate}%). Check backend logs for details.")
# Other sources (arXiv, CrossRef, Wikipedia, etc.)
other_sources = {k: v for k, v in source_stats.items() if k != "rss"}
if other_sources:
with st.expander("📚 Other Learning Sources", expanded=False):
for source_name, source_data in other_sources.items():
if isinstance(source_data, dict):
# Structure: {"enabled": True, "stats": {"status": "ok", ...}}
# If stats is None, source hasn't been used yet
stats = source_data.get("stats")
if stats is None:
# Source enabled but not used yet - show as "not_used" or "enabled"
status_icon = "🟡" if source_data.get("enabled", False) else "⚪"
status_text = "enabled" if source_data.get("enabled", False) else "disabled"
st.write(f"**{source_name.replace('_', ' ').title()}**: {status_icon} {status_text}")
elif isinstance(stats, dict):
# Stats available - check status
status = stats.get("status", "unknown")
status_icon = "🟢" if status == "ok" else "🔴"
st.write(f"**{source_name.replace('_', ' ').title()}**: {status_icon} {status}")
if stats.get("error_count", 0) > 0:
st.caption(f" ⚠️ {stats.get('error_count', 0)} error(s)")
if stats.get("last_error"):
st.caption(f" 📝 Last error: {stats['last_error'][:100]}...")
else:
# Invalid stats format
status_icon = "🔴"
st.write(f"**{source_name.replace('_', ' ').title()}**: {status_icon} unknown")
# Scheduler controls: Stop and Run Now (Admin-only)
col_stop, col_run_now, col_stats = st.columns(3)
with col_stop:
if not is_admin():
st.button("⏹️ Stop Scheduler", width='stretch', disabled=True, help="Admin access required")
elif st.button("⏹️ Stop Scheduler", width='stretch'):
try:
# Increased timeout to 30s to handle network latency (Railway deployment)
r = requests.post(
f"{API_BASE}/api/learning/scheduler/stop",
headers=get_api_headers(),
timeout=30
)
if r.status_code == 200:
st.session_state["last_action"] = "✅ Scheduler stopped successfully!"
st.rerun()
except requests.exceptions.Timeout:
# Timeout doesn't mean failure - scheduler may have stopped in background
# Check status to confirm
try:
status_check = get_json("/api/learning/scheduler/status", {}, timeout=10)
if not status_check.get("is_running", True):
st.session_state["last_action"] = "✅ Scheduler stopped successfully! (Confirmed via status check)"
st.rerun()
else:
st.session_state["last_error"] = "⏱️ Request timed out. Please check scheduler status - it may have stopped in background."
except:
st.session_state["last_error"] = "⏱️ Request timed out. Scheduler may have stopped - please refresh to check status."
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
st.session_state["last_error"] = f"❌ 401 Unauthorized: API key missing or invalid. Please set STILLME_API_KEY in Railway dashboard service variables."
elif e.response.status_code == 403:
st.session_state["last_error"] = f"❌ 403 Forbidden: Invalid API key. Please verify STILLME_API_KEY matches backend key."
else:
st.session_state["last_error"] = f"❌ Failed to stop scheduler: {e}"
except Exception as e:
st.session_state["last_error"] = f"❌ Failed to stop scheduler: {e}"
with col_run_now:
if not is_admin():
st.button("🚀 Run Now", width='stretch', disabled=True, help="Admin access required")
elif st.button("🚀 Run Now", width='stretch'):
# Store Vector DB stats BEFORE running to compare later
try:
initial_rag_stats = get_json("/api/rag/stats", {}, timeout=10)
st.session_state["initial_rag_stats"] = initial_rag_stats.get("stats", {})
except:
st.session_state["initial_rag_stats"] = {}
# Store current cycle count to detect completion
try:
current_status = get_json("/api/learning/scheduler/status", {}, timeout=10)
if current_status and current_status.get("status") == "ok":
st.session_state["learning_cycle_count_at_start"] = current_status.get("cycle_count", 0)
except:
st.session_state["learning_cycle_count_at_start"] = 0
# Make the API call (with short timeout for immediate feedback)
try:
# Non-blocking: returns 202 immediately
r = requests.post(f"{API_BASE}/api/learning/scheduler/run-now", timeout=5)
if r.status_code == 202:
data = r.json()
job_id = data.get("job_id")
st.session_state["learning_job_id"] = job_id
st.session_state["learning_job_started"] = True
st.session_state["learning_job_start_time"] = time_module.time()
# IMMEDIATE FEEDBACK
st.success("🚀 Learning cycle started! Running in background (2-5 minutes). Results will appear below when complete.")
elif r.status_code == 200:
# Sync mode (for tests) - immediate results
data = r.json()
entries = data.get("entries_fetched", 0)
filtered = data.get("entries_filtered", 0)
added = data.get("entries_added_to_rag", 0)
if filtered > 0:
st.session_state["last_action"] = f"✅ Learning cycle completed! Fetched {entries} entries, Filtered {filtered} (Low quality/Short), Added {added} to RAG."
else:
st.session_state["last_action"] = f"✅ Learning cycle completed! Fetched {entries} entries, added {added} to RAG."
st.session_state["learning_job_started"] = False
st.session_state["learning_cycle_result"] = data
st.success("✅ Learning cycle completed immediately!")
else:
st.session_state["last_error"] = f"❌ Failed: {r.json().get('detail', 'Unknown error')}"
st.error(st.session_state["last_error"])
except requests.exceptions.Timeout:
# Timeout is OK - job is running in background
st.session_state["learning_job_id"] = None
st.session_state["learning_job_started"] = True
st.session_state["learning_job_start_time"] = time_module.time()
# IMMEDIATE FEEDBACK even on timeout
st.success("🚀 Learning cycle started! Running in background (2-5 minutes). Results will appear below when complete.")
except Exception as e:
st.session_state["last_error"] = f"❌ Failed to start: {e}"
st.session_state["learning_job_started"] = False
st.error(st.session_state["last_error"])
# Rerun to show progress section
st.rerun()
with col_stats:
if st.button("📊 Learning Statistics", width='stretch', help="View detailed learning statistics (what StillMe learned/didn't learn and why)"):
st.session_state["show_learning_stats"] = True
st.rerun()
# Display Learning Statistics Dialog (Task Manager style)
if st.session_state.get("show_learning_stats", False):
st.markdown("---")
with st.expander("📊 Learning Statistics", expanded=True):
try:
# Get RSS fetch history
fetch_history = get_json("/api/learning/rss/fetch-history", {"limit": 200}, timeout=30)
# Handle None response
if fetch_history is None:
st.warning("⚠️ Backend returned no data. RSS fetch history may not be initialized yet.")
st.caption("💡 Run a learning cycle first to generate statistics.")
if st.button("❌ Close Statistics", use_container_width=True):
st.session_state["show_learning_stats"] = False
st.rerun()
return
# Ensure items is a list
items = fetch_history.get("items", [])
if items is None:
items = []
if items and len(items) > 0:
st.markdown("### 📋 Learning Activity Table")
st.caption(f"Showing {len(items)} most recent learning items")
# Create Task Manager style table
from datetime import datetime
# Prepare data for table
table_data = []
for item in items:
source = item.get("source_url", item.get("source", "Unknown"))
title = item.get("title", "No title")[:60] + "..." if len(item.get("title", "")) > 60 else item.get("title", "No title")
status = item.get("status", "Unknown")
# Ensure reason is always a string (never None)
reason = item.get("status_reason") or ""
if reason is None:
reason = ""
timestamp = item.get("fetch_timestamp", item.get("timestamp", ""))
# Format timestamp - convert UTC to local timezone (GMT+7)
try:
if timestamp:
if isinstance(timestamp, str):
# Parse UTC timestamp
if timestamp.endswith('Z'):
timestamp = timestamp[:-1] + '+00:00'
dt_utc = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
# Convert UTC to GMT+7 (Vietnam timezone)
from datetime import timezone, timedelta
gmt7 = timezone(timedelta(hours=7))
dt_local = dt_utc.astimezone(gmt7)
formatted_time = dt_local.strftime("%b %d %Y %H:%M:%S")
else:
formatted_time = str(timestamp)
else:
formatted_time = "N/A"
except:
formatted_time = str(timestamp) if timestamp else "N/A"
# Determine status icon and color
if "Added" in status or "added" in status.lower():
status_icon = "✅"
status_color = "green"
elif "Filtered" in status or "filtered" in status.lower():
status_icon = "⚠️"
status_color = "orange"
elif "Failed" in status or "failed" in status.lower():
status_icon = "❌"
status_color = "red"
else:
status_icon = "ℹ️"
status_color = "gray"
table_data.append({
"Source": source[:40] + "..." if len(source) > 40 else source,
"Title": title,
"Status": f"{status_icon} {status}",
"Reason": (reason[:50] + "..." if len(reason) > 50 else reason) if reason else "",
"Timestamp": formatted_time
})
# Create DataFrame and display
df = pd.DataFrame(table_data)
# Style the DataFrame
def highlight_status(row):
if "✅" in str(row["Status"]):
return ['background-color: #1e3a2e'] * len(row)
elif "⚠️" in str(row["Status"]):
return ['background-color: #3a2e1e'] * len(row)
elif "❌" in str(row["Status"]):
return ['background-color: #3a1e1e'] * len(row)
return [''] * len(row)
st.dataframe(
df.style.apply(highlight_status, axis=1),
use_container_width=True,
height=400
)
# Summary statistics
st.markdown("### 📈 Summary")
col_sum1, col_sum2, col_sum3, col_sum4 = st.columns(4)
added_count = sum(1 for item in items if "Added" in item.get("status", ""))
filtered_count = sum(1 for item in items if "Filtered" in item.get("status", ""))
failed_count = sum(1 for item in items if "Failed" in item.get("status", ""))
total = len(items)
with col_sum1:
st.metric("Total Items", total)
with col_sum2:
st.metric("✅ Learned", added_count, delta=f"{round(added_count/total*100, 1)}%" if total > 0 else "0%")
with col_sum3:
st.metric("⚠️ Filtered", filtered_count, delta=f"{round(filtered_count/total*100, 1)}%" if total > 0 else "0%")
with col_sum4:
st.metric("❌ Failed", failed_count, delta=f"{round(failed_count/total*100, 1)}%" if total > 0 else "0%")
# Filter reasons breakdown
filter_reasons = {}
for item in items:
if "Filtered" in item.get("status", ""):
reason = item.get("status_reason", "Unknown reason")
filter_reasons[reason] = filter_reasons.get(reason, 0) + 1
if filter_reasons:
st.markdown("### 🔍 Filter Reasons Breakdown")
for reason, count in sorted(filter_reasons.items(), key=lambda x: x[1], reverse=True):
st.write(f"- **{reason}**: {count} items")
else:
st.info("📭 No learning history available yet. Run a learning cycle to see statistics.")
except Exception as e:
import traceback
error_detail = str(e)
error_traceback = traceback.format_exc()
st.error(f"❌ Failed to load learning statistics: {error_detail}")
st.caption("💡 Make sure backend is running and RSS fetch history is enabled.")
# Show detailed error for debugging
with st.expander("🔍 Error Details (for debugging)", expanded=False):
st.code(error_traceback, language="text")
# Close button
if st.button("❌ Close Statistics", use_container_width=True):
st.session_state["show_learning_stats"] = False
st.rerun()
# Display learning cycle progress if job is running
if st.session_state.get("learning_job_started"):
job_id = st.session_state.get("learning_job_id")
st.markdown("---")
st.subheader("📊 Learning Cycle Progress")
# Skip polling if job_id is None or "timeout_fallback" (not a real job ID)
if not job_id or job_id == "timeout_fallback":
# Check scheduler status to see if cycle has completed
# Get current scheduler status to check if cycle finished
try:
current_scheduler_status = get_json("/api/learning/scheduler/status", {}, timeout=90)
except requests.exceptions.Timeout:
# Backend is busy - likely still processing
current_scheduler_status = {}
if current_scheduler_status and current_scheduler_status.get("status") == "ok":
is_running = current_scheduler_status.get("is_running", False)
last_run_time = current_scheduler_status.get("last_run_time")
cycle_count = current_scheduler_status.get("cycle_count", 0)
# Check if we have a stored cycle_count to compare
stored_cycle_count = st.session_state.get("learning_cycle_count_at_start", None)
# If stored_cycle_count is None, set it to current cycle_count (first check after timeout)
if stored_cycle_count is None:
st.session_state["learning_cycle_count_at_start"] = cycle_count
stored_cycle_count = cycle_count
# If scheduler is not running AND cycle_count increased, cycle completed
if not is_running and cycle_count > stored_cycle_count:
# Get current Vector DB stats to show what changed
try:
current_rag_stats = get_json("/api/rag/stats", {}, timeout=10)
current_stats = current_rag_stats.get("stats", {})
initial_stats = st.session_state.get("initial_rag_stats", {})
# Calculate changes
initial_total = initial_stats.get("total_documents", 0)
current_total = current_stats.get("total_documents", 0)
docs_added = current_total - initial_total
initial_knowledge = initial_stats.get("knowledge_documents", 0)
current_knowledge = current_stats.get("knowledge_documents", 0)
knowledge_added = current_knowledge - initial_knowledge
# Show detailed results
st.success("✅ Learning cycle completed!")
if docs_added > 0:
st.info(f"📊 **Results:** Added {docs_added} new documents to Vector DB ({knowledge_added} knowledge docs). Total: {current_total} documents.")
elif docs_added == 0 and current_total > 0:
st.info(f"📊 **Results:** No new documents added. Total: {current_total} documents (may have filtered out low-quality content).")
else:
st.info(f"📊 **Results:** Vector DB now has {current_total} documents.")
# Try to get more details from scheduler if available
if last_run_time:
st.caption(f"⏰ Completed at: {last_run_time}")
except Exception as stats_error:
st.success("✅ Learning cycle completed!")
st.info("💡 Check Vector DB Stats above and scheduler status below for details.")
# Clear job tracking
st.session_state["learning_job_started"] = False
st.session_state["learning_job_id"] = None
st.session_state["learning_cycle_count_at_start"] = None
st.session_state["initial_rag_stats"] = {}
elif not is_running and last_run_time:
# Scheduler stopped and has a last_run_time - cycle likely completed
# Check if Vector DB stats changed to confirm
try:
current_rag_stats = get_json("/api/rag/stats", {}, timeout=10)
current_stats = current_rag_stats.get("stats", {})
initial_stats = st.session_state.get("initial_rag_stats", {})
initial_total = initial_stats.get("total_documents", 0)
current_total = current_stats.get("total_documents", 0)
docs_added = current_total - initial_total
# If stats changed, cycle definitely completed
if docs_added > 0 or (current_total > 0 and initial_total == 0):
st.success("✅ Learning cycle completed!")
initial_knowledge = initial_stats.get("knowledge_documents", 0)
current_knowledge = current_stats.get("knowledge_documents", 0)
knowledge_added = current_knowledge - initial_knowledge
if docs_added > 0:
st.info(f"📊 **Results:** Added {docs_added} new documents to Vector DB ({knowledge_added} knowledge docs). Total: {current_total} documents.")
else:
st.info(f"📊 **Results:** Vector DB now has {current_total} documents.")
if st.button("✅ Dismiss", key="dismiss_cycle"):
st.session_state["learning_job_started"] = False
st.session_state["learning_job_id"] = None
st.session_state["learning_cycle_count_at_start"] = None
st.session_state["initial_rag_stats"] = {}
st.rerun()
else:
# Stats didn't change - may still be processing or no new content
st.info("⏳ Learning cycle may have completed. Scheduler is stopped.")
st.info("💡 **Tip:** Check Vector DB Stats above and scheduler status below. If cycle completed, you can dismiss this message.")
if st.button("✅ Dismiss (Cycle Completed)", key="dismiss_cycle"):
st.session_state["learning_job_started"] = False
st.session_state["learning_job_id"] = None
st.session_state["learning_cycle_count_at_start"] = None
st.session_state["initial_rag_stats"] = {}
st.rerun()
except:
# Fallback if can't get stats
st.info("⏳ Learning cycle may have completed. Scheduler is stopped.")
st.info("💡 **Tip:** Check scheduler status below. If cycle completed, you can dismiss this message.")
if st.button("✅ Dismiss (Cycle Completed)", key="dismiss_cycle_fallback"):
st.session_state["learning_job_started"] = False
st.session_state["learning_job_id"] = None
st.session_state["learning_cycle_count_at_start"] = None