-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
979 lines (840 loc) · 32.7 KB
/
app.py
File metadata and controls
979 lines (840 loc) · 32.7 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
import streamlit as st
import json
from datetime import datetime
import logging
from typing import Dict, List, Optional
import sys
import os
import time
import uuid
from datetime import datetime, timedelta
# Add the parent directory to the path to import from src
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import our custom modules
from src.agent import KingArthurBakingAgent
from src.database import MongoDBManager
from src.config import settings
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- [ MODERN FACEBOOK-LIKE STYLES ] ---
def apply_professional_styles():
st.markdown("""
<style>
/* Modern fonts - Fallback safe for HF Spaces */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css');
/* Simple fonts */
* {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
}
/* Simple Design System */
:root {
--primary: #1877f2;
--primary-hover: #166fe5;
--background: #f0f2f5;
--surface: #ffffff;
--border: #e4e6ea;
--text-primary: #1c1e21;
--text-secondary: #65676b;
--success: #42b883;
--shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
--radius: 8px;
}
/* Base layout */
.main {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--background) !important;
color: var(--text-primary);
}
.main .block-container {
max-width: 1200px;
padding: 1.5rem;
margin: 0 auto;
}
/* Fixed chat input at bottom of screen */
.stChatFloatingInputContainer {
position: fixed !important;
bottom: 0 !important;
left: 0 !important;
right: 0 !important;
z-index: 1000 !important;
background: var(--background) !important;
border-top: 1px solid var(--border) !important;
padding: 1rem !important;
margin: 0 !important;
display: flex !important;
justify-content: center !important;
align-items: center !important;
}
/* Adjust for sidebar on desktop */
@media (min-width: 769px) {
.stChatFloatingInputContainer {
left: 336px !important; /* Standard Streamlit sidebar width */
}
}
/* Center and constrain chat input styling */
.stChatInputContainer {
margin: 0 auto !important;
max-width: 800px !important;
width: 100% !important;
box-sizing: border-box !important;
}
/* Ensure proper spacing around centered input */
.stChatFloatingInputContainer > div {
width: 100% !important;
max-width: 800px !important;
margin: 0 auto !important;
}
/* Add padding to main content so last message isn't hidden */
.stMainBlockContainer {
padding-bottom: 200px !important;
}
/* Ensure messages don't get hidden behind fixed input */
.stChatMessageContainer {
margin-bottom: 1rem !important;
}
/* Chat messages container */
.stChatMessageContainer {
max-height: calc(100vh - 240px) !important;
overflow-y: auto !important;
padding-bottom: 150px !important;
}
/* Ensure proper scrolling */
.stApp {
overflow-y: auto !important;
}
/* Simple Background */
.stApp {
background: var(--background) !important;
}
.main {
background: var(--background) !important;
}
/* Simple header */
.app-header {
background: var(--primary);
color: white;
padding: 2rem;
border-radius: var(--radius);
text-align: center;
margin-bottom: 2rem;
box-shadow: var(--shadow);
}
.app-header h1 {
font-size: 2.5rem;
font-weight: 800;
margin: 0 0 0.5rem 0;
position: relative;
z-index: 1;
}
.app-header p {
font-size: 1.25rem;
opacity: 0.9;
margin: 0;
font-weight: 400;
position: relative;
z-index: 1;
}
/* Chat messages */
.stChatMessage {
background: var(--surface) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
margin-bottom: 1rem !important;
box-shadow: var(--shadow) !important;
}
/* User messages */
div[data-testid="stChatMessage"]:has(div[data-testid="stAvatar-user"]) {
background: var(--primary) !important;
color: white !important;
border: none !important;
}
div[data-testid="stChatMessage"]:has(div[data-testid="stAvatar-user"]) * {
color: white !important;
}
/* Assistant messages */
div[data-testid="stChatMessage"]:has(div[data-testid="stAvatar-assistant"]) {
background: var(--surface) !important;
border: 1px solid var(--border) !important;
}
/* Chat input */
.stChatInputContainer {
background: var(--surface) !important;
border: 2px solid var(--border) !important;
border-radius: var(--radius) !important;
box-shadow: var(--shadow) !important;
transition: all 0.2s ease !important;
}
.stChatInputContainer:focus-within {
border-color: var(--primary) !important;
box-shadow: 0 0 0 3px rgba(24, 119, 242, 0.1) !important;
}
/* Horizontal image layout in chat messages */
.stChatMessage div:has(img) {
display: flex !important;
flex-wrap: wrap !important;
gap: 0.5rem !important;
align-items: flex-start !important;
}
/* Small image size constraints in chat messages */
.stChatMessage img {
max-width: 120px !important;
max-height: 90px !important;
width: auto !important;
height: auto !important;
border-radius: var(--radius) !important;
box-shadow: var(--shadow) !important;
object-fit: cover !important;
flex-shrink: 0 !important;
}
/* Responsive image sizing for smaller screens */
@media (max-width: 768px) {
.stChatMessage img {
max-width: 80px !important;
max-height: 60px !important;
}
}
/* Sidebar */
.stSidebar {
background: var(--surface) !important;
border-right: 1px solid var(--border) !important;
padding: 1rem !important;
}
.stSidebar > div {
background: transparent !important;
}
/* Sidebar sections */
.sidebar-section {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.75rem;
margin-bottom: 0.75rem;
box-shadow: var(--shadow);
}
.sidebar-section h3 {
color: var(--text-primary);
font-size: 0.85rem;
font-weight: 600;
margin: 0 0 0.5rem 0;
display: flex;
align-items: center;
gap: 0.5rem;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.sidebar-section h3 i {
font-size: 0.8rem;
color: var(--primary);
}
/* Buttons */
.stButton > button {
background: var(--primary) !important;
color: white !important;
border: none !important;
border-radius: var(--radius) !important;
font-weight: 600 !important;
padding: 0.75rem 1.5rem !important;
box-shadow: var(--shadow) !important;
font-size: 0.9rem !important;
}
.stButton > button:hover {
background: var(--primary-hover) !important;
}
/* Info cards */
.info-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.75rem;
margin: 0.5rem 0;
}
.info-card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.5rem;
}
.info-card-title {
font-weight: 600;
color: var(--text-primary);
font-size: 0.85rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.info-card-value {
color: var(--text-secondary);
font-size: 0.8rem;
line-height: 1.4;
}
.info-card-header i {
font-size: 0.8rem;
color: var(--primary);
}
.info-card-badge {
background: var(--primary);
color: white;
font-size: 0.7rem;
padding: 0.25rem 0.5rem;
border-radius: var(--radius);
font-weight: 600;
}
.info-card-meta {
color: var(--text-secondary);
font-size: 0.7rem;
margin-top: 0.25rem;
font-style: italic;
}
/* Metrics */
.metric-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.75rem;
text-align: center;
box-shadow: var(--shadow);
margin: 0.5rem 0;
}
.metric-value {
font-size: 1.25rem;
font-weight: 700;
color: var(--primary);
margin-bottom: 0.25rem;
}
.metric-label {
font-size: 0.7rem;
color: var(--text-secondary);
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.3px;
}
/* Product cards */
.product-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.5rem;
margin: 1rem 0;
box-shadow: var(--shadow);
position: relative;
overflow: hidden;
}
.product-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 3px;
background: linear-gradient(90deg, var(--primary), var(--success));
}
.product-card:hover {
box-shadow: var(--shadow);
border-color: var(--primary);
}
.product-title {
font-size: 1.125rem;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 1rem;
line-height: 1.4;
}
.product-info {
margin: 0.75rem 0;
color: var(--text-secondary);
line-height: 1.6;
}
.product-price {
color: var(--success);
font-weight: 700;
font-size: 1.1rem;
}
.product-link {
display: inline-flex;
align-items: center;
gap: 0.5rem;
margin-top: 1rem;
padding: 0.75rem 1.5rem;
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
color: white;
text-decoration: none;
border-radius: var(--radius);
font-weight: 600;
transition: all 0.2s ease;
box-shadow: var(--shadow);
}
.product-link:hover {
transform: translateY(-1px);
box-shadow: var(--shadow-lg);
color: white;
}
/* Welcome card */
.welcome-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 2rem;
text-align: center;
margin: 2rem 0;
box-shadow: var(--shadow);
}
.welcome-card h2 {
color: var(--text-primary);
font-weight: 700;
margin-bottom: 1rem;
font-size: 1.5rem;
}
.welcome-card p {
color: var(--text-secondary);
line-height: 1.6;
font-size: 1rem;
}
/* Status pills */
.status-pill {
display: inline-flex;
align-items: center;
gap: 0.375rem;
padding: 0.25rem 0.75rem;
background: var(--surface);
border-radius: var(--radius);
font-size: 0.7rem;
font-weight: 600;
color: var(--text-secondary);
border: 1px solid var(--border);
}
.status-pill.connected {
background: #d1fae5;
color: var(--success);
border-color: var(--success);
}
.status-pill.warning {
background: #fef3c7;
color: orange;
border-color: orange;
}
.status-pill i {
font-size: 0.65rem;
}
/* Loading message */
.loading-message {
background: var(--surface);
color: var(--text-primary);
padding: 1.5rem;
border-radius: var(--radius);
text-align: center;
font-weight: 500;
border: 1px solid var(--border);
box-shadow: var(--shadow);
}
/* Hide unnecessary elements */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
.stDeployButton {display: none;}
/* Responsive design */
@media (max-width: 768px) {
.main .block-container {
padding: 1rem 0.5rem;
}
.app-header {
padding: 2rem 1rem;
}
.app-header h1 {
font-size: 2rem;
}
.sidebar-section {
padding: 1rem;
}
.stChatFloatingInputContainer {
padding: 0.5rem !important;
left: 0 !important; /* Full width on mobile */
right: 0 !important;
display: flex !important;
justify-content: center !important;
align-items: center !important;
}
.stChatInputContainer {
max-width: 95% !important; /* Slightly smaller on mobile for better margins */
}
.stMainBlockContainer {
padding-bottom: 180px !important; /* Increased padding on mobile */
}
}
</style>
<script>
// Auto-scroll to show latest message above fixed input
function scrollToLatestMessage() {
setTimeout(() => {
// Try to get actual input container height
const inputContainer = document.querySelector('.stChatFloatingInputContainer');
let inputHeight = 180; // Updated default fallback
if (inputContainer) {
const rect = inputContainer.getBoundingClientRect();
inputHeight = rect.height;
}
const additionalPadding = 50; // Increased extra space for comfort
const totalOffset = inputHeight + additionalPadding;
// Scroll to bottom but leave space for input bar
const scrollPosition = document.body.scrollHeight - window.innerHeight - totalOffset;
window.scrollTo({
top: Math.max(0, scrollPosition),
behavior: 'smooth'
});
}, 500); // Increased timeout for better reliability
}
// Enhanced observer for new messages
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
// Check if new chat messages were added
const newNodes = Array.from(mutation.addedNodes);
const hasChatMessage = newNodes.some(node =>
node.nodeType === Node.ELEMENT_NODE &&
(node.querySelector('[data-testid="stChatMessage"]') ||
node.getAttribute && node.getAttribute('data-testid') === 'stChatMessage')
);
if (hasChatMessage) {
scrollToLatestMessage();
}
}
});
});
// Start observing when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
const targetNode = document.body;
observer.observe(targetNode, {
childList: true,
subtree: true
});
});
</script>
""", unsafe_allow_html=True)
@st.cache_resource
def initialize_components():
"""Initialize the database manager and agent (cached for performance)."""
try:
# Single shared database manager for all users
db_manager = MongoDBManager()
return db_manager
except Exception as e:
logger.error(f"Failed to initialize components: {e}")
st.error(f"⚠️ Failed to initialize components: {str(e)}")
return None
def cleanup_idle_sessions():
"""Clean up idle user sessions to prevent memory leaks."""
current_time = datetime.now()
timeout_minutes = 30 # Clean sessions idle for more than 30 minutes
keys_to_remove = []
for key in st.session_state.keys():
if isinstance(key, str) and key.startswith("agent_"):
# Check if session has been idle
last_activity = st.session_state.get(f"{key}_last_activity", current_time)
if isinstance(last_activity, datetime) and (current_time - last_activity).total_seconds() > timeout_minutes * 60:
keys_to_remove.append(key)
keys_to_remove.append(f"{key}_last_activity")
for key in keys_to_remove:
if key in st.session_state:
del st.session_state[key]
if keys_to_remove:
logger.info(f"Cleaned up {len(keys_to_remove)//2} idle sessions")
def get_user_agent(db_manager, user_id: Optional[str] = None):
"""Get or create user-specific agent with shared database connection."""
if not user_id:
user_id = st.session_state.get("user_id", str(uuid.uuid4())[:8])
st.session_state.user_id = user_id
# Clean up idle sessions periodically
if len([k for k in st.session_state.keys() if isinstance(k, str) and k.startswith("agent_")]) > 5:
cleanup_idle_sessions()
# Create lightweight agent per user but share database connection
agent_key = f"agent_{user_id}"
activity_key = f"{agent_key}_last_activity"
if agent_key not in st.session_state:
st.session_state[agent_key] = KingArthurBakingAgent(
db_manager=db_manager,
user_id=user_id
)
# Update last activity
st.session_state[activity_key] = datetime.now()
return st.session_state[agent_key]
def render_sidebar(db_manager: Optional[MongoDBManager]):
with st.sidebar:
# Enhanced header
st.markdown("""
<div class="sidebar-section">
<h3><i class="fas fa-bread-slice"></i> King Arthur Baking AI</h3>
<div class="info-card-value">Professional baking guidance & product recommendations</div>
</div>
""", unsafe_allow_html=True)
# Controls
col1, col2 = st.columns(2)
with col1:
if st.button("🔄 New Chat", use_container_width=True):
# Clear chat history and reset conversation thread
st.session_state.messages = []
if "thread_id" in st.session_state:
del st.session_state.thread_id
st.rerun()
with col2:
if st.button("📥 Export", use_container_width=True):
if "messages" in st.session_state and st.session_state.messages:
chat_export = json.dumps(st.session_state.messages, indent=2)
st.download_button(
"JSON",
chat_export,
f"chat_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
"application/json",
use_container_width=True
)
# Enhanced stats
render_enhanced_stats(db_manager)
# Enhanced status
render_enhanced_status(db_manager)
def render_chat_view():
# Professional header
st.markdown("""
<div class="app-header">
<h1>🍞 King Arthur Baking AI</h1>
<p>Professional baking guidance and product recommendations</p>
</div>
""", unsafe_allow_html=True)
# Initialize chat history and thread_id in session state
if "messages" not in st.session_state:
st.session_state.messages = []
# Initialize thread_id for conversation memory
if "thread_id" not in st.session_state:
st.session_state.thread_id = f"conversation_{str(uuid.uuid4())[:8]}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
# Welcome message for new users
if not st.session_state.messages:
st.markdown("""
<div class="welcome-card">
<h2>Welcome to your baking assistant</h2>
<p>Ask about products, recipes, techniques, or get personalized recommendations for your baking projects.</p>
</div>
""", unsafe_allow_html=True)
# Chat history
for message in st.session_state.messages:
with st.chat_message(name=message["role"]):
st.markdown(message["content"])
if message.get("products"):
render_product_cards(message["products"])
def main():
st.set_page_config(
page_title="King Arthur Baking AI",
layout="centered",
initial_sidebar_state="expanded",
page_icon="🍞"
)
apply_professional_styles()
# Initialize components (cached)
db_manager = initialize_components()
if not db_manager:
st.stop()
render_sidebar(db_manager)
render_chat_view()
# --- Chat Input ---
prompt = st.chat_input("Ask about King Arthur Baking products or techniques...")
if prompt:
# Basic validation
if len(prompt.strip()) < 3:
st.error("Please enter a longer question.")
return
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Process response with spinner
with st.spinner("Processing your request..."):
try:
# Get user-specific agent
agent = get_user_agent(db_manager)
# Pass thread_id for conversation memory
response = agent.chat(prompt, thread_id=st.session_state.thread_id)
if isinstance(response, dict):
# Try to get content from the formatted response first
content = response.get("response", "")
# Fallback to extracting from messages if response field is empty
if not content and response.get("messages"):
try:
last_message = response["messages"][-1]
content = getattr(last_message, 'content', str(last_message))
except (IndexError, AttributeError):
content = "I couldn't process your request."
# Get products from the response
products = response.get("products", [])
# Ensure content is not empty
if not content:
content = "I processed your request successfully."
else:
content = str(response) if response else "I couldn't generate a response."
products = []
# Display assistant response
with st.chat_message("assistant"):
st.markdown(content)
if products:
render_product_cards(products)
# Save to session
st.session_state.messages.append({
"role": "assistant",
"content": content,
"products": products
})
# Auto-scroll to show latest message above fixed input
st.markdown(
'<script>setTimeout(() => { if (typeof scrollToLatestMessage !== "undefined") { scrollToLatestMessage(); } else { window.scrollTo(0, document.body.scrollHeight - 180); } }, 300);</script>',
unsafe_allow_html=True
)
except Exception as e:
error_msg = "Sorry, I encountered an error. Please try again."
logger.error(f"Chat error: {e}")
# Display error in chat message
with st.chat_message("assistant"):
st.error(error_msg)
st.session_state.messages.append({
"role": "assistant",
"content": error_msg,
"products": []
})
# Auto-scroll to show latest message above fixed input
st.markdown(
'<script>setTimeout(() => { if (typeof scrollToLatestMessage !== "undefined") { scrollToLatestMessage(); } else { window.scrollTo(0, document.body.scrollHeight - 180); } }, 300);</script>',
unsafe_allow_html=True
)
# --- [ HELPER FUNCTIONS ] ---
def render_product_cards(products: List[Dict]):
"""Render minimal, professional product cards."""
if not products:
return
st.markdown("### 🛍️ Recommended Products")
# Display up to 4 products for cleaner layout
products_to_show = products[:4]
cols = st.columns(min(len(products_to_show), 2))
for i, product in enumerate(products_to_show):
col = cols[i % len(cols)]
with col:
try:
name = str(product.get('name', 'Unknown Product')).replace('"', '"').replace("'", "'")
price = str(product.get('price', 'Price not available'))
description = str(product.get('description', 'No description available'))
url = product.get('url', '#')
# Clean truncation
if len(description) > 100:
description = description[:97] + "..."
# Price formatting
if price != 'Price not available' and not price.startswith('$'):
if price.replace('.', '').replace(',', '').isdigit():
price = f"${price}"
st.markdown(f"""
<div class="product-card">
<div class="product-title">{name}</div>
<div class="product-info"><strong>Price:</strong> <span class="product-price">{price}</span></div>
<div class="product-info">{description}</div>
<a href="{url}" target="_blank" class="product-link">
<i class="fas fa-external-link-alt"></i>
View Product
</a>
</div>
""", unsafe_allow_html=True)
except Exception as e:
logger.error(f"Error rendering product card: {e}")
col.error("Unable to load product")
# Show additional count
if len(products) > 4:
st.caption(f"Showing 4 of {len(products)} products")
def render_enhanced_stats(db_manager: Optional[MongoDBManager]):
"""Display enhanced statistics with more details."""
st.markdown("""
<div class="sidebar-section">
<h3><i class="fas fa-chart-line"></i> Statistics</h3>
</div>
""", unsafe_allow_html=True)
try:
if db_manager:
stats = db_manager.get_stats()
total_products = stats.get('total_products', 0)
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{total_products:,}</div>
<div class="metric-label">Products Available</div>
</div>
""", unsafe_allow_html=True)
except Exception as e:
logger.error(f"Could not render stats: {e}")
# Message analytics
if "messages" in st.session_state:
messages_count = len(st.session_state.messages)
user_messages = len([m for m in st.session_state.messages if m["role"] == "user"])
st.markdown(f"""
<div class="info-card">
<div class="info-card-header">
<div class="info-card-title">
<i class="fas fa-comments"></i> Conversation
</div>
<div class="info-card-badge">{messages_count}</div>
</div>
<div class="info-card-value">{user_messages} questions asked</div>
</div>
""", unsafe_allow_html=True)
def render_enhanced_status(db_manager: Optional[MongoDBManager]):
"""Display enhanced system status with details."""
st.markdown("""
<div class="sidebar-section">
<h3><i class="fas fa-heartbeat"></i> System Health</h3>
</div>
""", unsafe_allow_html=True)
# Database status with details
try:
if db_manager:
stats = db_manager.get_stats()
total_products = stats.get('total_products', 0)
if total_products > 0:
status_class = "connected"
status_text = "Connected"
status_desc = "Database accessible • Fast response"
else:
status_class = "warning"
status_text = "Limited"
status_desc = "Database accessible • Limited products"
else:
status_class = ""
status_text = "Offline"
status_desc = "Database not accessible"
except Exception as e:
status_class = ""
status_text = "Error"
status_desc = "Connection error occurred"
st.markdown(f"""
<div class="info-card">
<div class="info-card-header">
<div class="info-card-title">
<i class="fas fa-database"></i> Database
</div>
<div class="status-pill {status_class}">
<i class="fas fa-circle"></i> {status_text}
</div>
</div>
<div class="info-card-value">{status_desc}</div>
</div>
""", unsafe_allow_html=True)
# AI status with details
db_status = db_manager is not None if db_manager else False
ai_status = "Online" if db_status else "Offline"
ai_class = "connected" if db_status else ""
ai_desc = "GPT-4 powered • Ready to help" if db_status else "Agent not initialized"
st.markdown(f"""
<div class="info-card">
<div class="info-card-header">
<div class="info-card-title">
<i class="fas fa-robot"></i> AI Assistant
</div>
<div class="status-pill {ai_class}">
<i class="fas fa-circle"></i> {ai_status}
</div>
</div>
<div class="info-card-value">{ai_desc}</div>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()