Danielleeee commited on
Commit
5f59ec2
·
verified ·
1 Parent(s): 97c9b79

Upload 4 files

Browse files
Files changed (4) hide show
  1. README (1).md +59 -0
  2. app.py +352 -0
  3. requirements (1).txt +17 -0
  4. style.css +49 -0
README (1).md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ESCP Notebook Runner
3
+ emoji: 📊
4
+ colorFrom: indigo
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 5.23.3
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # ESCP Notebook Runner
13
+
14
+ This Hugging Face Space runs a Jupyter notebook on two CSV datasets and exposes the results in a Gradio dashboard.
15
+
16
+ ## Included files
17
+
18
+ - `app.py` — Gradio app that uploads or reuses the bundled notebook and CSV files
19
+ - `analysis.ipynb` — your uploaded notebook, renamed for stable execution
20
+ - `synthetic_book_reviews.csv` — bundled reviews dataset
21
+ - `synthetic_sales_data.csv` — bundled sales dataset
22
+ - `requirements.txt` — Python dependencies for the Space
23
+ - `style.css` — clean styling with **no background image**
24
+ - `artifacts/` — figures and tables generated by the notebook
25
+ - `runs/` — executed notebook copies produced by papermill
26
+
27
+ ## How the app works
28
+
29
+ 1. The user uploads a notebook and two CSV files, or keeps the bundled defaults.
30
+ 2. The app copies them to the fixed names expected by the notebook:
31
+ - `analysis.ipynb`
32
+ - `synthetic_book_reviews.csv`
33
+ - `synthetic_sales_data.csv`
34
+ 3. Papermill executes the notebook inside the Space.
35
+ 4. The app loads generated figures and tables from `artifacts/py/`.
36
+
37
+ ## Important note
38
+
39
+ Your notebook currently contains a `!pip install ...` cell. The Space will still run, but builds are cleaner and faster when dependencies live in `requirements.txt` and that install cell is removed from the notebook later.
40
+
41
+ ## Deploy on Hugging Face Spaces
42
+
43
+ 1. Create a new **Gradio** Space.
44
+ 2. Upload all files from this folder.
45
+ 3. Wait for the Space build to finish.
46
+ 4. Open the **Run Notebook** tab and click **Run Full Pipeline**.
47
+ 5. Open **Dashboard** and click **Refresh Dashboard**.
48
+
49
+ ## Expected notebook outputs
50
+
51
+ The dashboard looks for these files if the notebook generates them:
52
+
53
+ - `artifacts/py/figures/*.png`
54
+ - `artifacts/py/tables/df_dashboard.csv`
55
+ - `artifacts/py/tables/sentiment_counts_sampled.csv`
56
+ - `artifacts/py/tables/top_titles_by_units_sold.csv`
57
+ - `artifacts/py/figures/kpis.json`
58
+
59
+ If one of these files is missing, the related chart shows a placeholder instead of crashing.
app.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI-Assisted Code — Academic Integrity Notice
2
+ # Generated with The App Builder. ESCP coursework.
3
+ # Student must be able to explain all code when asked.
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import time
9
+ import traceback
10
+ from pathlib import Path
11
+
12
+ import gradio as gr
13
+ import pandas as pd
14
+ import papermill as pm
15
+ import plotly.graph_objects as go
16
+
17
+
18
+ BASE_DIR = Path(__file__).resolve().parent
19
+ RUNS_DIR = BASE_DIR / "runs"
20
+ ART_DIR = BASE_DIR / "artifacts"
21
+ FIG_DIR = ART_DIR / "py" / "figures"
22
+ TAB_DIR = ART_DIR / "py" / "tables"
23
+
24
+ DEFAULT_NOTEBOOK = BASE_DIR / "analysis.ipynb"
25
+ DEFAULT_REVIEWS = BASE_DIR / "synthetic_book_reviews.csv"
26
+ DEFAULT_SALES = BASE_DIR / "synthetic_sales_data.csv"
27
+
28
+ NOTEBOOK_TARGET = BASE_DIR / "analysis.ipynb"
29
+ REVIEWS_TARGET = BASE_DIR / "synthetic_book_reviews.csv"
30
+ SALES_TARGET = BASE_DIR / "synthetic_sales_data.csv"
31
+
32
+ PAPERMILL_TIMEOUT = int(os.getenv("PAPERMILL_TIMEOUT", "1800"))
33
+ MAX_PREVIEW_ROWS = int(os.getenv("MAX_PREVIEW_ROWS", "50"))
34
+ MAX_LOG_CHARS = int(os.getenv("MAX_LOG_CHARS", "8000"))
35
+
36
+
37
+ def ensure_dirs() -> None:
38
+ """Create the folders used by the app."""
39
+ for path in [RUNS_DIR, FIG_DIR, TAB_DIR]:
40
+ path.mkdir(parents=True, exist_ok=True)
41
+
42
+
43
+ def load_css() -> str:
44
+ """Load custom CSS from disk."""
45
+ css_path = BASE_DIR / "style.css"
46
+ return css_path.read_text(encoding="utf-8") if css_path.exists() else ""
47
+
48
+
49
+ def stamp() -> str:
50
+ """Create a timestamp for output notebook names."""
51
+ return time.strftime("%Y%m%d-%H%M%S")
52
+
53
+
54
+ def tail(text: str) -> str:
55
+ """Trim long logs so the textbox stays readable."""
56
+ return (text or "")[-MAX_LOG_CHARS:]
57
+
58
+
59
+ def safe_copy(uploaded_path: str | None, fallback: Path, target: Path) -> str:
60
+ """Copy uploaded file to the filename expected by the notebook."""
61
+ source = Path(uploaded_path) if uploaded_path else fallback
62
+ if not source.exists():
63
+ raise FileNotFoundError(f"Missing file: {source.name}")
64
+ if source.resolve() != target.resolve():
65
+ shutil.copy(source, target)
66
+ return source.name
67
+
68
+
69
+ def prepare_inputs(
70
+ notebook_file: str | None,
71
+ reviews_file: str | None,
72
+ sales_file: str | None,
73
+ ) -> dict:
74
+ """Normalize uploaded files so the notebook can read fixed filenames."""
75
+ return {
76
+ "notebook": safe_copy(notebook_file, DEFAULT_NOTEBOOK, NOTEBOOK_TARGET),
77
+ "reviews": safe_copy(reviews_file, DEFAULT_REVIEWS, REVIEWS_TARGET),
78
+ "sales": safe_copy(sales_file, DEFAULT_SALES, SALES_TARGET),
79
+ }
80
+
81
+
82
+ def run_pipeline(
83
+ notebook_file: str | None,
84
+ reviews_file: str | None,
85
+ sales_file: str | None,
86
+ ) -> str:
87
+ """Execute the notebook against the selected CSV files."""
88
+ ensure_dirs()
89
+ try:
90
+ chosen = prepare_inputs(notebook_file, reviews_file, sales_file)
91
+ output_nb = RUNS_DIR / f"run_{stamp()}_analysis.ipynb"
92
+ pm.execute_notebook(
93
+ input_path=str(NOTEBOOK_TARGET),
94
+ output_path=str(output_nb),
95
+ cwd=str(BASE_DIR),
96
+ log_output=True,
97
+ progress_bar=False,
98
+ request_save_on_cell_execute=True,
99
+ execution_timeout=PAPERMILL_TIMEOUT,
100
+ )
101
+ tables = ", ".join(list_tables()) or "(none)"
102
+ figures = ", ".join(list_figures()) or "(none)"
103
+ return (
104
+ "✅ Pipeline finished successfully.\n\n"
105
+ f"Notebook used: {chosen['notebook']}\n"
106
+ f"Reviews CSV used: {chosen['reviews']}\n"
107
+ f"Sales CSV used: {chosen['sales']}\n"
108
+ f"Executed notebook copy: {output_nb.name}\n\n"
109
+ f"Generated figures: {figures}\n"
110
+ f"Generated tables: {tables}"
111
+ )
112
+ except Exception as exc:
113
+ return tail(f"❌ Pipeline failed: {exc}\n\n{traceback.format_exc()}")
114
+
115
+
116
+ def list_figures() -> list[str]:
117
+ """List PNG and JPG files produced by the notebook."""
118
+ exts = {".png", ".jpg", ".jpeg"}
119
+ return sorted(p.name for p in FIG_DIR.iterdir() if p.suffix.lower() in exts)
120
+
121
+
122
+ def list_tables() -> list[str]:
123
+ """List CSV and JSON files produced by the notebook."""
124
+ exts = {".csv", ".json"}
125
+ return sorted(p.name for p in TAB_DIR.iterdir() if p.suffix.lower() in exts)
126
+
127
+
128
+ def load_json(path: Path) -> dict:
129
+ """Read a JSON file safely."""
130
+ try:
131
+ return json.loads(path.read_text(encoding="utf-8"))
132
+ except Exception:
133
+ return {}
134
+
135
+
136
+ def load_table(path: Path) -> pd.DataFrame:
137
+ """Open CSV or JSON artifacts for preview."""
138
+ try:
139
+ if path.suffix.lower() == ".json":
140
+ obj = load_json(path)
141
+ return pd.DataFrame([obj]) if isinstance(obj, dict) else pd.DataFrame(obj)
142
+ return pd.read_csv(path, nrows=MAX_PREVIEW_ROWS)
143
+ except Exception as exc:
144
+ return pd.DataFrame([{"error": str(exc)}])
145
+
146
+
147
+ def gallery_items() -> list[tuple[str, str]]:
148
+ """Build the Gradio gallery payload."""
149
+ items = []
150
+ for path in sorted(FIG_DIR.glob("*")):
151
+ if path.suffix.lower() in {".png", ".jpg", ".jpeg"}:
152
+ caption = path.stem.replace("_", " ").title()
153
+ items.append((str(path), caption))
154
+ return items
155
+
156
+
157
+ def kpi_cards_html() -> str:
158
+ """Render a simple KPI row without any background image."""
159
+ kpi_path = FIG_DIR / "kpis.json"
160
+ kpis = load_json(kpi_path)
161
+ if not kpis:
162
+ return (
163
+ '<div class="card empty-card">'
164
+ '<div class="card-title">No KPIs yet</div>'
165
+ '<div class="card-value">Run the notebook first</div>'
166
+ "</div>"
167
+ )
168
+
169
+ blocks = ['<div class="kpi-grid">']
170
+ for key, value in kpis.items():
171
+ label = key.replace("_", " ").title()
172
+ shown = f"{value:,.0f}" if isinstance(value, (int, float)) else str(value)
173
+ blocks.append(
174
+ '<div class="card">'
175
+ f'<div class="card-title">{label}</div>'
176
+ f'<div class="card-value">{shown}</div>'
177
+ "</div>"
178
+ )
179
+ blocks.append("</div>")
180
+ return "".join(blocks)
181
+
182
+
183
+ def empty_chart(title: str) -> go.Figure:
184
+ """Show a placeholder chart when notebook outputs are missing."""
185
+ fig = go.Figure()
186
+ fig.update_layout(
187
+ title=title,
188
+ template="plotly_white",
189
+ height=420,
190
+ paper_bgcolor="white",
191
+ plot_bgcolor="white",
192
+ annotations=[{
193
+ "text": "Run the notebook to generate this chart.",
194
+ "xref": "paper",
195
+ "yref": "paper",
196
+ "x": 0.5,
197
+ "y": 0.5,
198
+ "showarrow": False,
199
+ }],
200
+ )
201
+ return fig
202
+
203
+
204
+ def build_sales_chart() -> go.Figure:
205
+ """Build a line chart from df_dashboard.csv."""
206
+ path = TAB_DIR / "df_dashboard.csv"
207
+ if not path.exists():
208
+ return empty_chart("Monthly Overview")
209
+ df = pd.read_csv(path)
210
+ date_col = next((c for c in df.columns if "month" in c.lower()), None)
211
+ value_cols = [c for c in df.columns if c != date_col and pd.api.types.is_numeric_dtype(df[c])]
212
+ if not date_col or not value_cols:
213
+ return empty_chart("Monthly Overview")
214
+ df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
215
+ fig = go.Figure()
216
+ for column in value_cols:
217
+ fig.add_trace(go.Scatter(
218
+ x=df[date_col],
219
+ y=df[column],
220
+ mode="lines+markers",
221
+ name=column.replace("_", " ").title(),
222
+ ))
223
+ fig.update_layout(
224
+ title="Monthly Overview",
225
+ template="plotly_white",
226
+ height=420,
227
+ paper_bgcolor="white",
228
+ plot_bgcolor="white",
229
+ hovermode="x unified",
230
+ )
231
+ return fig
232
+
233
+
234
+ def build_top_sellers_chart() -> go.Figure:
235
+ """Build a horizontal bar chart from top_titles_by_units_sold.csv."""
236
+ path = TAB_DIR / "top_titles_by_units_sold.csv"
237
+ if not path.exists():
238
+ return empty_chart("Top Selling Titles")
239
+ df = pd.read_csv(path).head(15)
240
+ title_col = next((c for c in df.columns if "title" in c.lower()), df.columns[0])
241
+ value_col = next((c for c in df.columns if "unit" in c.lower()), df.columns[-1])
242
+ fig = go.Figure(go.Bar(x=df[value_col], y=df[title_col], orientation="h"))
243
+ fig.update_layout(
244
+ title="Top Selling Titles",
245
+ template="plotly_white",
246
+ height=max(420, len(df) * 28),
247
+ paper_bgcolor="white",
248
+ plot_bgcolor="white",
249
+ )
250
+ fig.update_yaxes(autorange="reversed")
251
+ return fig
252
+
253
+
254
+ def build_sentiment_chart() -> go.Figure:
255
+ """Build a stacked sentiment chart from sentiment_counts_sampled.csv."""
256
+ path = TAB_DIR / "sentiment_counts_sampled.csv"
257
+ if not path.exists():
258
+ return empty_chart("Sentiment Distribution")
259
+ df = pd.read_csv(path)
260
+ title_col = df.columns[0]
261
+ sentiment_cols = [c for c in ["negative", "neutral", "positive"] if c in df.columns]
262
+ if not sentiment_cols:
263
+ return empty_chart("Sentiment Distribution")
264
+ fig = go.Figure()
265
+ for column in sentiment_cols:
266
+ fig.add_trace(go.Bar(x=df[column], y=df[title_col], name=column.title(), orientation="h"))
267
+ fig.update_layout(
268
+ title="Sentiment Distribution",
269
+ template="plotly_white",
270
+ height=max(420, len(df) * 28),
271
+ barmode="stack",
272
+ paper_bgcolor="white",
273
+ plot_bgcolor="white",
274
+ )
275
+ fig.update_yaxes(autorange="reversed")
276
+ return fig
277
+
278
+
279
+ def refresh_table(choice: str) -> pd.DataFrame:
280
+ """Load the selected table into the preview component."""
281
+ if not choice:
282
+ return pd.DataFrame([{"hint": "Choose a table first."}])
283
+ return load_table(TAB_DIR / choice)
284
+
285
+
286
+ def refresh_dashboard() -> tuple:
287
+ """Refresh every dashboard component in one click."""
288
+ choices = list_tables()
289
+ default_choice = choices[0] if choices else None
290
+ default_df = refresh_table(default_choice) if default_choice else pd.DataFrame()
291
+ return (
292
+ kpi_cards_html(),
293
+ build_sales_chart(),
294
+ build_sentiment_chart(),
295
+ build_top_sellers_chart(),
296
+ gallery_items(),
297
+ gr.update(choices=choices, value=default_choice),
298
+ default_df,
299
+ )
300
+
301
+
302
+ ensure_dirs()
303
+
304
+ with gr.Blocks(title="Notebook Runner Space") as demo:
305
+ gr.Markdown(
306
+ "# ESCP Notebook Runner\n"
307
+ "Upload a notebook and two CSV files, then run the full analysis in one click."
308
+ )
309
+
310
+ with gr.Tab("1. Run Notebook"):
311
+ gr.Markdown(
312
+ "The notebook expects these exact filenames inside the Space:\n"
313
+ "`analysis.ipynb`, `synthetic_book_reviews.csv`, and `synthetic_sales_data.csv`.\n"
314
+ "This app renames your uploaded files automatically before execution."
315
+ )
316
+ notebook_file = gr.File(label="Notebook (.ipynb)", file_types=[".ipynb"], type="filepath")
317
+ reviews_file = gr.File(label="Reviews CSV", file_types=[".csv"], type="filepath")
318
+ sales_file = gr.File(label="Sales CSV", file_types=[".csv"], type="filepath")
319
+ run_button = gr.Button("Run Full Pipeline", variant="primary")
320
+ run_log = gr.Textbox(label="Execution Log", lines=18, interactive=False)
321
+ run_button.click(
322
+ run_pipeline,
323
+ inputs=[notebook_file, reviews_file, sales_file],
324
+ outputs=[run_log],
325
+ )
326
+
327
+ with gr.Tab("2. Dashboard"):
328
+ kpis = gr.HTML(value=kpi_cards_html())
329
+ refresh_button = gr.Button("Refresh Dashboard", variant="primary")
330
+ chart_sales = gr.Plot(label="Monthly Overview")
331
+ chart_sentiment = gr.Plot(label="Sentiment Distribution")
332
+ chart_top = gr.Plot(label="Top Sellers")
333
+ gallery = gr.Gallery(label="Generated Figures", columns=2, height=420)
334
+ table_name = gr.Dropdown(label="Generated Tables", choices=[], interactive=True)
335
+ table_preview = gr.Dataframe(label="Table Preview", interactive=False)
336
+
337
+ refresh_button.click(
338
+ refresh_dashboard,
339
+ outputs=[kpis, chart_sales, chart_sentiment, chart_top, gallery, table_name, table_preview],
340
+ )
341
+ table_name.change(refresh_table, inputs=[table_name], outputs=[table_preview])
342
+
343
+ with gr.Tab("3. Project Files"):
344
+ gr.Markdown(
345
+ "Bundled defaults included in this starter project:\n"
346
+ "- `analysis.ipynb`\n"
347
+ "- `synthetic_book_reviews.csv`\n"
348
+ "- `synthetic_sales_data.csv`\n"
349
+ "- `artifacts/` for notebook outputs"
350
+ )
351
+
352
+ demo.launch(css=load_css(), allowed_paths=[str(BASE_DIR)])
requirements (1).txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio==5.23.3
2
+ pandas==2.2.3
3
+ papermill==2.6.0
4
+ plotly==6.0.1
5
+ matplotlib==3.10.1
6
+ seaborn==0.13.2
7
+ numpy==2.2.4
8
+ statsmodels==0.14.4
9
+ vaderSentiment==3.3.2
10
+ textblob==0.19.0
11
+ faker==37.1.0
12
+ transformers==4.49.0
13
+ huggingface_hub==0.29.3
14
+ requests==2.32.3
15
+ nbformat==5.10.4
16
+ ipykernel==6.29.5
17
+ jupyter-client==8.6.3
style.css ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* AI-Assisted Code — Academic Integrity Notice
2
+ Generated with The App Builder. ESCP coursework.
3
+ Student must be able to explain all code when asked. */
4
+
5
+ body, .gradio-container {
6
+ background: #f7f9fc !important;
7
+ }
8
+
9
+ .gradio-container {
10
+ max-width: 1100px !important;
11
+ }
12
+
13
+ #component-0, .block {
14
+ border-radius: 14px;
15
+ }
16
+
17
+ .kpi-grid {
18
+ display: grid;
19
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
20
+ gap: 12px;
21
+ margin-bottom: 18px;
22
+ }
23
+
24
+ .card {
25
+ background: white;
26
+ border: 1px solid #dbe4f0;
27
+ border-radius: 14px;
28
+ padding: 16px;
29
+ box-shadow: 0 2px 10px rgba(15, 23, 42, 0.05);
30
+ }
31
+
32
+ .empty-card {
33
+ text-align: center;
34
+ }
35
+
36
+ .card-title {
37
+ color: #546274;
38
+ font-size: 12px;
39
+ font-weight: 700;
40
+ text-transform: uppercase;
41
+ margin-bottom: 8px;
42
+ letter-spacing: 0.06em;
43
+ }
44
+
45
+ .card-value {
46
+ color: #152235;
47
+ font-size: 24px;
48
+ font-weight: 700;
49
+ }