Repository navigation
Expand file tree
/
Copy pathchatbot_app.py
More file actions
1774 lines (1516 loc) · 72.3 KB
/
Copy pathchatbot_app.py
File metadata and controls
1774 lines (1516 loc) · 72.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
"""
SmartRAG ChatBot - Minimalistic ChatGPT-style Interface
A clean, modern chat interface for the SmartRAG system with file management.
"""
import streamlit as st
import os
import time
from datetime import datetime
from pathlib import Path
import json
from typing import List, Dict
import tempfile
# Import SmartRAG system
from multimodal_rag.system import MultimodalRAGSystem
from multimodal_rag.base import QueryRequest
# Import for speech-to-text
try:
import whisper
WHISPER_AVAILABLE = True
except ImportError:
WHISPER_AVAILABLE = False
# Import for file handling and database
import sqlite3
import base64
from io import BytesIO
from PIL import Image
import mimetypes
# Page configuration
st.set_page_config(
page_title="SmartRAG ChatBot",
page_icon="🤖", # Traditional bot icon
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for ChatGPT-like styling
st.markdown("""
<style>
/* Main chat interface background and text */
/* Target the main page body/container */
.stApp {
background-color: #f0f2f6 !important; /* Very light grey/off-white for the main background */
color: #333333 !important; /* Dark text for general page content */
}
/* Sidebar styling (already somewhat light, but confirming) */
.css-1d391kg, .css-1544g2n, .stSidebar,
.css-1lcbmhc, .css-12oz5g7, .css-1y4p8pa,
section[data-testid="stSidebar"], section[data-testid="stSidebar"] > div {
background-color: #ffffff !important; /* White sidebar */
color: #333333 !important; /* Dark text in sidebar */
min-width: 250px !important;
}
/* Sidebar toggle button (using a clear blue accent) */
button[kind="header"], .css-1rs6os button, [data-testid="collapsedControl"],
section[data-testid="stSidebar"] button[kind="header"] {
background-color: #4a90e2 !important;
color: white !important;
border-radius: 8px !important;
}
/* Collapsed sidebar */
section[data-testid="stSidebar"][aria-expanded="false"] {
width: 50px !important;
min-width: 50px !important;
}
/* Hide Streamlit defaults */
#MainMenu, footer, header {visibility: hidden;}
/* Custom button (clear blue) */
.stButton > button {
background-color: #4a90e2;
color: white;
border: none;
border-radius: 8px;
padding: 0.5rem 1rem;
}
.stButton > button:hover {
background-color: #357abd;
}
/* System Status / Ready / Speech-to-Text Available boxes (light backgrounds with clear text) */
.stSuccess {
background-color: #e6f0fa; /* Very light blue */
color: #1f4e79; /* Dark blue text */
border: 1px solid #4a90e2;
border-radius: 8px;
}
.stError {
background-color: #fcebea; /* Very light red */
color: #721c24; /* Dark red text */
border: 1px solid #e24a4a;
border-radius: 8px;
}
/* File uploader area */
.stFileUploader {
border: 2px dashed #4a90e2;
border-radius: 8px;
padding: 20px;
text-align: center;
background: #ffffff; /* White background */
}
/* Progress bar */
.stProgress > div > div > div {
background-color: #4a90e2;
}
/* Chat with your Documents title area / Main area background (was dark blue/green) */
/* Targeting the main container where the "Chat with your Documents" header lives */
/* This might be a container div that was set to dark. We'll set it to white/light grey */
/* If the header itself is in a custom component, you might need to find its specific class. */
/* Assuming a general container for the main chat area */
.main-chat-container {
background-color: #ffffff !important; /* White background for the main card/area */
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.05); /* Soft shadow */
}
/* The "SmartRAG system initialized successfully!" box (was dark green) */
/* This uses the stSuccess styling, which is now light blue/white */
/* The SmartRAG welcome box (was dark blue) */
.st-bv .stMarkdown { /* Target stMarkdown if it's used for this box */
background-color: #e6f0fa !important; /* Light blue background for info box */
color: #1f4e79 !important; /* Dark text */
padding: 15px !important;
border-radius: 10px !important;
border-left: 4px solid #4a90e2 !important;
}
/* The "Drag and drop file here" box (was using stFileUploader) */
/* It is now white with blue dashed border */
/* Chat messages - User messages (Using light green for a clear contrast) */
.user-message {
background: #dcf8c6 !important; /* Very light green bubble */
color: #333333 !important; /* Dark text */
padding: 15px !important;
border-radius: 15px !important;
margin: 10px 0 !important;
border-left: 4px solid #4caf50 !important; /* Clear green accent */
box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
}
/* Chat messages - Assistant messages (Using light blue for a clear contrast) */
.assistant-message {
background: #e9f5ff !important; /* Very light blue bubble */
color: #333333 !important; /* Dark text */
padding: 15px !important;
border-radius: 15px !important;
margin: 10px 0 !important;
border-left: 4px solid #4a90e2 !important; /* Clear blue accent */
box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
}
/* Input styling - Use light theme colors for the text input */
.stTextInput > div > div > input {
background-color: #ffffff;
border: 2px solid #cccccc; /* Soft grey border */
border-radius: 25px;
color: #000000; /* Black text */
padding: 12px 20px;
}
.stTextInput > div > div > input:focus {
border-color: #4a90e2; /* Blue border on focus */
box-shadow: 0 0 10px rgba(74, 144, 226, 0.3);
outline: none;
}
/* Chat input container */
.chat-input-container {
display: flex;
align-items: center;
background: #ffffff; /* White background for the bar */
border: 2px solid #ccc; /* Light border */
border-radius: 25px;
padding: 8px 12px;
margin: 20px auto;
max-width: 800px;
}
/* Expander headers */
.streamlit-expanderHeader {
background: #f1f1f1; /* Light grey header */
color: #333333; /* Dark text */
border-radius: 8px;
}
/* Ensure all text elements have proper contrast in light theme */
h1, h2, h3, h4, h5, h6 {
color: #2c3e50 !important; /* Dark blue-grey for headers */
}
.stMarkdown {
color: #333333 !important; /* Dark text for markdown */
}
.stText {
color: #333333 !important; /* Dark text for general text */
}
/* Info boxes and alerts */
.stInfo {
background-color: #e6f3ff !important;
color: #0066cc !important;
border: 1px solid #b3d9ff !important;
}
.stWarning {
background-color: #fff3cd !important;
color: #856404 !important;
border: 1px solid #ffeaa7 !important;
}
/* Ensure form submit buttons are visible */
.stForm button {
background-color: #4a90e2 !important;
color: white !important;
border: none !important;
border-radius: 8px !important;
padding: 8px 16px !important;
font-weight: 500 !important;
margin-top: 10px !important;
}
.stForm button:hover {
background-color: #357abd !important;
}
/* Chat container styling for light theme - remove frame */
.chat-container {
background-color: transparent !important;
border: none !important;
border-radius: 0 !important;
padding: 0 !important;
margin: 0 !important;
}
/* Sources text in responses */
.assistant-message small {
color: #555555 !important;
font-style: italic;
}
/* Main title and subtitle styling */
[data-testid="stMarkdownContainer"] h1 {
color: #2c3e50 !important;
}
/* Italic subtitle styling */
[data-testid="stMarkdownContainer"] em {
color: #555555 !important;
}
/* File uploader text */
.stFileUploader label {
color: #333333 !important;
}
/* Selectbox and other input labels */
.stSelectbox label, .stTextInput label, .stTextArea label {
color: #333333 !important;
}
/* File uploader styling for light theme - fix dark dropzone */
.stFileUploader [data-testid="stFileUploaderDropzone"] {
background-color: #f5f5f5 !important;
color: #333333 !important;
border: 2px dashed #4a90e2 !important;
}
.stFileUploader [data-testid="stFileUploaderDropzone"] * {
color: #333333 !important;
}
/* Fix file uploader instruction text */
.stFileUploader [data-testid="stFileUploaderInstructions"] {
color: #333333 !important;
}
/* Button text colors for light gray buttons */
button[style*="background-color: rgb(43, 43, 43)"] {
background-color: #e0e0e0 !important;
color: #333333 !important;
border: 1px solid #cccccc !important;
}
/* Sidebar button styling */
.css-1d391kg button {
background-color: #e0e0e0 !important;
color: #333333 !important;
}
/* Status container text should be visible */
.element-container[style*="background"] {
color: white !important;
}
.element-container[style*="background"] * {
color: white !important;
}
/* Fix secondary buttons and dark containers */
.stButton button[kind="secondary"] {
background-color: #e0e0e0 !important;
color: #333333 !important;
border: 1px solid #cccccc !important;
}
/* Fix expander headers that might be dark */
.streamlit-expanderHeader {
background-color: #f5f5f5 !important;
color: #333333 !important;
}
/* Additional targeting for expander text visibility */
.streamlit-expanderHeader p,
.streamlit-expanderHeader span,
.streamlit-expanderHeader div,
.streamlit-expanderHeader summary {
color: #333333 !important;
}
/* Target Streamlit's data-testid attributes for expanders */
[data-testid="stExpanderDetails"] summary {
color: #333333 !important;
}
[data-testid="stExpanderDetails"] summary > div {
color: #333333 !important;
}
/* Fix any potential white text in expanders */
.streamlit-expanderHeader * {
color: #333333 !important;
}
/* Fix any sidebar components that might be dark */
.css-1d391kg .stSelectbox > div > div {
background-color: #f5f5f5 !important;
color: #333333 !important;
}
/* Fix Data Management section */
div[data-testid="column"] button {
background-color: #e0e0e0 !important;
color: #333333 !important;
}
/* Additional file uploader fixes */
.stFileUploader {
background-color: #f5f5f5 !important;
color: #333333 !important;
}
.stFileUploader label {
color: #333333 !important;
}
/* Upload Documents expander header */
.stExpander [data-testid="stExpanderToggleIcon"] + div {
background-color: #e8e8e8 !important;
color: #333333 !important;
border-radius: 8px !important;
padding: 8px !important;
}
/* Expander summary/header */
.stExpander summary {
background-color: #e8e8e8 !important;
color: #333333 !important;
border-radius: 8px !important;
padding: 10px !important;
font-weight: bold !important;
}
/* Fix Streamlit metrics text color - targeting the sidebar status elements */
.stMetric {
color: #333333 !important;
}
.stMetric label {
color: #333333 !important;
}
.stMetric [data-testid="metric-label"] {
color: #333333 !important;
}
.stMetric [data-testid="metric-value"] {
color: #333333 !important;
}
/* Additional targeting for sidebar metrics */
.css-1d391kg .stMetric,
.css-1d391kg .stMetric label,
.css-1d391kg .stMetric div {
color: #333333 !important;
}
/* More comprehensive metric targeting */
[data-testid="metric-container"],
[data-testid="metric-container"] *,
.metric-container,
.metric-container *,
.stMetric *,
.metric * {
color: #333333 !important;
}
/* Target metric values specifically */
.metric .metric-value,
[data-testid="metric-value"],
.stMetric-value,
.css-1xarl3l,
.css-16huue1 {
color: #333333 !important;
}
/* Sidebar specific overrides */
.css-1d391kg * {
color: #333333 !important;
}
/* File uploader browse button */
.stFileUploader button,
.stFileUploader [data-testid="baseButton-secondary"] {
background-color: #e8e8e8 !important;
color: #333333 !important;
border: 1px solid #cccccc !important;
border-radius: 6px !important;
}
/* All secondary buttons (like Browse Files) */
button[kind="secondary"] {
background-color: #e8e8e8 !important;
color: #333333 !important;
border: 1px solid #cccccc !important;
}
</style>
""", unsafe_allow_html=True)
# Custom CSS and JavaScript for sidebar and light theme fixes
st.markdown("""
<style>
/* Force dark text for main content areas but preserve white text in dark containers */
.main .block-container {
color: #333333 !important;
}
/* Preserve white text in dark containers */
.main .block-container [style*="background-color: rgb(43, 43, 43)"] * {
color: white !important;
}
.main .block-container [style*="background-color: rgb(70, 130, 180)"] * {
color: white !important;
}
.main .block-container [style*="background-color: rgb(34, 139, 34)"] * {
color: white !important;
}
/* Fix sidebar text visibility */
.css-1d391kg {
color: #333333 !important;
}
/* But preserve white text in dark sidebar elements */
.css-1d391kg [style*="background-color: rgb(43, 43, 43)"] * {
color: white !important;
}
.css-1d391kg [style*="background-color: rgb(70, 130, 180)"] * {
color: white !important;
}
.css-1d391kg [style*="background-color: rgb(34, 139, 34)"] * {
color: white !important;
}
</style>
<script>
// Ensure sidebar toggle is always accessible
document.addEventListener('DOMContentLoaded', function() {
// Find and ensure sidebar toggle is visible
function ensureSidebarToggle() {
const toggleButtons = document.querySelectorAll('button[kind="header"], button[data-testid="collapsedControl"]');
toggleButtons.forEach(button => {
if (button) {
button.style.display = 'block';
button.style.visibility = 'visible';
button.style.opacity = '1';
}
});
}
ensureSidebarToggle();
setInterval(ensureSidebarToggle, 1000);
});
</script>
""", unsafe_allow_html=True)
# File Storage Database Functions
def init_file_storage_db():
"""Initialize SQLite database for file storage."""
conn = sqlite3.connect('file_storage.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS stored_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL,
file_type TEXT NOT NULL,
file_size INTEGER NOT NULL,
file_content BLOB NOT NULL,
upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
file_hash TEXT UNIQUE NOT NULL
)
''')
conn.commit()
conn.close()
def store_file_in_db(filename: str, file_content: bytes, file_type: str, file_size: int, file_hash: str, upload_time: str = None) -> bool:
"""Store file in SQLite database."""
from datetime import datetime
try:
conn = sqlite3.connect('file_storage.db')
cursor = conn.cursor()
# Use provided upload_time or current local time
if upload_time is None:
upload_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
INSERT OR REPLACE INTO stored_files
(filename, file_type, file_size, file_content, file_hash, upload_time)
VALUES (?, ?, ?, ?, ?, ?)
''', (filename, file_type, file_size, file_content, file_hash, upload_time))
conn.commit()
conn.close()
return True
except Exception as e:
st.error(f"Error storing file in database: {str(e)}")
return False
def get_file_from_db(filename: str) -> tuple:
"""Retrieve file from SQLite database."""
try:
conn = sqlite3.connect('file_storage.db')
cursor = conn.cursor()
cursor.execute('''
SELECT filename, file_type, file_size, file_content, upload_time
FROM stored_files
WHERE filename = ?
ORDER BY upload_time DESC
LIMIT 1
''', (filename,))
result = cursor.fetchone()
conn.close()
return result
except Exception as e:
st.error(f"Error retrieving file from database: {str(e)}")
return None
def get_all_stored_files() -> list:
"""Get list of all stored files."""
try:
conn = sqlite3.connect('file_storage.db')
cursor = conn.cursor()
cursor.execute('''
SELECT filename, file_type, file_size, upload_time
FROM stored_files
ORDER BY upload_time DESC
''')
results = cursor.fetchall()
conn.close()
return results
except Exception as e:
st.error(f"Error getting file list: {str(e)}")
return []
def get_files_by_time_range(start_time: str, end_time: str = None) -> list:
"""Get files uploaded within a specific time range."""
try:
conn = sqlite3.connect('file_storage.db')
cursor = conn.cursor()
if end_time:
cursor.execute('''
SELECT filename, file_type, file_size, upload_time
FROM stored_files
WHERE upload_time BETWEEN ? AND ?
ORDER BY upload_time DESC
''', (start_time, end_time))
else:
cursor.execute('''
SELECT filename, file_type, file_size, upload_time
FROM stored_files
WHERE upload_time >= ?
ORDER BY upload_time DESC
''', (start_time,))
results = cursor.fetchall()
conn.close()
return results
except Exception as e:
st.error(f"Error getting files by time range: {str(e)}")
return []
def search_files_by_timestamp(query_time: str) -> str:
"""Search for files uploaded around a specific time and return formatted response."""
from datetime import datetime, timedelta
import re
try:
# Parse different time formats
time_patterns = [
r'(\d{1,2}):(\d{2})', # HH:MM
r'(\d{1,2})\.(\d{2})', # HH.MM
r'(\d{1,2}):(\d{2}):(\d{2})', # HH:MM:SS
]
hour, minute = None, None
for pattern in time_patterns:
match = re.search(pattern, query_time)
if match:
hour = int(match.group(1))
minute = int(match.group(2))
break
if hour is None or minute is None:
return "❌ Could not parse time format. Please use formats like '14:20', '2:30 PM', or '14.20'."
# Get today's date with the specified time
today = datetime.now().date()
target_time = datetime.combine(today, datetime.min.time().replace(hour=hour, minute=minute))
# Search within ±30 minutes of the target time
start_time = target_time - timedelta(minutes=30)
end_time = target_time + timedelta(minutes=30)
# Query database
conn = sqlite3.connect('file_storage.db')
cursor = conn.cursor()
cursor.execute('''
SELECT filename, file_type, upload_time
FROM stored_files
WHERE upload_time BETWEEN ? AND ?
ORDER BY ABS(strftime('%s', upload_time) - strftime('%s', ?))
''', (start_time.strftime('%Y-%m-%d %H:%M:%S'),
end_time.strftime('%Y-%m-%d %H:%M:%S'),
target_time.strftime('%Y-%m-%d %H:%M:%S')))
results = cursor.fetchall()
conn.close()
if not results:
return f"No documents were uploaded around {query_time}."
# For single result, give direct answer
if len(results) == 1:
filename, file_type, upload_time = results[0]
upload_dt = datetime.strptime(upload_time, '%Y-%m-%d %H:%M:%S')
formatted_time = upload_dt.strftime('%H:%M')
return f"At {query_time}, you uploaded **{filename}** ({file_type}) at {formatted_time}."
# For multiple results, list them
response = f"Around {query_time}, you uploaded:\n\n"
for filename, file_type, upload_time in results:
upload_dt = datetime.strptime(upload_time, '%Y-%m-%d %H:%M:%S')
formatted_time = upload_dt.strftime('%H:%M')
response += f"• **{filename}** at {formatted_time}\n"
return response
except Exception as e:
return f"❌ Error searching files by timestamp: {str(e)}"
# Initialize session state
def init_session_state():
"""Initialize session state variables."""
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'rag_system' not in st.session_state:
st.session_state.rag_system = None
if 'uploaded_files' not in st.session_state:
st.session_state.uploaded_files = []
if 'system_initialized' not in st.session_state:
st.session_state.system_initialized = False
if 'whisper_model' not in st.session_state:
st.session_state.whisper_model = None
if 'transcribed_text' not in st.session_state:
st.session_state.transcribed_text = ""
if 'input_hash' not in st.session_state:
st.session_state.input_hash = ""
if 'viewing_file' not in st.session_state:
st.session_state.viewing_file = None
if 'show_file_viewer' not in st.session_state:
st.session_state.show_file_viewer = False
# Initialize file storage database
init_file_storage_db()
if 'audio_processing' not in st.session_state:
st.session_state.audio_processing = False
if 'show_audio_upload' not in st.session_state:
st.session_state.show_audio_upload = False
if 'transcribed_message' not in st.session_state:
st.session_state.transcribed_message = ""
if 'last_processed_input' not in st.session_state:
st.session_state.last_processed_input = ""
if 'input_hash' not in st.session_state:
st.session_state.input_hash = ""
def get_whisper_model():
"""Get or initialize the Whisper model."""
if st.session_state.whisper_model is None and WHISPER_AVAILABLE:
with st.spinner("🎙️ Loading Whisper model..."):
try:
st.session_state.whisper_model = whisper.load_model("base")
st.success("✅ Whisper model loaded successfully!")
except Exception as e:
st.error(f"❌ Failed to load Whisper model: {str(e)}")
return None
return st.session_state.whisper_model
def transcribe_audio(audio_bytes):
"""Transcribe audio bytes using Whisper."""
if not WHISPER_AVAILABLE:
return "Error: Whisper not available"
whisper_model = get_whisper_model()
if whisper_model is None:
return "Error: Could not load Whisper model"
try:
# Save audio bytes to temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
temp_audio.write(audio_bytes)
temp_audio_path = temp_audio.name
# Transcribe with Whisper
st.session_state.audio_processing = True
result = whisper_model.transcribe(temp_audio_path)
transcript = result.get('text', '').strip()
# Clean up temp file
os.unlink(temp_audio_path)
st.session_state.audio_processing = False
return transcript if transcript else "No speech detected"
except Exception as e:
st.session_state.audio_processing = False
if os.path.exists(temp_audio_path):
os.unlink(temp_audio_path)
return f"Error transcribing audio: {str(e)}"
def render_file_viewer():
"""Render file viewer for displaying stored documents."""
if st.session_state.viewing_file:
filename = st.session_state.viewing_file
file_data = get_file_from_db(filename)
if file_data:
filename, file_type, file_size, file_content, upload_time = file_data
# Create file viewer modal
with st.container():
col1, col2, col3 = st.columns([1, 8, 1])
with col2:
st.markdown(f"### 📄 Viewing: {filename}")
st.markdown(f"**Type:** {file_type} | **Size:** {file_size:,} bytes | **Uploaded:** {upload_time}")
# Close button
if st.button("❌ Close Viewer", key="close_viewer"):
st.session_state.viewing_file = None
st.session_state.show_file_viewer = False
st.rerun()
st.markdown("---")
# Display file content based on type
if file_type.startswith('image/'):
# Display image
image = Image.open(BytesIO(file_content))
st.image(image, caption=filename, use_column_width=True)
elif file_type == 'application/pdf':
# Enhanced PDF viewer with embedded display
st.markdown("**📄 PDF Document**")
# Create tabs for different viewing options
tab1, tab2 = st.tabs(["📖 View PDF", "📥 Download"])
with tab1:
try:
# Create base64 encoded PDF for embedded viewing
import base64
base64_pdf = base64.b64encode(file_content).decode('utf-8')
# Embed PDF using iframe
pdf_display = f"""
<div style="border: 2px solid #4a90e2; border-radius: 10px; overflow: hidden;">
<iframe src="data:application/pdf;base64,{base64_pdf}"
width="100%" height="600"
style="border: none;"
type="application/pdf">
<p style="padding: 20px; text-align: center;">
Your browser does not support inline PDF viewing.
Please use the Download tab to get the PDF file.
</p>
</iframe>
</div>
"""
st.markdown(pdf_display, unsafe_allow_html=True)
# Additional controls
col_pdf1, col_pdf2 = st.columns(2)
with col_pdf1:
if st.button("🔗 Open in New Tab", key="open_new_tab"):
st.markdown(f"""
<script>
window.open("data:application/pdf;base64,{base64_pdf}", "_blank");
</script>
""", unsafe_allow_html=True)
st.success("PDF opened in new tab!")
with col_pdf2:
st.download_button(
label="� Save PDF",
data=file_content,
file_name=filename,
mime=file_type,
key="pdf_download_inline"
)
except Exception as e:
st.error(f"❌ Error displaying PDF: {str(e)}")
st.info("📋 Please use the Download tab to access the PDF.")
with tab2:
st.markdown("### 📥 Download Options")
st.download_button(
label="📥 Download PDF",
data=file_content,
file_name=filename,
mime=file_type,
use_container_width=True,
key="pdf_download_tab"
)
st.markdown(f"""
**File Information:**
- 📄 **Name**: {filename}
- 📏 **Size**: {file_size:,} bytes ({file_size/1024:.1f} KB)
- 🕒 **Uploaded**: {upload_time}
""")
st.info("💡 **Tip**: You can also view the PDF directly in the 'View PDF' tab above!")
elif file_type in ['application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/msword']:
# Display Word document download link
st.markdown("**Word Document**")
st.download_button(
label="📥 Download Document",
data=file_content,
file_name=filename,
mime=file_type
)
st.info("Word documents can be downloaded and viewed in Microsoft Word or compatible applications.")
elif file_type.startswith('audio/'):
# Display audio player
st.markdown("**Audio File**")
st.audio(file_content, format=file_type)
elif file_type.startswith('text/'):
# Display text content
try:
text_content = file_content.decode('utf-8')
st.text_area("File Content:", text_content, height=400)
except:
st.error("Unable to display text content")
st.download_button(
label="📥 Download File",
data=file_content,
file_name=filename,
mime=file_type
)
else:
# Generic file download
st.markdown("**File Download**")
st.download_button(
label="📥 Download File",
data=file_content,
file_name=filename,
mime=file_type
)
else:
st.error(f"File '{filename}' not found in database.")
if st.button("❌ Close"):
st.session_state.viewing_file = None
st.session_state.show_file_viewer = False
st.rerun()
def render_custom_chat_input():
"""Render clean chat input bar with speech-to-text functionality."""
# Create a clean input container
col1, col2, col3 = st.columns([1, 10, 1])
with col1:
# Microphone/Speech-to-text button
if WHISPER_AVAILABLE:
if st.button("🎙️", help="Upload audio for speech-to-text", key="stt_btn"):
st.session_state.show_audio_upload = True
else:
st.button("🎙️", disabled=True, help="Whisper not available - install openai-whisper")
with col2:
# Use a form to prevent continuous re-evaluation with unique key based on message count
message_count = len(st.session_state.messages)
with st.form(key=f"chat_form_{message_count}", clear_on_submit=True):
text_message = st.text_input(
"message",
placeholder="Type your message or upload audio for speech-to-text...",
label_visibility="collapsed",
key=f"chat_input_field_{message_count}"
)
submit_button = st.form_submit_button("Send", use_container_width=True)
if submit_button and text_message.strip():
return text_message.strip()
with col3:
# Visual send indicator (form handles submission now)
st.markdown("<div style='text-align: center; padding: 8px; color: #333333;'>📝</div>", unsafe_allow_html=True)
# Audio upload modal when microphone is clicked - more compact
if st.session_state.get('show_audio_upload', False):
with st.expander("🎙️ Speech-to-Text", expanded=True):
audio_file = st.file_uploader(
"Choose an audio file",
type=['wav', 'mp3', 'm4a', 'ogg', 'flac', 'webm'],
key=f"speech_to_text_upload_{message_count}"
)
col_transcribe, col_cancel = st.columns([1, 1])
with col_transcribe:
if audio_file and st.button("🎯 Transcribe", key="transcribe_btn"):
with st.spinner("🎙️ Converting speech to text..."):
transcript = transcribe_audio_file(audio_file)
if transcript and not transcript.startswith("Error"):
st.session_state.show_audio_upload = False
st.session_state.transcribed_message = transcript
st.rerun()
elif transcript:
st.error(transcript)
with col_cancel:
if st.button("❌ Cancel", key="cancel_stt"):
st.session_state.show_audio_upload = False
st.rerun()
# Return transcribed message if available
if st.session_state.get('transcribed_message', ''):
result = st.session_state.transcribed_message
st.session_state.transcribed_message = ""
return result
return None
def transcribe_audio_file(audio_file):
"""Transcribe an uploaded audio file."""
if not WHISPER_AVAILABLE:
st.error("Whisper not available")
return None
whisper_model = get_whisper_model()
if whisper_model is None:
st.error("Could not load Whisper model")