GodRad commited on
Commit
075d616
Β·
verified Β·
1 Parent(s): afcc7b5

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +581 -0
app.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAG SaaS Platform - Streamlit UI (Optimized for HF Spaces)
3
+ Fast startup with lazy imports
4
+ """
5
+ import streamlit as st
6
+
7
+ # Lazy imports - only import when needed
8
+ def lazy_import_requests():
9
+ import requests
10
+ return requests
11
+
12
+ def lazy_import_pandas():
13
+ import pandas as pd
14
+ return pd
15
+
16
+ def lazy_import_time():
17
+ import time
18
+ return time
19
+
20
+ # Page Configuration - MUST be first Streamlit command
21
+ st.set_page_config(
22
+ page_title="RAG SaaS Platform",
23
+ page_icon="πŸ”",
24
+ layout="wide",
25
+ initial_sidebar_state="expanded",
26
+ )
27
+
28
+ # Minimal CSS - reduced for faster loading
29
+ st.markdown("""
30
+ <style>
31
+ .stButton>button {
32
+ width: 100%; border-radius: 5px; height: 3em;
33
+ background-color: #1f6feb; color: white; font-weight: bold;
34
+ }
35
+ .source-badge {
36
+ display: inline-block; padding: 5px 10px; border-radius: 5px;
37
+ margin: 2px; font-size: 12px; font-weight: bold;
38
+ }
39
+ .source-file {background-color: #1f6feb; color: white;}
40
+ .source-web {background-color: #238636; color: white;}
41
+ .source-youtube {background-color: #da3633; color: white;}
42
+ </style>
43
+ """, unsafe_allow_html=True)
44
+
45
+ # Initialize session state
46
+ if 'tenant_id' not in st.session_state:
47
+ st.session_state.tenant_id = None
48
+ if 'access_token' not in st.session_state:
49
+ st.session_state.access_token = None
50
+ if 'api_url' not in st.session_state:
51
+ st.session_state.api_url = "http://localhost:7860"
52
+
53
+ # Sidebar Configuration
54
+ with st.sidebar:
55
+ st.title("βš™οΈ Configuration")
56
+
57
+ # API URL
58
+ api_url = st.text_input(
59
+ "Backend API URL",
60
+ value=st.session_state.api_url,
61
+ help="URL of the RAG SaaS backend"
62
+ )
63
+ st.session_state.api_url = api_url
64
+
65
+ st.divider()
66
+
67
+ # Authentication Section
68
+ st.subheader("πŸ” Authentication")
69
+
70
+ if not st.session_state.tenant_id:
71
+ # Login/Register tabs
72
+ tab1, tab2 = st.tabs(["Login", "Register"])
73
+
74
+ with tab1:
75
+ st.caption("Login with Tenant ID")
76
+ login_tenant_id = st.text_input("Tenant ID", key="login_tenant_id")
77
+ login_username = st.text_input("Username/Email", key="login_username")
78
+ login_password = st.text_input("Password", type="password", key="login_password")
79
+
80
+ if st.button("Login", key="login_btn"):
81
+ requests = lazy_import_requests()
82
+ try:
83
+ response = requests.post(
84
+ f"{api_url}/v1/auth/login",
85
+ json={
86
+ "tenant_id": login_tenant_id,
87
+ "username": login_username,
88
+ "password": login_password
89
+ }
90
+ )
91
+ if response.status_code == 200:
92
+ data = response.json()
93
+ st.session_state.tenant_id = data['tenant_id']
94
+ st.session_state.access_token = data['access_token']
95
+ st.success(f"βœ… Logged in as {data['tenant_name']}")
96
+ st.rerun()
97
+ else:
98
+ st.error(f"Login failed: {response.json().get('detail', 'Unknown error')}")
99
+ except Exception as e:
100
+ st.error(f"Connection error: {e}")
101
+
102
+ with tab2:
103
+ st.caption("Create New Tenant Account")
104
+ reg_name = st.text_input("Organization Name", key="reg_name")
105
+ reg_email = st.text_input("Admin Email", key="reg_email")
106
+ reg_password = st.text_input("Admin Password", type="password", key="reg_password")
107
+
108
+ if st.button("Create Tenant", key="register_btn"):
109
+ requests = lazy_import_requests()
110
+ try:
111
+ response = requests.post(
112
+ f"{api_url}/v1/auth/tenants",
113
+ json={
114
+ "name": reg_name,
115
+ "admin_email": reg_email,
116
+ "admin_password": reg_password
117
+ }
118
+ )
119
+ if response.status_code == 200:
120
+ data = response.json()
121
+ st.success(f"βœ… Tenant created!")
122
+ st.info(f"**Your Tenant ID:** `{data['tenant_id']}`\n\n⚠️ Save this ID - you'll need it to login!")
123
+ else:
124
+ st.error(f"Registration failed: {response.json().get('detail', 'Unknown error')}")
125
+ except Exception as e:
126
+ st.error(f"Connection error: {e}")
127
+ else:
128
+ # Logged in state
129
+ st.success(f"βœ… Logged in")
130
+ st.caption(f"Tenant ID: `{st.session_state.tenant_id}`")
131
+
132
+ if st.button("Logout"):
133
+ st.session_state.tenant_id = None
134
+ st.session_state.access_token = None
135
+ st.rerun()
136
+
137
+ # Main Content
138
+ if not st.session_state.tenant_id:
139
+ st.title("πŸ” RAG SaaS Platform")
140
+ st.info("πŸ‘ˆ Please login or create a tenant account to continue")
141
+
142
+ # Show platform features
143
+ st.subheader("Platform Features")
144
+ col1, col2, col3 = st.columns(3)
145
+
146
+ with col1:
147
+ st.markdown("### πŸ“„ Multi-Source Retrieval")
148
+ st.write("Unified search across documents, URLs, and YouTube videos")
149
+
150
+ with col2:
151
+ st.markdown("### πŸ“Š Tenant Metrics")
152
+ st.write("Isolated metrics tracking for each tenant")
153
+
154
+ with col3:
155
+ st.markdown("### ⚑ Optimized Performance")
156
+ st.write("Model caching with 70-90% latency reduction")
157
+
158
+ else:
159
+ # Logged in - show main interface
160
+ st.title(f"πŸ” RAG SaaS Platform")
161
+
162
+ # Main tabs
163
+ tab1, tab2, tab3, tab4 = st.tabs(["πŸ’¬ Ask Questions", "πŸ“ Manage Sources", "πŸ“Š Metrics", "ℹ️ About"])
164
+
165
+ # Tab 1: Ask Questions
166
+ with tab1:
167
+ st.header("Ask Questions")
168
+
169
+ # Show active sources
170
+ try:
171
+ response = requests.get(
172
+ f"{api_url}/v1/sources/active",
173
+ headers={"X-Tenant-ID": st.session_state.tenant_id}
174
+ )
175
+ if response.status_code == 200:
176
+ data = response.json()
177
+ active_sources = data.get('active_sources', [])
178
+ source_types = data.get('source_types_present', [])
179
+
180
+ if source_types:
181
+ st.success(f"βœ… Active sources: {', '.join(source_types)}")
182
+
183
+ # Show source badges
184
+ badges_html = ""
185
+ for source_type in source_types:
186
+ badge_class = f"source-{source_type}"
187
+ badges_html += f'<span class="source-badge {badge_class}">{source_type.upper()}</span>'
188
+ st.markdown(badges_html, unsafe_allow_html=True)
189
+ else:
190
+ st.warning("⚠️ No active sources. Add sources in the 'Manage Sources' tab.")
191
+ except Exception as e:
192
+ st.error(f"Error fetching sources: {e}")
193
+
194
+ st.divider()
195
+
196
+ # Question input
197
+ question = st.text_area("Your Question", placeholder="What would you like to know?", height=100)
198
+
199
+ col1, col2 = st.columns([3, 1])
200
+ with col1:
201
+ top_k = st.slider("Number of results", 5, 20, 10)
202
+ with col2:
203
+ ask_btn = st.button("πŸ” Ask", use_container_width=True, type="primary")
204
+
205
+ if ask_btn and question:
206
+ with st.spinner("πŸ” Searching across all sources..."):
207
+ try:
208
+ # Measure total request time
209
+ request_start_time = time.time()
210
+
211
+ response = requests.post(
212
+ f"{api_url}/v1/ask/",
213
+ headers={"X-Tenant-ID": st.session_state.tenant_id},
214
+ json={"query": question, "top_k": top_k}
215
+ )
216
+
217
+ # Calculate total elapsed time
218
+ total_elapsed_ms = (time.time() - request_start_time) * 1000
219
+
220
+ if response.status_code == 200:
221
+ data = response.json()
222
+
223
+ # Display answer
224
+ st.markdown("### πŸ’‘ Answer")
225
+ st.markdown(f"**{data['answer']}**")
226
+
227
+ st.divider()
228
+
229
+ # ===== ENHANCED LATENCY METRICS DISPLAY =====
230
+ st.markdown("### ⚑ Performance Metrics")
231
+
232
+ # Get latency values from backend
233
+ retrieval_time = data.get('retrieval_time_ms', 0)
234
+ generation_time = data.get('generation_time_ms', 0)
235
+ backend_total = retrieval_time + generation_time
236
+ network_overhead = total_elapsed_ms - backend_total
237
+
238
+ # Create 5 columns for detailed metrics
239
+ col1, col2, col3, col4, col5 = st.columns(5)
240
+
241
+ with col1:
242
+ st.metric(
243
+ "πŸ” Retrieval",
244
+ f"{retrieval_time:.0f}ms",
245
+ help="Time to search across all sources"
246
+ )
247
+
248
+ with col2:
249
+ st.metric(
250
+ "πŸ€– Generation",
251
+ f"{generation_time:.0f}ms",
252
+ help="Time to generate the answer"
253
+ )
254
+
255
+ with col3:
256
+ st.metric(
257
+ "βš™οΈ Backend Total",
258
+ f"{backend_total:.0f}ms",
259
+ help="Total backend processing time"
260
+ )
261
+
262
+ with col4:
263
+ st.metric(
264
+ "🌐 Network",
265
+ f"{network_overhead:.0f}ms",
266
+ help="Network latency (request + response)"
267
+ )
268
+
269
+ with col5:
270
+ # Color-code total time
271
+ total_color = "🟒" if total_elapsed_ms < 500 else "🟑" if total_elapsed_ms < 1000 else "πŸ”΄"
272
+ st.metric(
273
+ f"{total_color} Total Time",
274
+ f"{total_elapsed_ms:.0f}ms",
275
+ help="End-to-end response time"
276
+ )
277
+
278
+ # Visual latency breakdown
279
+ st.markdown("#### Latency Breakdown")
280
+ latency_data = {
281
+ "Retrieval": retrieval_time,
282
+ "Generation": generation_time,
283
+ "Network": max(0, network_overhead)
284
+ }
285
+
286
+ # Create a simple bar chart representation
287
+ total_for_percentage = sum(latency_data.values())
288
+ if total_for_percentage > 0:
289
+ breakdown_html = '<div style="display: flex; width: 100%; height: 30px; border-radius: 5px; overflow: hidden;">'
290
+
291
+ colors = {
292
+ "Retrieval": "#1f6feb",
293
+ "Generation": "#238636",
294
+ "Network": "#da3633"
295
+ }
296
+
297
+ for component, time_ms in latency_data.items():
298
+ percentage = (time_ms / total_for_percentage) * 100
299
+ color = colors.get(component, "#666")
300
+ breakdown_html += f'<div style="background-color: {color}; width: {percentage}%; display: flex; align-items: center; justify-content: center; color: white; font-size: 11px; font-weight: bold;" title="{component}: {time_ms:.0f}ms ({percentage:.1f}%)">{component[:3]}</div>'
301
+
302
+ breakdown_html += '</div>'
303
+ st.markdown(breakdown_html, unsafe_allow_html=True)
304
+
305
+ # Show percentage breakdown
306
+ breakdown_text = " | ".join([
307
+ f"{comp}: {(time_ms/total_for_percentage)*100:.1f}% ({time_ms:.0f}ms)"
308
+ for comp, time_ms in latency_data.items()
309
+ ])
310
+ st.caption(breakdown_text)
311
+
312
+ st.divider()
313
+
314
+ # Display confidence
315
+ confidence = data.get('confidence', 0)
316
+ confidence_color = "🟒" if confidence > 0.7 else "🟑" if confidence > 0.4 else "πŸ”΄"
317
+ st.metric(
318
+ f"{confidence_color} Answer Confidence",
319
+ f"{confidence:.1%}",
320
+ help="Model's confidence in the answer quality"
321
+ )
322
+
323
+ # Display sources used
324
+ if 'sources_used' in data and data['sources_used']:
325
+ st.markdown("### πŸ“š Sources Used")
326
+ sources_html = ""
327
+ for source_type in data['sources_used']:
328
+ badge_class = f"source-{source_type}"
329
+ sources_html += f'<span class="source-badge {badge_class}">{source_type.upper()}</span>'
330
+ st.markdown(sources_html, unsafe_allow_html=True)
331
+ st.caption(f"Retrieved from {len(data['sources_used'])} different source type(s)")
332
+
333
+ # Display citations
334
+ if data.get('citations'):
335
+ st.markdown("### πŸ“– Citations")
336
+ for i, citation in enumerate(data['citations'], 1):
337
+ with st.expander(f"Citation {i} - {citation.get('source_type', 'unknown').upper()}"):
338
+ st.json(citation)
339
+ else:
340
+ st.error(f"❌ Error: {response.json().get('detail', 'Unknown error')}")
341
+ except Exception as e:
342
+ st.error(f"❌ Request failed: {e}")
343
+ st.exception(e)
344
+
345
+
346
+ # Tab 2: Manage Sources
347
+ with tab2:
348
+ st.header("Manage Sources")
349
+
350
+ # Sub-tabs for different source types
351
+ source_tab1, source_tab2, source_tab3, source_tab4 = st.tabs(
352
+ ["πŸ“„ Documents", "🌐 URLs", "πŸŽ₯ YouTube", "πŸ“‹ All Sources"]
353
+ )
354
+
355
+ with source_tab1:
356
+ st.subheader("Upload Documents")
357
+ st.info("Upload PDF, DOCX, or TXT files")
358
+ uploaded_file = st.file_uploader("Choose a file", type=['pdf', 'docx', 'txt'])
359
+
360
+ if uploaded_file and st.button("Upload & Ingest"):
361
+ with st.spinner("Uploading and ingesting..."):
362
+ try:
363
+ files = {"file": uploaded_file}
364
+ response = requests.post(
365
+ f"{api_url}/v1/ingest/upload",
366
+ headers={"X-Tenant-ID": st.session_state.tenant_id},
367
+ files=files
368
+ )
369
+ if response.status_code == 200:
370
+ st.success("βœ… Document uploaded and ingested successfully!")
371
+ else:
372
+ st.error(f"Upload failed: {response.json().get('detail', 'Unknown error')}")
373
+ except Exception as e:
374
+ st.error(f"Upload error: {e}")
375
+
376
+ with source_tab2:
377
+ st.subheader("Add Web URLs")
378
+ url = st.text_input("Enter URL", placeholder="https://example.com/article")
379
+ url_name = st.text_input("Source Name (optional)", placeholder="Company Blog")
380
+
381
+ if st.button("Add URL") and url:
382
+ with st.spinner("Adding URL..."):
383
+ try:
384
+ response = requests.post(
385
+ f"{api_url}/v1/ingest/url",
386
+ headers={"X-Tenant-ID": st.session_state.tenant_id},
387
+ json={"url": url, "name": url_name or url}
388
+ )
389
+ if response.status_code == 200:
390
+ st.success("βœ… URL added and ingestion started!")
391
+ else:
392
+ st.error(f"Failed: {response.json().get('detail', 'Unknown error')}")
393
+ except Exception as e:
394
+ st.error(f"Error: {e}")
395
+
396
+ with source_tab3:
397
+ st.subheader("Add YouTube Videos")
398
+ st.info("βœ… Captions-first strategy with transcript upload fallback")
399
+
400
+ youtube_url = st.text_input("YouTube URL", placeholder="https://youtube.com/watch?v=...")
401
+ video_name = st.text_input("Video Name (optional)")
402
+
403
+ transcript_file = st.file_uploader(
404
+ "Upload Transcript (optional)",
405
+ type=['vtt', 'srt', 'txt'],
406
+ help="If video has no captions, upload a transcript file"
407
+ )
408
+
409
+ owner_attestation = st.checkbox(
410
+ "I attest that I have rights to use this content",
411
+ help="Required: Confirm you own or have permission to use this video"
412
+ )
413
+
414
+ if st.button("Add YouTube Video") and youtube_url and owner_attestation:
415
+ with st.spinner("Adding YouTube video..."):
416
+ try:
417
+ files = {}
418
+ if transcript_file:
419
+ files['transcript_file'] = transcript_file
420
+
421
+ data = {
422
+ 'youtube_url': youtube_url,
423
+ 'name': video_name or youtube_url,
424
+ 'owner_attestation': str(owner_attestation).lower()
425
+ }
426
+
427
+ response = requests.post(
428
+ f"{api_url}/v1/sources/youtube",
429
+ headers={"X-Tenant-ID": st.session_state.tenant_id},
430
+ data=data,
431
+ files=files if files else None
432
+ )
433
+
434
+ if response.status_code == 200:
435
+ result = response.json()
436
+ st.success(f"βœ… YouTube source added! Strategy: {result.get('strategy', 'captions_api')}")
437
+ else:
438
+ st.error(f"Failed: {response.json().get('detail', 'Unknown error')}")
439
+ except Exception as e:
440
+ st.error(f"Error: {e}")
441
+
442
+ with source_tab4:
443
+ st.subheader("All Sources")
444
+
445
+ try:
446
+ response = requests.get(
447
+ f"{api_url}/v1/sources/",
448
+ headers={"X-Tenant-ID": st.session_state.tenant_id}
449
+ )
450
+
451
+ if response.status_code == 200:
452
+ sources = response.json()
453
+
454
+ if sources:
455
+ for source in sources:
456
+ with st.expander(f"{source['name']} ({source['type']})"):
457
+ st.write(f"**ID:** {source['id']}")
458
+ st.write(f"**Type:** {source['type']}")
459
+ st.write(f"**URI:** {source['uri']}")
460
+ st.write(f"**Created:** {source.get('created_at', 'N/A')}")
461
+
462
+ # Toggle source
463
+ col1, col2 = st.columns(2)
464
+ with col1:
465
+ if st.button(f"Disable", key=f"disable_{source['id']}"):
466
+ requests.put(
467
+ f"{api_url}/v1/sources/{source['id']}/toggle?enabled=false",
468
+ headers={"X-Tenant-ID": st.session_state.tenant_id}
469
+ )
470
+ st.rerun()
471
+ with col2:
472
+ if st.button(f"Enable", key=f"enable_{source['id']}"):
473
+ requests.put(
474
+ f"{api_url}/v1/sources/{source['id']}/toggle?enabled=true",
475
+ headers={"X-Tenant-ID": st.session_state.tenant_id}
476
+ )
477
+ st.rerun()
478
+ else:
479
+ st.info("No sources yet. Add sources using the tabs above.")
480
+ except Exception as e:
481
+ st.error(f"Error loading sources: {e}")
482
+
483
+ # Tab 3: Metrics
484
+ with tab3:
485
+ st.header("πŸ“Š Your Metrics")
486
+
487
+ # Time range selector
488
+ hours = st.selectbox("Time Range", [1, 6, 12, 24, 48, 168], index=3, format_func=lambda x: f"Last {x} hours")
489
+
490
+ if st.button("Refresh Metrics"):
491
+ try:
492
+ response = requests.get(
493
+ f"{api_url}/v1/tenants/{st.session_state.tenant_id}/metrics?hours={hours}",
494
+ headers={"X-Tenant-ID": st.session_state.tenant_id}
495
+ )
496
+
497
+ if response.status_code == 200:
498
+ metrics = response.json()
499
+ counters = metrics.get('counters', {})
500
+
501
+ # Display key metrics
502
+ col1, col2, col3, col4 = st.columns(4)
503
+
504
+ with col1:
505
+ st.metric("Total Retrievals", counters.get('retrieval_total', 0))
506
+ with col2:
507
+ st.metric("Total Generations", counters.get('generation_total', 0))
508
+ with col3:
509
+ st.metric("Sources Created", counters.get('sources_created', 0))
510
+ with col4:
511
+ st.metric("Ingestions", counters.get('ingestion_total', 0))
512
+
513
+ st.divider()
514
+
515
+ # Show all counters
516
+ st.subheader("All Metrics")
517
+ if counters:
518
+ df = pd.DataFrame(list(counters.items()), columns=['Metric', 'Value'])
519
+ st.dataframe(df, use_container_width=True)
520
+ else:
521
+ st.info("No metrics data yet. Start using the platform to see metrics!")
522
+
523
+ # Time series data
524
+ if metrics.get('time_series'):
525
+ st.subheader("Time Series Data")
526
+ for metric_name, data_points in metrics['time_series'].items():
527
+ if data_points:
528
+ st.write(f"**{metric_name}**")
529
+ df = pd.DataFrame(data_points)
530
+ st.line_chart(df.set_index('timestamp')['value'])
531
+ else:
532
+ st.error(f"Failed to load metrics: {response.json().get('detail', 'Unknown error')}")
533
+ except Exception as e:
534
+ st.error(f"Error: {e}")
535
+
536
+ st.divider()
537
+
538
+ # Cache statistics
539
+ st.subheader("πŸš€ Performance Metrics")
540
+ try:
541
+ response = requests.get(f"{api_url}/v1/metrics/cache-stats")
542
+ if response.status_code == 200:
543
+ cache_stats = response.json()
544
+
545
+ col1, col2, col3 = st.columns(3)
546
+ with col1:
547
+ st.metric("Cache Hit Rate", f"{cache_stats.get('hit_rate', 0):.1%}")
548
+ with col2:
549
+ st.metric("Cache Size", f"{cache_stats.get('cache_size', 0)}/{cache_stats.get('cache_max_size', 0)}")
550
+ with col3:
551
+ st.metric("Model Load Time", f"{cache_stats.get('model_load_time_seconds', 0):.1f}s")
552
+ except Exception as e:
553
+ st.warning(f"Cache stats unavailable: {e}")
554
+
555
+ # Tab 4: About
556
+ with tab4:
557
+ st.header("ℹ️ About RAG SaaS Platform")
558
+
559
+ st.markdown("""
560
+ ### Features
561
+
562
+ βœ… **Multi-Source Retrieval** - Unified search across documents, URLs, and YouTube videos
563
+ βœ… **Tenant Isolation** - Complete data and metrics separation per tenant
564
+ βœ… **Optimized Performance** - Model caching with 70-90% latency reduction
565
+ βœ… **Compliant YouTube** - Captions-first with transcript upload fallback
566
+ βœ… **Comprehensive Metrics** - Track all your usage and performance
567
+
568
+ ### How It Works
569
+
570
+ 1. **Add Sources** - Upload documents, add URLs, or YouTube videos
571
+ 2. **Ask Questions** - The system retrieves from ALL your sources
572
+ 3. **Get Answers** - Receive answers with citations from multiple sources
573
+ 4. **Track Metrics** - Monitor your usage and performance
574
+
575
+ ### Technical Details
576
+
577
+ - **Backend:** FastAPI with SQLite/PostgreSQL
578
+ - **Vector Store:** Local (upgradeable to Qdrant/Pgvector)
579
+ - **Models:** Local CPU-optimized (Qwen 0.5B + MiniLM)
580
+ - **Retrieval:** RRF fusion with diversity constraints
581
+ """)