thanhtai435 commited on
Commit
be9ca41
·
verified ·
1 Parent(s): 1d779ef

Add frontend/streamlit_app.py

Browse files
Files changed (1) hide show
  1. frontend/streamlit_app.py +388 -0
frontend/streamlit_app.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Streamlit Frontend - Agentic BI Dashboard
3
+ ==========================================
4
+ Multi-page dashboard with:
5
+ - KPI Overview
6
+ - Agentic Chat Interface
7
+ - Real-time Monitoring
8
+ - Automated Reports
9
+ """
10
+
11
+ import streamlit as st
12
+ import pandas as pd
13
+ import plotly.express as px
14
+ import plotly.graph_objects as go
15
+ from datetime import datetime, timedelta
16
+ import os
17
+
18
+ # ============================================================
19
+ # PAGE CONFIG
20
+ # ============================================================
21
+
22
+ st.set_page_config(
23
+ page_title="🤖 Agentic BI - E-commerce Analytics",
24
+ page_icon="🤖",
25
+ layout="wide",
26
+ initial_sidebar_state="expanded"
27
+ )
28
+
29
+ # ============================================================
30
+ # SIDEBAR
31
+ # ============================================================
32
+
33
+ with st.sidebar:
34
+ st.image("https://img.icons8.com/3d-fluency/94/robot-2.png", width=80)
35
+ st.title("Agentic BI")
36
+ st.markdown("---")
37
+
38
+ page = st.radio(
39
+ "Navigation",
40
+ ["📊 KPI Dashboard", "💬 AI Analytics Chat", "⚡ Real-time Monitor", "📋 Reports"],
41
+ index=0
42
+ )
43
+
44
+ st.markdown("---")
45
+ st.markdown("### System Status")
46
+
47
+ col1, col2 = st.columns(2)
48
+ with col1:
49
+ st.metric("Kafka", "✅ Online")
50
+ with col2:
51
+ st.metric("PostgreSQL", "✅ Online")
52
+
53
+ col1, col2 = st.columns(2)
54
+ with col1:
55
+ st.metric("ClickHouse", "✅ Online")
56
+ with col2:
57
+ st.metric("Agent", "✅ Ready")
58
+
59
+ st.markdown("---")
60
+ st.caption("Agentic BI v1.0 | Olist E-commerce Dataset")
61
+ st.caption(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
62
+
63
+
64
+ # ============================================================
65
+ # PAGE: KPI DASHBOARD
66
+ # ============================================================
67
+
68
+ if page == "📊 KPI Dashboard":
69
+ st.title("📊 E-commerce KPI Dashboard")
70
+ st.markdown("Real-time business metrics from the Olist marketplace")
71
+
72
+ # Top KPI Cards
73
+ col1, col2, col3, col4, col5 = st.columns(5)
74
+
75
+ with col1:
76
+ st.metric(
77
+ "💰 Total GMV",
78
+ "R$ 15.4M",
79
+ "+12.3%",
80
+ help="Gross Merchandise Value = price + freight"
81
+ )
82
+ with col2:
83
+ st.metric(
84
+ "📦 Total Orders",
85
+ "99,441",
86
+ "+8.5%",
87
+ )
88
+ with col3:
89
+ st.metric(
90
+ "💵 Avg Order Value",
91
+ "R$ 154.78",
92
+ "+3.2%",
93
+ )
94
+ with col4:
95
+ st.metric(
96
+ "🚚 On-time Delivery",
97
+ "93.2%",
98
+ "-1.1%",
99
+ delta_color="inverse"
100
+ )
101
+ with col5:
102
+ st.metric(
103
+ "⭐ Avg Review Score",
104
+ "4.09",
105
+ "+0.05",
106
+ )
107
+
108
+ st.markdown("---")
109
+
110
+ # Charts Row 1
111
+ col1, col2 = st.columns(2)
112
+
113
+ with col1:
114
+ st.subheader("📈 Monthly Revenue Trend")
115
+ # Sample data for demonstration
116
+ months = pd.date_range('2017-01', '2018-10', freq='M')
117
+ revenue = [380000, 450000, 520000, 490000, 560000, 610000,
118
+ 580000, 640000, 750000, 820000, 1200000, 680000,
119
+ 720000, 780000, 850000, 820000, 910000, 980000,
120
+ 1050000, 1100000, 1350000, 900000]
121
+
122
+ fig = px.line(
123
+ x=months, y=revenue,
124
+ labels={'x': 'Month', 'y': 'Revenue (BRL)'},
125
+ template='plotly_white'
126
+ )
127
+ fig.update_traces(line_color='#E53935', line_width=3)
128
+ fig.update_layout(height=350)
129
+ st.plotly_chart(fig, use_container_width=True)
130
+
131
+ with col2:
132
+ st.subheader("🗺️ Revenue by State")
133
+ states = ['SP', 'RJ', 'MG', 'RS', 'PR', 'SC', 'BA', 'DF', 'ES', 'GO']
134
+ state_rev = [5200000, 2100000, 1800000, 1200000, 1100000,
135
+ 800000, 700000, 600000, 500000, 400000]
136
+
137
+ fig = px.bar(
138
+ x=states, y=state_rev,
139
+ labels={'x': 'State', 'y': 'Revenue (BRL)'},
140
+ template='plotly_white',
141
+ color=state_rev,
142
+ color_continuous_scale='Reds'
143
+ )
144
+ fig.update_layout(height=350, showlegend=False)
145
+ st.plotly_chart(fig, use_container_width=True)
146
+
147
+ # Charts Row 2
148
+ col1, col2, col3 = st.columns(3)
149
+
150
+ with col1:
151
+ st.subheader("💳 Payment Methods")
152
+ payment_data = {
153
+ 'Type': ['Credit Card', 'Boleto', 'Voucher', 'Debit Card'],
154
+ 'Count': [73886, 19784, 5775, 1529]
155
+ }
156
+ fig = px.pie(
157
+ payment_data, names='Type', values='Count',
158
+ color_discrete_sequence=['#E53935', '#FF5722', '#FF9800', '#FFC107'],
159
+ template='plotly_white'
160
+ )
161
+ fig.update_layout(height=300)
162
+ st.plotly_chart(fig, use_container_width=True)
163
+
164
+ with col2:
165
+ st.subheader("⭐ Review Distribution")
166
+ scores = [1, 2, 3, 4, 5]
167
+ counts = [11424, 3151, 8179, 19142, 57328]
168
+ colors = ['#E53935', '#FF5722', '#FF9800', '#FFC107', '#4CAF50']
169
+
170
+ fig = px.bar(
171
+ x=scores, y=counts,
172
+ labels={'x': 'Score', 'y': 'Count'},
173
+ template='plotly_white',
174
+ color=scores,
175
+ color_discrete_sequence=colors
176
+ )
177
+ fig.update_layout(height=300, showlegend=False)
178
+ st.plotly_chart(fig, use_container_width=True)
179
+
180
+ with col3:
181
+ st.subheader("📦 Top Categories")
182
+ categories = ['Bed/Bath/Table', 'Health/Beauty', 'Sports/Leisure',
183
+ 'Furniture', 'Computers']
184
+ cat_rev = [1850000, 1520000, 1180000, 980000, 870000]
185
+
186
+ fig = px.barh(
187
+ x=cat_rev, y=categories,
188
+ labels={'x': 'Revenue (BRL)', 'y': ''},
189
+ template='plotly_white',
190
+ color=cat_rev,
191
+ color_continuous_scale='Reds'
192
+ )
193
+ fig.update_layout(height=300, showlegend=False, yaxis={'categoryorder': 'total ascending'})
194
+ st.plotly_chart(fig, use_container_width=True)
195
+
196
+
197
+ # ============================================================
198
+ # PAGE: AI ANALYTICS CHAT
199
+ # ============================================================
200
+
201
+ elif page == "💬 AI Analytics Chat":
202
+ st.title("💬 AI-Powered Analytics Chat")
203
+ st.markdown("Ask questions about the e-commerce data in natural language")
204
+
205
+ # Chat interface
206
+ if "messages" not in st.session_state:
207
+ st.session_state.messages = [
208
+ {
209
+ "role": "assistant",
210
+ "content": (
211
+ "🤖 Xin chào! Tôi là Agentic BI Assistant.\n\n"
212
+ "Tôi có thể giúp bạn phân tích dữ liệu e-commerce Olist. "
213
+ "Hãy hỏi bất kỳ câu hỏi nào, ví dụ:\n\n"
214
+ "- *Doanh thu tháng này so với tháng trước?*\n"
215
+ "- *Top 5 seller có hiệu suất cao nhất?*\n"
216
+ "- *Tỷ lệ giao hàng trễ theo từng bang?*\n"
217
+ "- *Phát hiện bất thường trong doanh thu tuần qua*\n"
218
+ "- *Vẽ biểu đồ xu hướng đơn hàng theo tháng*"
219
+ )
220
+ }
221
+ ]
222
+
223
+ # Display chat history
224
+ for message in st.session_state.messages:
225
+ with st.chat_message(message["role"]):
226
+ st.markdown(message["content"])
227
+
228
+ # Chat input
229
+ if prompt := st.chat_input("Nhập câu hỏi của bạn..."):
230
+ st.session_state.messages.append({"role": "user", "content": prompt})
231
+ with st.chat_message("user"):
232
+ st.markdown(prompt)
233
+
234
+ with st.chat_message("assistant"):
235
+ with st.spinner("🔄 Đang phân tích..."):
236
+ # Here we would call the orchestrator agent
237
+ # For demo, show a template response
238
+ response = (
239
+ f"📊 **Phân tích cho câu hỏi:** *{prompt}*\n\n"
240
+ "🔄 Agent đang xử lý...\n\n"
241
+ "*(Kết nối với Orchestrator Agent để có kết quả thực tế)*"
242
+ )
243
+ st.markdown(response)
244
+ st.session_state.messages.append({"role": "assistant", "content": response})
245
+
246
+ # Quick action buttons
247
+ st.markdown("---")
248
+ st.subheader("⚡ Quick Actions")
249
+
250
+ col1, col2, col3, col4 = st.columns(4)
251
+ with col1:
252
+ if st.button("📈 Revenue Report"):
253
+ st.info("Generating revenue report...")
254
+ with col2:
255
+ if st.button("🔍 Anomaly Scan"):
256
+ st.info("Scanning for anomalies...")
257
+ with col3:
258
+ if st.button("🏪 Seller Analysis"):
259
+ st.info("Analyzing seller performance...")
260
+ with col4:
261
+ if st.button("👥 Customer Segments"):
262
+ st.info("Computing customer segments...")
263
+
264
+
265
+ # ============================================================
266
+ # PAGE: REAL-TIME MONITOR
267
+ # ============================================================
268
+
269
+ elif page == "⚡ Real-time Monitor":
270
+ st.title("⚡ Real-time Streaming Monitor")
271
+ st.markdown("Live metrics from Apache Kafka → Flink → ClickHouse pipeline")
272
+
273
+ # Auto-refresh
274
+ auto_refresh = st.checkbox("Auto-refresh (5s)", value=False)
275
+
276
+ col1, col2, col3, col4 = st.columns(4)
277
+ with col1:
278
+ st.metric("📨 Events/sec", "1,247", "+156")
279
+ with col2:
280
+ st.metric("📦 Orders (5min)", "43", "+5")
281
+ with col3:
282
+ st.metric("💰 Revenue (5min)", "R$ 6,720", "+R$ 890")
283
+ with col4:
284
+ st.metric("🔔 Active Alerts", "2", "-1", delta_color="inverse")
285
+
286
+ st.markdown("---")
287
+
288
+ col1, col2 = st.columns(2)
289
+
290
+ with col1:
291
+ st.subheader("📊 Kafka Topic Throughput")
292
+ topics = ['orders.created', 'orders.items', 'orders.payments',
293
+ 'orders.status', 'orders.delivered', 'reviews.submitted']
294
+ throughput = [245, 312, 198, 156, 89, 67]
295
+
296
+ fig = px.bar(
297
+ x=topics, y=throughput,
298
+ labels={'x': 'Topic', 'y': 'Messages/min'},
299
+ template='plotly_white',
300
+ color=throughput,
301
+ color_continuous_scale='RdYlGn'
302
+ )
303
+ fig.update_layout(height=300, showlegend=False)
304
+ st.plotly_chart(fig, use_container_width=True)
305
+
306
+ with col2:
307
+ st.subheader("🔔 Recent Anomaly Alerts")
308
+ alerts = pd.DataFrame({
309
+ 'Time': ['14:05', '13:42', '12:15', '11:30', '10:45'],
310
+ 'Type': ['Revenue Drop', 'Late Delivery Spike', 'Payment Failure',
311
+ 'Review Score Drop', 'Order Surge'],
312
+ 'Severity': ['🔴 Critical', '🟡 Warning', '🟡 Warning',
313
+ '🟢 Info', '🟢 Info'],
314
+ 'Status': ['Investigating', 'Resolved', 'Resolved',
315
+ 'Monitoring', 'Resolved']
316
+ })
317
+ st.dataframe(alerts, use_container_width=True, hide_index=True)
318
+
319
+ st.markdown("---")
320
+ st.subheader("📈 Pipeline Health")
321
+
322
+ col1, col2, col3 = st.columns(3)
323
+ with col1:
324
+ st.markdown("**Kafka Consumer Lag**")
325
+ st.progress(15, text="15 messages behind")
326
+ with col2:
327
+ st.markdown("**Flink Job Status**")
328
+ st.progress(100, text="All 4 jobs running ✅")
329
+ with col3:
330
+ st.markdown("**ClickHouse Ingestion**")
331
+ st.progress(98, text="98% write success rate")
332
+
333
+
334
+ # ============================================================
335
+ # PAGE: REPORTS
336
+ # ============================================================
337
+
338
+ elif page == "📋 Reports":
339
+ st.title("📋 Automated Reports")
340
+ st.markdown("AI-generated business intelligence reports")
341
+
342
+ st.subheader("📅 Scheduled Reports")
343
+
344
+ reports = pd.DataFrame({
345
+ 'Report': ['Daily Revenue Summary', 'Weekly Seller Performance',
346
+ 'Monthly Customer Analysis', 'Anomaly Investigation Report',
347
+ 'Delivery SLA Report'],
348
+ 'Schedule': ['Daily 8:00 AM', 'Weekly Monday', 'Monthly 1st',
349
+ 'On anomaly detection', 'Daily 6:00 AM'],
350
+ 'Last Run': ['Today 08:00', 'Mon 08:00', 'Apr 01',
351
+ 'Today 14:05', 'Today 06:00'],
352
+ 'Status': ['✅ Generated', '✅ Generated', '✅ Generated',
353
+ '🔄 Generating', '✅ Generated']
354
+ })
355
+
356
+ st.dataframe(reports, use_container_width=True, hide_index=True)
357
+
358
+ st.markdown("---")
359
+
360
+ st.subheader("📄 Latest Report: Daily Revenue Summary")
361
+
362
+ with st.expander("View Report", expanded=True):
363
+ st.markdown("""
364
+ ### 📊 Daily Revenue Summary - April 27, 2026
365
+
366
+ **Generated by: Insight Agent (automatic)**
367
+
368
+ #### Key Findings:
369
+
370
+ 1. **Revenue**: R$ 52,340 (+8.3% vs yesterday, +12.1% vs same day last week)
371
+ 2. **Orders**: 342 orders processed (+15 vs yesterday)
372
+ 3. **AOV**: R$ 153.04 (-2.1% vs yesterday — more small orders)
373
+ 4. **Top Category**: Bed/Bath/Table (R$ 8,920, 17.0% of daily revenue)
374
+ 5. **Delivery SLA**: 94.2% on-time (+1.1% improvement)
375
+
376
+ #### 🔔 Alerts:
377
+ - ⚠️ Payment failures spiked at 14:00-14:05 (12 failures vs baseline 2)
378
+ - ℹ️ Seller #a1b2c3 had 0 orders today (usually averages 5/day)
379
+
380
+ #### 📈 Recommendations:
381
+ - Investigate payment gateway issue at 14:00
382
+ - Contact seller #a1b2c3 to check inventory/status
383
+ - Consider promotion for Sports/Leisure category (declining 3 weeks)
384
+ """)
385
+
386
+ if st.button("🤖 Generate New Report"):
387
+ with st.spinner("Agent generating report..."):
388
+ st.success("Report generation triggered! Check back in 1-2 minutes.")