Yulu1 commited on
Commit
955fd11
·
verified ·
1 Parent(s): a565991

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -596
app.py DELETED
@@ -1,596 +0,0 @@
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, Optional, Tuple
8
-
9
- import pandas as pd
10
- import gradio as gr
11
- import papermill as pm
12
-
13
- # Optional LLM (HuggingFace Inference API)
14
- try:
15
- from huggingface_hub import InferenceClient
16
- except Exception:
17
- InferenceClient = None
18
-
19
- # =========================================================
20
- # CONFIG
21
- # =========================================================
22
-
23
- BASE_DIR = Path(__file__).resolve().parent
24
-
25
- NB1 = os.environ.get("NB1", "pythonanalysis.ipynb").strip()
26
- NB2 = os.environ.get("NB2", "ranalysis.ipynb").strip()
27
-
28
- RUNS_DIR = BASE_DIR / "runs"
29
- ART_DIR = BASE_DIR / "artifacts"
30
- PY_FIG_DIR = ART_DIR / "py" / "figures"
31
- PY_TAB_DIR = ART_DIR / "py" / "tables"
32
- R_FIG_DIR = ART_DIR / "r" / "figures"
33
- R_TAB_DIR = ART_DIR / "r" / "tables"
34
-
35
- PAPERMILL_TIMEOUT = int(os.environ.get("PAPERMILL_TIMEOUT", "1800"))
36
- MAX_PREVIEW_ROWS = int(os.environ.get("MAX_FILE_PREVIEW_ROWS", "50"))
37
- MAX_LOG_CHARS = int(os.environ.get("MAX_LOG_CHARS", "8000"))
38
-
39
- HF_API_KEY = os.environ.get("HF_API_KEY", "").strip()
40
- MODEL_NAME = os.environ.get("MODEL_NAME", "deepseek-ai/DeepSeek-R1").strip()
41
- HF_PROVIDER = os.environ.get("HF_PROVIDER", "novita").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, R_FIG_DIR, R_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
- "r": {
83
- "figures": _ls(R_FIG_DIR, (".png", ".jpg", ".jpeg")),
84
- "tables": _ls(R_TAB_DIR, (".csv", ".json")),
85
- },
86
- }
87
-
88
- # =========================================================
89
- # PIPELINE RUNNERS
90
- # =========================================================
91
-
92
- def run_notebook(nb_name: str) -> str:
93
- ensure_dirs()
94
- nb_in = BASE_DIR / nb_name
95
- if not nb_in.exists():
96
- return f"ERROR: {nb_name} not found."
97
- nb_out = RUNS_DIR / f"run_{stamp()}_{nb_name}"
98
- pm.execute_notebook(
99
- input_path=str(nb_in),
100
- output_path=str(nb_out),
101
- cwd=str(BASE_DIR),
102
- log_output=True,
103
- progress_bar=False,
104
- request_save_on_cell_execute=True,
105
- execution_timeout=PAPERMILL_TIMEOUT,
106
- )
107
- return f"Executed {nb_name}"
108
-
109
-
110
- def run_datacreation() -> str:
111
- try:
112
- log = run_notebook(NB1)
113
- csvs = [f.name for f in BASE_DIR.glob("*.csv")]
114
- return f"OK {log}\n\nCSVs now in /app:\n" + "\n".join(f" - {c}" for c in sorted(csvs))
115
- except Exception as e:
116
- return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"
117
-
118
-
119
- def run_pythonanalysis() -> str:
120
- try:
121
- log = run_notebook(NB2)
122
- idx = artifacts_index()
123
- figs = idx["python"]["figures"]
124
- tabs = idx["python"]["tables"]
125
- return (
126
- f"OK {log}\n\n"
127
- f"Figures: {', '.join(figs) or '(none)'}\n"
128
- f"Tables: {', '.join(tabs) or '(none)'}"
129
- )
130
- except Exception as e:
131
- return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"
132
-
133
- except Exception as e:
134
- return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"
135
-
136
-
137
- def run_full_pipeline() -> str:
138
- logs = []
139
- logs.append("=" * 50)
140
- logs.append("STEP 1/2: Data Creation")
141
- logs.append("=" * 50)
142
- logs.append(run_datacreation())
143
- logs.append("")
144
- logs.append("=" * 50)
145
- logs.append("STEP 2/2: Python Analysis")
146
- logs.append("=" * 50)
147
- logs.append(run_pythonanalysis())
148
- return "\n".join(logs)
149
-
150
-
151
- # =========================================================
152
- # GALLERY LOADERS
153
- # =========================================================
154
-
155
- def _load_all_figures() -> List[Tuple[str, str]]:
156
- """Return list of (filepath, caption) for Gallery."""
157
- items = []
158
- for p in sorted(PY_FIG_DIR.glob("*.png")):
159
- items.append((str(p), f"Python | {p.stem.replace('_', ' ').title()}"))
160
- for p in sorted(R_FIG_DIR.glob("*.png")):
161
- items.append((str(p), f"R | {p.stem.replace('_', ' ').title()}"))
162
- return items
163
-
164
-
165
- def _load_table_safe(path: Path) -> pd.DataFrame:
166
- try:
167
- if path.suffix == ".json":
168
- obj = _read_json(path)
169
- if isinstance(obj, dict):
170
- return pd.DataFrame([obj])
171
- return pd.DataFrame(obj)
172
- return _read_csv(path)
173
- except Exception as e:
174
- return pd.DataFrame([{"error": str(e)}])
175
-
176
-
177
- def refresh_gallery():
178
- """Called when user clicks Refresh on Gallery tab."""
179
- figures = _load_all_figures()
180
- idx = artifacts_index()
181
-
182
- # Build table choices
183
- table_choices = []
184
- for scope in ("python", "r"):
185
- for name in idx[scope]["tables"]:
186
- table_choices.append(f"{scope}/{name}")
187
-
188
- # Default: show first table if available
189
- default_df = pd.DataFrame()
190
- if table_choices:
191
- parts = table_choices[0].split("/", 1)
192
- base = PY_TAB_DIR if parts[0] == "python" else R_TAB_DIR
193
- default_df = _load_table_safe(base / parts[1])
194
-
195
- return (
196
- figures if figures else [],
197
- gr.update(choices=table_choices, value=table_choices[0] if table_choices else None),
198
- default_df,
199
- )
200
-
201
-
202
- def on_table_select(choice: str):
203
- if not choice or "/" not in choice:
204
- return pd.DataFrame([{"hint": "Select a table above."}])
205
- scope, name = choice.split("/", 1)
206
- base = {"python": PY_TAB_DIR, "r": R_TAB_DIR}.get(scope)
207
- if not base:
208
- return pd.DataFrame([{"error": f"Unknown scope: {scope}"}])
209
- path = base / name
210
- if not path.exists():
211
- return pd.DataFrame([{"error": f"File not found: {path}"}])
212
- return _load_table_safe(path)
213
-
214
-
215
- # =========================================================
216
- # KPI LOADER
217
- # =========================================================
218
-
219
- def load_kpis() -> Dict[str, Any]:
220
- for candidate in [PY_TAB_DIR / "kpis.json", PY_FIG_DIR / "kpis.json"]:
221
- if candidate.exists():
222
- try:
223
- return _read_json(candidate)
224
- except Exception:
225
- pass
226
- return {}
227
-
228
-
229
- # =========================================================
230
- # AI DASHBOARD (Tab 3) -- LLM picks what to display
231
- # =========================================================
232
-
233
- DASHBOARD_SYSTEM = """You are an AI dashboard assistant for a book-sales analytics app.
234
- The user asks questions or requests about their data. You have access to pre-computed
235
- artifacts from Python and R analysis pipelines.
236
-
237
- AVAILABLE ARTIFACTS (only reference ones that exist):
238
- {artifacts_json}
239
-
240
- KPI SUMMARY: {kpis_json}
241
-
242
- YOUR JOB:
243
- 1. Answer the user's question conversationally using the KPIs and your knowledge of the artifacts.
244
- 2. At the END of your response, output a JSON block (fenced with ```json ... ```) that tells
245
- the dashboard which artifact to display. The JSON must have this shape:
246
- {{"show": "figure"|"table"|"none", "scope": "python"|"r", "filename": "..."}}
247
-
248
- - Use "show": "figure" to display a chart image.
249
- - Use "show": "table" to display a CSV/JSON table.
250
- - Use "show": "none" if no artifact is relevant.
251
-
252
- RULES:
253
- - If the user asks about sales trends or forecasting by title, show sales_trends or arima figures.
254
- - If the user asks about sentiment, show sentiment figure or sentiment_counts table.
255
- - If the user asks about R regression, the R notebook focuses on forecasting, show accuracy_table.csv.
256
- - If the user asks about forecast accuracy or model comparison, show accuracy_table.csv or forecast_compare.png.
257
- - If the user asks about top sellers, show top_titles_by_units_sold.csv.
258
- - If the user asks a general data question, pick the most relevant artifact.
259
- - Keep your answer concise (2-4 sentences), then the JSON block.
260
- """
261
-
262
- JSON_BLOCK_RE = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL)
263
- FALLBACK_JSON_RE = re.compile(r"\{[^{}]*\"show\"[^{}]*\}", re.DOTALL)
264
-
265
-
266
- def _parse_display_directive(text: str) -> Dict[str, str]:
267
- m = JSON_BLOCK_RE.search(text)
268
- if m:
269
- try:
270
- return json.loads(m.group(1))
271
- except json.JSONDecodeError:
272
- pass
273
- m = FALLBACK_JSON_RE.search(text)
274
- if m:
275
- try:
276
- return json.loads(m.group(0))
277
- except json.JSONDecodeError:
278
- pass
279
- return {"show": "none"}
280
-
281
-
282
- def _clean_response(text: str) -> str:
283
- """Strip the JSON directive block from the displayed response."""
284
- return JSON_BLOCK_RE.sub("", text).strip()
285
-
286
-
287
- def ai_chat(user_msg: str, history: list):
288
- """Chat function for the AI Dashboard tab."""
289
- if not user_msg or not user_msg.strip():
290
- return history, "", None, None
291
-
292
- idx = artifacts_index()
293
- kpis = load_kpis()
294
-
295
- if not LLM_ENABLED:
296
- reply, directive = _keyword_fallback(user_msg, idx, kpis)
297
- else:
298
- system = DASHBOARD_SYSTEM.format(
299
- artifacts_json=json.dumps(idx, indent=2),
300
- kpis_json=json.dumps(kpis, indent=2) if kpis else "(no KPIs yet, run the pipeline first)",
301
- )
302
- msgs = [{"role": "system", "content": system}]
303
- for entry in (history or [])[-6:]:
304
- msgs.append(entry)
305
- msgs.append({"role": "user", "content": user_msg})
306
-
307
- try:
308
- r = llm_client.chat_completion(
309
- model=MODEL_NAME,
310
- messages=msgs,
311
- temperature=0.3,
312
- max_tokens=600,
313
- stream=False,
314
- )
315
- raw = (
316
- r["choices"][0]["message"]["content"]
317
- if isinstance(r, dict)
318
- else r.choices[0].message.content
319
- )
320
- directive = _parse_display_directive(raw)
321
- reply = _clean_response(raw)
322
- except Exception as e:
323
- reply = f"LLM error: {e}. Falling back to keyword matching."
324
- reply_fb, directive = _keyword_fallback(user_msg, idx, kpis)
325
- reply += "\n\n" + reply_fb
326
-
327
- # Resolve artifact paths
328
- fig_out = None
329
- tab_out = None
330
- show = directive.get("show", "none")
331
- scope = directive.get("scope", "")
332
- fname = directive.get("filename", "")
333
-
334
- if show == "figure" and scope and fname:
335
- base = {"python": PY_FIG_DIR, "r": R_FIG_DIR}.get(scope)
336
- if base and (base / fname).exists():
337
- fig_out = str(base / fname)
338
- else:
339
- reply += f"\n\n*(Could not find figure: {scope}/{fname})*"
340
-
341
- if show == "table" and scope and fname:
342
- base = {"python": PY_TAB_DIR, "r": R_TAB_DIR}.get(scope)
343
- if base and (base / fname).exists():
344
- tab_out = _load_table_safe(base / fname)
345
- else:
346
- reply += f"\n\n*(Could not find table: {scope}/{fname})*"
347
-
348
- new_history = (history or []) + [
349
- {"role": "user", "content": user_msg},
350
- {"role": "assistant", "content": reply},
351
- ]
352
-
353
- return new_history, "", fig_out, tab_out
354
-
355
-
356
- def _keyword_fallback(msg: str, idx: Dict, kpis: Dict) -> Tuple[str, Dict]:
357
- """Simple keyword matcher when LLM is unavailable."""
358
- msg_lower = msg.lower()
359
-
360
- if not any(idx[s]["figures"] or idx[s]["tables"] for s in ("python", "r")):
361
- return (
362
- "No artifacts found yet. Please run the pipeline first (Tab 1), "
363
- "then come back here to explore the results.",
364
- {"show": "none"},
365
- )
366
-
367
- kpi_text = ""
368
- if kpis:
369
- total = kpis.get("total_units_sold", 0)
370
- kpi_text = (
371
- f"Quick summary: **{kpis.get('n_titles', '?')}** book titles across "
372
- f"**{kpis.get('n_months', '?')}** months, with **{total:,.0f}** total units sold."
373
- )
374
-
375
- if any(w in msg_lower for w in ["trend", "sales trend", "monthly sale"]):
376
- return (
377
- f"Here are the sales trends for sampled titles. {kpi_text}",
378
- {"show": "figure", "scope": "python", "filename": "sales_trends_sampled_titles.png"},
379
- )
380
-
381
- if any(w in msg_lower for w in ["sentiment", "review", "positive", "negative"]):
382
- return (
383
- f"Here is the sentiment distribution across sampled book titles. {kpi_text}",
384
- {"show": "figure", "scope": "python", "filename": "sentiment_distribution_sampled_titles.png"},
385
- )
386
-
387
- if any(w in msg_lower for w in ["arima", "forecast", "predict"]):
388
- if "compar" in msg_lower or "ets" in msg_lower or "accuracy" in msg_lower:
389
- if "forecast_compare.png" in idx.get("r", {}).get("figures", []):
390
- return (
391
- "Here is the ARIMA+Fourier vs ETS forecast comparison from the R analysis.",
392
- {"show": "figure", "scope": "r", "filename": "forecast_compare.png"},
393
- )
394
- return (
395
- f"Here are the ARIMA forecasts for sampled titles from the Python analysis. {kpi_text}",
396
- {"show": "figure", "scope": "python", "filename": "arima_forecasts_sampled_titles.png"},
397
- )
398
-
399
- if any(w in msg_lower for w in ["regression", "lm", "coefficient", "price effect", "rating effect"]):
400
- return (
401
- "The R notebook focuses on forecasting rather than regression. "
402
- "Here is the forecast accuracy comparison instead.",
403
- {"show": "table", "scope": "r", "filename": "accuracy_table.csv"},
404
- )
405
-
406
- if any(w in msg_lower for w in ["top", "best sell", "popular", "rank"]):
407
- return (
408
- f"Here are the top-selling titles by units sold. {kpi_text}",
409
- {"show": "table", "scope": "python", "filename": "top_titles_by_units_sold.csv"},
410
- )
411
-
412
- if any(w in msg_lower for w in ["accuracy", "benchmark", "rmse", "mape"]):
413
- return (
414
- "Here is the forecast accuracy comparison (ARIMA+Fourier vs ETS) from the R analysis.",
415
- {"show": "table", "scope": "r", "filename": "accuracy_table.csv"},
416
- )
417
-
418
- if any(w in msg_lower for w in ["r analysis", "r output", "r result"]):
419
- if "forecast_compare.png" in idx.get("r", {}).get("figures", []):
420
- return (
421
- "Here is the main R output: forecast model comparison plot.",
422
- {"show": "figure", "scope": "r", "filename": "forecast_compare.png"},
423
- )
424
-
425
- if any(w in msg_lower for w in ["dashboard", "overview", "summary", "kpi"]):
426
- return (
427
- f"Dashboard overview: {kpi_text}\n\nAsk me about sales trends, sentiment, forecasts, "
428
- "forecast accuracy, or top sellers to see specific visualizations.",
429
- {"show": "table", "scope": "python", "filename": "df_dashboard.csv"},
430
- )
431
-
432
- # Default
433
- return (
434
- f"I can show you various analyses. {kpi_text}\n\n"
435
- "Try asking about: **sales trends**, **sentiment**, **ARIMA forecasts**, "
436
- "**forecast accuracy**, **top sellers**, or **dashboard overview**.",
437
- {"show": "none"},
438
- )
439
-
440
-
441
- # =========================================================
442
- # UI
443
- # =========================================================
444
-
445
- ensure_dirs()
446
-
447
- def load_css() -> str:
448
- css_path = BASE_DIR / "style.css"
449
- return css_path.read_text(encoding="utf-8") if css_path.exists() else ""
450
-
451
-
452
- with gr.Blocks(title="RX12 Workshop App") as demo:
453
-
454
- gr.Markdown(
455
- "# RX12 - Intro to Python and R - Workshop App\n"
456
- "*The app to integrate the three notebooks in to get a functioning blueprint of the group project's final product*",
457
- elem_id="escp_title",
458
- )
459
-
460
- # ===========================================================
461
- # TAB 1 -- Pipeline Runner
462
- # ===========================================================
463
- with gr.Tab("Pipeline Runner"):
464
- gr.Markdown(
465
- )
466
-
467
- with gr.Row():
468
- with gr.Column(scale=1):
469
- btn_nb1 = gr.Button(
470
- "Step 1: Python Analysis",
471
- variant="secondary",
472
- )
473
- gr.Markdown(
474
- )
475
- with gr.Column(scale=1):
476
- btn_nb2 = gr.Button(
477
- "Step 2: R Analysis",
478
- variant="secondary",
479
- )
480
- gr.Markdown(
481
- )
482
-
483
- with gr.Row():
484
- btn_all = gr.Button(
485
- "Run All 2 Steps",
486
- variant="primary",
487
- )
488
-
489
- run_log = gr.Textbox(
490
- label="Execution Log",
491
- lines=18,
492
- max_lines=30,
493
- interactive=False,
494
- )
495
-
496
- btn_nb1.click(run_pythonanalysis, outputs=[run_log])
497
- btn_nb2.click(run_ranalysis, outputs=[run_log])
498
- btn_all.click(run_full_pipeline, outputs=[run_log])
499
-
500
- # ===========================================================
501
- # TAB 2 -- Results Gallery
502
- # ===========================================================
503
- with gr.Tab("Results Gallery"):
504
- gr.Markdown(
505
- "### All generated artifacts\n\n"
506
- "After running the pipeline, click **Refresh** to load all figures and tables. "
507
- "Figures are shown in the gallery; select a table from the dropdown to inspect it."
508
- )
509
-
510
- refresh_btn = gr.Button("Refresh Gallery", variant="primary")
511
-
512
- gr.Markdown("#### Figures")
513
- gallery = gr.Gallery(
514
- label="All Figures (Python + R)",
515
- columns=2,
516
- height=480,
517
- object_fit="contain",
518
- )
519
-
520
- gr.Markdown("#### Tables")
521
- table_dropdown = gr.Dropdown(
522
- label="Select a table to view",
523
- choices=[],
524
- interactive=True,
525
- )
526
- table_display = gr.Dataframe(
527
- label="Table Preview",
528
- interactive=False,
529
- )
530
-
531
- refresh_btn.click(
532
- refresh_gallery,
533
- outputs=[gallery, table_dropdown, table_display],
534
- )
535
- table_dropdown.change(
536
- on_table_select,
537
- inputs=[table_dropdown],
538
- outputs=[table_display],
539
- )
540
-
541
- # ===========================================================
542
- # TAB 3 -- AI Dashboard
543
- # ===========================================================
544
- with gr.Tab('"AI" Dashboard'):
545
- gr.Markdown(
546
- "### Ask questions, get visualisations\n\n"
547
- "Describe what you want to see and the AI will pick the right chart or table. "
548
- + (
549
- "*LLM is active.*"
550
- if LLM_ENABLED
551
- else "*No API key detected \u2014 using keyword matching. "
552
- "Set `HF_API_KEY` in Space secrets for full LLM support.*"
553
- )
554
- )
555
-
556
- with gr.Row(equal_height=True):
557
- with gr.Column(scale=1):
558
- chatbot = gr.Chatbot(
559
- label="Conversation",
560
- height=380,
561
- )
562
- user_input = gr.Textbox(
563
- label="Ask about your data",
564
- placeholder="e.g. Show me sales trends / What drives revenue? / Compare forecast models",
565
- lines=1,
566
- )
567
- gr.Examples(
568
- examples=[
569
- "Show me the sales trends",
570
- "What does the sentiment look like?",
571
- "Which titles sell the most?",
572
- "Show the forecast accuracy comparison",
573
- "Compare the ARIMA and ETS forecasts",
574
- "Give me a dashboard overview",
575
- ],
576
- inputs=user_input,
577
- )
578
-
579
- with gr.Column(scale=1):
580
- ai_figure = gr.Image(
581
- label="Visualisation",
582
- height=350,
583
- )
584
- ai_table = gr.Dataframe(
585
- label="Data Table",
586
- interactive=False,
587
- )
588
-
589
- user_input.submit(
590
- ai_chat,
591
- inputs=[user_input, chatbot],
592
- outputs=[chatbot, user_input, ai_figure, ai_table],
593
- )
594
-
595
-
596
- demo.launch(css=load_css(), allowed_paths=[str(BASE_DIR)])