-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
1745 lines (1509 loc) · 82.3 KB
/
Copy pathstreamlit_app.py
File metadata and controls
1745 lines (1509 loc) · 82.3 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
"""
Streamlit Interface for Insurance Claim Timeline Retrieval System
Workflow: Upload PDF → Preview Chunks → Index to ChromaDB → Query
"""
import streamlit as st
import os
import sys
import logging
import shutil
import time
from pathlib import Path
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables from .env file
# This ensures OPENAI_API_KEY and ANTHROPIC_API_KEY are available
load_dotenv()
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))
from src.indexing.document_loader import InsuranceClaimLoader
from src.indexing.chunking import HierarchicalChunker
# Page config
st.set_page_config(
page_title="Insurance Claim RAG System",
page_icon="📋",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
/* Reduce top padding from main content */
.block-container {
padding-top: 1rem !important;
}
/* Reduce top padding from sidebar */
[data-testid="stSidebar"] > div:first-child {
padding-top: 0.5rem !important;
}
.status-box {
padding: 8px 12px;
border-radius: 6px;
margin: 5px 0;
}
.status-no-db {
background-color: #ffebee;
border: 2px solid #f44336;
}
.status-has-db {
background-color: #e8f5e9;
border: 2px solid #4caf50;
}
.chunk-card {
border-radius: 8px;
padding: 12px;
margin: 8px 0;
}
.step-header {
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 10px 20px;
border-radius: 8px;
margin: 20px 0 10px 0;
}
/* Disable clear button and text editing in selectboxes */
[data-baseweb="select"] [data-testid="stSelectboxClearIcon"],
[data-baseweb="select"] svg[title="Clear"],
[data-baseweb="select"] [aria-label="Clear all"],
[data-baseweb="select"] .css-1dimb5e-indicatorContainer {
display: none !important;
pointer-events: none !important;
}
[data-baseweb="select"] input {
caret-color: transparent !important;
pointer-events: none !important;
user-select: none !important;
-webkit-user-select: none !important;
}
/* Make selectbox input non-editable */
div[data-baseweb="select"] input[aria-autocomplete="list"] {
pointer-events: none !important;
user-select: none !important;
}
/* Hide the clear button container */
[data-baseweb="select"] > div > div:last-child > div:first-child {
display: none !important;
}
</style>
""", unsafe_allow_html=True)
class StreamlitLogHandler(logging.Handler):
"""Custom log handler that captures logs for Streamlit display"""
def __init__(self):
super().__init__()
self.logs = []
def emit(self, record):
log_entry = self.format(record)
self.logs.append({
'time': datetime.now().strftime('%H:%M:%S'),
'level': record.levelname,
'message': log_entry
})
def get_logs(self):
return self.logs
def clear(self):
self.logs = []
# Initialize session state
if 'log_handler' not in st.session_state:
st.session_state.log_handler = StreamlitLogHandler()
st.session_state.log_handler.setFormatter(logging.Formatter('%(name)s - %(message)s'))
if 'chunks_preview' not in st.session_state:
st.session_state.chunks_preview = None
if 'documents' not in st.session_state:
st.session_state.documents = None
if 'system' not in st.session_state:
st.session_state.system = None
if 'uploaded_file_name' not in st.session_state:
st.session_state.uploaded_file_name = None
if 'query_history' not in st.session_state:
st.session_state.query_history = []
# Chunk size defaults
DEFAULT_CHUNK_SIZES = {
'large': 2048,
'medium': 512,
'small': 128
}
DEFAULT_OVERLAP_RATIO = 0.2
def setup_logging():
"""Setup logging to capture to our handler"""
# Only add handler to root logger to avoid duplicate logs from propagation
root_logger = logging.getLogger()
if st.session_state.log_handler not in root_logger.handlers:
root_logger.addHandler(st.session_state.log_handler)
root_logger.setLevel(logging.INFO)
# Set log levels for specific loggers without adding duplicate handlers
for logger_name in ['src.indexing', 'src.vector_store', 'src.agents', 'src.retrieval', 'src.mcp', 'httpx', 'main']:
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
def check_chroma_exists():
"""Check if ChromaDB exists and has data"""
import chromadb
from chromadb.config import Settings
chroma_dir = Path("./chroma_db")
abs_path = str(chroma_dir.absolute())
if not chroma_dir.exists():
return {
"exists": False,
"status": "No Vector Database Found",
"path": abs_path,
"message": "Upload a PDF to create the index",
"collections": []
}
try:
# Use chromadb directly with same settings as VectorStoreManager
client = chromadb.PersistentClient(
path=str(chroma_dir),
settings=Settings(
anonymized_telemetry=False,
allow_reset=True
)
)
# Check collections
try:
summary_col = client.get_collection("insurance_summaries")
summary_count = summary_col.count()
except:
summary_count = 0
try:
hier_col = client.get_collection("insurance_hierarchical")
hierarchical_count = hier_col.count()
except:
hierarchical_count = 0
# Get last modified time
import os
mtime = os.path.getmtime(chroma_dir)
last_modified = datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M')
if summary_count == 0 and hierarchical_count == 0:
return {
"exists": False,
"status": "Database Empty",
"path": abs_path,
"message": "No indexes found. Upload a PDF to create indexes.",
"collections": []
}
return {
"exists": True,
"status": "Connected",
"path": abs_path,
"last_modified": last_modified,
"collections": [
{"name": "Summary Index", "count": summary_count},
{"name": "Hierarchical Index", "count": hierarchical_count}
]
}
except Exception as e:
return {
"exists": False,
"status": f"Connection Error",
"path": abs_path,
"message": str(e),
"collections": []
}
def delete_chroma():
"""Delete ChromaDB directory completely"""
import chromadb
import gc
chroma_dir = Path("./chroma_db")
# Reset system state first
st.session_state.system = None
# Clear ChromaDB client cache
try:
chromadb.api.client.SharedSystemClient.clear_system_cache()
except:
pass
gc.collect()
if chroma_dir.exists():
try:
# Remove directory
shutil.rmtree(chroma_dir, ignore_errors=True)
# Double check it's gone, if not try again
if chroma_dir.exists():
time.sleep(0.5)
shutil.rmtree(chroma_dir, ignore_errors=True)
return True
except Exception as e:
st.error(f"Error deleting database: {e}")
return False
return False
def load_pdf(uploaded_file):
"""Load uploaded PDF and return documents"""
# Ensure data directory exists
data_dir = Path("./data")
data_dir.mkdir(exist_ok=True)
# Save uploaded file
file_path = data_dir / uploaded_file.name
with open(file_path, "wb") as f:
f.write(uploaded_file.getbuffer())
# Load with our loader
loader = InsuranceClaimLoader(data_dir=str(data_dir))
documents = loader.load_document(str(file_path))
return documents, file_path
def preview_chunks(documents, chunk_sizes, overlap_ratio):
"""Generate chunk preview without indexing"""
chunker = HierarchicalChunker(
chunk_sizes=chunk_sizes,
chunk_overlap_ratio=overlap_ratio
)
nodes = chunker.chunk_documents(documents)
chunks_info = []
for i, node in enumerate(nodes):
# Collect all metadata
metadata = dict(node.metadata)
# Parse page_numbers from string back to list for display
page_nums_str = node.metadata.get('page_numbers', '1')
pages = [int(p) for p in page_nums_str.split(',') if p] if page_nums_str else [1]
chunks_info.append({
'id': i + 1,
'node_id': node.id_,
'level': node.metadata.get('chunk_level', 'unknown'),
'pages': pages,
'start_page': node.metadata.get('start_page', 1),
'end_page': node.metadata.get('end_page', 1),
'size': node.metadata.get('chunk_size', 0),
'char_count': len(node.text),
'text': node.text,
'preview': node.text[:300] + '...' if len(node.text) > 300 else node.text,
'metadata': metadata
})
return chunks_info, nodes
def index_documents(documents, chunk_sizes, overlap_ratio):
"""Index documents into ChromaDB"""
from main import InsuranceClaimSystem
import gc
import chromadb
st.session_state.log_handler.clear()
setup_logging()
# Ensure clean state - clear all references
st.session_state.system = None
# Reset ChromaDB client cache
chromadb.api.client.SharedSystemClient.clear_system_cache()
gc.collect()
time.sleep(0.5)
# Force delete existing DB
chroma_dir = Path("./chroma_db")
if chroma_dir.exists():
shutil.rmtree(chroma_dir, ignore_errors=True)
time.sleep(0.5) # Wait for filesystem
if chroma_dir.exists():
shutil.rmtree(chroma_dir) # Try again without ignore_errors
# Create system (this will index)
system = InsuranceClaimSystem(
data_dir="./data",
chroma_dir="./chroma_db",
rebuild_indexes=True
)
st.session_state.system = system
return system
def run_query(query: str):
"""Run a query through the system"""
if not st.session_state.system:
return {"error": "System not initialized", "success": False}
st.session_state.log_handler.clear()
setup_logging()
start_time = time.time()
result = st.session_state.system.query(query)
elapsed = time.time() - start_time
result['elapsed_time'] = f"{elapsed:.2f}s"
result['logs'] = st.session_state.log_handler.get_logs()
st.session_state.query_history.append({
'query': query,
'result': result,
'timestamp': datetime.now().strftime('%H:%M:%S')
})
return result
# =============================================================================
# MAIN UI
# =============================================================================
st.title("Insurance Claim RAG System")
# Check database status
db_status = check_chroma_exists()
# =============================================================================
# SIDEBAR - Status & Controls
# =============================================================================
with st.sidebar:
# Header with status icon and tooltip showing path
status_icon = "🟢" if db_status['exists'] else "🔴"
tooltip_text = db_status.get('path', 'No database') if db_status['exists'] else 'No database found'
st.markdown(f'<h2 style="margin-bottom: 0.5rem; cursor: help;" title="{tooltip_text}">ChromaDB Status {status_icon}</h2>', unsafe_allow_html=True)
if db_status['exists']:
if 'last_modified' in db_status:
st.caption(f"🕐 Last updated: {db_status['last_modified']}")
st.divider()
st.markdown("""
<p style="font-weight: 600; font-size: 16px; margin-bottom: 5px;">Workflow</p>
<div style="line-height: 1.4; font-size: 14px;">
<span style="color: #888; text-decoration: line-through;">1. 📄 Upload PDF</span> ✓<br>
<span style="color: #888; text-decoration: line-through;">2. ⚙️ Configure Chunks</span> ✓<br>
<span style="color: #888; text-decoration: line-through;">3. 💾 Index to Database</span> ✓<br>
<strong>4. 🔍 Query the System</strong> ←
</div>
""", unsafe_allow_html=True)
st.divider()
st.subheader("Indexes")
for col in db_status['collections']:
st.markdown(f"**{col['name']}**: {col['count']} items")
st.divider()
if st.button("📄 Upload New Document", type="secondary", use_container_width=True):
delete_chroma()
st.session_state.chunks_preview = None
st.session_state.documents = None
st.session_state.uploaded_file_name = None
st.rerun()
if st.button("🗑️ Delete Database", type="secondary", use_container_width=True):
delete_chroma()
st.session_state.chunks_preview = None
st.session_state.documents = None
st.session_state.system = None
st.rerun()
else:
st.info("📄 Upload a PDF document to create the vector index.")
st.divider()
st.markdown("""
<p style="font-weight: 600; font-size: 16px; margin-bottom: 5px;">Workflow</p>
<div style="line-height: 1.4; font-size: 14px;">
1. 📄 Upload PDF<br>
2. ⚙️ Configure & Preview Chunks<br>
3. 💾 Index to Database<br>
4. 🔍 Query the System
</div>
""", unsafe_allow_html=True)
# =============================================================================
# MAIN CONTENT - Workflow Steps
# =============================================================================
if not db_status['exists']:
# ==========================================================================
# STEP 1: Upload PDF
# ==========================================================================
st.markdown('<div class="step-header"><h3 style="margin:0;">Step 1: Upload PDF Document</h3></div>', unsafe_allow_html=True)
uploaded_file = st.file_uploader(
"Choose a PDF file",
type=['pdf'],
help="Upload an insurance claim document to process"
)
if uploaded_file:
st.success(f"Uploaded: {uploaded_file.name}")
# Load the PDF (reload if file changed OR if documents are None due to session reset)
if st.session_state.uploaded_file_name != uploaded_file.name or st.session_state.documents is None:
with st.spinner("Loading PDF..."):
documents, file_path = load_pdf(uploaded_file)
st.session_state.documents = documents
st.session_state.uploaded_file_name = uploaded_file.name
st.session_state.chunks_preview = None # Reset preview
st.success(f"Loaded {len(documents)} document section(s)")
# ==========================================================================
# STEP 2: Configure Chunk Sizes & Preview
# ==========================================================================
st.markdown('<div class="step-header"><h3 style="margin:0;">Step 2: Configure Chunking & Preview</h3></div>', unsafe_allow_html=True)
st.caption("Adjust chunk sizes to control how the document is split for retrieval.")
col1, col2, col3, col4 = st.columns(4)
with col1:
large_size = st.number_input(
"Large Chunk (tokens)",
min_value=512,
max_value=4096,
value=DEFAULT_CHUNK_SIZES['large'],
step=256,
help="For broad context and summaries"
)
with col2:
medium_size = st.number_input(
"Medium Chunk (tokens)",
min_value=128,
max_value=1024,
value=DEFAULT_CHUNK_SIZES['medium'],
step=64,
help="Balanced context and precision"
)
with col3:
small_size = st.number_input(
"Small Chunk (tokens)",
min_value=64,
max_value=512,
value=DEFAULT_CHUNK_SIZES['small'],
step=32,
help="High precision for specific facts"
)
with col4:
overlap_ratio = st.slider(
"Overlap Ratio",
min_value=0.1,
max_value=0.4,
value=DEFAULT_OVERLAP_RATIO,
step=0.05,
help="Overlap between chunks (% of smallest)"
)
# Validate chunk sizes
chunk_sizes = sorted([large_size, medium_size, small_size], reverse=True)
if chunk_sizes != [large_size, medium_size, small_size]:
st.warning("Chunk sizes have been reordered: Large > Medium > Small")
# Preview button
if st.button("Preview Chunks", type="primary"):
if st.session_state.documents is None:
st.error("Documents not loaded. Please re-upload the PDF.")
else:
with st.spinner("Generating chunk preview..."):
chunks_info, nodes = preview_chunks(
st.session_state.documents,
chunk_sizes,
overlap_ratio
)
st.session_state.chunks_preview = chunks_info
st.session_state.chunk_sizes = chunk_sizes
st.session_state.overlap_ratio = overlap_ratio
# Display preview
if st.session_state.chunks_preview:
chunks = st.session_state.chunks_preview
st.divider()
st.subheader("Chunk Preview")
# Stats
col1, col2, col3, col4, col5 = st.columns(5)
large_count = len([c for c in chunks if c['level'] == 'large'])
medium_count = len([c for c in chunks if c['level'] == 'medium'])
small_count = len([c for c in chunks if c['level'] == 'small'])
col1.metric("Total Chunks", len(chunks))
col2.metric("Large", large_count, help=f"{chunk_sizes[0]} tokens")
col3.metric("Medium", medium_count, help=f"{chunk_sizes[1]} tokens")
col4.metric("Small", small_count, help=f"{chunk_sizes[2]} tokens")
all_pages = sorted(set(p for c in chunks for p in c['pages']))
col5.metric("Pages Covered", f"{min(all_pages)}-{max(all_pages)}")
# Filters
st.divider()
col1, col2, col3 = st.columns(3)
with col1:
level_filter = st.selectbox("Filter by Level", ["All", "large", "medium", "small"])
with col2:
page_filter = st.selectbox("Filter by Page", ["All"] + [str(p) for p in all_pages])
with col3:
search_text = st.text_input("Search text", "")
# Apply filters
filtered = chunks
if level_filter != "All":
filtered = [c for c in filtered if c['level'] == level_filter]
if page_filter != "All":
filtered = [c for c in filtered if int(page_filter) in c['pages']]
if search_text:
filtered = [c for c in filtered if search_text.lower() in c['text'].lower()]
st.caption(f"Showing {len(filtered)} of {len(chunks)} chunks")
# Display chunks
level_colors = {'large': '#e74c3c', 'medium': '#f39c12', 'small': '#27ae60'}
for chunk in filtered[:30]:
color = level_colors.get(chunk['level'], '#95a5a6')
pages_str = ', '.join(map(str, chunk['pages']))
with st.container():
st.markdown(f"""
<div style="border: 2px solid {color}; border-radius: 8px; padding: 12px; margin: 8px 0; background: #fafafa;">
<div style="display: flex; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; align-items: center;">
<span style="background: {color}; color: white; padding: 2px 12px; border-radius: 12px; font-weight: bold;">
{chunk['level'].upper()}
</span>
<span style="background: #3498db; color: white; padding: 2px 12px; border-radius: 12px;">
Pages: {pages_str}
</span>
<span style="background: #9b59b6; color: white; padding: 2px 12px; border-radius: 12px;">
~{chunk['size']} tokens
</span>
<span style="color: #666;">({chunk['char_count']} chars)</span>
<span style="color: #999; font-size: 11px;">ID: {chunk['node_id'][:12]}...</span>
</div>
<div style="font-family: monospace; font-size: 12px; color: #333; white-space: pre-wrap; max-height: 120px; overflow-y: auto; background: white; padding: 8px; border-radius: 4px;">
{chunk['preview']}
</div>
</div>
""", unsafe_allow_html=True)
# Metadata expander
with st.expander(f"📋 View Metadata", expanded=False):
metadata = chunk.get('metadata', {})
# Display metadata in a nice format
col1, col2 = st.columns(2)
meta_items = list(metadata.items())
half = len(meta_items) // 2 + 1
with col1:
for key, value in meta_items[:half]:
if isinstance(value, list):
value = ', '.join(map(str, value))
st.markdown(f"**{key}:** `{value}`")
with col2:
for key, value in meta_items[half:]:
if isinstance(value, list):
value = ', '.join(map(str, value))
st.markdown(f"**{key}:** `{value}`")
if len(filtered) > 30:
st.info(f"Showing first 30 of {len(filtered)} chunks")
# ==========================================================================
# STEP 3: Index to Database
# ==========================================================================
st.markdown('<div class="step-header"><h3 style="margin:0;">Step 3: Index to Vector Database</h3></div>', unsafe_allow_html=True)
st.caption("This will create embeddings and store chunks in ChromaDB. This process calls the OpenAI API.")
col1, col2 = st.columns([1, 3])
with col1:
if st.button("Index Document", type="primary", use_container_width=True):
progress = st.progress(0, text="Starting indexing...")
try:
progress.progress(10, text="Initializing system...")
system = index_documents(
st.session_state.documents,
st.session_state.chunk_sizes,
st.session_state.overlap_ratio
)
progress.progress(100, text="Complete!")
st.success("Document indexed successfully!")
time.sleep(1)
st.rerun()
except Exception as e:
st.error(f"Indexing failed: {str(e)}")
else:
# ==========================================================================
# DATABASE EXISTS - Show Query Interface with Tabs
# ==========================================================================
# Initialize system if needed
if not st.session_state.system:
with st.spinner("Loading system..."):
from main import InsuranceClaimSystem
setup_logging()
st.session_state.system = InsuranceClaimSystem(
data_dir="./data",
chroma_dir="./chroma_db",
rebuild_indexes=False
)
# Initialize active tab in session state
if 'active_main_tab' not in st.session_state:
st.session_state.active_main_tab = "🔍 Query"
# Create tab selector using radio buttons (maintains state across reruns)
tab_options = ["🔍 Query", "📚 Browse Vector DB", "📊 RAGAS Evaluation"]
selected_tab = st.radio(
"Navigation",
tab_options,
index=tab_options.index(st.session_state.active_main_tab),
horizontal=True,
label_visibility="collapsed",
key="main_tab_selector"
)
st.session_state.active_main_tab = selected_tab
st.divider()
# ==========================================================================
# TAB 1: Query Interface
# ==========================================================================
if selected_tab == "🔍 Query":
st.markdown('<div class="step-header"><h3 style="margin:0;">Query the Insurance Claim</h3></div>', unsafe_allow_html=True)
# Query input with form for Enter key submission
with st.form(key="query_form", clear_on_submit=False):
query = st.text_input(
"Enter your question:",
placeholder="e.g., What was the total repair cost? When did the accident occur?"
)
col1, col2, col3 = st.columns([1, 1, 4])
with col1:
query_btn = st.form_submit_button("Ask", type="primary", use_container_width=True)
# Example queries
with st.expander("Example Questions", expanded=True):
examples = [
"What is this insurance claim about?",
"What was the exact deductible amount?",
"When did the accident occur?",
"Summarize the timeline of events",
"Who was the claims adjuster?",
"What was the total repair cost?",
"What did the witnesses say?",
"How many days between the incident and claim filing?"
]
cols = st.columns(2)
for i, ex in enumerate(examples):
with cols[i % 2]:
if st.button(ex, key=f"ex_{i}", use_container_width=True):
# Store in session state and rerun
st.session_state.pending_query = ex
st.rerun()
# Check for pending query from example buttons
if 'pending_query' in st.session_state and st.session_state.pending_query:
query = st.session_state.pending_query
query_btn = True
st.session_state.pending_query = None
# Run query
if query_btn and query:
with st.spinner("Processing query..."):
result = run_query(query)
# Answer
st.subheader("Answer")
if result.get('success', False):
st.markdown(result.get('output', 'No output'))
st.caption(f"Response time: {result.get('elapsed_time', 'N/A')}")
else:
st.error(result.get('output', 'Error processing query'))
# Behind the scenes
with st.expander("Behind the Scenes (Execution Log)", expanded=True):
logs = result.get('logs', [])
if logs:
log_text = ""
for log in logs[-30:]:
color = '🟢' if log['level'] == 'INFO' else '🟡' if log['level'] == 'WARNING' else '🔴'
log_text += f"{color} [{log['time']}] {log['message']}\n"
st.code(log_text, language=None)
else:
st.info("No logs captured")
# Query History
if st.session_state.query_history:
st.divider()
st.subheader("Recent Queries")
for item in reversed(st.session_state.query_history[-5:]):
with st.expander(f"[{item['timestamp']}] {item['query'][:60]}..."):
st.markdown(f"**Q:** {item['query']}")
st.markdown(f"**A:** {item['result'].get('output', 'N/A')[:500]}...")
# ==========================================================================
# TAB 2: Browse Vector DB
# ==========================================================================
elif selected_tab == "📚 Browse Vector DB":
st.markdown('<div class="step-header"><h3 style="margin:0;">Browse Vector Database</h3></div>', unsafe_allow_html=True)
# Get ChromaDB data
import chromadb
from chromadb.config import Settings
chroma_dir = Path("./chroma_db")
try:
client = chromadb.PersistentClient(
path=str(chroma_dir),
settings=Settings(anonymized_telemetry=False, allow_reset=True)
)
# Collection selector
col1, col2 = st.columns([2, 1])
with col1:
collection_name = st.selectbox(
"Select Collection:",
["insurance_hierarchical", "insurance_summaries"]
)
with col2:
st.markdown("<br>", unsafe_allow_html=True) # Spacer to align with selectbox label
refresh_btn = st.button("🔄 Refresh", use_container_width=True)
try:
collection = client.get_collection(collection_name)
total_count = collection.count()
st.info(f"**{collection_name}**: {total_count} items")
# Filters
st.subheader("Filters")
col1, col2, col3 = st.columns(3)
with col1:
level_filter = st.selectbox(
"Chunk Level:",
["All", "large", "medium", "small"],
key="browse_level"
)
with col2:
page_filter = st.text_input("Page Number:", "", key="browse_page")
with col3:
search_text = st.text_input("Search Text:", "", key="browse_search")
# Build where filter
where_filter = None
if level_filter != "All":
where_filter = {"chunk_level": level_filter}
# Get items
limit = st.slider("Items to display:", 10, 100, 30)
if where_filter:
results = collection.get(
where=where_filter,
limit=limit,
include=["documents", "metadatas", "embeddings"]
)
else:
results = collection.get(
limit=limit,
include=["documents", "metadatas", "embeddings"]
)
# Filter by page if specified
if page_filter:
try:
page_num = int(page_filter)
filtered_indices = []
for i, meta in enumerate(results['metadatas']):
pages_str = meta.get('page_numbers', '1')
pages = [int(p) for p in pages_str.split(',') if p]
if page_num in pages:
filtered_indices.append(i)
results = {
'ids': [results['ids'][i] for i in filtered_indices],
'documents': [results['documents'][i] for i in filtered_indices],
'metadatas': [results['metadatas'][i] for i in filtered_indices],
'embeddings': [results['embeddings'][i] for i in filtered_indices] if results.get('embeddings') is not None else None
}
except ValueError:
pass
# Filter by search text
if search_text:
filtered_indices = []
for i, doc in enumerate(results['documents']):
if doc and search_text.lower() in doc.lower():
filtered_indices.append(i)
results = {
'ids': [results['ids'][i] for i in filtered_indices],
'documents': [results['documents'][i] for i in filtered_indices],
'metadatas': [results['metadatas'][i] for i in filtered_indices],
'embeddings': [results['embeddings'][i] for i in filtered_indices] if results.get('embeddings') else None
}
st.caption(f"Showing {len(results['ids'])} items")
# Build dataframe for table display
import pandas as pd
table_data = []
embeddings_list = results.get('embeddings') if results.get('embeddings') is not None else [None] * len(results['ids'])
for doc_id, doc, meta, emb in zip(results['ids'], results['documents'], results['metadatas'], embeddings_list):
row = {
'ID': doc_id[:15] + '...',
'Level': meta.get('chunk_level', 'N/A'),
'Pages': meta.get('page_numbers', '1'),
'Start Page': meta.get('start_page', 1),
'End Page': meta.get('end_page', 1),
'Tokens': meta.get('chunk_size', 0),
'Vector Dims': len(emb) if emb is not None else 0,
'Claim ID': meta.get('claim_id', 'N/A'),
'Section': meta.get('section_title', 'N/A')[:20],
'Content Preview': (doc[:150] + '...') if doc and len(doc) > 150 else (doc or 'No content'),
'Full Content': doc or 'No content',
'Full ID': doc_id
}
table_data.append(row)
df = pd.DataFrame(table_data)
# Display table
st.divider()
# Pagination controls
if 'browse_table_page' not in st.session_state:
st.session_state.browse_table_page = 0
page_size = 10
total_items = len(df)
total_pages = max(1, (total_items + page_size - 1) // page_size)
# Reset page if out of bounds
if st.session_state.browse_table_page >= total_pages:
st.session_state.browse_table_page = 0
# Pagination UI
col1, col2, col3, col4, col5 = st.columns([1, 1, 2, 1, 1])
with col1:
if st.button("⏮️ First", disabled=st.session_state.browse_table_page == 0, use_container_width=True):
st.session_state.browse_table_page = 0
st.rerun()
with col2:
if st.button("◀️ Prev", disabled=st.session_state.browse_table_page == 0, use_container_width=True):
st.session_state.browse_table_page -= 1
st.rerun()
with col3:
st.markdown(f"<div style='text-align: center; padding: 8px;'>Page {st.session_state.browse_table_page + 1} of {total_pages} ({total_items} items)</div>", unsafe_allow_html=True)
with col4:
if st.button("Next ▶️", disabled=st.session_state.browse_table_page >= total_pages - 1, use_container_width=True):
st.session_state.browse_table_page += 1
st.rerun()
with col5:
if st.button("Last ⏭️", disabled=st.session_state.browse_table_page >= total_pages - 1, use_container_width=True):
st.session_state.browse_table_page = total_pages - 1
st.rerun()
# Slice dataframe for current page
start_idx = st.session_state.browse_table_page * page_size
end_idx = min(start_idx + page_size, total_items)
df_page = df.iloc[start_idx:end_idx]
# Column configuration for better display with row selection
selection = st.dataframe(
df_page[['Level', 'Pages', 'Start Page', 'End Page', 'Tokens', 'Vector Dims', 'Claim ID', 'Content Preview']],
use_container_width=True,
hide_index=True,
column_config={
'Level': st.column_config.TextColumn('Level', width='small'),
'Pages': st.column_config.TextColumn('Pages', width='small'),
'Start Page': st.column_config.NumberColumn('Start', width='small'),
'End Page': st.column_config.NumberColumn('End', width='small'),
'Tokens': st.column_config.NumberColumn('Tokens', width='small'),
'Vector Dims': st.column_config.NumberColumn('Vector', width='small'),
'Claim ID': st.column_config.TextColumn('Claim', width='medium'),
'Content Preview': st.column_config.TextColumn('Content Preview', width='large'),
},
selection_mode="single-row",
on_select="rerun",
key="chunk_table_selection"
)
# Detail view for selected chunk (from current page)
st.divider()
st.subheader("Chunk Detail View")
# Get selected row from table click
selected_rows = selection.selection.rows if selection.selection else []
if selected_rows:
# Map back to full table index
selected_page_idx = selected_rows[0]
selected_idx = start_idx + selected_page_idx
selected = table_data[selected_idx]
meta = results['metadatas'][selected_idx]
embedding = results['embeddings'][selected_idx] if results.get('embeddings') is not None else None
col1, col2 = st.columns(2)
with col1:
st.markdown("**Metadata:**")
for key, value in meta.items():
# Skip _node_content as it's redundant with Full Content
if key == '_node_content':
continue
st.markdown(f"- **{key}:** `{value}`")
with col2:
st.markdown("**Full Content:**")
st.text_area("Content", value=selected['Full Content'], height=300, disabled=True)
# Display embedding vector
st.divider()
st.markdown("**Embedding Vector:**")
if embedding is not None:
import numpy as np
embedding_array = np.array(embedding)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Dimensions", len(embedding))
with col2:
st.metric("Min Value", f"{embedding_array.min():.6f}")