Cocolino123 commited on
Commit
3cf539b
·
verified ·
1 Parent(s): b17e4e2

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +842 -0
app.py ADDED
@@ -0,0 +1,842 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import time
5
+ import traceback
6
+ from pathlib import Path
7
+ from typing import Dict, Any, List, Tuple
8
+
9
+ import pandas as pd
10
+ import gradio as gr
11
+ import papermill as pm
12
+ import plotly.graph_objects as go
13
+
14
+ # Optional LLM (HuggingFace Inference API)
15
+ try:
16
+ from huggingface_hub import InferenceClient
17
+ except Exception:
18
+ InferenceClient = None
19
+
20
+ # =========================================================
21
+ # CONFIG
22
+ # =========================================================
23
+
24
+ BASE_DIR = Path(__file__).resolve().parent
25
+
26
+ NB1 = os.environ.get("NB1", "datacreation.ipynb").strip()
27
+ NB2 = os.environ.get("NB2", "pythonanalysis.ipynb").strip()
28
+
29
+ RUNS_DIR = BASE_DIR / "runs"
30
+ ART_DIR = BASE_DIR / "artifacts"
31
+ PY_FIG_DIR = ART_DIR / "py" / "figures"
32
+ PY_TAB_DIR = ART_DIR / "py" / "tables"
33
+
34
+ PAPERMILL_TIMEOUT = int(os.environ.get("PAPERMILL_TIMEOUT", "1800"))
35
+ MAX_PREVIEW_ROWS = int(os.environ.get("MAX_FILE_PREVIEW_ROWS", "50"))
36
+ MAX_LOG_CHARS = int(os.environ.get("MAX_LOG_CHARS", "8000"))
37
+
38
+ HF_API_KEY = os.environ.get("HF_API_KEY", "").strip()
39
+ MODEL_NAME = os.environ.get("MODEL_NAME", "deepseek-ai/DeepSeek-R1").strip()
40
+ HF_PROVIDER = os.environ.get("HF_PROVIDER", "novita").strip()
41
+ N8N_WEBHOOK_URL = os.environ.get("N8N_WEBHOOK_URL", "").strip()
42
+
43
+ LLM_ENABLED = bool(HF_API_KEY) and InferenceClient is not None
44
+ llm_client = (
45
+ InferenceClient(provider=HF_PROVIDER, api_key=HF_API_KEY)
46
+ if LLM_ENABLED
47
+ else None
48
+ )
49
+
50
+ # =========================================================
51
+ # HELPERS
52
+ # =========================================================
53
+
54
+ def ensure_dirs():
55
+ for p in [RUNS_DIR, ART_DIR, PY_FIG_DIR, PY_TAB_DIR]:
56
+ p.mkdir(parents=True, exist_ok=True)
57
+
58
+ def stamp():
59
+ return time.strftime("%Y%m%d-%H%M%S")
60
+
61
+ def tail(text: str, n: int = MAX_LOG_CHARS) -> str:
62
+ return (text or "")[-n:]
63
+
64
+ def _ls(dir_path: Path, exts: Tuple[str, ...]) -> List[str]:
65
+ if not dir_path.is_dir():
66
+ return []
67
+ return sorted(p.name for p in dir_path.iterdir() if p.is_file() and p.suffix.lower() in exts)
68
+
69
+ def _read_csv(path: Path) -> pd.DataFrame:
70
+ return pd.read_csv(path, nrows=MAX_PREVIEW_ROWS)
71
+
72
+ def _read_json(path: Path):
73
+ with path.open(encoding="utf-8") as f:
74
+ return json.load(f)
75
+
76
+ def artifacts_index() -> Dict[str, Any]:
77
+ return {
78
+ "python": {
79
+ "figures": _ls(PY_FIG_DIR, (".png", ".jpg", ".jpeg")),
80
+ "tables": _ls(PY_TAB_DIR, (".csv", ".json")),
81
+ },
82
+ }
83
+
84
+ # =========================================================
85
+ # PIPELINE RUNNERS
86
+ # =========================================================
87
+
88
+ def run_notebook(nb_name: str) -> str:
89
+ ensure_dirs()
90
+ nb_in = BASE_DIR / nb_name
91
+ if not nb_in.exists():
92
+ return f"ERROR: {nb_name} not found."
93
+ nb_out = RUNS_DIR / f"run_{stamp()}_{nb_name}"
94
+ pm.execute_notebook(
95
+ input_path=str(nb_in),
96
+ output_path=str(nb_out),
97
+ cwd=str(BASE_DIR),
98
+ log_output=True,
99
+ progress_bar=False,
100
+ request_save_on_cell_execute=True,
101
+ execution_timeout=PAPERMILL_TIMEOUT,
102
+ )
103
+ return f"Executed {nb_name}"
104
+
105
+
106
+ def run_datacreation() -> str:
107
+ try:
108
+ log = run_notebook(NB1)
109
+ csvs = [f.name for f in BASE_DIR.glob("*.csv")]
110
+ return f"OK {log}\n\nCSVs now in /app:\n" + "\n".join(f" - {c}" for c in sorted(csvs))
111
+ except Exception as e:
112
+ return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"
113
+
114
+
115
+ def run_pythonanalysis() -> str:
116
+ try:
117
+ log = run_notebook(NB2)
118
+ idx = artifacts_index()
119
+ figs = idx["python"]["figures"]
120
+ tabs = idx["python"]["tables"]
121
+ return (
122
+ f"OK {log}\n\n"
123
+ f"Figures: {', '.join(figs) or '(none)'}\n"
124
+ f"Tables: {', '.join(tabs) or '(none)'}"
125
+ )
126
+ except Exception as e:
127
+ return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"
128
+
129
+
130
+ def run_full_pipeline() -> str:
131
+ logs = []
132
+ logs.append("=" * 50)
133
+ logs.append("STEP 1/2: Data Creation (web scraping + synthetic data)")
134
+ logs.append("=" * 50)
135
+ logs.append(run_datacreation())
136
+ logs.append("")
137
+ logs.append("=" * 50)
138
+ logs.append("STEP 2/2: Python Analysis (sentiment, ARIMA, dashboard)")
139
+ logs.append("=" * 50)
140
+ logs.append(run_pythonanalysis())
141
+ return "\n".join(logs)
142
+
143
+
144
+ # =========================================================
145
+ # GALLERY LOADERS
146
+ # =========================================================
147
+
148
+ def _load_all_figures() -> List[Tuple[str, str]]:
149
+ """Return list of (filepath, caption) for Gallery."""
150
+ items = []
151
+ for p in sorted(PY_FIG_DIR.glob("*.png")):
152
+ items.append((str(p), p.stem.replace('_', ' ').title()))
153
+ return items
154
+
155
+
156
+ def _load_table_safe(path: Path) -> pd.DataFrame:
157
+ try:
158
+ if path.suffix == ".json":
159
+ obj = _read_json(path)
160
+ if isinstance(obj, dict):
161
+ return pd.DataFrame([obj])
162
+ return pd.DataFrame(obj)
163
+ return _read_csv(path)
164
+ except Exception as e:
165
+ return pd.DataFrame([{"error": str(e)}])
166
+
167
+
168
+ def refresh_gallery():
169
+ """Called when user clicks Refresh on Gallery tab."""
170
+ figures = _load_all_figures()
171
+ idx = artifacts_index()
172
+
173
+ table_choices = list(idx["python"]["tables"])
174
+
175
+ default_df = pd.DataFrame()
176
+ if table_choices:
177
+ default_df = _load_table_safe(PY_TAB_DIR / table_choices[0])
178
+
179
+ return (
180
+ figures if figures else [],
181
+ gr.update(choices=table_choices, value=table_choices[0] if table_choices else None),
182
+ default_df,
183
+ )
184
+
185
+
186
+ def on_table_select(choice: str):
187
+ if not choice:
188
+ return pd.DataFrame([{"hint": "Select a table above."}])
189
+ path = PY_TAB_DIR / choice
190
+ if not path.exists():
191
+ return pd.DataFrame([{"error": f"File not found: {choice}"}])
192
+ return _load_table_safe(path)
193
+
194
+
195
+ # =========================================================
196
+ # KPI LOADER
197
+ # =========================================================
198
+
199
+ def load_kpis() -> Dict[str, Any]:
200
+ for candidate in [PY_TAB_DIR / "kpis.json", PY_FIG_DIR / "kpis.json"]:
201
+ if candidate.exists():
202
+ try:
203
+ return _read_json(candidate)
204
+ except Exception:
205
+ pass
206
+ return {}
207
+
208
+
209
+ # =========================================================
210
+ # AI DASHBOARD -- LLM picks what to display
211
+ # =========================================================
212
+
213
+ DASHBOARD_SYSTEM = """You are an AI dashboard assistant for a book-sales analytics app.
214
+ The user asks questions or requests about their data. You have access to pre-computed
215
+ artifacts from a Python analysis pipeline.
216
+
217
+ AVAILABLE ARTIFACTS (only reference ones that exist):
218
+ {artifacts_json}
219
+
220
+ KPI SUMMARY: {kpis_json}
221
+
222
+ YOUR JOB:
223
+ 1. Answer the user's question conversationally using the KPIs and your knowledge of the artifacts.
224
+ 2. At the END of your response, output a JSON block (fenced with ```json ... ```) that tells
225
+ the dashboard which artifact to display. The JSON must have this shape:
226
+ {{"show": "figure"|"table"|"none", "scope": "python", "filename": "..."}}
227
+
228
+ - Use "show": "figure" to display a chart image.
229
+ - Use "show": "table" to display a CSV/JSON table.
230
+ - Use "show": "none" if no artifact is relevant.
231
+
232
+ RULES:
233
+ - If the user asks about sales trends or forecasting by title, show sales_trends or arima figures.
234
+ - If the user asks about sentiment, show sentiment figure or sentiment_counts table.
235
+ - If the user asks about forecast accuracy or ARIMA, show arima figures.
236
+ - If the user asks about top sellers, show top_titles_by_units_sold.csv.
237
+ - If the user asks a general data question, pick the most relevant artifact.
238
+ - Keep your answer concise (2-4 sentences), then the JSON block.
239
+ """
240
+
241
+ JSON_BLOCK_RE = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL)
242
+ FALLBACK_JSON_RE = re.compile(r"\{[^{}]*\"show\"[^{}]*\}", re.DOTALL)
243
+
244
+
245
+ def _parse_display_directive(text: str) -> Dict[str, str]:
246
+ m = JSON_BLOCK_RE.search(text)
247
+ if m:
248
+ try:
249
+ return json.loads(m.group(1))
250
+ except json.JSONDecodeError:
251
+ pass
252
+ m = FALLBACK_JSON_RE.search(text)
253
+ if m:
254
+ try:
255
+ return json.loads(m.group(0))
256
+ except json.JSONDecodeError:
257
+ pass
258
+ return {"show": "none"}
259
+
260
+
261
+ def _clean_response(text: str) -> str:
262
+ """Strip the JSON directive block from the displayed response."""
263
+ return JSON_BLOCK_RE.sub("", text).strip()
264
+
265
+
266
+ def _n8n_call(msg: str) -> Tuple[str, Dict]:
267
+ """Call the n8n webhook and return (reply, directive)."""
268
+ import requests as _req
269
+ webhook_url = os.environ.get("N8N_WEBHOOK_URL", "").strip()
270
+ if not webhook_url:
271
+ return "N8N_WEBHOOK_URL is not set.", None
272
+ try:
273
+ resp = _req.post(webhook_url, json={"question": msg}, timeout=30)
274
+ resp.raise_for_status()
275
+ data = resp.json()
276
+
277
+ # unwrap nested shapes e.g. {"output": {"answer": ...}}
278
+ if isinstance(data, list) and len(data) > 0:
279
+ data = data[0]
280
+ if "output" in data and isinstance(data["output"], dict):
281
+ data = data["output"]
282
+
283
+ answer = (
284
+ data.get("answer") or data.get("text") or
285
+ data.get("message") or data.get("response") or str(data)
286
+ )
287
+
288
+ # Map any chart string n8n returns → one of our three keys
289
+ raw_chart = str(data.get("chart") or data.get("chart_type") or "").lower().strip()
290
+ _alias = {
291
+ "sales": "sales", "viewership": "sales", "streams": "sales",
292
+ "monthly": "sales", "trend": "sales", "trends": "sales",
293
+ "arima": "sales", "forecast": "sales",
294
+ "sentiment": "sentiment", "reviews": "sentiment", "vader": "sentiment",
295
+ "top_sellers": "top_sellers", "top_shows": "top_sellers",
296
+ "renewal": "top_sellers", "renew": "top_sellers", "top": "top_sellers",
297
+ }
298
+ chart_key = _alias.get(raw_chart, "")
299
+
300
+ table_file = data.get("table") or data.get("filename") or ""
301
+
302
+ if chart_key:
303
+ return answer, {"show": "figure", "chart": chart_key}
304
+ if table_file:
305
+ return answer, {"show": "table", "scope": "python", "filename": table_file}
306
+ return answer, {"show": "none"}
307
+
308
+ except Exception as e:
309
+ return f"❌ n8n error: {e}", None
310
+
311
+
312
+ def _n8n_debug(msg: str) -> str:
313
+ """Raw debug call to n8n — shows exactly what comes back."""
314
+ import requests as _req
315
+ webhook_url = os.environ.get("N8N_WEBHOOK_URL", "").strip()
316
+ if not webhook_url:
317
+ return "❌ N8N_WEBHOOK_URL is not set in Space secrets."
318
+ try:
319
+ resp = _req.post(webhook_url, json={"question": msg}, timeout=30)
320
+ lines = [
321
+ f"✅ HTTP status: {resp.status_code}",
322
+ f"📋 Response headers: {dict(resp.headers)}",
323
+ f"📦 Raw body:\n{resp.text[:3000]}",
324
+ ]
325
+ try:
326
+ parsed = resp.json()
327
+ lines.append(f"\n✅ Parsed JSON:\n{json.dumps(parsed, indent=2)[:2000]}")
328
+ except Exception as je:
329
+ lines.append(f"\n❌ JSON parse error: {je}")
330
+ return "\n".join(lines)
331
+ except Exception as e:
332
+ return f"❌ Request failed: {e}"
333
+
334
+
335
+ def ai_chat(user_msg: str, history: list):
336
+ """Chat function for the AI Dashboard tab."""
337
+ if not user_msg or not user_msg.strip():
338
+ return history, "", None, None
339
+
340
+ idx = artifacts_index()
341
+ kpis = load_kpis()
342
+
343
+ # Priority: n8n webhook > HF LLM > keyword fallback
344
+ _active_webhook = os.environ.get("N8N_WEBHOOK_URL", "").strip()
345
+ if _active_webhook:
346
+ reply, directive = _n8n_call(user_msg)
347
+ if directive is None:
348
+ reply_fb, directive = _keyword_fallback(user_msg, idx, kpis)
349
+ reply += "\n\n" + reply_fb
350
+ elif not LLM_ENABLED:
351
+ reply, directive = _keyword_fallback(user_msg, idx, kpis)
352
+ else:
353
+ system = DASHBOARD_SYSTEM.format(
354
+ artifacts_json=json.dumps(idx, indent=2),
355
+ kpis_json=json.dumps(kpis, indent=2) if kpis else "(no KPIs yet, run the pipeline first)",
356
+ )
357
+ msgs = [{"role": "system", "content": system}]
358
+ for entry in (history or [])[-6:]:
359
+ msgs.append(entry)
360
+ msgs.append({"role": "user", "content": user_msg})
361
+
362
+ try:
363
+ r = llm_client.chat_completion(
364
+ model=MODEL_NAME,
365
+ messages=msgs,
366
+ temperature=0.3,
367
+ max_tokens=600,
368
+ stream=False,
369
+ )
370
+ raw = (
371
+ r["choices"][0]["message"]["content"]
372
+ if isinstance(r, dict)
373
+ else r.choices[0].message.content
374
+ )
375
+ directive = _parse_display_directive(raw)
376
+ reply = _clean_response(raw)
377
+ except Exception as e:
378
+ reply = f"LLM error: {e}. Falling back to keyword matching."
379
+ reply_fb, directive = _keyword_fallback(user_msg, idx, kpis)
380
+ reply += "\n\n" + reply_fb
381
+
382
+ # Resolve artifacts — build interactive Plotly charts when possible
383
+ chart_out = None
384
+ tab_out = None
385
+ show = directive.get("show", "none")
386
+ fname = directive.get("filename", "")
387
+ chart_name = directive.get("chart", "")
388
+
389
+ # Interactive chart builders keyed by name
390
+ chart_builders = {
391
+ "sales": build_sales_chart,
392
+ "sentiment": build_sentiment_chart,
393
+ "top_sellers": build_top_sellers_chart,
394
+ }
395
+ _chart_alias = {
396
+ "viewership": "sales", "streams": "sales", "monthly": "sales",
397
+ "trend": "sales", "trends": "sales", "arima": "sales", "forecast": "sales",
398
+ "reviews": "sentiment", "vader": "sentiment",
399
+ "top_shows": "top_sellers", "renewal": "top_sellers",
400
+ "renew": "top_sellers", "top": "top_sellers",
401
+ }
402
+ resolved = chart_builders.get(chart_name) or chart_builders.get(_chart_alias.get(chart_name, ""))
403
+ if resolved:
404
+ chart_out = resolved()
405
+ elif show == "figure" and fname:
406
+ if any(k in fname for k in ("stream", "view", "monthly", "arima", "forecast", "sales")):
407
+ chart_out = build_sales_chart()
408
+ elif any(k in fname for k in ("sentiment", "vader", "review")):
409
+ chart_out = build_sentiment_chart()
410
+ elif any(k in fname for k in ("renewal", "renew", "top", "recommend")):
411
+ chart_out = build_top_sellers_chart()
412
+ else:
413
+ chart_out = _empty_chart(f"No interactive chart for {fname}")
414
+
415
+ if show == "table" and fname:
416
+ fp = PY_TAB_DIR / fname
417
+ if fp.exists():
418
+ tab_out = _load_table_safe(fp)
419
+ else:
420
+ reply += f"\n\n*(Could not find table: {fname})*"
421
+
422
+ new_history = (history or []) + [
423
+ {"role": "user", "content": user_msg},
424
+ {"role": "assistant", "content": reply},
425
+ ]
426
+
427
+ return new_history, "", chart_out, tab_out
428
+
429
+
430
+ def _keyword_fallback(msg: str, idx: Dict, kpis: Dict) -> Tuple[str, Dict]:
431
+ """Simple keyword matcher when LLM is unavailable."""
432
+ msg_lower = msg.lower()
433
+
434
+ if not idx["python"]["figures"] and not idx["python"]["tables"]:
435
+ return (
436
+ "No artifacts found yet. Please run the pipeline first (Tab 1), "
437
+ "then come back here to explore the results.",
438
+ {"show": "none"},
439
+ )
440
+
441
+ kpi_text = ""
442
+ if kpis:
443
+ total = kpis.get("total_units_sold", 0)
444
+ kpi_text = (
445
+ f"Quick summary: **{kpis.get('n_titles', '?')}** book titles across "
446
+ f"**{kpis.get('n_months', '?')}** months, with **{total:,.0f}** total units sold."
447
+ )
448
+
449
+ if any(w in msg_lower for w in ["trend", "sales trend", "monthly sale"]):
450
+ return (
451
+ f"Here are the sales trends. {kpi_text}",
452
+ {"show": "figure", "chart": "sales"},
453
+ )
454
+
455
+ if any(w in msg_lower for w in ["sentiment", "review", "positive", "negative"]):
456
+ return (
457
+ f"Here is the sentiment distribution across sampled book titles. {kpi_text}",
458
+ {"show": "figure", "chart": "sentiment"},
459
+ )
460
+
461
+ if any(w in msg_lower for w in ["arima", "forecast", "predict"]):
462
+ return (
463
+ f"Here are the sales trends and forecasts. {kpi_text}",
464
+ {"show": "figure", "chart": "sales"},
465
+ )
466
+
467
+ if any(w in msg_lower for w in ["top", "best sell", "popular", "rank"]):
468
+ return (
469
+ f"Here are the top-selling titles by units sold. {kpi_text}",
470
+ {"show": "table", "scope": "python", "filename": "top_titles_by_units_sold.csv"},
471
+ )
472
+
473
+ if any(w in msg_lower for w in ["price", "pricing", "decision"]):
474
+ return (
475
+ f"Here are the pricing decisions. {kpi_text}",
476
+ {"show": "table", "scope": "python", "filename": "pricing_decisions.csv"},
477
+ )
478
+
479
+ if any(w in msg_lower for w in ["dashboard", "overview", "summary", "kpi"]):
480
+ return (
481
+ f"Dashboard overview: {kpi_text}\n\nAsk me about sales trends, sentiment, forecasts, "
482
+ "pricing, or top sellers to see specific visualizations.",
483
+ {"show": "table", "scope": "python", "filename": "df_dashboard.csv"},
484
+ )
485
+
486
+ # Default
487
+ return (
488
+ f"I can show you various analyses. {kpi_text}\n\n"
489
+ "Try asking about: **sales trends**, **sentiment**, **ARIMA forecasts**, "
490
+ "**pricing decisions**, **top sellers**, or **dashboard overview**.",
491
+ {"show": "none"},
492
+ )
493
+
494
+
495
+ # =========================================================
496
+ # KPI CARDS (BubbleBusters style)
497
+ # =========================================================
498
+
499
+ def render_kpi_cards() -> str:
500
+ kpis = load_kpis()
501
+ if not kpis:
502
+ return (
503
+ '<div style="background:rgba(255,255,255,.65);backdrop-filter:blur(16px);'
504
+ 'border-radius:20px;padding:28px;text-align:center;'
505
+ 'border:1.5px solid rgba(255,255,255,.7);'
506
+ 'box-shadow:0 8px 32px rgba(124,92,191,.08);">'
507
+ '<div style="font-size:36px;margin-bottom:10px;">📊</div>'
508
+ '<div style="color:#a48de8;font-size:14px;'
509
+ 'font-weight:800;margin-bottom:6px;">No data yet</div>'
510
+ '<div style="color:#9d8fc4;font-size:12px;">'
511
+ 'Run the pipeline to populate these cards.</div>'
512
+ '</div>'
513
+ )
514
+
515
+ def card(icon, label, value, colour):
516
+ return f"""
517
+ <div style="background:rgba(255,255,255,.72);backdrop-filter:blur(16px);
518
+ border-radius:20px;padding:18px 14px 16px;text-align:center;
519
+ border:1.5px solid rgba(255,255,255,.8);
520
+ box-shadow:0 4px 16px rgba(124,92,191,.08);
521
+ border-top:3px solid {colour};">
522
+ <div style="font-size:26px;margin-bottom:7px;line-height:1;">{icon}</div>
523
+ <div style="color:#9d8fc4;font-size:9.5px;text-transform:uppercase;
524
+ letter-spacing:1.8px;margin-bottom:7px;font-weight:800;">{label}</div>
525
+ <div style="color:#2d1f4e;font-size:16px;font-weight:800;">{value}</div>
526
+ </div>"""
527
+
528
+ kpi_config = [
529
+ ("n_titles", "📚", "Book Titles", "#a48de8"),
530
+ ("n_months", "📅", "Time Periods", "#7aa6f8"),
531
+ ("total_units_sold", "📦", "Units Sold", "#6ee7c7"),
532
+ ("total_revenue", "💰", "Revenue", "#3dcba8"),
533
+ ]
534
+
535
+ html = (
536
+ '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));'
537
+ 'gap:12px;margin-bottom:24px;">'
538
+ )
539
+ for key, icon, label, colour in kpi_config:
540
+ val = kpis.get(key)
541
+ if val is None:
542
+ continue
543
+ if isinstance(val, (int, float)) and val > 100:
544
+ val = f"{val:,.0f}"
545
+ html += card(icon, label, str(val), colour)
546
+ # Extra KPIs not in config
547
+ known = {k for k, *_ in kpi_config}
548
+ for key, val in kpis.items():
549
+ if key not in known:
550
+ label = key.replace("_", " ").title()
551
+ if isinstance(val, (int, float)) and val > 100:
552
+ val = f"{val:,.0f}"
553
+ html += card("📈", label, str(val), "#8fa8f8")
554
+ html += "</div>"
555
+ return html
556
+
557
+
558
+ # =========================================================
559
+ # INTERACTIVE PLOTLY CHARTS (BubbleBusters style)
560
+ # =========================================================
561
+
562
+ CHART_PALETTE = ["#7c5cbf", "#2ec4a0", "#e8537a", "#e8a230", "#5e8fef",
563
+ "#c45ea8", "#3dbacc", "#a0522d", "#6aaa3a", "#d46060"]
564
+
565
+ def _styled_layout(**kwargs) -> dict:
566
+ defaults = dict(
567
+ template="plotly_white",
568
+ paper_bgcolor="rgba(255,255,255,0.95)",
569
+ plot_bgcolor="rgba(255,255,255,0.98)",
570
+ font=dict(family="system-ui, sans-serif", color="#2d1f4e", size=12),
571
+ margin=dict(l=60, r=20, t=70, b=70),
572
+ legend=dict(
573
+ orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1,
574
+ bgcolor="rgba(255,255,255,0.92)",
575
+ bordercolor="rgba(124,92,191,0.35)", borderwidth=1,
576
+ ),
577
+ title=dict(font=dict(size=15, color="#4b2d8a")),
578
+ )
579
+ defaults.update(kwargs)
580
+ return defaults
581
+
582
+
583
+ def _empty_chart(title: str) -> go.Figure:
584
+ fig = go.Figure()
585
+ fig.update_layout(
586
+ title=title, height=420, template="plotly_white",
587
+ paper_bgcolor="rgba(255,255,255,0.95)",
588
+ annotations=[dict(text="Run the pipeline to generate data",
589
+ x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False,
590
+ font=dict(size=14, color="rgba(124,92,191,0.5)"))],
591
+ )
592
+ return fig
593
+
594
+
595
+ def build_sales_chart() -> go.Figure:
596
+ path = PY_TAB_DIR / "df_dashboard.csv"
597
+ if not path.exists():
598
+ return _empty_chart("Sales Trends — run the pipeline first")
599
+ df = pd.read_csv(path)
600
+ date_col = next((c for c in df.columns if "month" in c.lower() or "date" in c.lower()), None)
601
+ val_cols = [c for c in df.columns if c != date_col and df[c].dtype in ("float64", "int64")]
602
+ if not date_col or not val_cols:
603
+ return _empty_chart("Could not auto-detect columns in df_dashboard.csv")
604
+ df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
605
+ fig = go.Figure()
606
+ for i, col in enumerate(val_cols):
607
+ fig.add_trace(go.Scatter(
608
+ x=df[date_col], y=df[col], name=col.replace("_", " ").title(),
609
+ mode="lines+markers", line=dict(color=CHART_PALETTE[i % len(CHART_PALETTE)], width=2),
610
+ marker=dict(size=4),
611
+ hovertemplate=f"<b>{col.replace('_',' ').title()}</b><br>%{{x|%b %Y}}: %{{y:,.0f}}<extra></extra>",
612
+ ))
613
+ fig.update_layout(**_styled_layout(height=450, hovermode="x unified",
614
+ title=dict(text="Monthly Overview")))
615
+ fig.update_xaxes(gridcolor="rgba(124,92,191,0.15)", showgrid=True)
616
+ fig.update_yaxes(gridcolor="rgba(124,92,191,0.15)", showgrid=True)
617
+ return fig
618
+
619
+
620
+ def build_sentiment_chart() -> go.Figure:
621
+ path = PY_TAB_DIR / "sentiment_counts_sampled.csv"
622
+ if not path.exists():
623
+ return _empty_chart("Sentiment Distribution — run the pipeline first")
624
+ df = pd.read_csv(path)
625
+ title_col = df.columns[0]
626
+ sent_cols = [c for c in ["negative", "neutral", "positive"] if c in df.columns]
627
+ if not sent_cols:
628
+ return _empty_chart("No sentiment columns found in CSV")
629
+ colors = {"negative": "#e8537a", "neutral": "#5e8fef", "positive": "#2ec4a0"}
630
+ fig = go.Figure()
631
+ for col in sent_cols:
632
+ fig.add_trace(go.Bar(
633
+ name=col.title(), y=df[title_col], x=df[col],
634
+ orientation="h", marker_color=colors.get(col, "#888"),
635
+ hovertemplate=f"<b>{col.title()}</b>: %{{x}}<extra></extra>",
636
+ ))
637
+ fig.update_layout(**_styled_layout(
638
+ height=max(400, len(df) * 28), barmode="stack",
639
+ title=dict(text="Sentiment Distribution by Book"),
640
+ ))
641
+ fig.update_xaxes(title="Number of Reviews")
642
+ fig.update_yaxes(autorange="reversed")
643
+ return fig
644
+
645
+
646
+ def build_top_sellers_chart() -> go.Figure:
647
+ path = PY_TAB_DIR / "top_titles_by_units_sold.csv"
648
+ if not path.exists():
649
+ return _empty_chart("Top Sellers — run the pipeline first")
650
+ df = pd.read_csv(path).head(15)
651
+ title_col = next((c for c in df.columns if "title" in c.lower()), df.columns[0])
652
+ val_col = next((c for c in df.columns if "unit" in c.lower() or "sold" in c.lower()), df.columns[-1])
653
+ fig = go.Figure(go.Bar(
654
+ y=df[title_col], x=df[val_col], orientation="h",
655
+ marker=dict(color=df[val_col], colorscale=[[0, "#c5b4f0"], [1, "#7c5cbf"]]),
656
+ hovertemplate="<b>%{y}</b><br>Units: %{x:,.0f}<extra></extra>",
657
+ ))
658
+ fig.update_layout(**_styled_layout(
659
+ height=max(400, len(df) * 30),
660
+ title=dict(text="Top Selling Titles"), showlegend=False,
661
+ ))
662
+ fig.update_yaxes(autorange="reversed")
663
+ fig.update_xaxes(title="Total Units Sold")
664
+ return fig
665
+
666
+
667
+ def refresh_dashboard():
668
+ return render_kpi_cards(), build_sales_chart(), build_sentiment_chart(), build_top_sellers_chart()
669
+
670
+
671
+ # =========================================================
672
+ # UI
673
+ # =========================================================
674
+
675
+ ensure_dirs()
676
+
677
+ def load_css() -> str:
678
+ css_path = BASE_DIR / "style.css"
679
+ return css_path.read_text(encoding="utf-8") if css_path.exists() else ""
680
+
681
+
682
+ with gr.Blocks(title="AIBDM 2026 Workshop App") as demo:
683
+
684
+ gr.Markdown(
685
+ "# SE21 App Template\n"
686
+ "*This is an app template for SE21 students*",
687
+ elem_id="escp_title",
688
+ )
689
+
690
+ # ===========================================================
691
+ # TAB 1 -- Pipeline Runner
692
+ # ===========================================================
693
+ with gr.Tab("Pipeline Runner"):
694
+ gr.Markdown()
695
+
696
+ with gr.Row():
697
+ with gr.Column(scale=1):
698
+ btn_nb1 = gr.Button("Step 1: Data Creation", variant="secondary")
699
+ with gr.Column(scale=1):
700
+ btn_nb2 = gr.Button("Step 2: Python Analysis", variant="secondary")
701
+
702
+ with gr.Row():
703
+ btn_all = gr.Button("Run Full Pipeline (Both Steps)", variant="primary")
704
+
705
+ run_log = gr.Textbox(
706
+ label="Execution Log",
707
+ lines=18,
708
+ max_lines=30,
709
+ interactive=False,
710
+ )
711
+
712
+ btn_nb1.click(run_datacreation, outputs=[run_log])
713
+ btn_nb2.click(run_pythonanalysis, outputs=[run_log])
714
+ btn_all.click(run_full_pipeline, outputs=[run_log])
715
+
716
+ # ===========================================================
717
+ # TAB 2 -- Dashboard (KPIs + Interactive Charts + Gallery)
718
+ # ===========================================================
719
+ with gr.Tab("Dashboard"):
720
+ kpi_html = gr.HTML(value=render_kpi_cards)
721
+
722
+ refresh_btn = gr.Button("Refresh Dashboard", variant="primary")
723
+
724
+ gr.Markdown("#### Interactive Charts")
725
+ chart_sales = gr.Plot(label="Monthly Overview")
726
+ chart_sentiment = gr.Plot(label="Sentiment Distribution")
727
+ chart_top = gr.Plot(label="Top Sellers")
728
+
729
+ gr.Markdown("#### Static Figures (from notebooks)")
730
+ gallery = gr.Gallery(
731
+ label="Generated Figures",
732
+ columns=2,
733
+ height=480,
734
+ object_fit="contain",
735
+ )
736
+
737
+ gr.Markdown("#### Data Tables")
738
+ table_dropdown = gr.Dropdown(
739
+ label="Select a table to view",
740
+ choices=[],
741
+ interactive=True,
742
+ )
743
+ table_display = gr.Dataframe(
744
+ label="Table Preview",
745
+ interactive=False,
746
+ )
747
+
748
+ def _on_refresh():
749
+ kpi, c1, c2, c3 = refresh_dashboard()
750
+ figs, dd, df = refresh_gallery()
751
+ return kpi, c1, c2, c3, figs, dd, df
752
+
753
+ refresh_btn.click(
754
+ _on_refresh,
755
+ outputs=[kpi_html, chart_sales, chart_sentiment, chart_top,
756
+ gallery, table_dropdown, table_display],
757
+ )
758
+ table_dropdown.change(
759
+ on_table_select,
760
+ inputs=[table_dropdown],
761
+ outputs=[table_display],
762
+ )
763
+
764
+ # ===========================================================
765
+ # TAB 3 -- AI Dashboard
766
+ # ===========================================================
767
+ with gr.Tab('"AI" Dashboard'):
768
+ def _ai_status_md():
769
+ _wh = os.environ.get("N8N_WEBHOOK_URL", "").strip()
770
+ if _wh:
771
+ _s = "Connected to your **n8n workflow**. ✅"
772
+ elif LLM_ENABLED:
773
+ _s = "**LLM active.**"
774
+ else:
775
+ _s = "Using **keyword matching**."
776
+ return ("### Ask questions, get interactive visualisations\n\n"
777
+ f"Type a question and the system will pick the right chart or table. {_s}")
778
+ gr.Markdown(value=_ai_status_md)
779
+
780
+ with gr.Row(equal_height=True):
781
+ with gr.Column(scale=1):
782
+ chatbot = gr.Chatbot(
783
+ label="Conversation",
784
+ height=380,
785
+ )
786
+ user_input = gr.Textbox(
787
+ label="Ask about your data",
788
+ placeholder="e.g. Show me sales trends / What are the top sellers? / Sentiment analysis",
789
+ lines=1,
790
+ )
791
+ gr.Examples(
792
+ examples=[
793
+ "Show me the sales trends",
794
+ "What does the sentiment look like?",
795
+ "Which titles sell the most?",
796
+ "Show the ARIMA forecasts",
797
+ "What are the pricing decisions?",
798
+ "Give me a dashboard overview",
799
+ ],
800
+ inputs=user_input,
801
+ )
802
+
803
+ with gr.Column(scale=1):
804
+ ai_figure = gr.Plot(
805
+ label="Interactive Chart",
806
+ )
807
+ ai_table = gr.Dataframe(
808
+ label="Data Table",
809
+ interactive=False,
810
+ )
811
+
812
+ user_input.submit(
813
+ ai_chat,
814
+ inputs=[user_input, chatbot],
815
+ outputs=[chatbot, user_input, ai_figure, ai_table],
816
+ )
817
+
818
+
819
+ # ===========================================================
820
+ # TAB 4 -- n8n Debug
821
+ # ===========================================================
822
+ with gr.Tab("🔧 n8n Debug"):
823
+ gr.Markdown(
824
+ "### n8n Connection Debugger\n\n"
825
+ "Use this tab to see the **raw response** your n8n webhook sends back. "
826
+ "This tells you exactly what field names and values to expect."
827
+ )
828
+ with gr.Row():
829
+ debug_input = gr.Textbox(
830
+ label="Test question",
831
+ value="What are the top shows?",
832
+ lines=1,
833
+ )
834
+ debug_btn = gr.Button("Send to n8n & show raw response", variant="primary")
835
+ debug_output = gr.Textbox(
836
+ label="Raw n8n response",
837
+ lines=20,
838
+ interactive=False,
839
+ )
840
+ debug_btn.click(_n8n_debug, inputs=[debug_input], outputs=[debug_output])
841
+
842
+ demo.launch(css=load_css(), allowed_paths=[str(BASE_DIR)])