Spaces:
Running
Running
Upload 11 files
Browse files- .gitattributes +1 -0
- Dockerfile.txt +26 -0
- README.md +5 -4
- app.py +758 -0
- background_bottom.png +0 -0
- background_mid.png +0 -0
- background_top.png +3 -0
- datacreation.ipynb +1115 -0
- gitattributes.txt +36 -0
- phytonanalysis.ipynb +0 -0
- requirements.txt +17 -0
- style.css +326 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
background_top.png filter=lfs diff=lfs merge=lfs -text
|
Dockerfile.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 4 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 5 |
+
ENV PYTHONUNBUFFERED=1
|
| 6 |
+
|
| 7 |
+
ENV GRADIO_SERVER_NAME=0.0.0.0
|
| 8 |
+
ENV GRADIO_SERVER_PORT=7860
|
| 9 |
+
|
| 10 |
+
WORKDIR /app
|
| 11 |
+
COPY . /app
|
| 12 |
+
|
| 13 |
+
# Python deps (from requirements.txt)
|
| 14 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
+
|
| 16 |
+
# Notebook execution deps
|
| 17 |
+
RUN pip install --no-cache-dir notebook ipykernel papermill
|
| 18 |
+
|
| 19 |
+
# Pre-install packages the notebooks use via !pip install
|
| 20 |
+
RUN pip install --no-cache-dir textblob faker vaderSentiment transformers
|
| 21 |
+
|
| 22 |
+
RUN python -m ipykernel install --user --name python3 --display-name "Python 3"
|
| 23 |
+
|
| 24 |
+
EXPOSE 7860
|
| 25 |
+
|
| 26 |
+
CMD ["python", "app.py"]
|
README.md
CHANGED
|
@@ -1,10 +1,11 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: SE21 App Template
|
| 3 |
+
emoji: 📊
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
short_description: AI-enhanced analytics dashboard template for SE21 students
|
| 9 |
---
|
| 10 |
|
| 11 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,758 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 student's n8n webhook and return (reply, directive)."""
|
| 268 |
+
import requests as req
|
| 269 |
+
try:
|
| 270 |
+
resp = req.post(N8N_WEBHOOK_URL, json={"question": msg}, timeout=20)
|
| 271 |
+
data = resp.json()
|
| 272 |
+
answer = data.get("answer", "No response from n8n workflow.")
|
| 273 |
+
chart = data.get("chart", "none")
|
| 274 |
+
if chart and chart != "none":
|
| 275 |
+
return answer, {"show": "figure", "chart": chart}
|
| 276 |
+
return answer, {"show": "none"}
|
| 277 |
+
except Exception as e:
|
| 278 |
+
return f"n8n error: {e}. Falling back to keyword matching.", None
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def ai_chat(user_msg: str, history: list):
|
| 282 |
+
"""Chat function for the AI Dashboard tab."""
|
| 283 |
+
if not user_msg or not user_msg.strip():
|
| 284 |
+
return history, "", None, None
|
| 285 |
+
|
| 286 |
+
idx = artifacts_index()
|
| 287 |
+
kpis = load_kpis()
|
| 288 |
+
|
| 289 |
+
# Priority: n8n webhook > HF LLM > keyword fallback
|
| 290 |
+
if N8N_WEBHOOK_URL:
|
| 291 |
+
reply, directive = _n8n_call(user_msg)
|
| 292 |
+
if directive is None:
|
| 293 |
+
reply_fb, directive = _keyword_fallback(user_msg, idx, kpis)
|
| 294 |
+
reply += "\n\n" + reply_fb
|
| 295 |
+
elif 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 artifacts — build interactive Plotly charts when possible
|
| 328 |
+
chart_out = None
|
| 329 |
+
tab_out = None
|
| 330 |
+
show = directive.get("show", "none")
|
| 331 |
+
fname = directive.get("filename", "")
|
| 332 |
+
chart_name = directive.get("chart", "")
|
| 333 |
+
|
| 334 |
+
# Interactive chart builders keyed by name
|
| 335 |
+
chart_builders = {
|
| 336 |
+
"sales": build_sales_chart,
|
| 337 |
+
"sentiment": build_sentiment_chart,
|
| 338 |
+
"top_sellers": build_top_sellers_chart,
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
if chart_name and chart_name in chart_builders:
|
| 342 |
+
chart_out = chart_builders[chart_name]()
|
| 343 |
+
elif show == "figure" and fname:
|
| 344 |
+
# Fallback: try to match filename to a chart builder
|
| 345 |
+
if "sales_trend" in fname:
|
| 346 |
+
chart_out = build_sales_chart()
|
| 347 |
+
elif "sentiment" in fname:
|
| 348 |
+
chart_out = build_sentiment_chart()
|
| 349 |
+
elif "arima" in fname or "forecast" in fname:
|
| 350 |
+
chart_out = build_sales_chart() # closest interactive equivalent
|
| 351 |
+
else:
|
| 352 |
+
chart_out = _empty_chart(f"No interactive chart for {fname}")
|
| 353 |
+
|
| 354 |
+
if show == "table" and fname:
|
| 355 |
+
fp = PY_TAB_DIR / fname
|
| 356 |
+
if fp.exists():
|
| 357 |
+
tab_out = _load_table_safe(fp)
|
| 358 |
+
else:
|
| 359 |
+
reply += f"\n\n*(Could not find table: {fname})*"
|
| 360 |
+
|
| 361 |
+
new_history = (history or []) + [
|
| 362 |
+
{"role": "user", "content": user_msg},
|
| 363 |
+
{"role": "assistant", "content": reply},
|
| 364 |
+
]
|
| 365 |
+
|
| 366 |
+
return new_history, "", chart_out, tab_out
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _keyword_fallback(msg: str, idx: Dict, kpis: Dict) -> Tuple[str, Dict]:
|
| 370 |
+
"""Simple keyword matcher when LLM is unavailable."""
|
| 371 |
+
msg_lower = msg.lower()
|
| 372 |
+
|
| 373 |
+
if not idx["python"]["figures"] and not idx["python"]["tables"]:
|
| 374 |
+
return (
|
| 375 |
+
"No artifacts found yet. Please run the pipeline first (Tab 1), "
|
| 376 |
+
"then come back here to explore the results.",
|
| 377 |
+
{"show": "none"},
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
kpi_text = ""
|
| 381 |
+
if kpis:
|
| 382 |
+
total = kpis.get("total_units_sold", 0)
|
| 383 |
+
kpi_text = (
|
| 384 |
+
f"Quick summary: **{kpis.get('n_titles', '?')}** book titles across "
|
| 385 |
+
f"**{kpis.get('n_months', '?')}** months, with **{total:,.0f}** total units sold."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
if any(w in msg_lower for w in ["trend", "sales trend", "monthly sale"]):
|
| 389 |
+
return (
|
| 390 |
+
f"Here are the sales trends. {kpi_text}",
|
| 391 |
+
{"show": "figure", "chart": "sales"},
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
if any(w in msg_lower for w in ["sentiment", "review", "positive", "negative"]):
|
| 395 |
+
return (
|
| 396 |
+
f"Here is the sentiment distribution across sampled book titles. {kpi_text}",
|
| 397 |
+
{"show": "figure", "chart": "sentiment"},
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
if any(w in msg_lower for w in ["arima", "forecast", "predict"]):
|
| 401 |
+
return (
|
| 402 |
+
f"Here are the sales trends and forecasts. {kpi_text}",
|
| 403 |
+
{"show": "figure", "chart": "sales"},
|
| 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 ["price", "pricing", "decision"]):
|
| 413 |
+
return (
|
| 414 |
+
f"Here are the pricing decisions. {kpi_text}",
|
| 415 |
+
{"show": "table", "scope": "python", "filename": "pricing_decisions.csv"},
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
if any(w in msg_lower for w in ["dashboard", "overview", "summary", "kpi"]):
|
| 419 |
+
return (
|
| 420 |
+
f"Dashboard overview: {kpi_text}\n\nAsk me about sales trends, sentiment, forecasts, "
|
| 421 |
+
"pricing, or top sellers to see specific visualizations.",
|
| 422 |
+
{"show": "table", "scope": "python", "filename": "df_dashboard.csv"},
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
# Default
|
| 426 |
+
return (
|
| 427 |
+
f"I can show you various analyses. {kpi_text}\n\n"
|
| 428 |
+
"Try asking about: **sales trends**, **sentiment**, **ARIMA forecasts**, "
|
| 429 |
+
"**pricing decisions**, **top sellers**, or **dashboard overview**.",
|
| 430 |
+
{"show": "none"},
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
# =========================================================
|
| 435 |
+
# KPI CARDS (BubbleBusters style)
|
| 436 |
+
# =========================================================
|
| 437 |
+
|
| 438 |
+
def render_kpi_cards() -> str:
|
| 439 |
+
kpis = load_kpis()
|
| 440 |
+
if not kpis:
|
| 441 |
+
return (
|
| 442 |
+
'<div style="background:rgba(255,255,255,.65);backdrop-filter:blur(16px);'
|
| 443 |
+
'border-radius:20px;padding:28px;text-align:center;'
|
| 444 |
+
'border:1.5px solid rgba(255,255,255,.7);'
|
| 445 |
+
'box-shadow:0 8px 32px rgba(124,92,191,.08);">'
|
| 446 |
+
'<div style="font-size:36px;margin-bottom:10px;">📊</div>'
|
| 447 |
+
'<div style="color:#a48de8;font-size:14px;'
|
| 448 |
+
'font-weight:800;margin-bottom:6px;">No data yet</div>'
|
| 449 |
+
'<div style="color:#9d8fc4;font-size:12px;">'
|
| 450 |
+
'Run the pipeline to populate these cards.</div>'
|
| 451 |
+
'</div>'
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
def card(icon, label, value, colour):
|
| 455 |
+
return f"""
|
| 456 |
+
<div style="background:rgba(255,255,255,.72);backdrop-filter:blur(16px);
|
| 457 |
+
border-radius:20px;padding:18px 14px 16px;text-align:center;
|
| 458 |
+
border:1.5px solid rgba(255,255,255,.8);
|
| 459 |
+
box-shadow:0 4px 16px rgba(124,92,191,.08);
|
| 460 |
+
border-top:3px solid {colour};">
|
| 461 |
+
<div style="font-size:26px;margin-bottom:7px;line-height:1;">{icon}</div>
|
| 462 |
+
<div style="color:#9d8fc4;font-size:9.5px;text-transform:uppercase;
|
| 463 |
+
letter-spacing:1.8px;margin-bottom:7px;font-weight:800;">{label}</div>
|
| 464 |
+
<div style="color:#2d1f4e;font-size:16px;font-weight:800;">{value}</div>
|
| 465 |
+
</div>"""
|
| 466 |
+
|
| 467 |
+
kpi_config = [
|
| 468 |
+
("n_titles", "📚", "Book Titles", "#a48de8"),
|
| 469 |
+
("n_months", "📅", "Time Periods", "#7aa6f8"),
|
| 470 |
+
("total_units_sold", "📦", "Units Sold", "#6ee7c7"),
|
| 471 |
+
("total_revenue", "💰", "Revenue", "#3dcba8"),
|
| 472 |
+
]
|
| 473 |
+
|
| 474 |
+
html = (
|
| 475 |
+
'<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));'
|
| 476 |
+
'gap:12px;margin-bottom:24px;">'
|
| 477 |
+
)
|
| 478 |
+
for key, icon, label, colour in kpi_config:
|
| 479 |
+
val = kpis.get(key)
|
| 480 |
+
if val is None:
|
| 481 |
+
continue
|
| 482 |
+
if isinstance(val, (int, float)) and val > 100:
|
| 483 |
+
val = f"{val:,.0f}"
|
| 484 |
+
html += card(icon, label, str(val), colour)
|
| 485 |
+
# Extra KPIs not in config
|
| 486 |
+
known = {k for k, *_ in kpi_config}
|
| 487 |
+
for key, val in kpis.items():
|
| 488 |
+
if key not in known:
|
| 489 |
+
label = key.replace("_", " ").title()
|
| 490 |
+
if isinstance(val, (int, float)) and val > 100:
|
| 491 |
+
val = f"{val:,.0f}"
|
| 492 |
+
html += card("📈", label, str(val), "#8fa8f8")
|
| 493 |
+
html += "</div>"
|
| 494 |
+
return html
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
# =========================================================
|
| 498 |
+
# INTERACTIVE PLOTLY CHARTS (BubbleBusters style)
|
| 499 |
+
# =========================================================
|
| 500 |
+
|
| 501 |
+
CHART_PALETTE = ["#7c5cbf", "#2ec4a0", "#e8537a", "#e8a230", "#5e8fef",
|
| 502 |
+
"#c45ea8", "#3dbacc", "#a0522d", "#6aaa3a", "#d46060"]
|
| 503 |
+
|
| 504 |
+
def _styled_layout(**kwargs) -> dict:
|
| 505 |
+
defaults = dict(
|
| 506 |
+
template="plotly_white",
|
| 507 |
+
paper_bgcolor="rgba(255,255,255,0.95)",
|
| 508 |
+
plot_bgcolor="rgba(255,255,255,0.98)",
|
| 509 |
+
font=dict(family="system-ui, sans-serif", color="#2d1f4e", size=12),
|
| 510 |
+
margin=dict(l=60, r=20, t=70, b=70),
|
| 511 |
+
legend=dict(
|
| 512 |
+
orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1,
|
| 513 |
+
bgcolor="rgba(255,255,255,0.92)",
|
| 514 |
+
bordercolor="rgba(124,92,191,0.35)", borderwidth=1,
|
| 515 |
+
),
|
| 516 |
+
title=dict(font=dict(size=15, color="#4b2d8a")),
|
| 517 |
+
)
|
| 518 |
+
defaults.update(kwargs)
|
| 519 |
+
return defaults
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def _empty_chart(title: str) -> go.Figure:
|
| 523 |
+
fig = go.Figure()
|
| 524 |
+
fig.update_layout(
|
| 525 |
+
title=title, height=420, template="plotly_white",
|
| 526 |
+
paper_bgcolor="rgba(255,255,255,0.95)",
|
| 527 |
+
annotations=[dict(text="Run the pipeline to generate data",
|
| 528 |
+
x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False,
|
| 529 |
+
font=dict(size=14, color="rgba(124,92,191,0.5)"))],
|
| 530 |
+
)
|
| 531 |
+
return fig
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def build_sales_chart() -> go.Figure:
|
| 535 |
+
path = PY_TAB_DIR / "df_dashboard.csv"
|
| 536 |
+
if not path.exists():
|
| 537 |
+
return _empty_chart("Sales Trends — run the pipeline first")
|
| 538 |
+
df = pd.read_csv(path)
|
| 539 |
+
date_col = next((c for c in df.columns if "month" in c.lower() or "date" in c.lower()), None)
|
| 540 |
+
val_cols = [c for c in df.columns if c != date_col and df[c].dtype in ("float64", "int64")]
|
| 541 |
+
if not date_col or not val_cols:
|
| 542 |
+
return _empty_chart("Could not auto-detect columns in df_dashboard.csv")
|
| 543 |
+
df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
|
| 544 |
+
fig = go.Figure()
|
| 545 |
+
for i, col in enumerate(val_cols):
|
| 546 |
+
fig.add_trace(go.Scatter(
|
| 547 |
+
x=df[date_col], y=df[col], name=col.replace("_", " ").title(),
|
| 548 |
+
mode="lines+markers", line=dict(color=CHART_PALETTE[i % len(CHART_PALETTE)], width=2),
|
| 549 |
+
marker=dict(size=4),
|
| 550 |
+
hovertemplate=f"<b>{col.replace('_',' ').title()}</b><br>%{{x|%b %Y}}: %{{y:,.0f}}<extra></extra>",
|
| 551 |
+
))
|
| 552 |
+
fig.update_layout(**_styled_layout(height=450, hovermode="x unified",
|
| 553 |
+
title=dict(text="Monthly Overview")))
|
| 554 |
+
fig.update_xaxes(gridcolor="rgba(124,92,191,0.15)", showgrid=True)
|
| 555 |
+
fig.update_yaxes(gridcolor="rgba(124,92,191,0.15)", showgrid=True)
|
| 556 |
+
return fig
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def build_sentiment_chart() -> go.Figure:
|
| 560 |
+
path = PY_TAB_DIR / "sentiment_counts_sampled.csv"
|
| 561 |
+
if not path.exists():
|
| 562 |
+
return _empty_chart("Sentiment Distribution — run the pipeline first")
|
| 563 |
+
df = pd.read_csv(path)
|
| 564 |
+
title_col = df.columns[0]
|
| 565 |
+
sent_cols = [c for c in ["negative", "neutral", "positive"] if c in df.columns]
|
| 566 |
+
if not sent_cols:
|
| 567 |
+
return _empty_chart("No sentiment columns found in CSV")
|
| 568 |
+
colors = {"negative": "#e8537a", "neutral": "#5e8fef", "positive": "#2ec4a0"}
|
| 569 |
+
fig = go.Figure()
|
| 570 |
+
for col in sent_cols:
|
| 571 |
+
fig.add_trace(go.Bar(
|
| 572 |
+
name=col.title(), y=df[title_col], x=df[col],
|
| 573 |
+
orientation="h", marker_color=colors.get(col, "#888"),
|
| 574 |
+
hovertemplate=f"<b>{col.title()}</b>: %{{x}}<extra></extra>",
|
| 575 |
+
))
|
| 576 |
+
fig.update_layout(**_styled_layout(
|
| 577 |
+
height=max(400, len(df) * 28), barmode="stack",
|
| 578 |
+
title=dict(text="Sentiment Distribution by Book"),
|
| 579 |
+
))
|
| 580 |
+
fig.update_xaxes(title="Number of Reviews")
|
| 581 |
+
fig.update_yaxes(autorange="reversed")
|
| 582 |
+
return fig
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def build_top_sellers_chart() -> go.Figure:
|
| 586 |
+
path = PY_TAB_DIR / "top_titles_by_units_sold.csv"
|
| 587 |
+
if not path.exists():
|
| 588 |
+
return _empty_chart("Top Sellers — run the pipeline first")
|
| 589 |
+
df = pd.read_csv(path).head(15)
|
| 590 |
+
title_col = next((c for c in df.columns if "title" in c.lower()), df.columns[0])
|
| 591 |
+
val_col = next((c for c in df.columns if "unit" in c.lower() or "sold" in c.lower()), df.columns[-1])
|
| 592 |
+
fig = go.Figure(go.Bar(
|
| 593 |
+
y=df[title_col], x=df[val_col], orientation="h",
|
| 594 |
+
marker=dict(color=df[val_col], colorscale=[[0, "#c5b4f0"], [1, "#7c5cbf"]]),
|
| 595 |
+
hovertemplate="<b>%{y}</b><br>Units: %{x:,.0f}<extra></extra>",
|
| 596 |
+
))
|
| 597 |
+
fig.update_layout(**_styled_layout(
|
| 598 |
+
height=max(400, len(df) * 30),
|
| 599 |
+
title=dict(text="Top Selling Titles"), showlegend=False,
|
| 600 |
+
))
|
| 601 |
+
fig.update_yaxes(autorange="reversed")
|
| 602 |
+
fig.update_xaxes(title="Total Units Sold")
|
| 603 |
+
return fig
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def refresh_dashboard():
|
| 607 |
+
return render_kpi_cards(), build_sales_chart(), build_sentiment_chart(), build_top_sellers_chart()
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
# =========================================================
|
| 611 |
+
# UI
|
| 612 |
+
# =========================================================
|
| 613 |
+
|
| 614 |
+
ensure_dirs()
|
| 615 |
+
|
| 616 |
+
def load_css() -> str:
|
| 617 |
+
css_path = BASE_DIR / "style.css"
|
| 618 |
+
return css_path.read_text(encoding="utf-8") if css_path.exists() else ""
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
with gr.Blocks(title="AIBDM 2026 Workshop App") as demo:
|
| 622 |
+
|
| 623 |
+
gr.Markdown(
|
| 624 |
+
"# SE21 App Template\n"
|
| 625 |
+
"*This is an app template for SE21 students*",
|
| 626 |
+
elem_id="escp_title",
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
# ===========================================================
|
| 630 |
+
# TAB 1 -- Pipeline Runner
|
| 631 |
+
# ===========================================================
|
| 632 |
+
with gr.Tab("Pipeline Runner"):
|
| 633 |
+
gr.Markdown()
|
| 634 |
+
|
| 635 |
+
with gr.Row():
|
| 636 |
+
with gr.Column(scale=1):
|
| 637 |
+
btn_nb1 = gr.Button("Step 1: Data Creation", variant="secondary")
|
| 638 |
+
with gr.Column(scale=1):
|
| 639 |
+
btn_nb2 = gr.Button("Step 2: Python Analysis", variant="secondary")
|
| 640 |
+
|
| 641 |
+
with gr.Row():
|
| 642 |
+
btn_all = gr.Button("Run Full Pipeline (Both Steps)", variant="primary")
|
| 643 |
+
|
| 644 |
+
run_log = gr.Textbox(
|
| 645 |
+
label="Execution Log",
|
| 646 |
+
lines=18,
|
| 647 |
+
max_lines=30,
|
| 648 |
+
interactive=False,
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
btn_nb1.click(run_datacreation, outputs=[run_log])
|
| 652 |
+
btn_nb2.click(run_pythonanalysis, outputs=[run_log])
|
| 653 |
+
btn_all.click(run_full_pipeline, outputs=[run_log])
|
| 654 |
+
|
| 655 |
+
# ===========================================================
|
| 656 |
+
# TAB 2 -- Dashboard (KPIs + Interactive Charts + Gallery)
|
| 657 |
+
# ===========================================================
|
| 658 |
+
with gr.Tab("Dashboard"):
|
| 659 |
+
kpi_html = gr.HTML(value=render_kpi_cards)
|
| 660 |
+
|
| 661 |
+
refresh_btn = gr.Button("Refresh Dashboard", variant="primary")
|
| 662 |
+
|
| 663 |
+
gr.Markdown("#### Interactive Charts")
|
| 664 |
+
chart_sales = gr.Plot(label="Monthly Overview")
|
| 665 |
+
chart_sentiment = gr.Plot(label="Sentiment Distribution")
|
| 666 |
+
chart_top = gr.Plot(label="Top Sellers")
|
| 667 |
+
|
| 668 |
+
gr.Markdown("#### Static Figures (from notebooks)")
|
| 669 |
+
gallery = gr.Gallery(
|
| 670 |
+
label="Generated Figures",
|
| 671 |
+
columns=2,
|
| 672 |
+
height=480,
|
| 673 |
+
object_fit="contain",
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
gr.Markdown("#### Data Tables")
|
| 677 |
+
table_dropdown = gr.Dropdown(
|
| 678 |
+
label="Select a table to view",
|
| 679 |
+
choices=[],
|
| 680 |
+
interactive=True,
|
| 681 |
+
)
|
| 682 |
+
table_display = gr.Dataframe(
|
| 683 |
+
label="Table Preview",
|
| 684 |
+
interactive=False,
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
def _on_refresh():
|
| 688 |
+
kpi, c1, c2, c3 = refresh_dashboard()
|
| 689 |
+
figs, dd, df = refresh_gallery()
|
| 690 |
+
return kpi, c1, c2, c3, figs, dd, df
|
| 691 |
+
|
| 692 |
+
refresh_btn.click(
|
| 693 |
+
_on_refresh,
|
| 694 |
+
outputs=[kpi_html, chart_sales, chart_sentiment, chart_top,
|
| 695 |
+
gallery, table_dropdown, table_display],
|
| 696 |
+
)
|
| 697 |
+
table_dropdown.change(
|
| 698 |
+
on_table_select,
|
| 699 |
+
inputs=[table_dropdown],
|
| 700 |
+
outputs=[table_display],
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
# ===========================================================
|
| 704 |
+
# TAB 3 -- AI Dashboard
|
| 705 |
+
# ===========================================================
|
| 706 |
+
with gr.Tab('"AI" Dashboard'):
|
| 707 |
+
_ai_status = (
|
| 708 |
+
"Connected to your **n8n workflow**." if N8N_WEBHOOK_URL
|
| 709 |
+
else "**LLM active.**" if LLM_ENABLED
|
| 710 |
+
else "Using **keyword matching**. Upgrade options: "
|
| 711 |
+
"set `N8N_WEBHOOK_URL` to connect your n8n workflow, "
|
| 712 |
+
"or set `HF_API_KEY` for direct LLM access."
|
| 713 |
+
)
|
| 714 |
+
gr.Markdown(
|
| 715 |
+
"### Ask questions, get interactive visualisations\n\n"
|
| 716 |
+
f"Type a question and the system will pick the right interactive chart or table. {_ai_status}"
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
with gr.Row(equal_height=True):
|
| 720 |
+
with gr.Column(scale=1):
|
| 721 |
+
chatbot = gr.Chatbot(
|
| 722 |
+
label="Conversation",
|
| 723 |
+
height=380,
|
| 724 |
+
)
|
| 725 |
+
user_input = gr.Textbox(
|
| 726 |
+
label="Ask about your data",
|
| 727 |
+
placeholder="e.g. Show me sales trends / What are the top sellers? / Sentiment analysis",
|
| 728 |
+
lines=1,
|
| 729 |
+
)
|
| 730 |
+
gr.Examples(
|
| 731 |
+
examples=[
|
| 732 |
+
"Show me the sales trends",
|
| 733 |
+
"What does the sentiment look like?",
|
| 734 |
+
"Which titles sell the most?",
|
| 735 |
+
"Show the ARIMA forecasts",
|
| 736 |
+
"What are the pricing decisions?",
|
| 737 |
+
"Give me a dashboard overview",
|
| 738 |
+
],
|
| 739 |
+
inputs=user_input,
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
with gr.Column(scale=1):
|
| 743 |
+
ai_figure = gr.Plot(
|
| 744 |
+
label="Interactive Chart",
|
| 745 |
+
)
|
| 746 |
+
ai_table = gr.Dataframe(
|
| 747 |
+
label="Data Table",
|
| 748 |
+
interactive=False,
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
user_input.submit(
|
| 752 |
+
ai_chat,
|
| 753 |
+
inputs=[user_input, chatbot],
|
| 754 |
+
outputs=[chatbot, user_input, ai_figure, ai_table],
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
demo.launch(css=load_css(), allowed_paths=[str(BASE_DIR)])
|
background_bottom.png
ADDED
|
background_mid.png
ADDED
|
background_top.png
ADDED
|
Git LFS Details
|
datacreation.ipynb
ADDED
|
@@ -0,0 +1,1115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {
|
| 6 |
+
"id": "4ba6aba8"
|
| 7 |
+
},
|
| 8 |
+
"source": [
|
| 9 |
+
"# 🤖 **Data Collection, Creation, Storage, and Processing**\n"
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "markdown",
|
| 14 |
+
"metadata": {
|
| 15 |
+
"id": "jpASMyIQMaAq"
|
| 16 |
+
},
|
| 17 |
+
"source": [
|
| 18 |
+
"## **1.** 📦 Install required packages"
|
| 19 |
+
]
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "code",
|
| 23 |
+
"execution_count": 1,
|
| 24 |
+
"metadata": {
|
| 25 |
+
"colab": {
|
| 26 |
+
"base_uri": "https://localhost:8080/"
|
| 27 |
+
},
|
| 28 |
+
"id": "f48c8f8c",
|
| 29 |
+
"outputId": "f8d51091-958a-4036-b813-fcd48731812d"
|
| 30 |
+
},
|
| 31 |
+
"outputs": [
|
| 32 |
+
{
|
| 33 |
+
"output_type": "stream",
|
| 34 |
+
"name": "stdout",
|
| 35 |
+
"text": [
|
| 36 |
+
"Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
|
| 37 |
+
"Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
|
| 38 |
+
"Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
|
| 39 |
+
"Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
|
| 40 |
+
"Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
|
| 41 |
+
"Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
|
| 42 |
+
"Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
|
| 43 |
+
"Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
|
| 44 |
+
"Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
|
| 45 |
+
"Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
|
| 46 |
+
"Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
|
| 47 |
+
"Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
|
| 48 |
+
"Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
|
| 49 |
+
"Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.62.0)\n",
|
| 50 |
+
"Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.5.0)\n",
|
| 51 |
+
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
|
| 52 |
+
"Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
|
| 53 |
+
"Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
|
| 54 |
+
"Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
|
| 55 |
+
"Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
|
| 56 |
+
"Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
|
| 57 |
+
"Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
|
| 58 |
+
"Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
|
| 59 |
+
"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
|
| 60 |
+
]
|
| 61 |
+
}
|
| 62 |
+
],
|
| 63 |
+
"source": [
|
| 64 |
+
"!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
|
| 65 |
+
]
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "markdown",
|
| 69 |
+
"metadata": {
|
| 70 |
+
"id": "lquNYCbfL9IM"
|
| 71 |
+
},
|
| 72 |
+
"source": [
|
| 73 |
+
"## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
|
| 74 |
+
]
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "markdown",
|
| 78 |
+
"metadata": {
|
| 79 |
+
"id": "0IWuNpxxYDJF"
|
| 80 |
+
},
|
| 81 |
+
"source": [
|
| 82 |
+
"### *a. Initial setup*\n",
|
| 83 |
+
"Define the base url of the website you will scrape as well as how and what you will scrape"
|
| 84 |
+
]
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"execution_count": 2,
|
| 89 |
+
"metadata": {
|
| 90 |
+
"id": "91d52125"
|
| 91 |
+
},
|
| 92 |
+
"outputs": [],
|
| 93 |
+
"source": [
|
| 94 |
+
"import requests\n",
|
| 95 |
+
"from bs4 import BeautifulSoup\n",
|
| 96 |
+
"import pandas as pd\n",
|
| 97 |
+
"import time\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
|
| 100 |
+
"headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"titles, prices, ratings = [], [], []"
|
| 103 |
+
]
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "markdown",
|
| 107 |
+
"metadata": {
|
| 108 |
+
"id": "oCdTsin2Yfp3"
|
| 109 |
+
},
|
| 110 |
+
"source": [
|
| 111 |
+
"### *b. Fill titles, prices, and ratings from the web pages*"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"execution_count": 3,
|
| 117 |
+
"metadata": {
|
| 118 |
+
"id": "xqO5Y3dnYhxt"
|
| 119 |
+
},
|
| 120 |
+
"outputs": [],
|
| 121 |
+
"source": [
|
| 122 |
+
"# Loop through all 50 pages\n",
|
| 123 |
+
"for page in range(1, 51):\n",
|
| 124 |
+
" url = base_url.format(page)\n",
|
| 125 |
+
" response = requests.get(url, headers=headers)\n",
|
| 126 |
+
" soup = BeautifulSoup(response.content, \"html.parser\")\n",
|
| 127 |
+
" books = soup.find_all(\"article\", class_=\"product_pod\")\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" for book in books:\n",
|
| 130 |
+
" titles.append(book.h3.a[\"title\"])\n",
|
| 131 |
+
" prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
|
| 132 |
+
" ratings.append(book.p.get(\"class\")[1])\n",
|
| 133 |
+
"\n",
|
| 134 |
+
" time.sleep(0.5) # polite scraping delay"
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "markdown",
|
| 139 |
+
"metadata": {
|
| 140 |
+
"id": "T0TOeRC4Yrnn"
|
| 141 |
+
},
|
| 142 |
+
"source": [
|
| 143 |
+
"### *c. ✋🏻🛑⛔️ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
|
| 144 |
+
]
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"execution_count": 5,
|
| 149 |
+
"metadata": {
|
| 150 |
+
"id": "l5FkkNhUYTHh"
|
| 151 |
+
},
|
| 152 |
+
"outputs": [],
|
| 153 |
+
"source": [
|
| 154 |
+
"df_books = pd.DataFrame({\n",
|
| 155 |
+
" \"title\": titles,\n",
|
| 156 |
+
" \"price\": prices,\n",
|
| 157 |
+
" \"rating\": ratings\n",
|
| 158 |
+
"})"
|
| 159 |
+
]
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "markdown",
|
| 163 |
+
"metadata": {
|
| 164 |
+
"id": "duI5dv3CZYvF"
|
| 165 |
+
},
|
| 166 |
+
"source": [
|
| 167 |
+
"### *d. Save web-scraped dataframe either as a CSV or Excel file*"
|
| 168 |
+
]
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"execution_count": 6,
|
| 173 |
+
"metadata": {
|
| 174 |
+
"id": "lC1U_YHtZifh"
|
| 175 |
+
},
|
| 176 |
+
"outputs": [],
|
| 177 |
+
"source": [
|
| 178 |
+
"# 💾 Save to CSV\n",
|
| 179 |
+
"df_books.to_csv(\"books_data.csv\", index=False)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"# 💾 Or save to Excel\n",
|
| 182 |
+
"# df_books.to_excel(\"books_data.xlsx\", index=False)"
|
| 183 |
+
]
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "markdown",
|
| 187 |
+
"metadata": {
|
| 188 |
+
"id": "qMjRKMBQZlJi"
|
| 189 |
+
},
|
| 190 |
+
"source": [
|
| 191 |
+
"### *e. ✋🏻🛑⛔️ View first fiew lines*"
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"execution_count": 7,
|
| 197 |
+
"metadata": {
|
| 198 |
+
"colab": {
|
| 199 |
+
"base_uri": "https://localhost:8080/",
|
| 200 |
+
"height": 204
|
| 201 |
+
},
|
| 202 |
+
"id": "O_wIvTxYZqCK",
|
| 203 |
+
"outputId": "70f4452e-d214-43bb-9910-43cbc005480a"
|
| 204 |
+
},
|
| 205 |
+
"outputs": [
|
| 206 |
+
{
|
| 207 |
+
"output_type": "execute_result",
|
| 208 |
+
"data": {
|
| 209 |
+
"text/plain": [
|
| 210 |
+
" title price rating\n",
|
| 211 |
+
"0 A Light in the Attic 51.77 Three\n",
|
| 212 |
+
"1 Tipping the Velvet 53.74 One\n",
|
| 213 |
+
"2 Soumission 50.10 One\n",
|
| 214 |
+
"3 Sharp Objects 47.82 Four\n",
|
| 215 |
+
"4 Sapiens: A Brief History of Humankind 54.23 Five"
|
| 216 |
+
],
|
| 217 |
+
"text/html": [
|
| 218 |
+
"\n",
|
| 219 |
+
" <div id=\"df-48ba0e17-743a-4ebb-9c53-fc4223caf207\" class=\"colab-df-container\">\n",
|
| 220 |
+
" <div>\n",
|
| 221 |
+
"<style scoped>\n",
|
| 222 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 223 |
+
" vertical-align: middle;\n",
|
| 224 |
+
" }\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" .dataframe tbody tr th {\n",
|
| 227 |
+
" vertical-align: top;\n",
|
| 228 |
+
" }\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" .dataframe thead th {\n",
|
| 231 |
+
" text-align: right;\n",
|
| 232 |
+
" }\n",
|
| 233 |
+
"</style>\n",
|
| 234 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 235 |
+
" <thead>\n",
|
| 236 |
+
" <tr style=\"text-align: right;\">\n",
|
| 237 |
+
" <th></th>\n",
|
| 238 |
+
" <th>title</th>\n",
|
| 239 |
+
" <th>price</th>\n",
|
| 240 |
+
" <th>rating</th>\n",
|
| 241 |
+
" </tr>\n",
|
| 242 |
+
" </thead>\n",
|
| 243 |
+
" <tbody>\n",
|
| 244 |
+
" <tr>\n",
|
| 245 |
+
" <th>0</th>\n",
|
| 246 |
+
" <td>A Light in the Attic</td>\n",
|
| 247 |
+
" <td>51.77</td>\n",
|
| 248 |
+
" <td>Three</td>\n",
|
| 249 |
+
" </tr>\n",
|
| 250 |
+
" <tr>\n",
|
| 251 |
+
" <th>1</th>\n",
|
| 252 |
+
" <td>Tipping the Velvet</td>\n",
|
| 253 |
+
" <td>53.74</td>\n",
|
| 254 |
+
" <td>One</td>\n",
|
| 255 |
+
" </tr>\n",
|
| 256 |
+
" <tr>\n",
|
| 257 |
+
" <th>2</th>\n",
|
| 258 |
+
" <td>Soumission</td>\n",
|
| 259 |
+
" <td>50.10</td>\n",
|
| 260 |
+
" <td>One</td>\n",
|
| 261 |
+
" </tr>\n",
|
| 262 |
+
" <tr>\n",
|
| 263 |
+
" <th>3</th>\n",
|
| 264 |
+
" <td>Sharp Objects</td>\n",
|
| 265 |
+
" <td>47.82</td>\n",
|
| 266 |
+
" <td>Four</td>\n",
|
| 267 |
+
" </tr>\n",
|
| 268 |
+
" <tr>\n",
|
| 269 |
+
" <th>4</th>\n",
|
| 270 |
+
" <td>Sapiens: A Brief History of Humankind</td>\n",
|
| 271 |
+
" <td>54.23</td>\n",
|
| 272 |
+
" <td>Five</td>\n",
|
| 273 |
+
" </tr>\n",
|
| 274 |
+
" </tbody>\n",
|
| 275 |
+
"</table>\n",
|
| 276 |
+
"</div>\n",
|
| 277 |
+
" <div class=\"colab-df-buttons\">\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" <div class=\"colab-df-container\">\n",
|
| 280 |
+
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-48ba0e17-743a-4ebb-9c53-fc4223caf207')\"\n",
|
| 281 |
+
" title=\"Convert this dataframe to an interactive table.\"\n",
|
| 282 |
+
" style=\"display:none;\">\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
|
| 285 |
+
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
|
| 286 |
+
" </svg>\n",
|
| 287 |
+
" </button>\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" <style>\n",
|
| 290 |
+
" .colab-df-container {\n",
|
| 291 |
+
" display:flex;\n",
|
| 292 |
+
" gap: 12px;\n",
|
| 293 |
+
" }\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" .colab-df-convert {\n",
|
| 296 |
+
" background-color: #E8F0FE;\n",
|
| 297 |
+
" border: none;\n",
|
| 298 |
+
" border-radius: 50%;\n",
|
| 299 |
+
" cursor: pointer;\n",
|
| 300 |
+
" display: none;\n",
|
| 301 |
+
" fill: #1967D2;\n",
|
| 302 |
+
" height: 32px;\n",
|
| 303 |
+
" padding: 0 0 0 0;\n",
|
| 304 |
+
" width: 32px;\n",
|
| 305 |
+
" }\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" .colab-df-convert:hover {\n",
|
| 308 |
+
" background-color: #E2EBFA;\n",
|
| 309 |
+
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
|
| 310 |
+
" fill: #174EA6;\n",
|
| 311 |
+
" }\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" .colab-df-buttons div {\n",
|
| 314 |
+
" margin-bottom: 4px;\n",
|
| 315 |
+
" }\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" [theme=dark] .colab-df-convert {\n",
|
| 318 |
+
" background-color: #3B4455;\n",
|
| 319 |
+
" fill: #D2E3FC;\n",
|
| 320 |
+
" }\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" [theme=dark] .colab-df-convert:hover {\n",
|
| 323 |
+
" background-color: #434B5C;\n",
|
| 324 |
+
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
|
| 325 |
+
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
|
| 326 |
+
" fill: #FFFFFF;\n",
|
| 327 |
+
" }\n",
|
| 328 |
+
" </style>\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" <script>\n",
|
| 331 |
+
" const buttonEl =\n",
|
| 332 |
+
" document.querySelector('#df-48ba0e17-743a-4ebb-9c53-fc4223caf207 button.colab-df-convert');\n",
|
| 333 |
+
" buttonEl.style.display =\n",
|
| 334 |
+
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" async function convertToInteractive(key) {\n",
|
| 337 |
+
" const element = document.querySelector('#df-48ba0e17-743a-4ebb-9c53-fc4223caf207');\n",
|
| 338 |
+
" const dataTable =\n",
|
| 339 |
+
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
|
| 340 |
+
" [key], {});\n",
|
| 341 |
+
" if (!dataTable) return;\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
|
| 344 |
+
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
|
| 345 |
+
" + ' to learn more about interactive tables.';\n",
|
| 346 |
+
" element.innerHTML = '';\n",
|
| 347 |
+
" dataTable['output_type'] = 'display_data';\n",
|
| 348 |
+
" await google.colab.output.renderOutput(dataTable, element);\n",
|
| 349 |
+
" const docLink = document.createElement('div');\n",
|
| 350 |
+
" docLink.innerHTML = docLinkHtml;\n",
|
| 351 |
+
" element.appendChild(docLink);\n",
|
| 352 |
+
" }\n",
|
| 353 |
+
" </script>\n",
|
| 354 |
+
" </div>\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" </div>\n",
|
| 358 |
+
" </div>\n"
|
| 359 |
+
],
|
| 360 |
+
"application/vnd.google.colaboratory.intrinsic+json": {
|
| 361 |
+
"type": "dataframe",
|
| 362 |
+
"variable_name": "df_books",
|
| 363 |
+
"summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
|
| 364 |
+
}
|
| 365 |
+
},
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"execution_count": 7
|
| 368 |
+
}
|
| 369 |
+
],
|
| 370 |
+
"source": [
|
| 371 |
+
"df_books.head()"
|
| 372 |
+
]
|
| 373 |
+
},
|
| 374 |
+
{
|
| 375 |
+
"cell_type": "markdown",
|
| 376 |
+
"metadata": {
|
| 377 |
+
"id": "p-1Pr2szaqLk"
|
| 378 |
+
},
|
| 379 |
+
"source": [
|
| 380 |
+
"## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
|
| 381 |
+
]
|
| 382 |
+
},
|
| 383 |
+
{
|
| 384 |
+
"cell_type": "markdown",
|
| 385 |
+
"metadata": {
|
| 386 |
+
"id": "SIaJUGIpaH4V"
|
| 387 |
+
},
|
| 388 |
+
"source": [
|
| 389 |
+
"### *a. Initial setup*"
|
| 390 |
+
]
|
| 391 |
+
},
|
| 392 |
+
{
|
| 393 |
+
"cell_type": "code",
|
| 394 |
+
"execution_count": 14,
|
| 395 |
+
"metadata": {
|
| 396 |
+
"id": "-gPXGcRPuV_9"
|
| 397 |
+
},
|
| 398 |
+
"outputs": [],
|
| 399 |
+
"source": [
|
| 400 |
+
"import numpy as np\n",
|
| 401 |
+
"import random\n",
|
| 402 |
+
"from datetime import datetime\n",
|
| 403 |
+
"import warnings\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 406 |
+
"random.seed(2025)\n",
|
| 407 |
+
"np.random.seed(2025)"
|
| 408 |
+
]
|
| 409 |
+
},
|
| 410 |
+
{
|
| 411 |
+
"cell_type": "markdown",
|
| 412 |
+
"metadata": {
|
| 413 |
+
"id": "pY4yCoIuaQqp"
|
| 414 |
+
},
|
| 415 |
+
"source": [
|
| 416 |
+
"### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
|
| 417 |
+
]
|
| 418 |
+
},
|
| 419 |
+
{
|
| 420 |
+
"cell_type": "code",
|
| 421 |
+
"execution_count": 15,
|
| 422 |
+
"metadata": {
|
| 423 |
+
"id": "mnd5hdAbaNjz"
|
| 424 |
+
},
|
| 425 |
+
"outputs": [],
|
| 426 |
+
"source": [
|
| 427 |
+
"def generate_popularity_score(rating):\n",
|
| 428 |
+
" base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
|
| 429 |
+
" trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
|
| 430 |
+
" return int(np.clip(base + trend_factor, 1, 5))"
|
| 431 |
+
]
|
| 432 |
+
},
|
| 433 |
+
{
|
| 434 |
+
"cell_type": "markdown",
|
| 435 |
+
"metadata": {
|
| 436 |
+
"id": "n4-TaNTFgPak"
|
| 437 |
+
},
|
| 438 |
+
"source": [
|
| 439 |
+
"### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
|
| 440 |
+
]
|
| 441 |
+
},
|
| 442 |
+
{
|
| 443 |
+
"cell_type": "code",
|
| 444 |
+
"execution_count": 17,
|
| 445 |
+
"metadata": {
|
| 446 |
+
"id": "V-G3OCUCgR07"
|
| 447 |
+
},
|
| 448 |
+
"outputs": [],
|
| 449 |
+
"source": [
|
| 450 |
+
"df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)"
|
| 451 |
+
]
|
| 452 |
+
},
|
| 453 |
+
{
|
| 454 |
+
"cell_type": "markdown",
|
| 455 |
+
"metadata": {
|
| 456 |
+
"id": "HnngRNTgacYt"
|
| 457 |
+
},
|
| 458 |
+
"source": [
|
| 459 |
+
"### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
|
| 460 |
+
]
|
| 461 |
+
},
|
| 462 |
+
{
|
| 463 |
+
"cell_type": "code",
|
| 464 |
+
"execution_count": 18,
|
| 465 |
+
"metadata": {
|
| 466 |
+
"id": "kUtWmr8maZLZ"
|
| 467 |
+
},
|
| 468 |
+
"outputs": [],
|
| 469 |
+
"source": [
|
| 470 |
+
"def get_sentiment(popularity_score):\n",
|
| 471 |
+
" if popularity_score <= 2:\n",
|
| 472 |
+
" return \"negative\"\n",
|
| 473 |
+
" elif popularity_score == 3:\n",
|
| 474 |
+
" return \"neutral\"\n",
|
| 475 |
+
" else:\n",
|
| 476 |
+
" return \"positive\""
|
| 477 |
+
]
|
| 478 |
+
},
|
| 479 |
+
{
|
| 480 |
+
"cell_type": "markdown",
|
| 481 |
+
"metadata": {
|
| 482 |
+
"id": "HF9F9HIzgT7Z"
|
| 483 |
+
},
|
| 484 |
+
"source": [
|
| 485 |
+
"### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
|
| 486 |
+
]
|
| 487 |
+
},
|
| 488 |
+
{
|
| 489 |
+
"cell_type": "code",
|
| 490 |
+
"execution_count": 20,
|
| 491 |
+
"metadata": {
|
| 492 |
+
"id": "tafQj8_7gYCG"
|
| 493 |
+
},
|
| 494 |
+
"outputs": [],
|
| 495 |
+
"source": [
|
| 496 |
+
"df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)"
|
| 497 |
+
]
|
| 498 |
+
},
|
| 499 |
+
{
|
| 500 |
+
"cell_type": "markdown",
|
| 501 |
+
"metadata": {
|
| 502 |
+
"id": "T8AdKkmASq9a"
|
| 503 |
+
},
|
| 504 |
+
"source": [
|
| 505 |
+
"## **4.** 📈 Generate synthetic book sales data of 18 months"
|
| 506 |
+
]
|
| 507 |
+
},
|
| 508 |
+
{
|
| 509 |
+
"cell_type": "markdown",
|
| 510 |
+
"metadata": {
|
| 511 |
+
"id": "OhXbdGD5fH0c"
|
| 512 |
+
},
|
| 513 |
+
"source": [
|
| 514 |
+
"### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
|
| 515 |
+
]
|
| 516 |
+
},
|
| 517 |
+
{
|
| 518 |
+
"cell_type": "code",
|
| 519 |
+
"execution_count": 21,
|
| 520 |
+
"metadata": {
|
| 521 |
+
"id": "qkVhYPXGbgEn"
|
| 522 |
+
},
|
| 523 |
+
"outputs": [],
|
| 524 |
+
"source": [
|
| 525 |
+
"def generate_sales_profile(sentiment):\n",
|
| 526 |
+
" months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
|
| 527 |
+
"\n",
|
| 528 |
+
" if sentiment == \"positive\":\n",
|
| 529 |
+
" base = random.randint(200, 300)\n",
|
| 530 |
+
" trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
|
| 531 |
+
" elif sentiment == \"negative\":\n",
|
| 532 |
+
" base = random.randint(20, 80)\n",
|
| 533 |
+
" trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
|
| 534 |
+
" else: # neutral\n",
|
| 535 |
+
" base = random.randint(80, 160)\n",
|
| 536 |
+
" trend = np.full(len(months), base + random.randint(-10, 10))\n",
|
| 537 |
+
"\n",
|
| 538 |
+
" seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
|
| 539 |
+
" noise = np.random.normal(0, 5, len(months))\n",
|
| 540 |
+
" monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
|
| 541 |
+
"\n",
|
| 542 |
+
" return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
|
| 543 |
+
]
|
| 544 |
+
},
|
| 545 |
+
{
|
| 546 |
+
"cell_type": "markdown",
|
| 547 |
+
"metadata": {
|
| 548 |
+
"id": "L2ak1HlcgoTe"
|
| 549 |
+
},
|
| 550 |
+
"source": [
|
| 551 |
+
"### *b. Run the function as part of building sales_data*"
|
| 552 |
+
]
|
| 553 |
+
},
|
| 554 |
+
{
|
| 555 |
+
"cell_type": "code",
|
| 556 |
+
"execution_count": 22,
|
| 557 |
+
"metadata": {
|
| 558 |
+
"id": "SlJ24AUafoDB"
|
| 559 |
+
},
|
| 560 |
+
"outputs": [],
|
| 561 |
+
"source": [
|
| 562 |
+
"sales_data = []\n",
|
| 563 |
+
"for _, row in df_books.iterrows():\n",
|
| 564 |
+
" records = generate_sales_profile(row[\"sentiment_label\"])\n",
|
| 565 |
+
" for month, units in records:\n",
|
| 566 |
+
" sales_data.append({\n",
|
| 567 |
+
" \"title\": row[\"title\"],\n",
|
| 568 |
+
" \"month\": month,\n",
|
| 569 |
+
" \"units_sold\": units,\n",
|
| 570 |
+
" \"sentiment_label\": row[\"sentiment_label\"]\n",
|
| 571 |
+
" })"
|
| 572 |
+
]
|
| 573 |
+
},
|
| 574 |
+
{
|
| 575 |
+
"cell_type": "markdown",
|
| 576 |
+
"metadata": {
|
| 577 |
+
"id": "4IXZKcCSgxnq"
|
| 578 |
+
},
|
| 579 |
+
"source": [
|
| 580 |
+
"### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*"
|
| 581 |
+
]
|
| 582 |
+
},
|
| 583 |
+
{
|
| 584 |
+
"cell_type": "code",
|
| 585 |
+
"execution_count": 32,
|
| 586 |
+
"metadata": {
|
| 587 |
+
"id": "wcN6gtiZg-ws"
|
| 588 |
+
},
|
| 589 |
+
"outputs": [],
|
| 590 |
+
"source": [
|
| 591 |
+
"df_sales = pd.DataFrame(sales_data)"
|
| 592 |
+
]
|
| 593 |
+
},
|
| 594 |
+
{
|
| 595 |
+
"cell_type": "markdown",
|
| 596 |
+
"metadata": {
|
| 597 |
+
"id": "EhIjz9WohAmZ"
|
| 598 |
+
},
|
| 599 |
+
"source": [
|
| 600 |
+
"### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
|
| 601 |
+
]
|
| 602 |
+
},
|
| 603 |
+
{
|
| 604 |
+
"cell_type": "code",
|
| 605 |
+
"execution_count": 33,
|
| 606 |
+
"metadata": {
|
| 607 |
+
"colab": {
|
| 608 |
+
"base_uri": "https://localhost:8080/"
|
| 609 |
+
},
|
| 610 |
+
"id": "MzbZvLcAhGaH",
|
| 611 |
+
"outputId": "f8e7bf73-aa0b-4321-a337-897da532c60e"
|
| 612 |
+
},
|
| 613 |
+
"outputs": [
|
| 614 |
+
{
|
| 615 |
+
"output_type": "stream",
|
| 616 |
+
"name": "stdout",
|
| 617 |
+
"text": [
|
| 618 |
+
" title month units_sold sentiment_label\n",
|
| 619 |
+
"0 A Light in the Attic 2024-09 237 positive\n",
|
| 620 |
+
"1 A Light in the Attic 2024-10 249 positive\n",
|
| 621 |
+
"2 A Light in the Attic 2024-11 245 positive\n",
|
| 622 |
+
"3 A Light in the Attic 2024-12 253 positive\n",
|
| 623 |
+
"4 A Light in the Attic 2025-01 257 positive\n"
|
| 624 |
+
]
|
| 625 |
+
}
|
| 626 |
+
],
|
| 627 |
+
"source": [
|
| 628 |
+
"df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
|
| 629 |
+
"\n",
|
| 630 |
+
"print(df_sales.head())"
|
| 631 |
+
]
|
| 632 |
+
},
|
| 633 |
+
{
|
| 634 |
+
"cell_type": "markdown",
|
| 635 |
+
"metadata": {
|
| 636 |
+
"id": "7g9gqBgQMtJn"
|
| 637 |
+
},
|
| 638 |
+
"source": [
|
| 639 |
+
"## **5.** 🎯 Generate synthetic customer reviews"
|
| 640 |
+
]
|
| 641 |
+
},
|
| 642 |
+
{
|
| 643 |
+
"cell_type": "markdown",
|
| 644 |
+
"metadata": {
|
| 645 |
+
"id": "Gi4y9M9KuDWx"
|
| 646 |
+
},
|
| 647 |
+
"source": [
|
| 648 |
+
"### *a. ✋🏻🛑⛔️ Ask ChatGPT to create a list of 50 distinct generic book review texts for the sentiment labels \"positive\", \"neutral\", and \"negative\" called synthetic_reviews_by_sentiment*"
|
| 649 |
+
]
|
| 650 |
+
},
|
| 651 |
+
{
|
| 652 |
+
"cell_type": "code",
|
| 653 |
+
"execution_count": 34,
|
| 654 |
+
"metadata": {
|
| 655 |
+
"id": "b3cd2a50"
|
| 656 |
+
},
|
| 657 |
+
"outputs": [],
|
| 658 |
+
"source": [
|
| 659 |
+
"synthetic_reviews_by_sentiment = {\n",
|
| 660 |
+
" \"positive\": [\n",
|
| 661 |
+
" \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
|
| 662 |
+
" \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
|
| 663 |
+
" \"One of the best books I've read this year — inspiring and emotionally rich.\",\n",
|
| 664 |
+
" ],\n",
|
| 665 |
+
" \"neutral\": [\n",
|
| 666 |
+
" \"An average book — not great, but not bad either.\",\n",
|
| 667 |
+
" \"Some parts really stood out, others felt a bit flat.\",\n",
|
| 668 |
+
" \"It was okay overall. A decent way to pass the time.\",\n",
|
| 669 |
+
" ],\n",
|
| 670 |
+
" \"negative\": [\n",
|
| 671 |
+
" \"I struggled to get through this one — it just didn’t grab me.\",\n",
|
| 672 |
+
" \"The plot was confusing and the characters felt underdeveloped.\",\n",
|
| 673 |
+
" \"Disappointing. I had high hopes, but they weren't met.\",\n",
|
| 674 |
+
" ]\n",
|
| 675 |
+
"}"
|
| 676 |
+
]
|
| 677 |
+
},
|
| 678 |
+
{
|
| 679 |
+
"cell_type": "markdown",
|
| 680 |
+
"metadata": {
|
| 681 |
+
"id": "fQhfVaDmuULT"
|
| 682 |
+
},
|
| 683 |
+
"source": [
|
| 684 |
+
"### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
|
| 685 |
+
]
|
| 686 |
+
},
|
| 687 |
+
{
|
| 688 |
+
"cell_type": "code",
|
| 689 |
+
"execution_count": 36,
|
| 690 |
+
"metadata": {
|
| 691 |
+
"id": "l2SRc3PjuTGM"
|
| 692 |
+
},
|
| 693 |
+
"outputs": [],
|
| 694 |
+
"source": [
|
| 695 |
+
"review_rows = []\n",
|
| 696 |
+
"\n",
|
| 697 |
+
"for _, row in df_books.iterrows():\n",
|
| 698 |
+
" title = row[\"title\"]\n",
|
| 699 |
+
" sentiment_label = row[\"sentiment_label\"]\n",
|
| 700 |
+
"\n",
|
| 701 |
+
" review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
|
| 702 |
+
"\n",
|
| 703 |
+
" sampled_reviews = random.choices(review_pool, k=10)\n",
|
| 704 |
+
"\n",
|
| 705 |
+
" for review_text in sampled_reviews:\n",
|
| 706 |
+
" review_rows.append({\n",
|
| 707 |
+
" \"title\": title,\n",
|
| 708 |
+
" \"sentiment_label\": sentiment_label,\n",
|
| 709 |
+
" \"review_text\": review_text,\n",
|
| 710 |
+
" \"rating\": row[\"rating\"],\n",
|
| 711 |
+
" \"popularity_score\": row[\"popularity_score\"]\n",
|
| 712 |
+
" })"
|
| 713 |
+
]
|
| 714 |
+
},
|
| 715 |
+
{
|
| 716 |
+
"cell_type": "markdown",
|
| 717 |
+
"metadata": {
|
| 718 |
+
"id": "bmJMXF-Bukdm"
|
| 719 |
+
},
|
| 720 |
+
"source": [
|
| 721 |
+
"### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
|
| 722 |
+
]
|
| 723 |
+
},
|
| 724 |
+
{
|
| 725 |
+
"cell_type": "code",
|
| 726 |
+
"execution_count": 37,
|
| 727 |
+
"metadata": {
|
| 728 |
+
"id": "ZUKUqZsuumsp"
|
| 729 |
+
},
|
| 730 |
+
"outputs": [],
|
| 731 |
+
"source": [
|
| 732 |
+
"df_reviews = pd.DataFrame(review_rows)\n",
|
| 733 |
+
"df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
|
| 734 |
+
]
|
| 735 |
+
},
|
| 736 |
+
{
|
| 737 |
+
"cell_type": "markdown",
|
| 738 |
+
"source": [
|
| 739 |
+
"### *c. inputs for R*"
|
| 740 |
+
],
|
| 741 |
+
"metadata": {
|
| 742 |
+
"id": "_602pYUS3gY5"
|
| 743 |
+
}
|
| 744 |
+
},
|
| 745 |
+
{
|
| 746 |
+
"cell_type": "code",
|
| 747 |
+
"execution_count": 38,
|
| 748 |
+
"metadata": {
|
| 749 |
+
"colab": {
|
| 750 |
+
"base_uri": "https://localhost:8080/"
|
| 751 |
+
},
|
| 752 |
+
"id": "3946e521",
|
| 753 |
+
"outputId": "74288e92-a5fc-4e2d-a54b-c97c66f8df78"
|
| 754 |
+
},
|
| 755 |
+
"outputs": [
|
| 756 |
+
{
|
| 757 |
+
"output_type": "stream",
|
| 758 |
+
"name": "stdout",
|
| 759 |
+
"text": [
|
| 760 |
+
"✅ Wrote synthetic_title_level_features.csv\n",
|
| 761 |
+
"✅ Wrote synthetic_monthly_revenue_series.csv\n"
|
| 762 |
+
]
|
| 763 |
+
}
|
| 764 |
+
],
|
| 765 |
+
"source": [
|
| 766 |
+
"import numpy as np\n",
|
| 767 |
+
"\n",
|
| 768 |
+
"def _safe_num(s):\n",
|
| 769 |
+
" return pd.to_numeric(\n",
|
| 770 |
+
" pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
|
| 771 |
+
" errors=\"coerce\"\n",
|
| 772 |
+
" )\n",
|
| 773 |
+
"\n",
|
| 774 |
+
"# --- Clean book metadata (price/rating) ---\n",
|
| 775 |
+
"df_books_r = df_books.copy()\n",
|
| 776 |
+
"if \"price\" in df_books_r.columns:\n",
|
| 777 |
+
" df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
|
| 778 |
+
"if \"rating\" in df_books_r.columns:\n",
|
| 779 |
+
" df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
|
| 780 |
+
"\n",
|
| 781 |
+
"df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
|
| 782 |
+
"\n",
|
| 783 |
+
"# --- Clean sales ---\n",
|
| 784 |
+
"df_sales_r = df_sales.copy()\n",
|
| 785 |
+
"df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
|
| 786 |
+
"df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
|
| 787 |
+
"df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
|
| 788 |
+
"\n",
|
| 789 |
+
"# --- Clean reviews ---\n",
|
| 790 |
+
"df_reviews_r = df_reviews.copy()\n",
|
| 791 |
+
"df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
|
| 792 |
+
"df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
|
| 793 |
+
"if \"rating\" in df_reviews_r.columns:\n",
|
| 794 |
+
" df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
|
| 795 |
+
"if \"popularity_score\" in df_reviews_r.columns:\n",
|
| 796 |
+
" df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
|
| 797 |
+
"\n",
|
| 798 |
+
"# --- Sentiment shares per title (from reviews) ---\n",
|
| 799 |
+
"sent_counts = (\n",
|
| 800 |
+
" df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
|
| 801 |
+
" .size()\n",
|
| 802 |
+
" .unstack(fill_value=0)\n",
|
| 803 |
+
")\n",
|
| 804 |
+
"for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
|
| 805 |
+
" if lab not in sent_counts.columns:\n",
|
| 806 |
+
" sent_counts[lab] = 0\n",
|
| 807 |
+
"\n",
|
| 808 |
+
"sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
|
| 809 |
+
"den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
|
| 810 |
+
"sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
|
| 811 |
+
"sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
|
| 812 |
+
"sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
|
| 813 |
+
"sent_counts = sent_counts.reset_index()\n",
|
| 814 |
+
"\n",
|
| 815 |
+
"# --- Sales aggregation per title ---\n",
|
| 816 |
+
"sales_by_title = (\n",
|
| 817 |
+
" df_sales_r.dropna(subset=[\"title\"])\n",
|
| 818 |
+
" .groupby(\"title\", as_index=False)\n",
|
| 819 |
+
" .agg(\n",
|
| 820 |
+
" months_observed=(\"month\", \"nunique\"),\n",
|
| 821 |
+
" avg_units_sold=(\"units_sold\", \"mean\"),\n",
|
| 822 |
+
" total_units_sold=(\"units_sold\", \"sum\"),\n",
|
| 823 |
+
" )\n",
|
| 824 |
+
")\n",
|
| 825 |
+
"\n",
|
| 826 |
+
"# --- Title-level features (join sales + books + sentiment) ---\n",
|
| 827 |
+
"df_title = (\n",
|
| 828 |
+
" sales_by_title\n",
|
| 829 |
+
" .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
|
| 830 |
+
" .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
|
| 831 |
+
" on=\"title\", how=\"left\")\n",
|
| 832 |
+
")\n",
|
| 833 |
+
"\n",
|
| 834 |
+
"df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
|
| 835 |
+
"df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
|
| 836 |
+
"\n",
|
| 837 |
+
"df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
|
| 838 |
+
"print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
|
| 839 |
+
"\n",
|
| 840 |
+
"# --- Monthly revenue series (proxy: units_sold * price) ---\n",
|
| 841 |
+
"monthly_rev = (\n",
|
| 842 |
+
" df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
|
| 843 |
+
")\n",
|
| 844 |
+
"monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
|
| 845 |
+
"\n",
|
| 846 |
+
"df_monthly = (\n",
|
| 847 |
+
" monthly_rev.dropna(subset=[\"month\"])\n",
|
| 848 |
+
" .groupby(\"month\", as_index=False)[\"revenue\"]\n",
|
| 849 |
+
" .sum()\n",
|
| 850 |
+
" .rename(columns={\"revenue\": \"total_revenue\"})\n",
|
| 851 |
+
" .sort_values(\"month\")\n",
|
| 852 |
+
")\n",
|
| 853 |
+
"# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
|
| 854 |
+
"if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
|
| 855 |
+
" df_monthly = (\n",
|
| 856 |
+
" df_sales_r.dropna(subset=[\"month\"])\n",
|
| 857 |
+
" .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
|
| 858 |
+
" .sum()\n",
|
| 859 |
+
" .rename(columns={\"units_sold\": \"total_revenue\"})\n",
|
| 860 |
+
" .sort_values(\"month\")\n",
|
| 861 |
+
" )\n",
|
| 862 |
+
"\n",
|
| 863 |
+
"df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
|
| 864 |
+
"df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
|
| 865 |
+
"print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
|
| 866 |
+
]
|
| 867 |
+
},
|
| 868 |
+
{
|
| 869 |
+
"cell_type": "markdown",
|
| 870 |
+
"metadata": {
|
| 871 |
+
"id": "RYvGyVfXuo54"
|
| 872 |
+
},
|
| 873 |
+
"source": [
|
| 874 |
+
"### *d. ✋🏻🛑⛔️ View the first few lines*"
|
| 875 |
+
]
|
| 876 |
+
},
|
| 877 |
+
{
|
| 878 |
+
"cell_type": "code",
|
| 879 |
+
"execution_count": 39,
|
| 880 |
+
"metadata": {
|
| 881 |
+
"colab": {
|
| 882 |
+
"base_uri": "https://localhost:8080/",
|
| 883 |
+
"height": 204
|
| 884 |
+
},
|
| 885 |
+
"id": "xfE8NMqOurKo",
|
| 886 |
+
"outputId": "20ffb4b7-caae-4bef-8c22-a00205097b0b"
|
| 887 |
+
},
|
| 888 |
+
"outputs": [
|
| 889 |
+
{
|
| 890 |
+
"output_type": "execute_result",
|
| 891 |
+
"data": {
|
| 892 |
+
"text/plain": [
|
| 893 |
+
" title sentiment_label \\\n",
|
| 894 |
+
"0 A Light in the Attic positive \n",
|
| 895 |
+
"1 A Light in the Attic positive \n",
|
| 896 |
+
"2 A Light in the Attic positive \n",
|
| 897 |
+
"3 A Light in the Attic positive \n",
|
| 898 |
+
"4 A Light in the Attic positive \n",
|
| 899 |
+
"\n",
|
| 900 |
+
" review_text rating popularity_score \n",
|
| 901 |
+
"0 One of the best books I've read this year — in... Three 4 \n",
|
| 902 |
+
"1 A compelling and heartwarming read that stayed... Three 4 \n",
|
| 903 |
+
"2 One of the best books I've read this year — in... Three 4 \n",
|
| 904 |
+
"3 A compelling and heartwarming read that stayed... Three 4 \n",
|
| 905 |
+
"4 A compelling and heartwarming read that stayed... Three 4 "
|
| 906 |
+
],
|
| 907 |
+
"text/html": [
|
| 908 |
+
"\n",
|
| 909 |
+
" <div id=\"df-bd957f7d-f3aa-467c-bcd5-c57d3f645f5b\" class=\"colab-df-container\">\n",
|
| 910 |
+
" <div>\n",
|
| 911 |
+
"<style scoped>\n",
|
| 912 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 913 |
+
" vertical-align: middle;\n",
|
| 914 |
+
" }\n",
|
| 915 |
+
"\n",
|
| 916 |
+
" .dataframe tbody tr th {\n",
|
| 917 |
+
" vertical-align: top;\n",
|
| 918 |
+
" }\n",
|
| 919 |
+
"\n",
|
| 920 |
+
" .dataframe thead th {\n",
|
| 921 |
+
" text-align: right;\n",
|
| 922 |
+
" }\n",
|
| 923 |
+
"</style>\n",
|
| 924 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 925 |
+
" <thead>\n",
|
| 926 |
+
" <tr style=\"text-align: right;\">\n",
|
| 927 |
+
" <th></th>\n",
|
| 928 |
+
" <th>title</th>\n",
|
| 929 |
+
" <th>sentiment_label</th>\n",
|
| 930 |
+
" <th>review_text</th>\n",
|
| 931 |
+
" <th>rating</th>\n",
|
| 932 |
+
" <th>popularity_score</th>\n",
|
| 933 |
+
" </tr>\n",
|
| 934 |
+
" </thead>\n",
|
| 935 |
+
" <tbody>\n",
|
| 936 |
+
" <tr>\n",
|
| 937 |
+
" <th>0</th>\n",
|
| 938 |
+
" <td>A Light in the Attic</td>\n",
|
| 939 |
+
" <td>positive</td>\n",
|
| 940 |
+
" <td>One of the best books I've read this year — in...</td>\n",
|
| 941 |
+
" <td>Three</td>\n",
|
| 942 |
+
" <td>4</td>\n",
|
| 943 |
+
" </tr>\n",
|
| 944 |
+
" <tr>\n",
|
| 945 |
+
" <th>1</th>\n",
|
| 946 |
+
" <td>A Light in the Attic</td>\n",
|
| 947 |
+
" <td>positive</td>\n",
|
| 948 |
+
" <td>A compelling and heartwarming read that stayed...</td>\n",
|
| 949 |
+
" <td>Three</td>\n",
|
| 950 |
+
" <td>4</td>\n",
|
| 951 |
+
" </tr>\n",
|
| 952 |
+
" <tr>\n",
|
| 953 |
+
" <th>2</th>\n",
|
| 954 |
+
" <td>A Light in the Attic</td>\n",
|
| 955 |
+
" <td>positive</td>\n",
|
| 956 |
+
" <td>One of the best books I've read this year — in...</td>\n",
|
| 957 |
+
" <td>Three</td>\n",
|
| 958 |
+
" <td>4</td>\n",
|
| 959 |
+
" </tr>\n",
|
| 960 |
+
" <tr>\n",
|
| 961 |
+
" <th>3</th>\n",
|
| 962 |
+
" <td>A Light in the Attic</td>\n",
|
| 963 |
+
" <td>positive</td>\n",
|
| 964 |
+
" <td>A compelling and heartwarming read that stayed...</td>\n",
|
| 965 |
+
" <td>Three</td>\n",
|
| 966 |
+
" <td>4</td>\n",
|
| 967 |
+
" </tr>\n",
|
| 968 |
+
" <tr>\n",
|
| 969 |
+
" <th>4</th>\n",
|
| 970 |
+
" <td>A Light in the Attic</td>\n",
|
| 971 |
+
" <td>positive</td>\n",
|
| 972 |
+
" <td>A compelling and heartwarming read that stayed...</td>\n",
|
| 973 |
+
" <td>Three</td>\n",
|
| 974 |
+
" <td>4</td>\n",
|
| 975 |
+
" </tr>\n",
|
| 976 |
+
" </tbody>\n",
|
| 977 |
+
"</table>\n",
|
| 978 |
+
"</div>\n",
|
| 979 |
+
" <div class=\"colab-df-buttons\">\n",
|
| 980 |
+
"\n",
|
| 981 |
+
" <div class=\"colab-df-container\">\n",
|
| 982 |
+
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-bd957f7d-f3aa-467c-bcd5-c57d3f645f5b')\"\n",
|
| 983 |
+
" title=\"Convert this dataframe to an interactive table.\"\n",
|
| 984 |
+
" style=\"display:none;\">\n",
|
| 985 |
+
"\n",
|
| 986 |
+
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
|
| 987 |
+
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
|
| 988 |
+
" </svg>\n",
|
| 989 |
+
" </button>\n",
|
| 990 |
+
"\n",
|
| 991 |
+
" <style>\n",
|
| 992 |
+
" .colab-df-container {\n",
|
| 993 |
+
" display:flex;\n",
|
| 994 |
+
" gap: 12px;\n",
|
| 995 |
+
" }\n",
|
| 996 |
+
"\n",
|
| 997 |
+
" .colab-df-convert {\n",
|
| 998 |
+
" background-color: #E8F0FE;\n",
|
| 999 |
+
" border: none;\n",
|
| 1000 |
+
" border-radius: 50%;\n",
|
| 1001 |
+
" cursor: pointer;\n",
|
| 1002 |
+
" display: none;\n",
|
| 1003 |
+
" fill: #1967D2;\n",
|
| 1004 |
+
" height: 32px;\n",
|
| 1005 |
+
" padding: 0 0 0 0;\n",
|
| 1006 |
+
" width: 32px;\n",
|
| 1007 |
+
" }\n",
|
| 1008 |
+
"\n",
|
| 1009 |
+
" .colab-df-convert:hover {\n",
|
| 1010 |
+
" background-color: #E2EBFA;\n",
|
| 1011 |
+
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
|
| 1012 |
+
" fill: #174EA6;\n",
|
| 1013 |
+
" }\n",
|
| 1014 |
+
"\n",
|
| 1015 |
+
" .colab-df-buttons div {\n",
|
| 1016 |
+
" margin-bottom: 4px;\n",
|
| 1017 |
+
" }\n",
|
| 1018 |
+
"\n",
|
| 1019 |
+
" [theme=dark] .colab-df-convert {\n",
|
| 1020 |
+
" background-color: #3B4455;\n",
|
| 1021 |
+
" fill: #D2E3FC;\n",
|
| 1022 |
+
" }\n",
|
| 1023 |
+
"\n",
|
| 1024 |
+
" [theme=dark] .colab-df-convert:hover {\n",
|
| 1025 |
+
" background-color: #434B5C;\n",
|
| 1026 |
+
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
|
| 1027 |
+
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
|
| 1028 |
+
" fill: #FFFFFF;\n",
|
| 1029 |
+
" }\n",
|
| 1030 |
+
" </style>\n",
|
| 1031 |
+
"\n",
|
| 1032 |
+
" <script>\n",
|
| 1033 |
+
" const buttonEl =\n",
|
| 1034 |
+
" document.querySelector('#df-bd957f7d-f3aa-467c-bcd5-c57d3f645f5b button.colab-df-convert');\n",
|
| 1035 |
+
" buttonEl.style.display =\n",
|
| 1036 |
+
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
|
| 1037 |
+
"\n",
|
| 1038 |
+
" async function convertToInteractive(key) {\n",
|
| 1039 |
+
" const element = document.querySelector('#df-bd957f7d-f3aa-467c-bcd5-c57d3f645f5b');\n",
|
| 1040 |
+
" const dataTable =\n",
|
| 1041 |
+
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
|
| 1042 |
+
" [key], {});\n",
|
| 1043 |
+
" if (!dataTable) return;\n",
|
| 1044 |
+
"\n",
|
| 1045 |
+
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
|
| 1046 |
+
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
|
| 1047 |
+
" + ' to learn more about interactive tables.';\n",
|
| 1048 |
+
" element.innerHTML = '';\n",
|
| 1049 |
+
" dataTable['output_type'] = 'display_data';\n",
|
| 1050 |
+
" await google.colab.output.renderOutput(dataTable, element);\n",
|
| 1051 |
+
" const docLink = document.createElement('div');\n",
|
| 1052 |
+
" docLink.innerHTML = docLinkHtml;\n",
|
| 1053 |
+
" element.appendChild(docLink);\n",
|
| 1054 |
+
" }\n",
|
| 1055 |
+
" </script>\n",
|
| 1056 |
+
" </div>\n",
|
| 1057 |
+
"\n",
|
| 1058 |
+
"\n",
|
| 1059 |
+
" </div>\n",
|
| 1060 |
+
" </div>\n"
|
| 1061 |
+
],
|
| 1062 |
+
"application/vnd.google.colaboratory.intrinsic+json": {
|
| 1063 |
+
"type": "dataframe",
|
| 1064 |
+
"variable_name": "df_reviews",
|
| 1065 |
+
"summary": "{\n \"name\": \"df_reviews\",\n \"rows\": 10000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"sentiment_label\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"positive\",\n \"negative\",\n \"neutral\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"review_text\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 9,\n \"samples\": [\n \"Some parts really stood out, others felt a bit flat.\",\n \"A compelling and heartwarming read that stayed with me long after I finished.\",\n \"Disappointing. I had high hopes, but they weren't met.\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"popularity_score\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 5,\n \"num_unique_values\": 5,\n \"samples\": [\n 1,\n 5,\n 3\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
|
| 1066 |
+
}
|
| 1067 |
+
},
|
| 1068 |
+
"metadata": {},
|
| 1069 |
+
"execution_count": 39
|
| 1070 |
+
}
|
| 1071 |
+
],
|
| 1072 |
+
"source": [
|
| 1073 |
+
"df_reviews.head()"
|
| 1074 |
+
]
|
| 1075 |
+
}
|
| 1076 |
+
],
|
| 1077 |
+
"metadata": {
|
| 1078 |
+
"colab": {
|
| 1079 |
+
"collapsed_sections": [
|
| 1080 |
+
"jpASMyIQMaAq",
|
| 1081 |
+
"lquNYCbfL9IM",
|
| 1082 |
+
"0IWuNpxxYDJF",
|
| 1083 |
+
"oCdTsin2Yfp3",
|
| 1084 |
+
"T0TOeRC4Yrnn",
|
| 1085 |
+
"duI5dv3CZYvF",
|
| 1086 |
+
"qMjRKMBQZlJi",
|
| 1087 |
+
"p-1Pr2szaqLk",
|
| 1088 |
+
"SIaJUGIpaH4V",
|
| 1089 |
+
"pY4yCoIuaQqp",
|
| 1090 |
+
"n4-TaNTFgPak",
|
| 1091 |
+
"HnngRNTgacYt",
|
| 1092 |
+
"HF9F9HIzgT7Z",
|
| 1093 |
+
"T8AdKkmASq9a",
|
| 1094 |
+
"OhXbdGD5fH0c",
|
| 1095 |
+
"L2ak1HlcgoTe",
|
| 1096 |
+
"4IXZKcCSgxnq",
|
| 1097 |
+
"EhIjz9WohAmZ",
|
| 1098 |
+
"Gi4y9M9KuDWx",
|
| 1099 |
+
"fQhfVaDmuULT",
|
| 1100 |
+
"bmJMXF-Bukdm",
|
| 1101 |
+
"RYvGyVfXuo54"
|
| 1102 |
+
],
|
| 1103 |
+
"provenance": []
|
| 1104 |
+
},
|
| 1105 |
+
"kernelspec": {
|
| 1106 |
+
"display_name": "Python 3",
|
| 1107 |
+
"name": "python3"
|
| 1108 |
+
},
|
| 1109 |
+
"language_info": {
|
| 1110 |
+
"name": "python"
|
| 1111 |
+
}
|
| 1112 |
+
},
|
| 1113 |
+
"nbformat": 4,
|
| 1114 |
+
"nbformat_minor": 0
|
| 1115 |
+
}
|
gitattributes.txt
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
background_top.png filter=lfs diff=lfs merge=lfs -text
|
phytonanalysis.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==6.0.0
|
| 2 |
+
pandas>=2.0.0
|
| 3 |
+
numpy>=1.24.0
|
| 4 |
+
matplotlib>=3.7.0
|
| 5 |
+
seaborn>=0.13.0
|
| 6 |
+
statsmodels>=0.14.0
|
| 7 |
+
scikit-learn>=1.3.0
|
| 8 |
+
papermill>=2.5.0
|
| 9 |
+
nbformat>=5.9.0
|
| 10 |
+
pillow>=10.0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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* --- Target the Gradio app wrapper for backgrounds --- */
|
| 2 |
+
gradio-app,
|
| 3 |
+
.gradio-app,
|
| 4 |
+
.main,
|
| 5 |
+
#app,
|
| 6 |
+
[data-testid="app"] {
|
| 7 |
+
background-color: rgb(40,9,109) !important;
|
| 8 |
+
background-image:
|
| 9 |
+
url('https://huggingface.co/spaces/atascioglu/SE21AppTemplate/resolve/main/background_top.png'),
|
| 10 |
+
url('https://huggingface.co/spaces/atascioglu/SE21AppTemplate/resolve/main/background_mid.png'),
|
| 11 |
+
url('https://huggingface.co/spaces/atascioglu/SE21AppTemplate/resolve/main/background_bottom.png') !important;
|
| 12 |
+
background-position:
|
| 13 |
+
top center,
|
| 14 |
+
0 913px,
|
| 15 |
+
bottom center !important;
|
| 16 |
+
background-repeat:
|
| 17 |
+
no-repeat,
|
| 18 |
+
repeat-y,
|
| 19 |
+
no-repeat !important;
|
| 20 |
+
background-size:
|
| 21 |
+
100% auto,
|
| 22 |
+
100% auto,
|
| 23 |
+
100% auto !important;
|
| 24 |
+
min-height: 100vh !important;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
/* --- Fallback on html/body --- */
|
| 28 |
+
html, body {
|
| 29 |
+
background-color: rgb(40,9,109) !important;
|
| 30 |
+
margin: 0 !important;
|
| 31 |
+
padding: 0 !important;
|
| 32 |
+
min-height: 100vh !important;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/* Bottom image is now part of the main background layers (positioned at bottom center) */
|
| 36 |
+
|
| 37 |
+
/* --- Main container --- */
|
| 38 |
+
.gradio-container {
|
| 39 |
+
max-width: 1400px !important;
|
| 40 |
+
width: 94vw !important;
|
| 41 |
+
margin: 0 auto !important;
|
| 42 |
+
padding-top: 220px !important;
|
| 43 |
+
padding-bottom: 150px !important;
|
| 44 |
+
background: transparent !important;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/* --- Title in ESCP gold --- */
|
| 48 |
+
#escp_title h1 {
|
| 49 |
+
color: rgb(242,198,55) !important;
|
| 50 |
+
font-size: 3rem !important;
|
| 51 |
+
font-weight: 800 !important;
|
| 52 |
+
text-align: center !important;
|
| 53 |
+
margin: 0 0 12px 0 !important;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/* --- Subtitle --- */
|
| 57 |
+
#escp_title p, #escp_title em {
|
| 58 |
+
color: rgba(255,255,255,0.85) !important;
|
| 59 |
+
text-align: center !important;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/* --- Tab bar background --- */
|
| 63 |
+
.tabs > .tab-nav,
|
| 64 |
+
.tab-nav,
|
| 65 |
+
div[role="tablist"],
|
| 66 |
+
.svelte-tabs > .tab-nav {
|
| 67 |
+
background: rgba(40,9,109,0.6) !important;
|
| 68 |
+
border-radius: 10px 10px 0 0 !important;
|
| 69 |
+
padding: 4px !important;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/* --- ALL tab buttons: force white text --- */
|
| 73 |
+
.tabs > .tab-nav button,
|
| 74 |
+
.tab-nav button,
|
| 75 |
+
div[role="tablist"] button,
|
| 76 |
+
button[role="tab"],
|
| 77 |
+
.svelte-tabs button,
|
| 78 |
+
.tab-nav > button,
|
| 79 |
+
.tabs button {
|
| 80 |
+
color: #ffffff !important;
|
| 81 |
+
font-weight: 600 !important;
|
| 82 |
+
border: none !important;
|
| 83 |
+
background: transparent !important;
|
| 84 |
+
padding: 10px 20px !important;
|
| 85 |
+
border-radius: 8px 8px 0 0 !important;
|
| 86 |
+
opacity: 1 !important;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
/* --- Selected tab: ESCP gold --- */
|
| 90 |
+
.tabs > .tab-nav button.selected,
|
| 91 |
+
.tab-nav button.selected,
|
| 92 |
+
button[role="tab"][aria-selected="true"],
|
| 93 |
+
button[role="tab"].selected,
|
| 94 |
+
div[role="tablist"] button[aria-selected="true"],
|
| 95 |
+
.svelte-tabs button.selected {
|
| 96 |
+
color: rgb(242,198,55) !important;
|
| 97 |
+
background: rgba(255,255,255,0.12) !important;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/* --- Unselected tabs: ensure visibility --- */
|
| 101 |
+
.tabs > .tab-nav button:not(.selected),
|
| 102 |
+
.tab-nav button:not(.selected),
|
| 103 |
+
button[role="tab"][aria-selected="false"],
|
| 104 |
+
button[role="tab"]:not(.selected),
|
| 105 |
+
div[role="tablist"] button:not([aria-selected="true"]) {
|
| 106 |
+
color: #ffffff !important;
|
| 107 |
+
opacity: 1 !important;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/* --- White card panels --- */
|
| 111 |
+
.gradio-container .gr-block,
|
| 112 |
+
.gradio-container .gr-box,
|
| 113 |
+
.gradio-container .gr-panel,
|
| 114 |
+
.gradio-container .gr-group {
|
| 115 |
+
background: #ffffff !important;
|
| 116 |
+
border-radius: 10px !important;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/* --- Tab content area --- */
|
| 120 |
+
.tabitem {
|
| 121 |
+
background: rgba(255,255,255,0.95) !important;
|
| 122 |
+
border-radius: 0 0 10px 10px !important;
|
| 123 |
+
padding: 16px !important;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
/* --- Inputs --- */
|
| 127 |
+
.gradio-container input,
|
| 128 |
+
.gradio-container textarea,
|
| 129 |
+
.gradio-container select {
|
| 130 |
+
background: #ffffff !important;
|
| 131 |
+
border: 1px solid #d1d5db !important;
|
| 132 |
+
border-radius: 8px !important;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
/* --- Buttons: ESCP purple primary --- */
|
| 136 |
+
.gradio-container button:not([role="tab"]) {
|
| 137 |
+
font-weight: 600 !important;
|
| 138 |
+
padding: 10px 16px !important;
|
| 139 |
+
border-radius: 10px !important;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
button.primary {
|
| 143 |
+
background-color: rgb(40,9,109) !important;
|
| 144 |
+
color: #ffffff !important;
|
| 145 |
+
border: none !important;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
button.primary:hover {
|
| 149 |
+
background-color: rgb(60,20,140) !important;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
button.secondary {
|
| 153 |
+
background-color: #ffffff !important;
|
| 154 |
+
color: rgb(40,9,109) !important;
|
| 155 |
+
border: 2px solid rgb(40,9,109) !important;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
button.secondary:hover {
|
| 159 |
+
background-color: rgb(240,238,250) !important;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
/* --- Dataframes --- */
|
| 163 |
+
[data-testid="dataframe"] {
|
| 164 |
+
background-color: #ffffff !important;
|
| 165 |
+
border-radius: 10px !important;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
table {
|
| 169 |
+
font-size: 0.85rem !important;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/* --- Chatbot (AI Dashboard tab) --- */
|
| 173 |
+
.gr-chatbot {
|
| 174 |
+
min-height: 380px !important;
|
| 175 |
+
background-color: #ffffff !important;
|
| 176 |
+
border-radius: 12px !important;
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
.gr-chatbot .message.user {
|
| 180 |
+
background-color: rgb(232,225,250) !important;
|
| 181 |
+
border-radius: 12px !important;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
.gr-chatbot .message.bot {
|
| 185 |
+
background-color: #f3f4f6 !important;
|
| 186 |
+
border-radius: 12px !important;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
/* --- Gallery --- */
|
| 190 |
+
.gallery {
|
| 191 |
+
background: #ffffff !important;
|
| 192 |
+
border-radius: 10px !important;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
/* --- Log textbox --- */
|
| 196 |
+
textarea {
|
| 197 |
+
font-family: monospace !important;
|
| 198 |
+
font-size: 0.8rem !important;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/* --- Markdown headings inside tabs --- */
|
| 202 |
+
.tabitem h3 {
|
| 203 |
+
color: rgb(40,9,109) !important;
|
| 204 |
+
font-weight: 700 !important;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
.tabitem h4 {
|
| 208 |
+
color: #374151 !important;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/* --- Examples row (AI Dashboard) --- */
|
| 212 |
+
.examples-row button {
|
| 213 |
+
background: rgb(240,238,250) !important;
|
| 214 |
+
color: rgb(40,9,109) !important;
|
| 215 |
+
border: 1px solid rgb(40,9,109) !important;
|
| 216 |
+
border-radius: 8px !important;
|
| 217 |
+
font-size: 0.85rem !important;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
.examples-row button:hover {
|
| 221 |
+
background: rgb(232,225,250) !important;
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
/* --- Header / footer: transparent over banner --- */
|
| 225 |
+
header, header *,
|
| 226 |
+
footer, footer * {
|
| 227 |
+
background: transparent !important;
|
| 228 |
+
box-shadow: none !important;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
footer a, footer button,
|
| 232 |
+
header a, header button {
|
| 233 |
+
background: transparent !important;
|
| 234 |
+
border: none !important;
|
| 235 |
+
box-shadow: none !important;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
#footer, #footer *,
|
| 239 |
+
[class*="footer"], [class*="footer"] *,
|
| 240 |
+
[class*="chip"], [class*="pill"], [class*="chip"] *, [class*="pill"] * {
|
| 241 |
+
background: transparent !important;
|
| 242 |
+
border: none !important;
|
| 243 |
+
box-shadow: none !important;
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
[data-testid*="api"], [data-testid*="settings"],
|
| 247 |
+
[id*="api"], [id*="settings"],
|
| 248 |
+
[class*="api"], [class*="settings"],
|
| 249 |
+
[class*="bottom"], [class*="toolbar"], [class*="controls"] {
|
| 250 |
+
background: transparent !important;
|
| 251 |
+
box-shadow: none !important;
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
[data-testid*="api"] *, [data-testid*="settings"] *,
|
| 255 |
+
[id*="api"] *, [id*="settings"] *,
|
| 256 |
+
[class*="api"] *, [class*="settings"] * {
|
| 257 |
+
background: transparent !important;
|
| 258 |
+
box-shadow: none !important;
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
section footer {
|
| 262 |
+
background: transparent !important;
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
section footer button,
|
| 266 |
+
section footer a {
|
| 267 |
+
background: transparent !important;
|
| 268 |
+
background-color: transparent !important;
|
| 269 |
+
border: none !important;
|
| 270 |
+
box-shadow: none !important;
|
| 271 |
+
color: white !important;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
section footer button:hover,
|
| 275 |
+
section footer button:focus,
|
| 276 |
+
section footer a:hover,
|
| 277 |
+
section footer a:focus {
|
| 278 |
+
background: transparent !important;
|
| 279 |
+
background-color: transparent !important;
|
| 280 |
+
box-shadow: none !important;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
section footer button,
|
| 284 |
+
section footer button * {
|
| 285 |
+
background: transparent !important;
|
| 286 |
+
background-color: transparent !important;
|
| 287 |
+
background-image: none !important;
|
| 288 |
+
box-shadow: none !important;
|
| 289 |
+
filter: none !important;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
section footer button::before,
|
| 293 |
+
section footer button::after {
|
| 294 |
+
background: transparent !important;
|
| 295 |
+
background-color: transparent !important;
|
| 296 |
+
background-image: none !important;
|
| 297 |
+
box-shadow: none !important;
|
| 298 |
+
filter: none !important;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
section footer a,
|
| 302 |
+
section footer a * {
|
| 303 |
+
background: transparent !important;
|
| 304 |
+
background-color: transparent !important;
|
| 305 |
+
box-shadow: none !important;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
.gradio-container footer button,
|
| 309 |
+
.gradio-container footer button *,
|
| 310 |
+
.gradio-container .footer button,
|
| 311 |
+
.gradio-container .footer button * {
|
| 312 |
+
background: transparent !important;
|
| 313 |
+
background-color: transparent !important;
|
| 314 |
+
background-image: none !important;
|
| 315 |
+
box-shadow: none !important;
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
.gradio-container footer button::before,
|
| 319 |
+
.gradio-container footer button::after,
|
| 320 |
+
.gradio-container .footer button::before,
|
| 321 |
+
.gradio-container .footer button::after {
|
| 322 |
+
background: transparent !important;
|
| 323 |
+
background-color: transparent !important;
|
| 324 |
+
background-image: none !important;
|
| 325 |
+
box-shadow: none !important;
|
| 326 |
+
}
|