Spaces:
Sleeping
Sleeping
Commit Β·
fc2d4fb
1
Parent(s): 83e29f1
Complete rewrite: pagination + date filter + JCC colors + full chat router
Browse files
app.py
CHANGED
|
@@ -1,130 +1,322 @@
|
|
| 1 |
-
import os,
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
-
|
| 7 |
-
from datetime import datetime, timedelta
|
| 8 |
import requests as _http
|
|
|
|
| 9 |
warnings.filterwarnings('ignore')
|
| 10 |
-
|
|
|
|
| 11 |
try:
|
| 12 |
import gradio_client.utils as _gcu
|
| 13 |
-
|
| 14 |
-
def
|
| 15 |
-
if not isinstance(
|
| 16 |
-
try: return
|
| 17 |
-
except
|
| 18 |
-
_gcu._json_schema_to_python_type =
|
| 19 |
-
except
|
| 20 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 21 |
|
|
|
|
| 22 |
SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
|
| 23 |
SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "")
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
_cache = {'df': pd.DataFrame(), 'loaded_at': 0}
|
| 27 |
-
|
| 28 |
-
BRANDS = ['Flame & Grill','Pie Palace','Chill Creamery','Sizzle Wings']
|
| 29 |
-
COLORS = ['#c9a84c','#2ecc71','#e74c3c','#9b59b6','#1abc9c','#f39c12','#3498db','#e67e22']
|
| 30 |
|
|
|
|
| 31 |
def load_data():
|
| 32 |
-
if not SUPABASE_URL or not SUPABASE_KEY:
|
|
|
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
if c in df.columns: df[c] = pd.to_numeric(df[c], errors='coerce').fillna(0)
|
| 41 |
-
|
| 42 |
-
df = df.dropna(subset=['date','actual_revenue_usd'])
|
| 43 |
-
df = df[df['actual_revenue_usd'] > 0].
|
| 44 |
-
print("Loaded
|
| 45 |
-
return df
|
| 46 |
-
except Exception as e:
|
|
|
|
|
|
|
| 47 |
def get_df():
|
| 48 |
now = time.time()
|
| 49 |
if now - _cache['loaded_at'] > CACHE_TTL or _cache['df'].empty:
|
| 50 |
fresh = load_data()
|
| 51 |
-
if not fresh.empty:
|
|
|
|
|
|
|
| 52 |
return _cache['df']
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def fmt(v):
|
| 59 |
-
if v >= 1e6: return "${:.2f}M"
|
| 60 |
-
if v >= 1e3: return "${:.0f}K"
|
| 61 |
-
return "${:,.0f}"
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
def build_kpi_html(dff=None):
|
| 65 |
-
if dff is None:
|
| 66 |
-
|
| 67 |
-
if dff.empty:
|
| 68 |
-
|
| 69 |
else:
|
| 70 |
-
|
| 71 |
bud = dff['budget_usd'].sum() if 'budget_usd' in dff.columns else 0
|
| 72 |
-
|
| 73 |
-
tc
|
| 74 |
-
tb
|
| 75 |
-
dr
|
| 76 |
-
return '<div style="background:linear-gradient(135deg,#0d1b2a,#1a3a5c);
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
fig1 = go.Figure()
|
| 88 |
-
fig1.add_trace(go.Bar(
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
daily = dff.groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 95 |
fig3 = go.Figure()
|
| 96 |
-
fig3.add_trace(go.Scatter(
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
fig6 = go.Figure()
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
try:
|
| 122 |
-
df =
|
| 123 |
-
if df.empty:
|
| 124 |
-
|
|
|
|
| 125 |
if seg_type == 'Overall':
|
| 126 |
seg = df.groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 127 |
-
label = 'All Complexes'
|
| 128 |
elif seg_type == 'By Complex':
|
| 129 |
seg = df[df['complex']==seg_name].groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 130 |
label = seg_name
|
|
@@ -133,206 +325,203 @@ def generate_forecast(seg_type, seg_name, horizon):
|
|
| 133 |
label = seg_name
|
| 134 |
else:
|
| 135 |
parts = seg_name.split(' | ')
|
| 136 |
-
if len(parts)==2
|
| 137 |
-
seg = df[(df['complex']==parts[0])&(df['brand']==parts[1])].groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 138 |
-
else:
|
| 139 |
-
seg = df.groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 140 |
label = seg_name
|
| 141 |
seg.columns = ['date','revenue']
|
| 142 |
seg = seg.sort_values('date').reset_index(drop=True)
|
| 143 |
if len(seg) < 7:
|
| 144 |
-
return go.Figure().update_layout(**
|
| 145 |
-
|
| 146 |
-
base = seg['revenue'].tail(min(
|
| 147 |
-
if
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
last_date_str = str(last_date)[:10]
|
| 153 |
fig = go.Figure()
|
| 154 |
-
fig.add_trace(go.Scatter(x=seg['date'],y=seg['revenue'],name='Historical',
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
fig.
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
return fig, summary
|
| 162 |
except Exception as e:
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
elif seg_type == 'By Brand': return gr.update(choices=BRANDS,value=BRANDS[0])
|
| 169 |
-
else:
|
| 170 |
-
opts = [cx+" | "+br for cx in COMPLEXES for br in BRANDS]
|
| 171 |
-
return gr.update(choices=opts,value=opts[0])
|
| 172 |
-
def route_intent(message):
|
| 173 |
-
df = get_df()
|
| 174 |
-
if df.empty: return None
|
| 175 |
m = message.lower()
|
| 176 |
-
latest =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
#
|
| 179 |
-
if any(x in m for x in ['underperform','below budget','struggling','worst','attention','concern','risk']):
|
| 180 |
-
if
|
| 181 |
-
recent =
|
| 182 |
perf = recent.groupby(['complex','brand']).apply(
|
| 183 |
lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum() if x['budget_usd'].sum()>0 else 1
|
| 184 |
-
).reset_index(name='ach')
|
| 185 |
-
under = perf[perf['ach']<0.90]
|
| 186 |
-
if under.empty: return "All sites above 90% budget achievement in last 7 days."
|
| 187 |
-
return "
|
| 188 |
-
["- {}/{}: {:.1f}%"
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
lines = ["vs Prior Month β Overall: ${:,.0f} vs ${:,.0f} ({:+.1f}%)".format(act,pm,(act-pm)/pm*100 if pm else 0)]
|
| 206 |
-
lines += ["- {}: ${:,.0f} vs ${:,.0f} ({:+.1f}%)".format(r.Index,r.actual,r.pm,(r.actual-r.pm)/r.pm*100 if r.pm else 0) for r in cx.itertuples()]
|
| 207 |
return "\n".join(lines)
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
lines
|
|
|
|
| 215 |
return "\n".join(lines)
|
| 216 |
|
| 217 |
-
#
|
| 218 |
-
if any(x in m for x in ['yesterday','today','latest day','last day']):
|
| 219 |
-
day =
|
| 220 |
-
if day.empty: return "No data for {
|
| 221 |
rev = day['actual_revenue_usd'].sum()
|
| 222 |
-
bud = day['budget_usd'].sum() if
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
return "{} revenue: ${:,.0f}{}\nBy complex:\n{}".format(latest.strftime('%b %d'),rev,ach,cx_b)
|
| 226 |
|
|
|
|
| 227 |
if any(x in m for x in ['7-day','7 day','last week','this week','weekly','week']):
|
| 228 |
-
w =
|
| 229 |
-
total = w['actual_revenue_usd'].sum()
|
| 230 |
-
bud = w['budget_usd'].sum() if
|
| 231 |
-
|
| 232 |
-
cx_b = "\n".join([" - {}:
|
| 233 |
-
return "Last 7 days:
|
| 234 |
|
|
|
|
| 235 |
if any(x in m for x in ['30-day','30 day','this month','monthly','month to date','mtd']):
|
| 236 |
-
w =
|
| 237 |
total = w['actual_revenue_usd'].sum()
|
| 238 |
-
bud = w['budget_usd'].sum() if
|
| 239 |
-
|
| 240 |
-
return "Last 30 days: ${:,.0f} total{}".format(total,ach)
|
| 241 |
|
| 242 |
-
# Customer
|
| 243 |
if any(x in m for x in ['customer','spend per','avg spend','average spend','foot traffic','footfall']):
|
| 244 |
-
if 'customer_count' not in
|
| 245 |
-
|
| 246 |
-
avs = df[df['customer_count']>0].groupby('complex').apply(
|
| 247 |
lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()).sort_values(ascending=False)
|
| 248 |
-
|
| 249 |
-
return "Total customers: {:,}\nAvg spend per customer:\n{}".
|
| 250 |
-
total_c, "\n".join(["- {}: ${:.2f}".format(cx,v) for cx,v in avs.items()]))
|
| 251 |
|
| 252 |
# Counter / throughput
|
| 253 |
if any(x in m for x in ['counter','till','throughput','revenue per counter']):
|
| 254 |
-
if 'revenue_per_counter' not in
|
| 255 |
-
rpc =
|
| 256 |
-
return "Revenue per counter:\n" + "\n".join(["- {}:
|
| 257 |
|
| 258 |
# Day of week
|
| 259 |
if any(x in m for x in ['best day','peak day','busiest','day of week','highest day']):
|
| 260 |
-
dow =
|
| 261 |
order = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
|
| 262 |
dow = dow.reindex([d for d in order if d in dow.index])
|
| 263 |
-
return "
|
| 264 |
-
["- {}: ${:,.0f}".format(d,v) for d,v in dow.sort_values(ascending=False).items()])
|
| 265 |
|
| 266 |
# Rankings
|
| 267 |
-
if any(x in m for x in ['rank','ranking','all complex','all brand','compare all','overview']):
|
| 268 |
-
cx =
|
| 269 |
-
br =
|
| 270 |
-
|
| 271 |
-
cx_lines = "\n".join(["{}. {}:
|
| 272 |
-
br_lines = "\n".join(["{}. {}:
|
| 273 |
-
return "Complex ranking:\n{}\n\nBrand ranking:\n{}"
|
| 274 |
-
|
| 275 |
-
# Top /
|
| 276 |
-
if any(x in m for x in ['top','best','highest','leading','number one'
|
| 277 |
-
g_cx=
|
| 278 |
-
|
|
|
|
| 279 |
|
|
|
|
| 280 |
if any(x in m for x in ['worst','lowest','bottom','poor','weakest']):
|
| 281 |
-
g_cx=
|
| 282 |
-
|
|
|
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
|
|
|
| 288 |
|
| 289 |
-
# Complex Γ Brand
|
| 290 |
for cx in COMPLEXES:
|
| 291 |
for br in BRANDS:
|
| 292 |
if cx.lower() in m and br.lower() in m:
|
| 293 |
-
sub=
|
| 294 |
if not sub.empty:
|
| 295 |
-
bud=sub['budget_usd'].sum() if
|
| 296 |
-
|
| 297 |
-
return "{}/{}: ${:,.0f} total{}, ${:,.0f}/day avg".format(
|
| 298 |
-
cx,br,sub['actual_revenue_usd'].sum(),ach,sub['actual_revenue_usd'].mean())
|
| 299 |
|
| 300 |
for cx in COMPLEXES:
|
| 301 |
if cx.lower() in m:
|
| 302 |
-
sub=
|
| 303 |
-
bud=sub['budget_usd'].sum() if
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
return "{}: ${:,.0f} total{}\nBy brand:\n{}".format(cx,sub['actual_revenue_usd'].sum(),ach,br_b)
|
| 307 |
|
| 308 |
for br in BRANDS:
|
| 309 |
if br.lower() in m:
|
| 310 |
-
sub=
|
| 311 |
-
bud=sub['budget_usd'].sum() if
|
| 312 |
-
|
| 313 |
-
return "{}:
|
| 314 |
|
| 315 |
return None
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
if
|
| 319 |
-
cx_rev =
|
| 320 |
-
br_rev =
|
| 321 |
-
has_bud = 'budget_usd' in
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
cx_lines = "\n".join(["-
|
| 326 |
-
br_lines = "\n".join(["-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
bud_ach = (total / df['budget_usd'].sum() * 100) if 'budget_usd' in df.columns and df['budget_usd'].sum()>0 else None
|
| 330 |
-
return f"""You are a QSR operations intelligence assistant for Savanna QSR Group, Zimbabwe.
|
| 331 |
-
You have access to live operational data from {len(df)} records covering {date_range}.
|
| 332 |
-
|
| 333 |
-
TOTAL REVENUE: ${total:,.2f}{(" (budget achievement: {:.1f}%)".format(bud_ach)) if bud_ach else ""}
|
| 334 |
-
TOP COMPLEX: {top_cx}
|
| 335 |
-
TOP BRAND: {top_br}
|
| 336 |
|
| 337 |
REVENUE BY COMPLEX:
|
| 338 |
{cx_lines}
|
|
@@ -340,77 +529,165 @@ REVENUE BY COMPLEX:
|
|
| 340 |
REVENUE BY BRAND:
|
| 341 |
{br_lines}
|
| 342 |
|
| 343 |
-
|
| 344 |
-
|
| 345 |
|
| 346 |
-
Answer
|
| 347 |
|
| 348 |
-
def chat(message, history):
|
| 349 |
if not message or not message.strip(): return ""
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
|
|
|
| 353 |
for h in (history or []):
|
| 354 |
-
if isinstance(h,
|
| 355 |
-
|
| 356 |
-
if h[
|
| 357 |
-
|
| 358 |
-
|
| 359 |
try:
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
"""
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
| 378 |
kpi_header = gr.HTML(value=build_kpi_html())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
with gr.Tabs():
|
| 380 |
-
|
|
|
|
|
|
|
| 381 |
with gr.Row():
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
dash_btn = gr.Button("Load Dashboard", variant="primary")
|
| 385 |
-
refresh_btn = gr.Button("Refresh Data", variant="secondary")
|
| 386 |
-
refresh_msg = gr.Markdown()
|
| 387 |
-
with gr.Row(): ch1=gr.Plot(show_label=False); ch2=gr.Plot(show_label=False)
|
| 388 |
-
with gr.Row(): ch3=gr.Plot(show_label=False); ch4=gr.Plot(show_label=False)
|
| 389 |
-
with gr.Row(): ch5=gr.Plot(show_label=False); ch6=gr.Plot(show_label=False)
|
| 390 |
-
dash_btn.click(build_dashboard,[period_sel],[kpi_header,ch1,ch2,ch3,ch4,ch5,ch6])
|
| 391 |
-
period_sel.change(build_dashboard,[period_sel],[kpi_header,ch1,ch2,ch3,ch4,ch5,ch6])
|
| 392 |
-
refresh_btn.click(refresh_data,[],[kpi_header,refresh_msg])
|
| 393 |
-
with gr.TabItem("Forecast"):
|
| 394 |
with gr.Row():
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
horizon = gr.Radio(choices=["7","14","30","60"],value="30",label="Horizon (days)")
|
| 398 |
-
fc_btn = gr.Button("Generate", variant="primary")
|
| 399 |
-
fc_chart = gr.Plot(show_label=False); fc_summary = gr.Markdown()
|
| 400 |
-
seg_type.change(update_seg_choices,[seg_type],[seg_name])
|
| 401 |
-
fc_btn.click(generate_forecast,[seg_type,seg_name,horizon],[fc_chart,fc_summary])
|
| 402 |
-
with gr.TabItem("Intelligence Chat"):
|
| 403 |
-
chatbot_box = gr.Chatbot(height=420,show_label=False)
|
| 404 |
with gr.Row():
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, time, warnings
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import plotly.graph_objects as go
|
|
|
|
|
|
|
| 6 |
import requests as _http
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
warnings.filterwarnings('ignore')
|
| 9 |
+
|
| 10 |
+
# ββ Gradio 5.x schema bug patch βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
try:
|
| 12 |
import gradio_client.utils as _gcu
|
| 13 |
+
_orig = _gcu._json_schema_to_python_type
|
| 14 |
+
def _safe(s, d):
|
| 15 |
+
if not isinstance(s, dict): return "any"
|
| 16 |
+
try: return _orig(s, d)
|
| 17 |
+
except: return "any"
|
| 18 |
+
_gcu._json_schema_to_python_type = _safe
|
| 19 |
+
except: pass
|
|
|
|
| 20 |
|
| 21 |
+
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
|
| 23 |
SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "")
|
| 24 |
+
OPENAI_KEY = os.environ.get("OPENAI_API_KEY", "")
|
| 25 |
+
COMPLEXES = ['Westgate Mall', 'City Centre', 'Eastpark', 'Northgate']
|
| 26 |
+
BRANDS = ['Flame & Grill', 'Pie Palace', 'Chill Creamery', 'Sizzle Wings']
|
| 27 |
+
|
| 28 |
+
# Stores Intelligence colour palette
|
| 29 |
+
C_GOLD = '#c9a84c'
|
| 30 |
+
C_NAVY = '#1e2d5e'
|
| 31 |
+
C_TEAL = '#1abc9c'
|
| 32 |
+
C_RED = '#e74c3c'
|
| 33 |
+
C_PURPLE = '#9b59b6'
|
| 34 |
+
C_BG = '#0a1628'
|
| 35 |
+
C_PLOT = '#0d1f38'
|
| 36 |
+
C_GRID = '#1a3a6e'
|
| 37 |
+
C_TEXT = '#c8d8f0'
|
| 38 |
+
BAR_COLS = [C_GOLD, C_NAVY, C_TEAL, C_RED, C_PURPLE, '#2ecc71', '#e67e22', '#3498db']
|
| 39 |
+
|
| 40 |
_cache = {'df': pd.DataFrame(), 'loaded_at': 0}
|
| 41 |
+
CACHE_TTL = 300
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
# ββ Data layer β paginated so we get ALL rows βββββββββββββββββββββββββββββββββ
|
| 44 |
def load_data():
|
| 45 |
+
if not SUPABASE_URL or not SUPABASE_KEY:
|
| 46 |
+
print("Supabase not configured"); return pd.DataFrame()
|
| 47 |
try:
|
| 48 |
+
all_rows, offset, batch = [], 0, 1000
|
| 49 |
+
while True:
|
| 50 |
+
r = _http.get(
|
| 51 |
+
f"{SUPABASE_URL}/rest/v1/daily_input?select=*&order=date&limit={batch}&offset={offset}",
|
| 52 |
+
headers={"apikey": SUPABASE_KEY, "Authorization": "Bearer " + SUPABASE_KEY}
|
| 53 |
+
)
|
| 54 |
+
if r.status_code != 200: print("HTTP", r.status_code); break
|
| 55 |
+
rows = r.json()
|
| 56 |
+
if not rows: break
|
| 57 |
+
all_rows.extend(rows)
|
| 58 |
+
if len(rows) < batch: break
|
| 59 |
+
offset += batch
|
| 60 |
+
if not all_rows: return pd.DataFrame()
|
| 61 |
+
df = pd.DataFrame(all_rows)
|
| 62 |
+
nums = ['actual_revenue_usd','budget_usd','customer_count','prior_month_actual',
|
| 63 |
+
'prior_year_actual','variance_vs_budget','variance_pct',
|
| 64 |
+
'avg_spend_per_cust','revenue_per_counter','counters_open',
|
| 65 |
+
'vs_prior_month_pct','vs_prior_year_pct','is_holiday']
|
| 66 |
+
for c in nums:
|
| 67 |
if c in df.columns: df[c] = pd.to_numeric(df[c], errors='coerce').fillna(0)
|
| 68 |
+
df['date'] = pd.to_datetime(df['date'], errors='coerce')
|
| 69 |
+
df = df.dropna(subset=['date','actual_revenue_usd'])
|
| 70 |
+
df = df[df['actual_revenue_usd'] > 0].sort_values('date').reset_index(drop=True)
|
| 71 |
+
print(f"Loaded {len(df)} rows ({df['date'].min().date()} β {df['date'].max().date()})")
|
| 72 |
+
return df
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print("Load error:", e); return pd.DataFrame()
|
| 75 |
+
|
| 76 |
def get_df():
|
| 77 |
now = time.time()
|
| 78 |
if now - _cache['loaded_at'] > CACHE_TTL or _cache['df'].empty:
|
| 79 |
fresh = load_data()
|
| 80 |
+
if not fresh.empty:
|
| 81 |
+
_cache['df'] = fresh
|
| 82 |
+
_cache['loaded_at'] = now
|
| 83 |
return _cache['df']
|
| 84 |
+
|
| 85 |
+
def filter_df(date_from, date_to):
|
| 86 |
+
df = get_df()
|
| 87 |
+
if df.empty: return df
|
| 88 |
+
try:
|
| 89 |
+
if date_from and str(date_from).strip():
|
| 90 |
+
df = df[df['date'] >= pd.to_datetime(str(date_from).strip())]
|
| 91 |
+
if date_to and str(date_to).strip():
|
| 92 |
+
df = df[df['date'] <= pd.to_datetime(str(date_to).strip())]
|
| 93 |
+
except: pass
|
| 94 |
+
return df
|
| 95 |
+
|
| 96 |
+
print("Loading data..."); _ = get_df()
|
| 97 |
+
|
| 98 |
+
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 99 |
def fmt(v):
|
| 100 |
+
if v >= 1e6: return f"${v/1e6:.2f}M"
|
| 101 |
+
if v >= 1e3: return f"${v/1e3:.0f}K"
|
| 102 |
+
return f"${v:,.0f}"
|
| 103 |
+
|
| 104 |
+
def dark_layout(title, height=320, margin=None):
|
| 105 |
+
m = margin or dict(l=150, r=30, t=45, b=40)
|
| 106 |
+
return dict(
|
| 107 |
+
title=dict(text=title, font=dict(color=C_GOLD, size=13), x=0),
|
| 108 |
+
paper_bgcolor=C_BG, plot_bgcolor=C_PLOT,
|
| 109 |
+
font=dict(color=C_TEXT, family='Arial', size=11),
|
| 110 |
+
height=height,
|
| 111 |
+
xaxis=dict(gridcolor=C_GRID, linecolor=C_GRID, tickfont=dict(color=C_TEXT), title_font=dict(color=C_TEXT)),
|
| 112 |
+
yaxis=dict(gridcolor=C_GRID, linecolor=C_GRID, tickfont=dict(color=C_TEXT), title_font=dict(color=C_TEXT)),
|
| 113 |
+
legend=dict(bgcolor='rgba(10,22,40,0.85)', bordercolor=C_GRID, borderwidth=1, font=dict(color=C_TEXT)),
|
| 114 |
+
margin=m
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def horiz_bar(x_vals, y_labels, colors, texts, title, height=280):
|
| 118 |
+
"""Horizontal bar with values inside, matching Stores Intelligence style."""
|
| 119 |
+
fig = go.Figure()
|
| 120 |
+
# Pick text color: dark for gold, white for navy/dark
|
| 121 |
+
text_colors = []
|
| 122 |
+
for c in (colors if isinstance(colors, list) else [colors]*len(x_vals)):
|
| 123 |
+
text_colors.append('#0a1628' if c in (C_GOLD, C_TEAL, '#2ecc71') else '#ffffff')
|
| 124 |
+
fig.add_trace(go.Bar(
|
| 125 |
+
x=x_vals, y=y_labels, orientation='h',
|
| 126 |
+
marker=dict(color=colors if isinstance(colors, list) else [colors]*len(x_vals),
|
| 127 |
+
line=dict(color=C_GRID, width=1)),
|
| 128 |
+
text=texts,
|
| 129 |
+
textposition='inside',
|
| 130 |
+
insidetextanchor='middle',
|
| 131 |
+
textfont=dict(color=text_colors if len(set(text_colors))>1 else text_colors[0],
|
| 132 |
+
size=12, family='Arial')
|
| 133 |
+
))
|
| 134 |
+
fig.update_layout(**dark_layout(title, height=height))
|
| 135 |
+
return fig
|
| 136 |
+
|
| 137 |
+
# ββ KPI header ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 138 |
def build_kpi_html(dff=None):
|
| 139 |
+
if dff is None: dff = get_df()
|
| 140 |
+
if dff is not None and not isinstance(dff, pd.DataFrame): dff = get_df()
|
| 141 |
+
if dff is None or dff.empty:
|
| 142 |
+
rev, ach, tc, tb, dr = "--", "--", "--", "--", "No data"
|
| 143 |
else:
|
| 144 |
+
rev = fmt(dff['actual_revenue_usd'].sum())
|
| 145 |
bud = dff['budget_usd'].sum() if 'budget_usd' in dff.columns else 0
|
| 146 |
+
ach = f"{dff['actual_revenue_usd'].sum()/bud*100:.1f}%" if bud > 0 else "--"
|
| 147 |
+
tc = dff.groupby('complex')['actual_revenue_usd'].sum().idxmax()
|
| 148 |
+
tb = dff.groupby('brand')['actual_revenue_usd'].sum().idxmax()
|
| 149 |
+
dr = f"{dff['date'].min().strftime('%b %d, %Y')} β {dff['date'].max().strftime('%b %d, %Y')}"
|
| 150 |
+
return f'''<div style="background:linear-gradient(135deg,#0d1b2a,#1a3a5c);
|
| 151 |
+
padding:16px 24px;border-radius:10px;border-left:4px solid {C_GOLD};margin-bottom:6px;">
|
| 152 |
+
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
|
| 153 |
+
<div>
|
| 154 |
+
<h2 style="color:#fff;margin:0;font-size:19px;font-weight:700;">π Savanna QSR Intelligence</h2>
|
| 155 |
+
<p style="color:#aed6f1;margin:3px 0 0;font-size:12px;">Live Operations Intelligence Β· Zimbabwe Β· Powered by Supabase</p>
|
| 156 |
+
</div>
|
| 157 |
+
<p style="color:{C_GOLD};margin:0;font-size:10px;font-weight:700;letter-spacing:2px;">NETRISYL INSIGHTS</p>
|
| 158 |
+
</div>
|
| 159 |
+
<div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;">
|
| 160 |
+
{''.join([f'<div style="background:rgba(10,22,40,0.75);padding:8px 16px;border-radius:7px;border:1px solid {C_GRID};text-align:center;min-width:80px;"><div style="color:{C_GOLD};font-size:16px;font-weight:700;">{v}</div><div style="color:#7fb3d3;font-size:10px;">{l}</div></div>'
|
| 161 |
+
for v,l in [(rev,"Total Revenue"),(ach,"Budget Ach."),(tc,"Top Complex"),(tb,"Top Brand"),(dr,"Date Range")]])}
|
| 162 |
+
</div>
|
| 163 |
+
</div>'''
|
| 164 |
+
|
| 165 |
+
# ββ Dashboard βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 166 |
+
def build_dashboard(date_from, date_to):
|
| 167 |
+
dff = filter_df(date_from, date_to)
|
| 168 |
+
kpi = build_kpi_html(dff)
|
| 169 |
+
if dff.empty:
|
| 170 |
+
e = go.Figure().update_layout(**dark_layout("No data β click Refresh"))
|
| 171 |
+
return kpi, e, e, e, e, e, e
|
| 172 |
+
|
| 173 |
+
# 1. Revenue by Complex β gold actual bar + navy budget overlay
|
| 174 |
+
cx = dff.groupby('complex').agg(
|
| 175 |
+
actual=('actual_revenue_usd','sum'), budget=('budget_usd','sum')
|
| 176 |
+
).reset_index().sort_values('actual', ascending=True)
|
| 177 |
fig1 = go.Figure()
|
| 178 |
+
fig1.add_trace(go.Bar(
|
| 179 |
+
name='Budget', x=cx['budget'], y=cx['complex'], orientation='h',
|
| 180 |
+
marker=dict(color='#2a4a8a', line=dict(color=C_GRID, width=1)), opacity=0.55
|
| 181 |
+
))
|
| 182 |
+
fig1.add_trace(go.Bar(
|
| 183 |
+
name='Actual', x=cx['actual'], y=cx['complex'], orientation='h',
|
| 184 |
+
marker=dict(color=C_GOLD, line=dict(color=C_NAVY, width=1)),
|
| 185 |
+
text=[fmt(v) for v in cx['actual']], textposition='inside',
|
| 186 |
+
insidetextanchor='middle', textfont=dict(color='#0a1628', size=12, family='Arial')
|
| 187 |
+
))
|
| 188 |
+
fig1.update_layout(**dark_layout("Revenue by Complex β Actual vs Budget", height=300),
|
| 189 |
+
barmode='overlay',
|
| 190 |
+
xaxis_tickprefix='$', xaxis_tickformat=',.0f')
|
| 191 |
+
|
| 192 |
+
# 2. Revenue by Brand
|
| 193 |
+
br = dff.groupby('brand')['actual_revenue_usd'].sum().reset_index().sort_values('actual_revenue_usd', ascending=True)
|
| 194 |
+
bud_br = dff.groupby('brand')['budget_usd'].sum() if 'budget_usd' in dff.columns else None
|
| 195 |
+
texts = []
|
| 196 |
+
for _, row in br.iterrows():
|
| 197 |
+
bv = bud_br[row['brand']] if bud_br is not None and bud_br.sum() > 0 else 0
|
| 198 |
+
ach = f" {row['actual_revenue_usd']/bv*100:.0f}%" if bv > 0 else ""
|
| 199 |
+
texts.append(f"{fmt(row['actual_revenue_usd'])}{ach}")
|
| 200 |
+
fig2 = go.Figure(go.Bar(
|
| 201 |
+
x=br['actual_revenue_usd'], y=br['brand'], orientation='h',
|
| 202 |
+
marker=dict(color=BAR_COLS[:len(br)], line=dict(color=C_GRID, width=1)),
|
| 203 |
+
text=texts, textposition='inside', insidetextanchor='middle',
|
| 204 |
+
textfont=dict(color='#ffffff', size=12, family='Arial')
|
| 205 |
+
))
|
| 206 |
+
fig2.update_layout(**dark_layout("Revenue by Brand", height=280),
|
| 207 |
+
xaxis_tickprefix='$', xaxis_tickformat=',.0f')
|
| 208 |
+
|
| 209 |
+
# 3. Daily Revenue Trend
|
| 210 |
daily = dff.groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 211 |
fig3 = go.Figure()
|
| 212 |
+
fig3.add_trace(go.Scatter(
|
| 213 |
+
x=daily['date'], y=daily['actual_revenue_usd'], name='Actual',
|
| 214 |
+
line=dict(color=C_GOLD, width=2.5), fill='tozeroy',
|
| 215 |
+
fillcolor='rgba(201,168,76,0.10)'
|
| 216 |
+
))
|
| 217 |
+
if 'budget_usd' in dff.columns:
|
| 218 |
+
daily_b = dff.groupby('date')['budget_usd'].sum().reset_index()
|
| 219 |
+
fig3.add_trace(go.Scatter(
|
| 220 |
+
x=daily_b['date'], y=daily_b['budget_usd'], name='Budget',
|
| 221 |
+
line=dict(color='#4a6a9e', width=1.5, dash='dot')
|
| 222 |
+
))
|
| 223 |
+
fig3.update_layout(**dark_layout("Daily Revenue Trend", height=340, margin=dict(l=80,r=30,t=45,b=50)),
|
| 224 |
+
hovermode='x unified',
|
| 225 |
+
yaxis_tickprefix='$', yaxis_tickformat=',.0f')
|
| 226 |
+
|
| 227 |
+
# 4. Avg Spend Per Customer
|
| 228 |
+
if 'customer_count' in dff.columns and dff['customer_count'].sum() > 0:
|
| 229 |
+
avs = dff[dff['customer_count']>0].groupby('complex').apply(
|
| 230 |
+
lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()
|
| 231 |
+
).reset_index(name='avg').sort_values('avg', ascending=True)
|
| 232 |
+
fig4 = go.Figure(go.Bar(
|
| 233 |
+
x=avs['avg'], y=avs['complex'], orientation='h',
|
| 234 |
+
marker=dict(color=C_TEAL, line=dict(color=C_NAVY, width=1)),
|
| 235 |
+
text=[f"${v:.2f}" for v in avs['avg']], textposition='inside',
|
| 236 |
+
insidetextanchor='middle', textfont=dict(color='#0a1628', size=12, family='Arial')
|
| 237 |
+
))
|
| 238 |
+
fig4.update_layout(**dark_layout("Avg Spend Per Customer", height=280),
|
| 239 |
+
xaxis_tickprefix='$', xaxis_tickformat=',.2f')
|
| 240 |
+
else:
|
| 241 |
+
fig4 = go.Figure().update_layout(**dark_layout("No customer data", height=280))
|
| 242 |
+
|
| 243 |
+
# 5. Budget Achievement Heatmap
|
| 244 |
+
if 'budget_usd' in dff.columns and dff['budget_usd'].sum() > 0:
|
| 245 |
+
try:
|
| 246 |
+
heat = dff.groupby(['complex','brand']).apply(
|
| 247 |
+
lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100
|
| 248 |
+
if x['budget_usd'].sum()>0 else 0
|
| 249 |
+
).reset_index(name='ach')
|
| 250 |
+
pivot = heat.pivot(index='complex', columns='brand', values='ach').fillna(0)
|
| 251 |
+
fig5 = go.Figure(go.Heatmap(
|
| 252 |
+
z=pivot.values, x=pivot.columns.tolist(), y=pivot.index.tolist(),
|
| 253 |
+
colorscale=[[0,'#c0392b'],[0.8,'#f39c12'],[1,'#2ecc71']],
|
| 254 |
+
zmid=100, zmin=70, zmax=130,
|
| 255 |
+
text=[[f"{v:.0f}%" for v in row] for row in pivot.values],
|
| 256 |
+
texttemplate="%{text}", textfont=dict(color='white', size=12),
|
| 257 |
+
colorbar=dict(tickfont=dict(color=C_TEXT))
|
| 258 |
+
))
|
| 259 |
+
fig5.update_layout(**dark_layout("Budget Achievement % (Complex Γ Brand)", height=280,
|
| 260 |
+
margin=dict(l=130,r=30,t=45,b=80)))
|
| 261 |
+
except:
|
| 262 |
+
fig5 = go.Figure().update_layout(**dark_layout("Budget heatmap unavailable", height=280))
|
| 263 |
+
else:
|
| 264 |
+
fig5 = go.Figure().update_layout(**dark_layout("No budget data", height=280))
|
| 265 |
+
|
| 266 |
+
# 6. Actual vs Prior Month vs Prior Year
|
| 267 |
+
has_pm = 'prior_month_actual' in dff.columns and dff['prior_month_actual'].sum() > 0
|
| 268 |
+
has_py = 'prior_year_actual' in dff.columns and dff['prior_year_actual'].sum() > 0
|
| 269 |
+
comp = dff.groupby('complex').agg(
|
| 270 |
+
actual=('actual_revenue_usd','sum'),
|
| 271 |
+
**({'pm':('prior_month_actual','sum')} if has_pm else {}),
|
| 272 |
+
**({'py':('prior_year_actual','sum')} if has_py else {})
|
| 273 |
+
).reset_index()
|
| 274 |
fig6 = go.Figure()
|
| 275 |
+
if has_py:
|
| 276 |
+
fig6.add_trace(go.Bar(name='Prior Year', x=comp['complex'], y=comp['py'],
|
| 277 |
+
marker=dict(color=C_NAVY, line=dict(color=C_GRID,width=1)),
|
| 278 |
+
text=[fmt(v) for v in comp['py']], textposition='inside',
|
| 279 |
+
insidetextanchor='middle', textfont=dict(color='#ffffff',size=11)))
|
| 280 |
+
if has_pm:
|
| 281 |
+
fig6.add_trace(go.Bar(name='Prior Month', x=comp['complex'], y=comp['pm'],
|
| 282 |
+
marker=dict(color=C_TEAL, line=dict(color=C_GRID,width=1)),
|
| 283 |
+
text=[fmt(v) for v in comp['pm']], textposition='inside',
|
| 284 |
+
insidetextanchor='middle', textfont=dict(color='#0a1628',size=11)))
|
| 285 |
+
fig6.add_trace(go.Bar(name='This Period', x=comp['complex'], y=comp['actual'],
|
| 286 |
+
marker=dict(color=C_GOLD, line=dict(color=C_NAVY,width=1)),
|
| 287 |
+
text=[fmt(v) for v in comp['actual']], textposition='inside',
|
| 288 |
+
insidetextanchor='middle', textfont=dict(color='#0a1628',size=11)))
|
| 289 |
+
fig6.update_layout(**dark_layout("Actual vs Prior Month vs Prior Year", height=340,
|
| 290 |
+
margin=dict(l=60,r=30,t=45,b=60)),
|
| 291 |
+
barmode='group', hovermode='x unified',
|
| 292 |
+
yaxis_tickprefix='$', yaxis_tickformat=',.0f')
|
| 293 |
+
|
| 294 |
+
return kpi, fig1, fig2, fig3, fig4, fig5, fig6
|
| 295 |
+
|
| 296 |
+
# ββ Forecast ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
GROWTH = 0.05
|
| 298 |
+
DOW = {0:0.85,1:0.90,2:0.92,3:0.95,4:1.05,5:1.20,6:1.15}
|
| 299 |
+
|
| 300 |
+
def update_seg_choices(seg_type):
|
| 301 |
+
if seg_type == 'Overall':
|
| 302 |
+
return gr.update(choices=['All Complexes & Brands'], value='All Complexes & Brands')
|
| 303 |
+
elif seg_type == 'By Complex':
|
| 304 |
+
return gr.update(choices=COMPLEXES, value=COMPLEXES[0])
|
| 305 |
+
elif seg_type == 'By Brand':
|
| 306 |
+
return gr.update(choices=BRANDS, value=BRANDS[0])
|
| 307 |
+
else:
|
| 308 |
+
opts = [f"{cx} | {br}" for cx in COMPLEXES for br in BRANDS]
|
| 309 |
+
return gr.update(choices=opts, value=opts[0])
|
| 310 |
+
|
| 311 |
+
def generate_forecast(seg_type, seg_name, horizon, date_from, date_to):
|
| 312 |
try:
|
| 313 |
+
df = filter_df(date_from, date_to)
|
| 314 |
+
if df.empty:
|
| 315 |
+
return go.Figure().update_layout(**dark_layout("No data for selected range")), "No data."
|
| 316 |
+
h = int(horizon)
|
| 317 |
if seg_type == 'Overall':
|
| 318 |
seg = df.groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 319 |
+
label = 'All Complexes & Brands'
|
| 320 |
elif seg_type == 'By Complex':
|
| 321 |
seg = df[df['complex']==seg_name].groupby('date')['actual_revenue_usd'].sum().reset_index()
|
| 322 |
label = seg_name
|
|
|
|
| 325 |
label = seg_name
|
| 326 |
else:
|
| 327 |
parts = seg_name.split(' | ')
|
| 328 |
+
seg = df[(df['complex']==parts[0])&(df['brand']==parts[1])].groupby('date')['actual_revenue_usd'].sum().reset_index() if len(parts)==2 else df.groupby('date')['actual_revenue_usd'].sum().reset_index()
|
|
|
|
|
|
|
|
|
|
| 329 |
label = seg_name
|
| 330 |
seg.columns = ['date','revenue']
|
| 331 |
seg = seg.sort_values('date').reset_index(drop=True)
|
| 332 |
if len(seg) < 7:
|
| 333 |
+
return go.Figure().update_layout(**dark_layout("Need at least 7 days of data for this segment")), "Insufficient data."
|
| 334 |
+
last = seg['date'].max()
|
| 335 |
+
base = float(seg['revenue'].tail(min(h, len(seg))).mean())
|
| 336 |
+
if np.isnan(base) or base <= 0: base = float(seg['revenue'].mean())
|
| 337 |
+
fc_dates = [last + timedelta(days=i+1) for i in range(h)]
|
| 338 |
+
fc_vals = [round(base * DOW[d.weekday()] * (1+GROWTH), 2) for d in fc_dates]
|
| 339 |
+
upper = [v*1.15 for v in fc_vals]
|
| 340 |
+
lower = [v*0.85 for v in fc_vals]
|
|
|
|
| 341 |
fig = go.Figure()
|
| 342 |
+
fig.add_trace(go.Scatter(x=seg['date'], y=seg['revenue'], name='Historical',
|
| 343 |
+
line=dict(color='#4a7aae', width=1.5), opacity=0.9,
|
| 344 |
+
hovertemplate='%{x|%b %d}<br>$%{y:,.0f}<extra>Historical</extra>'))
|
| 345 |
+
fig.add_trace(go.Scatter(
|
| 346 |
+
x=fc_dates+fc_dates[::-1], y=upper+lower[::-1],
|
| 347 |
+
fill='toself', fillcolor='rgba(201,168,76,0.15)',
|
| 348 |
+
line=dict(color='rgba(0,0,0,0)'), name='Confidence Band', hoverinfo='skip'))
|
| 349 |
+
fig.add_trace(go.Scatter(x=fc_dates, y=fc_vals, name=f'{h}-Day Forecast',
|
| 350 |
+
line=dict(color=C_GOLD, width=2.5, dash='dash'), mode='lines+markers',
|
| 351 |
+
marker=dict(size=5, color=C_GOLD),
|
| 352 |
+
hovertemplate='%{x|%b %d}<br>$%{y:,.0f}<extra>Forecast</extra>'))
|
| 353 |
+
fig.add_vline(x=str(last)[:10], line_dash='dot', line_color=C_GOLD, opacity=0.5)
|
| 354 |
+
layout = dark_layout(f"{label} β {h}-Day Forecast", height=460,
|
| 355 |
+
margin=dict(l=80,r=30,t=60,b=50))
|
| 356 |
+
layout['hovermode'] = 'x unified'
|
| 357 |
+
layout['yaxis_tickprefix'] = '$'
|
| 358 |
+
layout['yaxis_tickformat'] = ',.0f'
|
| 359 |
+
fig.update_layout(**layout)
|
| 360 |
+
total = sum(fc_vals); avg = total/h
|
| 361 |
+
peak = max(fc_vals); peak_d = fc_dates[fc_vals.index(peak)].strftime('%b %d, %Y')
|
| 362 |
+
summary = f"**{h}-Day Forecast β {label}**\n\n| Metric | Value |\n|---|---|\n| Predicted Total | **{fmt(total)}** |\n| Daily Average | **{fmt(avg)}** |\n| Peak Day | **{fmt(peak)}** on {peak_d} |\n| Period | {fc_dates[0].strftime('%b %d')} β {fc_dates[-1].strftime('%b %d, %Y')} |\n\n> *Day-of-week adjusted moving average with 5% growth factor.*"
|
| 363 |
return fig, summary
|
| 364 |
except Exception as e:
|
| 365 |
+
return go.Figure().update_layout(**dark_layout(f"Error: {e}", height=460)), f"Error: {e}"
|
| 366 |
+
|
| 367 |
+
# ββ Intelligence Chat βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 368 |
+
def route_intent(message, dff):
|
| 369 |
+
if dff is None or dff.empty: return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
m = message.lower()
|
| 371 |
+
latest = dff['date'].max()
|
| 372 |
+
has_bud = 'budget_usd' in dff.columns and dff['budget_usd'].sum() > 0
|
| 373 |
+
|
| 374 |
+
def ach_str(actual, budget):
|
| 375 |
+
return f" ({actual/budget*100:.1f}% of budget)" if budget > 0 else ""
|
| 376 |
|
| 377 |
+
# Underperformance
|
| 378 |
+
if any(x in m for x in ['underperform','below budget','struggling','worst','attention','concern','risk','flag']):
|
| 379 |
+
if not has_bud: return "No budget data available."
|
| 380 |
+
recent = dff[dff['date'] >= latest - timedelta(days=7)]
|
| 381 |
perf = recent.groupby(['complex','brand']).apply(
|
| 382 |
lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum() if x['budget_usd'].sum()>0 else 1
|
| 383 |
+
).reset_index(name='ach').sort_values('ach')
|
| 384 |
+
under = perf[perf['ach'] < 0.90]
|
| 385 |
+
if under.empty: return "All sites above 90% budget achievement in the last 7 days. No underperformers."
|
| 386 |
+
return "Sites below 90% budget (last 7 days):\n" + "\n".join(
|
| 387 |
+
[f"- {r.complex} / {r.brand}: {r.ach*100:.1f}%" for r in under.itertuples()])
|
| 388 |
+
|
| 389 |
+
# Budget achievement
|
| 390 |
+
if any(x in m for x in ['budget','achievement','target','variance']):
|
| 391 |
+
if not has_bud: return "No budget data."
|
| 392 |
+
overall = dff['actual_revenue_usd'].sum()/dff['budget_usd'].sum()*100
|
| 393 |
+
cx_ach = dff.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).sort_values(ascending=False)
|
| 394 |
+
br_ach = dff.groupby('brand').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).sort_values(ascending=False)
|
| 395 |
+
return f"Overall budget achievement: {overall:.1f}%\nBy complex:\n" + "\n".join([f" - {cx}: {v:.1f}%" for cx,v in cx_ach.items()]) + "\nBy brand:\n" + "\n".join([f" - {br}: {v:.1f}%" for br,v in br_ach.items()])
|
| 396 |
+
|
| 397 |
+
# Prior month
|
| 398 |
+
if any(x in m for x in ['prior month','last month','sdlm','month on month']):
|
| 399 |
+
if 'prior_month_actual' not in dff.columns or dff['prior_month_actual'].sum()==0: return "No prior month data."
|
| 400 |
+
act = dff['actual_revenue_usd'].sum(); pm = dff['prior_month_actual'].sum()
|
| 401 |
+
cx = dff.groupby('complex').agg(a=('actual_revenue_usd','sum'),p=('prior_month_actual','sum'))
|
| 402 |
+
lines = [f"vs Prior Month β Overall: {fmt(act)} vs {fmt(pm)} ({(act-pm)/pm*100:+.1f}%)"]
|
| 403 |
+
lines += [f" - {r.Index}: {fmt(r.a)} vs {fmt(r.p)} ({(r.a-r.p)/r.p*100:+.1f}%)" for r in cx.itertuples() if r.p>0]
|
|
|
|
|
|
|
| 404 |
return "\n".join(lines)
|
| 405 |
|
| 406 |
+
# Prior year
|
| 407 |
+
if any(x in m for x in ['prior year','last year','sdly','year on year']):
|
| 408 |
+
if 'prior_year_actual' not in dff.columns or dff['prior_year_actual'].sum()==0: return "No prior year data."
|
| 409 |
+
act = dff['actual_revenue_usd'].sum(); py = dff['prior_year_actual'].sum()
|
| 410 |
+
cx = dff.groupby('complex').agg(a=('actual_revenue_usd','sum'),p=('prior_year_actual','sum'))
|
| 411 |
+
lines = [f"vs Prior Year β Overall: {fmt(act)} vs {fmt(py)} ({(act-py)/py*100:+.1f}%)"]
|
| 412 |
+
lines += [f" - {r.Index}: {fmt(r.a)} vs {fmt(r.p)} ({(r.a-r.p)/r.p*100:+.1f}%)" for r in cx.itertuples() if r.p>0]
|
| 413 |
return "\n".join(lines)
|
| 414 |
|
| 415 |
+
# Yesterday / latest day
|
| 416 |
+
if any(x in m for x in ['yesterday','today','latest day','last day','daily']):
|
| 417 |
+
day = dff[dff['date']==latest]
|
| 418 |
+
if day.empty: return f"No data for {latest.strftime('%b %d')}."
|
| 419 |
rev = day['actual_revenue_usd'].sum()
|
| 420 |
+
bud = day['budget_usd'].sum() if has_bud else 0
|
| 421 |
+
cx_b = "\n".join([f" - {r.complex}: {fmt(r.actual_revenue_usd)}" for r in day.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
|
| 422 |
+
return f"{latest.strftime('%b %d, %Y')} revenue: {fmt(rev)}{ach_str(rev,bud)}\nBy complex:\n{cx_b}"
|
|
|
|
| 423 |
|
| 424 |
+
# 7-day / weekly
|
| 425 |
if any(x in m for x in ['7-day','7 day','last week','this week','weekly','week']):
|
| 426 |
+
w = dff[dff['date'] >= latest - timedelta(days=7)]
|
| 427 |
+
total = w['actual_revenue_usd'].sum()
|
| 428 |
+
bud = w['budget_usd'].sum() if has_bud else 0
|
| 429 |
+
davg = w.groupby('date')['actual_revenue_usd'].sum().mean()
|
| 430 |
+
cx_b = "\n".join([f" - {r.complex}: {fmt(r.actual_revenue_usd)}" for r in w.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
|
| 431 |
+
return f"Last 7 days: {fmt(total)} total{ach_str(total,bud)}, avg {fmt(davg)}/day\nBy complex:\n{cx_b}"
|
| 432 |
|
| 433 |
+
# 30-day / MTD
|
| 434 |
if any(x in m for x in ['30-day','30 day','this month','monthly','month to date','mtd']):
|
| 435 |
+
w = dff[dff['date'] >= latest - timedelta(days=30)]
|
| 436 |
total = w['actual_revenue_usd'].sum()
|
| 437 |
+
bud = w['budget_usd'].sum() if has_bud else 0
|
| 438 |
+
return f"Last 30 days: {fmt(total)} total{ach_str(total,bud)}"
|
|
|
|
| 439 |
|
| 440 |
+
# Customer / spend
|
| 441 |
if any(x in m for x in ['customer','spend per','avg spend','average spend','foot traffic','footfall']):
|
| 442 |
+
if 'customer_count' not in dff.columns or dff['customer_count'].sum()==0: return "No customer count data."
|
| 443 |
+
avs = dff[dff['customer_count']>0].groupby('complex').apply(
|
|
|
|
| 444 |
lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()).sort_values(ascending=False)
|
| 445 |
+
tc = int(dff['customer_count'].sum())
|
| 446 |
+
return f"Total customers: {tc:,}\nAvg spend per customer:\n" + "\n".join([f" - {cx}: ${v:.2f}" for cx,v in avs.items()])
|
|
|
|
| 447 |
|
| 448 |
# Counter / throughput
|
| 449 |
if any(x in m for x in ['counter','till','throughput','revenue per counter']):
|
| 450 |
+
if 'revenue_per_counter' not in dff.columns or dff['revenue_per_counter'].sum()==0: return "No counter data."
|
| 451 |
+
rpc = dff[dff['revenue_per_counter']>0].groupby('complex')['revenue_per_counter'].mean().sort_values(ascending=False)
|
| 452 |
+
return "Revenue per counter:\n" + "\n".join([f" - {cx}: {fmt(v)}" for cx,v in rpc.items()])
|
| 453 |
|
| 454 |
# Day of week
|
| 455 |
if any(x in m for x in ['best day','peak day','busiest','day of week','highest day']):
|
| 456 |
+
dow = dff.groupby(dff['date'].dt.day_name())['actual_revenue_usd'].mean()
|
| 457 |
order = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
|
| 458 |
dow = dow.reindex([d for d in order if d in dow.index])
|
| 459 |
+
return "Avg daily revenue by day of week:\n" + "\n".join([f" - {d}: {fmt(v)}" for d,v in dow.sort_values(ascending=False).items()])
|
|
|
|
| 460 |
|
| 461 |
# Rankings
|
| 462 |
+
if any(x in m for x in ['rank','ranking','all complex','all brand','compare all','overview','summary']):
|
| 463 |
+
cx = dff.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False)
|
| 464 |
+
br = dff.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False)
|
| 465 |
+
cx_ach = dff.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if has_bud and x['budget_usd'].sum()>0 else None)
|
| 466 |
+
cx_lines = "\n".join([f" {i+1}. {n}: {fmt(v)}{f' ({cx_ach[n]:.0f}% bud)' if cx_ach[n] else ''}" for i,(n,v) in enumerate(cx.items())])
|
| 467 |
+
br_lines = "\n".join([f" {i+1}. {n}: {fmt(v)}" for i,(n,v) in enumerate(br.items())])
|
| 468 |
+
return f"Complex ranking:\n{cx_lines}\n\nBrand ranking:\n{br_lines}"
|
| 469 |
+
|
| 470 |
+
# Top / best
|
| 471 |
+
if any(x in m for x in ['top','best','highest','leading','number one']):
|
| 472 |
+
g_cx = dff.groupby('complex')['actual_revenue_usd'].sum()
|
| 473 |
+
g_br = dff.groupby('brand')['actual_revenue_usd'].sum()
|
| 474 |
+
return f"Top complex: {g_cx.idxmax()} ({fmt(g_cx.max())})\nTop brand: {g_br.idxmax()} ({fmt(g_br.max())})"
|
| 475 |
|
| 476 |
+
# Worst / lowest
|
| 477 |
if any(x in m for x in ['worst','lowest','bottom','poor','weakest']):
|
| 478 |
+
g_cx = dff.groupby('complex')['actual_revenue_usd'].sum()
|
| 479 |
+
g_br = dff.groupby('brand')['actual_revenue_usd'].sum()
|
| 480 |
+
return f"Lowest complex: {g_cx.idxmin()} ({fmt(g_cx.min())})\nLowest brand: {g_br.idxmin()} ({fmt(g_br.min())})"
|
| 481 |
|
| 482 |
+
# Total
|
| 483 |
+
if any(x in m for x in ['total','overall revenue']):
|
| 484 |
+
total = dff['actual_revenue_usd'].sum()
|
| 485 |
+
bud = dff['budget_usd'].sum() if has_bud else 0
|
| 486 |
+
return f"Total revenue: {fmt(total)}{ach_str(total,bud)} across {len(dff):,} records"
|
| 487 |
|
| 488 |
+
# Complex Γ Brand
|
| 489 |
for cx in COMPLEXES:
|
| 490 |
for br in BRANDS:
|
| 491 |
if cx.lower() in m and br.lower() in m:
|
| 492 |
+
sub = dff[(dff['complex']==cx)&(dff['brand']==br)]
|
| 493 |
if not sub.empty:
|
| 494 |
+
bud = sub['budget_usd'].sum() if has_bud else 0
|
| 495 |
+
return f"{cx} / {br}: {fmt(sub['actual_revenue_usd'].sum())} total{ach_str(sub['actual_revenue_usd'].sum(),bud)}, {fmt(sub['actual_revenue_usd'].mean())}/day avg"
|
|
|
|
|
|
|
| 496 |
|
| 497 |
for cx in COMPLEXES:
|
| 498 |
if cx.lower() in m:
|
| 499 |
+
sub = dff[dff['complex']==cx]
|
| 500 |
+
bud = sub['budget_usd'].sum() if has_bud else 0
|
| 501 |
+
br_b = "\n".join([f" - {r.brand}: {fmt(r.actual_revenue_usd)}" for r in sub.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
|
| 502 |
+
return f"{cx}: {fmt(sub['actual_revenue_usd'].sum())} total{ach_str(sub['actual_revenue_usd'].sum(),bud)}\nBy brand:\n{br_b}"
|
|
|
|
| 503 |
|
| 504 |
for br in BRANDS:
|
| 505 |
if br.lower() in m:
|
| 506 |
+
sub = dff[dff['brand']==br]
|
| 507 |
+
bud = sub['budget_usd'].sum() if has_bud else 0
|
| 508 |
+
cx_b = "\n".join([f" - {r.complex}: {fmt(r.actual_revenue_usd)}" for r in sub.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
|
| 509 |
+
return f"{br}: {fmt(sub['actual_revenue_usd'].sum())} total{ach_str(sub['actual_revenue_usd'].sum(),bud)}\nBy complex:\n{cx_b}"
|
| 510 |
|
| 511 |
return None
|
| 512 |
+
|
| 513 |
+
def build_chat_context(dff):
|
| 514 |
+
if dff is None or dff.empty: return "No data loaded."
|
| 515 |
+
cx_rev = dff.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False)
|
| 516 |
+
br_rev = dff.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False)
|
| 517 |
+
has_bud = 'budget_usd' in dff.columns and dff['budget_usd'].sum() > 0
|
| 518 |
+
total = dff['actual_revenue_usd'].sum()
|
| 519 |
+
bud = dff['budget_usd'].sum() if has_bud else 0
|
| 520 |
+
dr = f"{dff['date'].min().strftime('%b %d, %Y')} to {dff['date'].max().strftime('%b %d, %Y')}"
|
| 521 |
+
cx_lines = "\n".join([f"- {cx}: {fmt(v)}{f' ({v/dff[dff.complex==cx].budget_usd.sum()*100:.0f}% bud)' if has_bud and dff[dff.complex==cx].budget_usd.sum()>0 else ''}" for cx,v in cx_rev.items()])
|
| 522 |
+
br_lines = "\n".join([f"- {br}: {fmt(v)}" for br,v in br_rev.items()])
|
| 523 |
+
return f"""You are the Savanna QSR Intelligence assistant for Netrisyl Insights, Zimbabwe.
|
| 524 |
+
Data range: {dr} | Records: {len(dff):,} | Total revenue: {fmt(total)}{f" ({total/bud*100:.1f}% of budget)" if has_bud else ""}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
|
| 526 |
REVENUE BY COMPLEX:
|
| 527 |
{cx_lines}
|
|
|
|
| 529 |
REVENUE BY BRAND:
|
| 530 |
{br_lines}
|
| 531 |
|
| 532 |
+
Complexes: {', '.join(COMPLEXES)}
|
| 533 |
+
Brands: {', '.join(BRANDS)}
|
| 534 |
|
| 535 |
+
Answer directly and concisely. Always cite figures. Use $ for amounts. Be honest when data is insufficient."""
|
| 536 |
|
| 537 |
+
def chat(message, history, date_from, date_to):
|
| 538 |
if not message or not message.strip(): return ""
|
| 539 |
+
dff = filter_df(date_from, date_to)
|
| 540 |
+
data_ctx = route_intent(message, dff)
|
| 541 |
+
system = build_chat_context(dff)
|
| 542 |
+
msgs = [{"role":"system","content":system}]
|
| 543 |
for h in (history or []):
|
| 544 |
+
if isinstance(h,(list,tuple)) and len(h)==2:
|
| 545 |
+
if h[0]: msgs.append({"role":"user","content":str(h[0])})
|
| 546 |
+
if h[1]: msgs.append({"role":"assistant","content":str(h[1])})
|
| 547 |
+
user_msg = f"{message}\n\n[COMPUTED DATA]: {data_ctx}" if data_ctx else message
|
| 548 |
+
msgs.append({"role":"user","content":user_msg})
|
| 549 |
try:
|
| 550 |
+
r = _http.post("https://api.openai.com/v1/chat/completions",
|
| 551 |
+
headers={"Authorization":f"Bearer {OPENAI_KEY}","Content-Type":"application/json"},
|
| 552 |
+
json={"model":"gpt-4o-mini","messages":msgs,"temperature":0.2,"max_tokens":700})
|
| 553 |
+
return r.json()["choices"][0]["message"]["content"]
|
| 554 |
+
except Exception as e: return f"β οΈ {e}"
|
| 555 |
+
|
| 556 |
+
def refresh_and_apply(date_from, date_to):
|
| 557 |
+
_cache['loaded_at'] = 0
|
| 558 |
+
dff = filter_df(date_from, date_to)
|
| 559 |
+
if dff.empty: return build_kpi_html(), "β οΈ No data β check Supabase connection"
|
| 560 |
+
full = get_df()
|
| 561 |
+
return build_kpi_html(dff), f"β
{len(full):,} rows loaded Β· Showing {len(dff):,} rows for selected range"
|
| 562 |
+
|
| 563 |
+
# ββ CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 564 |
+
CSS = f"""
|
| 565 |
+
body,.gradio-container{{background:{C_BG}!important;font-family:Arial,sans-serif!important;}}
|
| 566 |
+
.tab-nav{{background:#0d1628!important;border-bottom:2px solid {C_GRID}!important;padding:0 8px!important;}}
|
| 567 |
+
button[class*="tab-"]{{color:#7fb3d3!important;background:transparent!important;border:none!important;
|
| 568 |
+
border-bottom:3px solid transparent!important;padding:10px 18px!important;font-size:13px!important;font-weight:500!important;}}
|
| 569 |
+
button[class*="tab-"]:hover{{color:#fff!important;background:rgba(201,168,76,0.06)!important;}}
|
| 570 |
+
button[class*="tab-"][class*="selected"],div[role="tablist"] button[aria-selected="true"]{{
|
| 571 |
+
color:{C_GOLD}!important;border-bottom:3px solid {C_GOLD}!important;font-weight:700!important;}}
|
| 572 |
+
.gradio-container *{{color:{C_TEXT};}}
|
| 573 |
+
.gradio-container input,.gradio-container textarea{{
|
| 574 |
+
background:#0d1628!important;color:{C_TEXT}!important;border:1px solid {C_GRID}!important;border-radius:6px!important;}}
|
| 575 |
+
.gradio-container label,.gradio-container .label-wrap span{{color:#a8c8f0!important;}}
|
| 576 |
+
input[type="radio"]{{accent-color:{C_GOLD}!important;}}
|
| 577 |
+
button.primary,button[variant="primary"]{{background:{C_GOLD}!important;color:#0a1628!important;
|
| 578 |
+
font-weight:700!important;border:none!important;border-radius:6px!important;font-size:13px!important;}}
|
| 579 |
+
button.primary:hover{{background:#e0be6a!important;}}
|
| 580 |
+
button.secondary,button[variant="secondary"]{{background:{C_NAVY}!important;color:{C_TEXT}!important;
|
| 581 |
+
border:1px solid {C_GOLD}!important;border-radius:6px!important;}}
|
| 582 |
+
.gradio-container .block,.gradio-container .form{{background:#0d1628!important;
|
| 583 |
+
border:1px solid {C_GRID}!important;border-radius:8px!important;}}
|
| 584 |
+
ul[role="listbox"]{{background:#0d1628!important;border:1px solid {C_GOLD}!important;border-radius:6px!important;}}
|
| 585 |
+
ul[role="listbox"] li{{color:#fff!important;background:#0d1628!important;}}
|
| 586 |
+
ul[role="listbox"] li:hover,ul[role="listbox"] li[aria-selected="true"]{{background:{C_GOLD}!important;color:#0a1628!important;}}
|
| 587 |
+
div[class*="chatbot"],.chatbot{{background:#040c1a!important;border-radius:10px!important;}}
|
| 588 |
+
.gradio-container .prose{{color:{C_TEXT}!important;}}
|
| 589 |
+
.gradio-container .prose strong{{color:{C_GOLD}!important;}}
|
| 590 |
+
.gradio-container .prose th{{background:#0d1628!important;color:{C_GOLD}!important;}}
|
| 591 |
+
.gradio-container .prose td{{border-color:{C_GRID}!important;}}
|
| 592 |
+
::-webkit-scrollbar{{width:5px;height:5px;}}
|
| 593 |
+
::-webkit-scrollbar-thumb{{background:{C_GOLD};border-radius:4px;}}
|
| 594 |
+
footer{{display:none!important;}}
|
| 595 |
"""
|
| 596 |
+
|
| 597 |
+
# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 598 |
+
with gr.Blocks(title="Savanna QSR Intelligence | Netrisyl Insights", css=CSS) as demo:
|
| 599 |
+
|
| 600 |
kpi_header = gr.HTML(value=build_kpi_html())
|
| 601 |
+
|
| 602 |
+
# ββ Global date filter ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 603 |
+
with gr.Row():
|
| 604 |
+
date_from = gr.Textbox(label="From Date", placeholder="YYYY-MM-DD", scale=2)
|
| 605 |
+
date_to = gr.Textbox(label="To Date", placeholder="YYYY-MM-DD", scale=2)
|
| 606 |
+
apply_btn = gr.Button("Apply Filter", variant="primary", scale=1)
|
| 607 |
+
refresh_btn = gr.Button("Refresh Data", variant="secondary", scale=1)
|
| 608 |
+
filter_msg = gr.Markdown(scale=3)
|
| 609 |
+
|
| 610 |
with gr.Tabs():
|
| 611 |
+
|
| 612 |
+
# ββ Dashboard βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 613 |
+
with gr.TabItem("π Dashboard"):
|
| 614 |
with gr.Row():
|
| 615 |
+
ch1 = gr.Plot(show_label=False)
|
| 616 |
+
ch2 = gr.Plot(show_label=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 617 |
with gr.Row():
|
| 618 |
+
ch3 = gr.Plot(show_label=False)
|
| 619 |
+
ch4 = gr.Plot(show_label=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 620 |
with gr.Row():
|
| 621 |
+
ch5 = gr.Plot(show_label=False)
|
| 622 |
+
ch6 = gr.Plot(show_label=False)
|
| 623 |
+
|
| 624 |
+
# ββ Forecast ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 625 |
+
with gr.TabItem("π Forecast"):
|
| 626 |
+
gr.HTML(f"<p style='color:#7fb3d3;font-size:12px;margin:8px 0;'>Day-of-week adjusted moving average Β· 5% growth Β· Uses the date range selected above.</p>")
|
| 627 |
+
with gr.Row():
|
| 628 |
+
seg_type = gr.Radio(choices=['Overall','By Complex','By Brand','Complex Γ Brand'],
|
| 629 |
+
value='Overall', label="Segment Type")
|
| 630 |
+
seg_name = gr.Dropdown(choices=['All Complexes & Brands'],
|
| 631 |
+
value='All Complexes & Brands', label="Segment", interactive=True)
|
| 632 |
+
horizon = gr.Radio(choices=["7","14","30","60"], value="30", label="Horizon (days)")
|
| 633 |
+
fc_btn = gr.Button("β‘ Generate Forecast", variant="primary")
|
| 634 |
+
fc_chart = gr.Plot(show_label=False)
|
| 635 |
+
fc_summary = gr.Markdown()
|
| 636 |
+
|
| 637 |
+
# ββ Chat ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 638 |
+
with gr.TabItem("π¬ Intelligence Chat"):
|
| 639 |
+
gr.HTML(f"""<div style="background:#0d1628;border:1px solid {C_GRID};border-radius:8px;
|
| 640 |
+
padding:12px 16px;margin:8px 0 12px;">
|
| 641 |
+
<p style="color:{C_GOLD};font-weight:700;margin:0 0 5px;font-size:13px;">
|
| 642 |
+
π‘ Ask anything about Savanna QSR Group operations</p>
|
| 643 |
+
<p style="color:#7fb3d3;font-size:12px;margin:0;">
|
| 644 |
+
"Which complex is below budget?" Β· "Compare prior month revenue" Β·
|
| 645 |
+
"What's the 7-day trend?" Β· "Avg spend per customer?" Β·
|
| 646 |
+
"Rank all brands" Β· "Which site needs attention?"</p></div>""")
|
| 647 |
+
chatbot_box = gr.Chatbot(height=440, show_label=False)
|
| 648 |
+
with gr.Row():
|
| 649 |
+
chat_input = gr.Textbox(placeholder="Ask about operations...",
|
| 650 |
+
show_label=False, scale=9, container=False)
|
| 651 |
+
send_btn = gr.Button("Send β€", variant="primary", scale=1)
|
| 652 |
+
|
| 653 |
+
gr.HTML(f'<div style="text-align:center;margin-top:14px;padding:10px;border-top:1px solid {C_GRID};"><p style="color:{C_GOLD};font-size:10px;font-weight:700;letter-spacing:2px;margin:0;">NETRISYL INSIGHTS</p><p style="color:#4a6a9e;font-size:10px;margin:4px 0 0;">Data Β· Analytics Β· Intelligence Β· <a href="https://netrisyl.com" style="color:#7fb3d3;">netrisyl.com</a></p></div>')
|
| 654 |
+
|
| 655 |
+
# ββ Wiring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 656 |
+
dash_outputs = [kpi_header, ch1, ch2, ch3, ch4, ch5, ch6]
|
| 657 |
|
| 658 |
+
apply_btn.click(
|
| 659 |
+
fn=lambda df, dt: (refresh_and_apply(df, dt)[0], f"Showing filtered range") + build_dashboard(df, dt)[1:],
|
| 660 |
+
inputs=[date_from, date_to],
|
| 661 |
+
outputs=[kpi_header, filter_msg] + [ch1,ch2,ch3,ch4,ch5,ch6]
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
def apply_filter(df, dt):
|
| 665 |
+
kpi, msg = refresh_and_apply(df, dt) if False else (build_kpi_html(filter_df(df,dt)), "")
|
| 666 |
+
dash = build_dashboard(df, dt)
|
| 667 |
+
return [dash[0]] + [msg] + list(dash[1:])
|
| 668 |
+
|
| 669 |
+
apply_btn.click(fn=lambda df, dt: [build_kpi_html(filter_df(df,dt)), ""] + list(build_dashboard(df,dt)[1:]),
|
| 670 |
+
inputs=[date_from, date_to],
|
| 671 |
+
outputs=[kpi_header, filter_msg, ch1, ch2, ch3, ch4, ch5, ch6])
|
| 672 |
+
|
| 673 |
+
refresh_btn.click(fn=refresh_and_apply, inputs=[date_from, date_to],
|
| 674 |
+
outputs=[kpi_header, filter_msg])
|
| 675 |
+
|
| 676 |
+
seg_type.change(fn=update_seg_choices, inputs=[seg_type], outputs=[seg_name])
|
| 677 |
+
fc_btn.click(fn=generate_forecast,
|
| 678 |
+
inputs=[seg_type, seg_name, horizon, date_from, date_to],
|
| 679 |
+
outputs=[fc_chart, fc_summary])
|
| 680 |
+
|
| 681 |
+
def respond(message, history, df, dt):
|
| 682 |
+
if not message or not message.strip(): return history or [], ""
|
| 683 |
+
reply = chat(message, history or [], df, dt)
|
| 684 |
+
h = list(history or [])
|
| 685 |
+
h.append((message, reply))
|
| 686 |
+
return h, ""
|
| 687 |
+
|
| 688 |
+
send_btn.click(fn=respond, inputs=[chat_input, chatbot_box, date_from, date_to],
|
| 689 |
+
outputs=[chatbot_box, chat_input])
|
| 690 |
+
chat_input.submit(fn=respond, inputs=[chat_input, chatbot_box, date_from, date_to],
|
| 691 |
+
outputs=[chatbot_box, chat_input])
|
| 692 |
+
|
| 693 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
|