-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_today.patch
More file actions
1125 lines (1086 loc) · 51.3 KB
/
Copy pathdiff_today.patch
File metadata and controls
1125 lines (1086 loc) · 51.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
diff --git a/app.py b/app.py
index 948d34f..5f1189c 100644
--- a/app.py
+++ b/app.py
@@ -1,14 +1,15 @@
"""
-RAG Chatbot — Streamlit Application
+DocuMind — Streamlit Application
=====================================
Upload PDFs → ask questions → get citation-backed answers powered by
-local HuggingFace embeddings and Google Gemini.
+local HuggingFace embeddings, Groq LLM, and Gemini Vision OCR.
"""
import os
import re
import uuid
import shutil
+import base64
import streamlit as st
from dotenv import load_dotenv
@@ -29,16 +30,467 @@ GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
EMBEDDING_MODEL = "all-MiniLM-L6-v2"
VECTORS_BASE = os.path.join("data", "session_vectors")
+# ── Custom chat avatars (inline SVG data URIs) ────────────────────────
+_ASST_SVG = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
+ <defs>
+ <linearGradient id="ag" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0" stop-color="#18c99a"/>
+ <stop offset="1" stop-color="#0a7a5e"/>
+ </linearGradient>
+ </defs>
+ <circle cx="20" cy="20" r="20" fill="url(#ag)"/>
+ <path d="M20 9 L22.8 17.2 L31 20 L22.8 22.8 L20 31 L17.2 22.8 L9 20 L17.2 17.2 Z"
+ fill="white" opacity="0.92"/>
+</svg>"""
+
+_USER_SVG = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
+ <circle cx="20" cy="20" r="20" fill="#2a2d36"/>
+ <circle cx="20" cy="15" r="7" fill="#6b7a8d"/>
+ <path d="M6 36 Q6 27 20 27 Q34 27 34 36" fill="#6b7a8d"/>
+</svg>"""
+
+ASST_AVATAR = "data:image/svg+xml;base64," + base64.b64encode(_ASST_SVG.encode()).decode()
+USER_AVATAR = "data:image/svg+xml;base64," + base64.b64encode(_USER_SVG.encode()).decode()
+
# ── Page configuration ───────────────────────────────────────────────
st.set_page_config(
- page_title="RAG Chatbot — AI Document Assistant",
+ page_title="DocuMind — AI Document Assistant",
page_icon="🤖",
- layout="centered",
+ layout="wide",
+ initial_sidebar_state="expanded",
)
+# ── Global CSS — GPT-style dark minimal UI ───────────────────────────
+st.markdown("""
+<style>
+@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
+
+/* ── Base — cover every Streamlit structural element ─────────────── */
+html, body, .stApp,
+[data-testid="stAppViewContainer"],
+[data-testid="stHeader"],
+[data-testid="stToolbar"],
+[data-testid="stBottom"],
+[data-testid="stStatusWidget"],
+.stAppHeader,
+.stAppDeployButton,
+header {
+ background-color: #212121 !important;
+ font-family: 'Inter', -apple-system, sans-serif !important;
+}
+
+/* ── Streamlit top header toolbar ────────────────────────────────── */
+[data-testid="stHeader"] {
+ background: #212121 !important;
+ border-bottom: 1px solid rgba(255,255,255,0.06) !important;
+}
+/* Make the Deploy button text readable */
+[data-testid="stHeader"] button,
+[data-testid="stHeader"] [data-testid="stToolbarActions"] button {
+ color: #b0b0b0 !important;
+ background: transparent !important;
+ border-color: rgba(255,255,255,0.12) !important;
+}
+
+/* ── Bottom chat input container strip ───────────────────────────── */
+[data-testid="stBottom"],
+[data-testid="stBottom"] > div {
+ background: #212121 !important;
+ border-top: 1px solid rgba(255,255,255,0.06) !important;
+}
+
+/* ── Sidebar shell ───────────────────────────────────────────────── */
+[data-testid="stSidebar"] {
+ background-color: #171717 !important;
+ border-right: 1px solid rgba(255,255,255,0.06) !important;
+}
+[data-testid="stSidebar"] > div:first-child {
+ padding: 14px 10px 80px !important;
+}
+
+/* All sidebar text white ────────────────────────────────────────── */
+[data-testid="stSidebar"] p,
+[data-testid="stSidebar"] span,
+[data-testid="stSidebar"] label,
+[data-testid="stSidebar"] small,
+[data-testid="stSidebar"] div {
+ color: #d1d1d1 !important;
+}
+
+/* Sidebar section headings */
+[data-testid="stSidebar"] h2,
+[data-testid="stSidebar"] h3 {
+ color: #555 !important;
+ font-size: 0.68rem !important;
+ font-weight: 700 !important;
+ letter-spacing: 1.2px !important;
+ text-transform: uppercase !important;
+ margin: 18px 0 8px 2px !important;
+}
+
+/* ── New Chat button ─────────────────────────────────────────────── */
+[data-testid="stSidebar"] .stButton:first-of-type button {
+ background: #10a37f !important;
+ color: #fff !important;
+ border: none !important;
+ border-radius: 8px !important;
+ font-weight: 600 !important;
+ font-size: 0.87rem !important;
+ padding: 9px 0 !important;
+ transition: background 0.15s, transform 0.15s !important;
+ box-shadow: 0 2px 10px rgba(16,163,127,0.25) !important;
+}
+[data-testid="stSidebar"] .stButton:first-of-type button:hover {
+ background: #0d8f6e !important;
+ transform: translateY(-1px) !important;
+}
+
+/* ── All other sidebar buttons: secondary = dark bg + green glow border */
+[data-testid="stSidebar"] .stButton button,
+[data-testid="stSidebar"] .stButton button[kind="secondary"] {
+ background: rgba(16,163,127,0.04) !important;
+ background-color: rgba(16,163,127,0.04) !important;
+ border: 1px solid rgba(16,163,127,0.35) !important;
+ border-radius: 8px !important;
+ color: #c0c0c0 !important;
+ font-size: 0.79rem !important;
+ text-align: left !important;
+ padding: 7px 10px !important;
+ line-height: 1.45 !important;
+ white-space: pre-wrap !important;
+ transition: all 0.2s ease !important;
+ box-shadow: 0 0 6px rgba(16,163,127,0.18), inset 0 0 0 1px rgba(16,163,127,0.08) !important;
+}
+[data-testid="stSidebar"] .stButton button:hover,
+[data-testid="stSidebar"] .stButton button[kind="secondary"]:hover {
+ background: rgba(16,163,127,0.09) !important;
+ background-color: rgba(16,163,127,0.09) !important;
+ border-color: rgba(16,163,127,0.60) !important;
+ color: #e0e0e0 !important;
+ box-shadow: 0 0 10px rgba(16,163,127,0.30), inset 0 0 0 1px rgba(16,163,127,0.15) !important;
+}
+/* Active / currently selected session — solid green fill */
+[data-testid="stSidebar"] .stButton button[kind="primary"] {
+ background: #10a37f !important;
+ background-color: #10a37f !important;
+ border: 1px solid #10a37f !important;
+ color: #ffffff !important;
+ font-weight: 600 !important;
+ box-shadow: 0 2px 12px rgba(16,163,127,0.45) !important;
+}
+[data-testid="stSidebar"] .stButton button[kind="primary"]:hover {
+ background: #0d8f6e !important;
+ background-color: #0d8f6e !important;
+ border-color: #0d8f6e !important;
+ box-shadow: 0 4px 16px rgba(16,163,127,0.55) !important;
+}
+
+/* ── File uploader ───────────────────────────────────────────────── */
+[data-testid="stFileUploader"] {
+ background: rgba(255,255,255,0.02) !important;
+ border: 1.5px dashed rgba(255,255,255,0.12) !important;
+ border-radius: 10px !important;
+}
+[data-testid="stFileUploader"]:hover {
+ border-color: #10a37f !important;
+}
+[data-testid="stFileUploader"] label,
+[data-testid="stFileUploader"] p,
+[data-testid="stFileUploader"] span,
+[data-testid="stFileUploader"] small,
+[data-testid="stFileUploader"] * {
+ color: #c0c0c0 !important;
+ font-size: 0.82rem !important;
+}
+
+/* ── Main area ───────────────────────────────────────────────────── */
+.main .block-container {
+ max-width: 780px !important;
+ padding: 2rem 2rem 140px !important;
+ margin: 0 auto !important;
+}
+
+.main h1 {
+ color: #ececec !important;
+ font-size: 1.45rem !important;
+ font-weight: 700 !important;
+ letter-spacing: -0.3px !important;
+ margin-bottom: 2px !important;
+}
+
+/* Force ALL text in main visible */
+.main p, .main li, .main span, .main label,
+.stMarkdown p, .stMarkdown li, .stMarkdown span,
+.stMarkdown strong, .stMarkdown em, .stMarkdown code,
+[data-testid="stMarkdownContainer"] p,
+[data-testid="stMarkdownContainer"] li,
+[data-testid="stMarkdownContainer"] span {
+ color: #e0e0e0 !important;
+ line-height: 1.65 !important;
+}
+
+/* ── Chat messages ───────────────────────────────────────────────── */
+[data-testid="stChatMessage"] {
+ background: transparent !important;
+ padding: 6px 0 !important;
+ border: none !important;
+ animation: slideFade 0.20s ease-out;
+}
+@keyframes slideFade {
+ from { opacity:0; transform:translateY(6px); }
+ to { opacity:1; transform:translateY(0); }
+}
+/* Force ALL text inside any chat bubble to bright white */
+[data-testid="stChatMessage"] p,
+[data-testid="stChatMessage"] span,
+[data-testid="stChatMessage"] li,
+[data-testid="stChatMessage"] div,
+[data-testid="stChatMessage"] strong,
+[data-testid="stChatMessage"] em,
+[data-testid="stChatMessage"] code {
+ color: #ececec !important;
+}
+[data-testid="stChatMessage"] pre,
+[data-testid="stChatMessage"] h1,
+[data-testid="stChatMessage"] h2,
+[data-testid="stChatMessage"] h3,
+[data-testid="stChatMessage"] td,
+[data-testid="stChatMessage"] th {
+ color: #ececec !important;
+}
+
+/* ── Chat input bar ──────────────────────────────────────────────── */
+[data-testid="stChatInputContainer"] {
+ background: #2f2f2f !important;
+ border: 1.5px solid rgba(255,255,255,0.10) !important;
+ border-radius: 16px !important;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.30) !important;
+ transition: border-color 0.2s !important;
+}
+[data-testid="stChatInputContainer"]:focus-within {
+ border-color: rgba(16,163,127,0.50) !important;
+ box-shadow: 0 0 0 3px rgba(16,163,127,0.10) !important;
+}
+/* Input text — white, clearly visible */
+[data-testid="stChatInputContainer"] textarea {
+ background: transparent !important;
+ color: #f0f0f0 !important;
+ caret-color: #f0f0f0 !important;
+ font-size: 0.94rem !important;
+ font-family: 'Inter', sans-serif !important;
+}
+[data-testid="stChatInputContainer"] textarea::placeholder {
+ color: #4a4a4a !important;
+}
+
+/* ── Alert boxes ─────────────────────────────────────────────────── */
+[data-testid="stAlert"] {
+ border-radius: 10px !important;
+ font-size: 0.86rem !important;
+}
+[data-testid="stAlert"] p,
+[data-testid="stAlert"] span { color: inherit !important; }
+
+/* ── Spinner ─────────────────────────────────────────────────────── */
+[data-testid="stSpinner"] p { color: #888 !important; font-size: 0.83rem !important; }
+
+/* ── Dividers ────────────────────────────────────────────────────── */
+hr { border-color: rgba(255,255,255,0.07) !important; margin: 8px 0 !important; }
+
+/* ── Welcome card ────────────────────────────────────────────────── */
+.welcome-card {
+ background: rgba(255,255,255,0.02);
+ border: 1px solid rgba(255,255,255,0.07);
+ border-radius: 12px;
+ padding: 32px 24px;
+ margin: 36px 0 16px;
+ text-align: center;
+}
+.welcome-card h3 { color: #e0e0e0 !important; font-size: 1rem !important; font-weight: 600; margin-bottom: 6px; }
+.welcome-card p { color: #888 !important; font-size: 0.84rem !important; line-height: 1.6; }
+.welcome-card .steps { display:flex; justify-content:center; gap:44px; margin-top:24px; flex-wrap:wrap; }
+.welcome-card .step { display:flex; flex-direction:column; align-items:center; gap:7px; }
+.welcome-card .step-icon { font-size:1.4rem; }
+.welcome-card .step-label { color:#555 !important; font-size:0.74rem !important; font-weight:500; }
+
+/* ── Active doc badge ────────────────────────────────────────────── */
+.doc-badge {
+ display:inline-flex; align-items:center; gap:6px;
+ background:rgba(16,163,127,0.10);
+ border:1px solid rgba(16,163,127,0.38);
+ border-radius:20px; padding:4px 12px;
+ font-size:0.78rem; color:#5fd3ba !important; font-weight:500;
+ margin-top:6px;
+}
+
+/* ── Subtitle ────────────────────────────────────────────────────── */
+.subtitle-text { color:#888 !important; font-size:0.85rem !important; margin-bottom:1rem; line-height:1.5; }
+
+/* ── Scrollbar ───────────────────────────────────────────────────── */
+::-webkit-scrollbar { width:4px; }
+::-webkit-scrollbar-thumb { background:rgba(255,255,255,0.08); border-radius:10px; }
+::-webkit-scrollbar-thumb:hover { background:rgba(255,255,255,0.15); }
+
+/* ── Inline code ─────────────────────────────────────────────────── */
+[data-testid="stChatMessage"] code,
+[data-testid="stMarkdownContainer"] code {
+ background: #1e2030 !important;
+ color: #7dd3b8 !important;
+ border: 1px solid rgba(16,163,127,0.25) !important;
+ border-radius: 4px !important;
+ padding: 2px 6px !important;
+ font-family: 'JetBrains Mono', 'Fira Code', 'Courier New', monospace !important;
+ font-size: 0.85em !important;
+}
+
+/* ── Code blocks (pre) ───────────────────────────────────────────── */
+[data-testid="stChatMessage"] pre,
+[data-testid="stMarkdownContainer"] pre {
+ background: #1a1d2e !important;
+ border: 1px solid rgba(16,163,127,0.20) !important;
+ border-left: 3px solid #10a37f !important;
+ border-radius: 8px !important;
+ padding: 14px 16px !important;
+ overflow-x: auto !important;
+}
+[data-testid="stChatMessage"] pre code,
+[data-testid="stMarkdownContainer"] pre code {
+ background: transparent !important;
+ color: #d0e8d8 !important;
+ border: none !important;
+ padding: 0 !important;
+ font-size: 0.88rem !important;
+ line-height: 1.65 !important;
+}
+
+/* ── Markdown tables ─────────────────────────────────────────────── */
+[data-testid="stChatMessage"] table,
+[data-testid="stMarkdownContainer"] table {
+ border-collapse: collapse !important;
+ width: 100% !important;
+ font-size: 0.88rem !important;
+}
+[data-testid="stChatMessage"] th,
+[data-testid="stMarkdownContainer"] th {
+ background: rgba(16,163,127,0.15) !important;
+ color: #ececec !important;
+ border: 1px solid rgba(255,255,255,0.10) !important;
+ padding: 8px 12px !important;
+}
+[data-testid="stChatMessage"] td,
+[data-testid="stMarkdownContainer"] td {
+ background: rgba(255,255,255,0.02) !important;
+ color: #d0d0d0 !important;
+ border: 1px solid rgba(255,255,255,0.07) !important;
+ padding: 7px 12px !important;
+}
+
+/* ── Blockquotes ─────────────────────────────────────────────────── */
+[data-testid="stChatMessage"] blockquote,
+[data-testid="stMarkdownContainer"] blockquote {
+ border-left: 3px solid #10a37f !important;
+ background: rgba(16,163,127,0.05) !important;
+ margin: 8px 0 !important;
+ padding: 8px 14px !important;
+ color: #aaaaaa !important;
+ border-radius: 0 6px 6px 0 !important;
+}
+
+/* ── Links ───────────────────────────────────────────────────────── */
+[data-testid="stChatMessage"] a,
+[data-testid="stMarkdownContainer"] a {
+ color: #5fd3ba !important;
+ text-decoration: underline !important;
+ text-underline-offset: 2px !important;
+}
+[data-testid="stChatMessage"] a:hover,
+[data-testid="stMarkdownContainer"] a:hover {
+ color: #10a37f !important;
+}
+
+/* ── Code block copy button ──────────────────────────────────────── */
+[data-testid="stChatMessage"] pre button,
+[data-testid="stMarkdownContainer"] pre button,
+[data-testid="stCodeToolbar"] button,
+.stCodeBlock button,
+button[title="Copy to clipboard"],
+button[aria-label="Copy to clipboard"] {
+ background: #1e2030 !important;
+ background-color: #1e2030 !important;
+ color: #7dd3b8 !important;
+ border: 1px solid rgba(16,163,127,0.30) !important;
+ border-radius: 5px !important;
+ opacity: 1 !important;
+}
+button[title="Copy to clipboard"]:hover,
+button[aria-label="Copy to clipboard"]:hover {
+ background: rgba(16,163,127,0.20) !important;
+ color: #ffffff !important;
+}
+
+/* ── Alert / info / warning / error boxes ────────────────────────── */
+[data-testid="stAlert"],
+[data-testid="stNotification"],
+div[data-baseweb="notification"] {
+ background: #1a1d2e !important;
+ border-radius: 8px !important;
+ border-left-width: 3px !important;
+}
+/* info → blue-teal tint */
+[data-testid="stAlert"][data-type="info"],
+.stAlert.stInfo {
+ border-color: #3b9edd !important;
+ color: #b0d4f0 !important;
+}
+/* success → green tint */
+[data-testid="stAlert"][data-type="success"],
+.stAlert.stSuccess {
+ border-color: #10a37f !important;
+ color: #7dd3b8 !important;
+}
+/* warning → amber tint */
+[data-testid="stAlert"][data-type="warning"],
+.stAlert.stWarning {
+ border-color: #d4a017 !important;
+ color: #e8c97a !important;
+}
+/* error → red tint */
+[data-testid="stAlert"][data-type="error"],
+.stAlert.stError {
+ border-color: #c94040 !important;
+ color: #f0a0a0 !important;
+}
+/* Force all text inside alerts to be visible */
+[data-testid="stAlert"] p,
+[data-testid="stAlert"] span,
+[data-testid="stAlert"] div {
+ color: inherit !important;
+}
+
+/* ── Spinner ─────────────────────────────────────────────────────── */
+[data-testid="stSpinner"],
+[data-testid="stSpinner"] p,
+[data-testid="stSpinner"] span,
+.stSpinner p {
+ color: #a0a0a0 !important;
+ font-size: 0.88rem !important;
+}
+
+/* ── HR horizontal rule in chat ──────────────────────────────────── */
+[data-testid="stChatMessage"] hr,
+[data-testid="stMarkdownContainer"] hr {
+ border: none !important;
+ border-top: 1px solid rgba(16,163,127,0.25) !important;
+ margin: 14px 0 !important;
+}
+</style>
+""", unsafe_allow_html=True)
+
+
+
# ── Cache the embedding model (loads once per server session) ─────────
-@st.cache_resource(show_spinner="Loading embedding model (first time only)…")
+@st.cache_resource(show_spinner="⚙️ Loading AI models — first launch only…")
def get_embeddings():
from langchain_community.embeddings import HuggingFaceEmbeddings
return HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
@@ -59,6 +511,52 @@ class FileWrapper:
return self._content
+# ── Friendly error message helper ────────────────────────────────────
+def friendly_error(raw_error: str) -> str:
+ """Convert raw technical errors into user-friendly messages."""
+ e = str(raw_error).lower()
+ if "429" in e or "resource_exhausted" in e or "quota" in e:
+ return (
+ "⏳ **API rate limit reached.** The AI service is temporarily busy. "
+ "Please wait 30–60 seconds and try again. "
+ "If this happens often, your daily quota may be exhausted — "
+ "it resets automatically at midnight (Pacific time)."
+ )
+ if "api key" in e or "authentication" in e or "invalid_api_key" in e or "401" in e:
+ return (
+ "🔑 **API key error.** The AI service credentials are invalid or missing. "
+ "Please check that your `.env` file contains a valid `GROQ_API_KEY`."
+ )
+ if "connection" in e or "timeout" in e or "network" in e or "ssl" in e:
+ return (
+ "🌐 **Network issue.** Could not reach the AI service. "
+ "Please check your internet connection and try again."
+ )
+ if "no such file" in e or "filenotfounderror" in e:
+ return (
+ "📁 **File not found.** The session data may have been cleared. "
+ "Please upload your document(s) again to start a new session."
+ )
+ if "context_length" in e or "token" in e and "exceed" in e:
+ return (
+ "📄 **Document too large for a single query.** "
+ "Try breaking your question into smaller parts, "
+ "or reduce the number of documents in this session."
+ )
+ if "chroma" in e or "collection" in e or "embedding" in e:
+ return (
+ "🗄️ **Session data error.** The document index could not be loaded. "
+ "Please start a new chat and re-upload your files."
+ )
+ # Generic fallback — show a readable version, not the full stack trace
+ short = str(raw_error)[:200]
+ return (
+ f"❌ **Something went wrong.** "
+ f"Please try again, or start a new chat.\n\n"
+ f"<details><summary>Technical details</summary>{short}</details>"
+ )
+
+
# ── Session state defaults ───────────────────────────────────────────
for key, default in {
"chat_history": [],
@@ -75,17 +573,14 @@ for key, default in {
st.session_state[key] = default
-# ── Handle pending session resume (runs before sidebar) ──────────────
-# FAST PATH: session_vectors/{id}/ exists → load Chroma from disk (seconds)
-# READ-ONLY: no vectors → show history only, user can re-upload to resume
+# ── Handle pending session resume ─────────────────────────────────────
if st.session_state.pending_resume is not None:
resume_id = st.session_state.pending_resume
- st.session_state.pending_resume = None # Clear to avoid loops
+ st.session_state.pending_resume = None
vector_dir = os.path.join(VECTORS_BASE, resume_id)
if os.path.exists(vector_dir):
- # Fast path: load persisted Chroma — takes seconds, no re-embedding
with st.spinner("🔄 Restoring session…"):
try:
embeddings = get_embeddings()
@@ -98,21 +593,17 @@ if st.session_state.pending_resume is not None:
st.session_state.viewing_history = False
st.session_state.resume_no_create = True
except Exception as e:
- st.warning(f"⚠️ Could not load session vectors: {e}")
+ st.warning(friendly_error(e))
st.session_state.viewing_history = True
st.session_state.vector_store = None
else:
- # No persisted vectors — instant read-only mode.
- # (Sessions before vector-persistence feature fall here.)
st.session_state.viewing_history = True
st.session_state.vector_store = None
st.rerun()
-# ── LLM: Groq for chat, Gemini kept in ingest.py for OCR only ────────
-# Groq free tier: no daily limit, fast (500+ tokens/s)
-# Gemini free tier: 1500 RPD but shared with OCR → move chat to Groq
+# ── LLM ──────────────────────────────────────────────────────────────
LLM = ChatGroq(
model=GROQ_MODEL,
temperature=0.4,
@@ -156,7 +647,15 @@ PROMPT = ChatPromptTemplate.from_messages([
# ────────────────────────────────────────────────────────────────────
with st.sidebar:
- # ── ✏️ New Chat button ───────────────────────────────────────────
+ # ── Logo / brand ─────────────────────────────────────────────────
+ st.markdown("""
+ <div style="display:flex;align-items:center;gap:10px;padding:4px 4px 12px;">
+ <span style="font-size:1.4rem;">🤖</span>
+ <span style="font-weight:700;font-size:1rem;color:#ececec;letter-spacing:-0.3px;">DocuMind</span>
+ </div>
+ """, unsafe_allow_html=True)
+
+ # ── New Chat button ───────────────────────────────────────────────
if st.button("✏️ New Chat", use_container_width=True, type="primary"):
st.session_state.chat_history = []
st.session_state.vector_store = None
@@ -165,18 +664,18 @@ with st.sidebar:
st.session_state.viewing_history = False
st.session_state.last_file_ids = None
st.session_state.resume_no_create = False
- st.session_state.uploader_key += 1 # clears the file uploader widget
+ st.session_state.uploader_key += 1
st.rerun()
st.divider()
# ── Upload section ───────────────────────────────────────────────
- st.header("📄 Upload Documents")
+ st.header("Upload Documents")
uploaded_files = st.file_uploader(
"Choose one or more files (PDF, Word, or Image)",
type=["pdf", "docx", "jpg", "jpeg", "png", "webp", "gif"],
accept_multiple_files=True,
- help="Supported: PDF, Word (.docx), Images (.jpg, .jpeg, .png, .webp, .gif)",
+ help="Supported: PDF, Word (.docx), Images (.jpg .jpeg .png .webp .gif) — max 200 MB each",
key=f"uploader_{st.session_state.uploader_key}",
)
@@ -186,13 +685,11 @@ with st.sidebar:
if current_ids != previous_ids:
if st.session_state.resume_no_create:
- # After resume: uploader still shows old files — sync IDs only
- st.session_state.last_file_ids = current_ids
- st.session_state.resume_no_create = False
+ st.session_state.last_file_ids = current_ids
+ st.session_state.resume_no_create = False
else:
- with st.spinner("Processing documents…"):
+ with st.spinner("📖 Reading and indexing your documents…"):
try:
- # Read all bytes before any stream is consumed
file_data = [(f.name, f.read()) for f in uploaded_files]
st.session_state.vector_store = None
@@ -219,18 +716,19 @@ with st.sidebar:
history_mgr.create_session(session_id, doc_names)
history_mgr.save_session_files(session_id, file_data)
- st.success(f"✅ {len(doc_names)} file(s) processed!")
+ # st.success(f"✅ {len(doc_names)} file(s) ready — ask away!")
except Exception as e:
- st.error(f"❌ Error: {e}")
+ st.error(friendly_error(e))
+ # Active document badge
if st.session_state.vector_store is not None:
names = ", ".join(st.session_state.doc_names)
- st.info(f"📚 Active: **{names}**")
+ st.markdown(f'<div class="doc-badge">📚 {names}</div>', unsafe_allow_html=True)
st.divider()
- # ── Clear chat button ────────────────────────────────────────────
- if st.button("🗑️ Clear Chat History", use_container_width=True):
+ # ── Clear chat button ─────────────────────────────────────────────
+ if st.button("🗑️ Clear Chat History", use_container_width=True):
if st.session_state.session_id:
history_mgr.delete_session(st.session_state.session_id)
@@ -245,15 +743,15 @@ with st.sidebar:
st.divider()
- # ── Past sessions list ───────────────────────────────────────────
- st.header("📜 Past Sessions")
+ # ── Past sessions list ────────────────────────────────────────────
+ st.header("Past Sessions")
sessions = history_mgr.load_sessions()
active_id = st.session_state.session_id
if not sessions:
st.caption("No saved sessions yet.")
else:
- for s in sessions[:20]:
+ for s in sessions[:25]:
docs_label = ", ".join(s["documents"]) or "Unknown"
ts = s["timestamp"][:16].replace("T", " ")
msg_count = s["message_count"]
@@ -264,62 +762,96 @@ with st.sidebar:
use_container_width=True, type=btn_type):
full_session = history_mgr.get_session(s["id"])
if full_session:
- st.session_state.chat_history = full_session["messages"]
- st.session_state.doc_names = full_session["documents"]
- st.session_state.session_id = s["id"]
- st.session_state.pending_resume = s["id"]
- st.session_state.vector_store = None
+ st.session_state.chat_history = full_session["messages"]
+ st.session_state.doc_names = full_session["documents"]
+ st.session_state.session_id = s["id"]
+ st.session_state.pending_resume = s["id"]
+ st.session_state.vector_store = None
st.session_state.viewing_history = False
st.rerun()
+ # ── Powered-by footer ─────────────────────────────────────────────
+ st.markdown("""
+ <div style="position:fixed;bottom:16px;left:12px;right:12px;
+ text-align:center;font-size:0.72rem;color:#444;">
+ Groq · Llama 3.3 · Gemini · ChromaDB
+ </div>
+ """, unsafe_allow_html=True)
+
# ────────────────────────────────────────────────────────────────────
# MAIN CHAT INTERFACE
# ────────────────────────────────────────────────────────────────────
-st.title("🤖 RAG Chatbot")
+st.markdown('<h1>DocuMind</h1>', unsafe_allow_html=True)
st.markdown(
- "**AI-powered document assistant** — Upload files in the sidebar, "
- "then ask questions. Answers are grounded in your documents with "
- "source citations. _Powered by HuggingFace Embeddings & Google Gemini._"
+ '<p class="subtitle-text">AI-powered document assistant — '
+ 'Upload your files in the sidebar, then ask anything. '
+ 'Answers are grounded strictly in your documents.</p>',
+ unsafe_allow_html=True,
)
# Read-only banner
if st.session_state.viewing_history:
- st.warning(
- "📜 This is a read-only view of a past session "
- "(documents not available for this session). "
- "Upload files in the sidebar to continue chatting."
+ st.info(
+ "📜 **Past session loaded (read-only).** "
+ "The original document index is not available for this session. "
+ "Upload your files again in the sidebar to continue chatting."
)
+# Welcome card — shown only when no messages yet
+if not st.session_state.chat_history:
+ st.markdown("""
+ <div class="welcome-card">
+ <h3>Get started in 3 steps</h3>
+ <p>Ask questions about your PDFs, Word docs, and images — instantly.</p>
+ <div class="steps">
+ <div class="step">
+ <span class="step-icon">📄</span>
+ <span class="step-label">1. Upload a file</span>
+ </div>
+ <div class="step">
+ <span class="step-icon">✨</span>
+ <span class="step-label">2. AI indexes it</span>
+ </div>
+ <div class="step">
+ <span class="step-icon">💬</span>
+ <span class="step-label">3. Ask anything</span>
+ </div>
+ </div>
+ </div>
+ """, unsafe_allow_html=True)
+
# Render chat history
for message in st.session_state.chat_history:
- with st.chat_message(message["role"]):
- st.markdown(message["content"])
+ _avatar = ASST_AVATAR if message["role"] == "assistant" else USER_AVATAR
+ with st.chat_message(message["role"], avatar=_avatar):
+ msg_str = ('\u200B' if message["role"] == "user" else '') + message["content"]
+ st.markdown(msg_str)
-# Chat input — ALWAYS enabled (no disabled state)
+# Chat input — always enabled
user_query = st.chat_input("Ask a question about your document(s)…")
if user_query:
st.session_state.viewing_history = False
- with st.chat_message("user"):
- st.markdown(user_query)
+ with st.chat_message("user", avatar=USER_AVATAR):
+ st.markdown('\u200B' + user_query)
st.session_state.chat_history.append({"role": "user", "content": user_query})
- with st.chat_message("assistant"):
+ with st.chat_message("assistant", avatar=ASST_AVATAR):
+ message_placeholder = st.empty()
if st.session_state.vector_store is None:
- # No documents uploaded yet — friendly prompt
msg = (
- "📂 No documents loaded. "
- "Please upload a file in the sidebar first, "
+ "📂 **No documents loaded yet.**\n\n"
+ "Please upload a PDF, Word, or image file in the left sidebar first, "
"then ask your question."
)
- st.info(msg)
+ message_placeholder.markdown(msg)
st.session_state.chat_history.append({"role": "assistant", "content": msg})
else:
with st.spinner("Thinking…"):
try:
- # ── MMR Retriever ────────────────────────────────────
+ # ── MMR Retriever ─────────────────────────────────
num_docs = len(st.session_state.doc_names)
retriever = st.session_state.vector_store.as_retriever(
search_type="mmr",
@@ -330,7 +862,7 @@ if user_query:
},
)
- # ── Rule-based query decomposition ───────────────────
+ # ── Rule-based query decomposition ────────────────
def decompose_query(q: str) -> list[str]:
parts = re.split(r'[??。]|\band\b|\bAND\b', q)
parts = [p.strip() for p in parts if len(p.strip()) > 5]
@@ -346,7 +878,7 @@ if user_query:
{doc.page_content: doc for doc in all_docs}.values()
)
- # ── Chain ────────────────────────────────────────────
+ # ── Chain ─────────────────────────────────────────
document_prompt = PromptTemplate.from_template(
"Source: {source}\nContent: {page_content}"
)
@@ -365,10 +897,10 @@ if user_query:
{"role": "assistant", "content": answer}
)
except Exception as e:
- err = f"❌ Error generating response: {e}"
- st.error(err)
+ err_msg = friendly_error(e)
+ st.error(err_msg, icon="⚠️")
st.session_state.chat_history.append(
- {"role": "assistant", "content": err}
+ {"role": "assistant", "content": err_msg}
)
# Auto-save
@@ -377,3 +909,281 @@ if user_query:
st.session_state.session_id,
st.session_state.chat_history,
)
+
+# ── Global JS UI Engine (Layout & Theme) ──────────────────────────────
+import streamlit.components.v1 as components
+js_code = """
+<script>
+setInterval(() => {
+ const parent = window.parent.document;
+ if (!parent) return;
+
+ // 1. Theme Detection
+ const themeStr = localStorage.getItem('stActiveTheme');
+ const isLight = themeStr ? themeStr.includes('light') : window.matchMedia('(prefers-color-scheme: light)').matches;
+
+ // 2. Inject specific mode overrides
+ let styleTag = parent.getElementById('documind-light-theme');
+ if (isLight) {
+ if (!styleTag) {
+ styleTag = parent.createElement('style');
+ styleTag.id = 'documind-light-theme';
+ styleTag.innerHTML = `
+ /* Main Background & Sidebar */
+ html body .stApp, html body [data-testid="stAppViewContainer"],
+ html body [data-testid="stHeader"], html body [data-testid="stSidebar"],
+ html body [data-testid="stSidebar"] > div {
+ background-color: #ffffff !important;
+ }
+
+ /* Sidebar content */
+ html body [data-testid="stSidebar"] *,
+ html body [data-testid="stSidebar"] p, html body [data-testid="stSidebar"] span, html body [data-testid="stSidebar"] h1,
+ html body [data-testid="stSidebar"] h2, html body [data-testid="stSidebar"] h3, html body [data-testid="stSidebar"] div {
+ color: #000000 !important;
+ }
+
+ /* Welcome Card & Logo Text */
+ html body .welcome-card {
+ background-color: #ffffff !important;
+ border: 1px solid rgba(0,0,0,0.1) !important;
+ }
+ html body .welcome-card h3, html body .welcome-card h3 span {
+ color: #000000 !important;
+ }
+ html body .welcome-card h3 svg, html body .welcome-card h3 svg path {
+ fill: #000000 !important;
+ stroke: #000000 !important;
+ }
+ html body .welcome-card p, html body .welcome-card .step-label {
+ color: #333333 !important;
+ }
+
+ /* Uploader */
+ html body [data-testid="stFileUploader"] {
+ background-color: #fdfdfd !important;
+ border: 1.5px dashed rgba(0,0,0,0.2) !important;
+ }
+ html body [data-testid="stFileUploader"] *, html body [data-testid="stUploadedFile"] * {
+ color: #000000 !important;
+ }
+
+ /* Alerts (Success/Info boxes) */
+ html body div[data-testid="stAlert"], html body [data-testid="stAlert"][data-type="success"],
+ html body [data-testid="stAlert"][data-type="info"], html body [data-testid="stAlert"][data-type="warning"],
+ html body [data-testid="stAlert"][data-type="error"], html body .stAlert {
+ background: #ffffff !important;
+ background-color: #ffffff !important;
+ color: #000000 !important;
+ border: 1px solid rgba(0,0,0,0.15) !important;
+ }
+ html body [data-testid="stAlert"] *, html body .stAlert * {
+ color: #000000 !important;
+ }
+
+ /* Chat Input Box */
+ html body [data-testid="stChatInputContainer"] {
+ background-color: #fafafa !important; /* light grey fill */
+ border: 1.5px solid rgba(16,163,127,0.35) !important; /* pale green border */
+ }
+ html body [data-testid="stChatInputContainer"]:focus-within {
+ border: 1.5px solid rgba(16,163,127,0.8) !important;
+ }
+ html body [data-testid="stChatInputContainer"] textarea {
+ color: #000000 !important;
+ background-color: transparent !important;
+ -webkit-text-fill-color: #000000 !important;
+ }
+ html body [data-testid="stChatInputContainer"] svg {
+ stroke: #000000 !important;
+ fill: #000000 !important;
+ }
+
+ /* All General Main Texts (Including Main DocuMind Title) */
+ html body h1, html body h2, html body h3, html body h4, html body h5, html body h6,
+ html body .main h1, html body .main h2, html body .main h3, html body [data-testid="stAppViewContainer"] h1,
+ html body .stMarkdown, html body .stMarkdown p, html body .stMarkdown li, html body .stMarkdown a,
+ html body .stMarkdown strong, html body .stMarkdown b, html body .stMarkdown em, html body .stMarkdown span,
+ html body div[data-testid="stMarkdownContainer"] strong, html body div[data-testid="stMarkdownContainer"] b,
+ html body [data-testid="stChatMessage"] strong, html body [data-testid="stChatMessage"] b, html body [data-testid="stChatMessage"] em, html body [data-testid="stChatMessage"] span,
+ html body [data-testid="stChatMessage"] p, html body [data-testid="stChatMessage"] div {
+ color: #000000 !important;
+ }
+ html body *[data-testid="stChatMessage"] code *,
+ html body *[data-testid="stChatMessage"] code,
+ html body .stMarkdown code *,
+ html body .stMarkdown code {
+ color: #0a694e !important;
+ }
+ html body .subtitle-text {
+ color: #333333 !important;
+ }
+
+ /* Top Right buttons */
+ html body [data-testid="stHeader"] button, html body [data-testid="stToolbarActions"] button {
+ color: #000000 !important;
+ background-color: #ffffff !important;
+ border: 1px solid rgba(0,0,0,0.1) !important;
+ }
+ html body [data-testid="stHeader"] button:hover, html body [data-testid="stToolbarActions"] button:hover {
+ background-color: #f0f0f0 !important;
+ }
+
+ /* Bottom spacing */
+ html body [data-testid="stBottom"], html body [data-testid="stBottom"] > div {
+ background-color: #ffffff !important;
+ }
+
+ /* Sidebar inactive history items */
+ html body [class*="st-emotion-cache"] .history-item, html body .history-item {
+ border: 1px solid rgba(0,0,0,0.1) !important;
+ background: #ffffff !important;
+ color: #000000 !important;
+ }
+ html body .history-item.active-session {
+ background: rgba(16,163,127,0.15) !important;
+ border: 1px solid #10a37f !important;
+ }
+ `;
+ parent.head.appendChild(styleTag);
+ }
+ } else {
+ if (styleTag) styleTag.remove();
+ }
+
+ // 3. Layout and Bubble Styling per Message
+ const msgs = parent.querySelectorAll('[data-testid="stChatMessage"]');
+
+ // Explicit inline override for the main DocuMind Title just to absolutely guarantee
+ parent.querySelectorAll('h1').forEach(node => {
+ if (node.innerText.trim() === 'DocuMind') {
+ if (isLight) {
+ node.style.setProperty('color', '#000000', 'important');
+ } else {
+ if (node.style.color === 'rgb(0, 0, 0)') {
+ node.style.removeProperty('color');