Spaces:
Build error
Build error
Upload 4 files
Browse filesFiles changed (4)
- README (1).mdAdded+59
- app.pyAdded+352
- requirements (1).txtAdded+17
- style.cssAdded+49
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859---title: ESCP Notebook Runneremoji: 📊colorFrom: indigocolorTo: bluesdk: gradiosdk_version: 5.23.3app_file: app.pypinned: false---
# ESCP Notebook Runner
This Hugging Face Space runs a Jupyter notebook on two CSV datasets and exposes the results in a Gradio dashboard.
## Included files
- `app.py` — Gradio app that uploads or reuses the bundled notebook and CSV files- `analysis.ipynb` — your uploaded notebook, renamed for stable execution- `synthetic_book_reviews.csv` — bundled reviews dataset- `synthetic_sales_data.csv` — bundled sales dataset- `requirements.txt` — Python dependencies for the Space- `style.css` — clean styling with **no background image**- `artifacts/` — figures and tables generated by the notebook- `runs/` — executed notebook copies produced by papermill
## How the app works
1. The user uploads a notebook and two CSV files, or keeps the bundled defaults.2. The app copies them to the fixed names expected by the notebook: - `analysis.ipynb` - `synthetic_book_reviews.csv` - `synthetic_sales_data.csv`3. Papermill executes the notebook inside the Space.4. The app loads generated figures and tables from `artifacts/py/`.
## Important note
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.
## Deploy on Hugging Face Spaces
1. Create a new **Gradio** Space.2. Upload all files from this folder.3. Wait for the Space build to finish.4. Open the **Run Notebook** tab and click **Run Full Pipeline**.5. Open **Dashboard** and click **Refresh Dashboard**.
## Expected notebook outputs
The dashboard looks for these files if the notebook generates them:
- `artifacts/py/figures/*.png`- `artifacts/py/tables/df_dashboard.csv`- `artifacts/py/tables/sentiment_counts_sampled.csv`- `artifacts/py/tables/top_titles_by_units_sold.csv`- `artifacts/py/figures/kpis.json`
If one of these files is missing, the related chart shows a placeholder instead of crashing.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352# AI-Assisted Code — Academic Integrity Notice# Generated with The App Builder. ESCP coursework.# Student must be able to explain all code when asked.
import jsonimport osimport shutilimport timeimport tracebackfrom pathlib import Path
import gradio as grimport pandas as pdimport papermill as pmimport plotly.graph_objects as go
BASE_DIR = Path(__file__).resolve().parentRUNS_DIR = BASE_DIR / "runs"ART_DIR = BASE_DIR / "artifacts"FIG_DIR = ART_DIR / "py" / "figures"TAB_DIR = ART_DIR / "py" / "tables"
DEFAULT_NOTEBOOK = BASE_DIR / "analysis.ipynb"DEFAULT_REVIEWS = BASE_DIR / "synthetic_book_reviews.csv"DEFAULT_SALES = BASE_DIR / "synthetic_sales_data.csv"
NOTEBOOK_TARGET = BASE_DIR / "analysis.ipynb"REVIEWS_TARGET = BASE_DIR / "synthetic_book_reviews.csv"SALES_TARGET = BASE_DIR / "synthetic_sales_data.csv"
PAPERMILL_TIMEOUT = int(os.getenv("PAPERMILL_TIMEOUT", "1800"))MAX_PREVIEW_ROWS = int(os.getenv("MAX_PREVIEW_ROWS", "50"))MAX_LOG_CHARS = int(os.getenv("MAX_LOG_CHARS", "8000"))
def ensure_dirs() -> None: """Create the folders used by the app.""" for path in [RUNS_DIR, FIG_DIR, TAB_DIR]: path.mkdir(parents=True, exist_ok=True)
def load_css() -> str: """Load custom CSS from disk.""" css_path = BASE_DIR / "style.css" return css_path.read_text(encoding="utf-8") if css_path.exists() else ""
def stamp() -> str: """Create a timestamp for output notebook names.""" return time.strftime("%Y%m%d-%H%M%S")
def tail(text: str) -> str: """Trim long logs so the textbox stays readable.""" return (text or "")[-MAX_LOG_CHARS:]
def safe_copy(uploaded_path: str | None, fallback: Path, target: Path) -> str: """Copy uploaded file to the filename expected by the notebook.""" source = Path(uploaded_path) if uploaded_path else fallback if not source.exists(): raise FileNotFoundError(f"Missing file: {source.name}") if source.resolve() != target.resolve(): shutil.copy(source, target) return source.name
def prepare_inputs( notebook_file: str | None, reviews_file: str | None, sales_file: str | None,) -> dict: """Normalize uploaded files so the notebook can read fixed filenames.""" return { "notebook": safe_copy(notebook_file, DEFAULT_NOTEBOOK, NOTEBOOK_TARGET), "reviews": safe_copy(reviews_file, DEFAULT_REVIEWS, REVIEWS_TARGET), "sales": safe_copy(sales_file, DEFAULT_SALES, SALES_TARGET), }
def run_pipeline( notebook_file: str | None, reviews_file: str | None, sales_file: str | None,) -> str: """Execute the notebook against the selected CSV files.""" ensure_dirs() try: chosen = prepare_inputs(notebook_file, reviews_file, sales_file) output_nb = RUNS_DIR / f"run_{stamp()}_analysis.ipynb" pm.execute_notebook( input_path=str(NOTEBOOK_TARGET), output_path=str(output_nb), cwd=str(BASE_DIR), log_output=True, progress_bar=False, request_save_on_cell_execute=True, execution_timeout=PAPERMILL_TIMEOUT, ) tables = ", ".join(list_tables()) or "(none)" figures = ", ".join(list_figures()) or "(none)" return ( "✅ Pipeline finished successfully.\n\n" f"Notebook used: {chosen['notebook']}\n" f"Reviews CSV used: {chosen['reviews']}\n" f"Sales CSV used: {chosen['sales']}\n" f"Executed notebook copy: {output_nb.name}\n\n" f"Generated figures: {figures}\n" f"Generated tables: {tables}" ) except Exception as exc: return tail(f"❌ Pipeline failed: {exc}\n\n{traceback.format_exc()}")
def list_figures() -> list[str]: """List PNG and JPG files produced by the notebook.""" exts = {".png", ".jpg", ".jpeg"} return sorted(p.name for p in FIG_DIR.iterdir() if p.suffix.lower() in exts)
def list_tables() -> list[str]: """List CSV and JSON files produced by the notebook.""" exts = {".csv", ".json"} return sorted(p.name for p in TAB_DIR.iterdir() if p.suffix.lower() in exts)
def load_json(path: Path) -> dict: """Read a JSON file safely.""" try: return json.loads(path.read_text(encoding="utf-8")) except Exception: return {}
def load_table(path: Path) -> pd.DataFrame: """Open CSV or JSON artifacts for preview.""" try: if path.suffix.lower() == ".json": obj = load_json(path) return pd.DataFrame([obj]) if isinstance(obj, dict) else pd.DataFrame(obj) return pd.read_csv(path, nrows=MAX_PREVIEW_ROWS) except Exception as exc: return pd.DataFrame([{"error": str(exc)}])
def gallery_items() -> list[tuple[str, str]]: """Build the Gradio gallery payload.""" items = [] for path in sorted(FIG_DIR.glob("*")): if path.suffix.lower() in {".png", ".jpg", ".jpeg"}: caption = path.stem.replace("_", " ").title() items.append((str(path), caption)) return items
def kpi_cards_html() -> str: """Render a simple KPI row without any background image.""" kpi_path = FIG_DIR / "kpis.json" kpis = load_json(kpi_path) if not kpis: return ( '<div class="card empty-card">' '<div class="card-title">No KPIs yet</div>' '<div class="card-value">Run the notebook first</div>' "</div>" )
blocks = ['<div class="kpi-grid">'] for key, value in kpis.items(): label = key.replace("_", " ").title() shown = f"{value:,.0f}" if isinstance(value, (int, float)) else str(value) blocks.append( '<div class="card">' f'<div class="card-title">{label}</div>' f'<div class="card-value">{shown}</div>' "</div>" ) blocks.append("</div>") return "".join(blocks)
def empty_chart(title: str) -> go.Figure: """Show a placeholder chart when notebook outputs are missing.""" fig = go.Figure() fig.update_layout( title=title, template="plotly_white", height=420, paper_bgcolor="white", plot_bgcolor="white", annotations=[{ "text": "Run the notebook to generate this chart.", "xref": "paper", "yref": "paper", "x": 0.5, "y": 0.5, "showarrow": False, }], ) return fig
def build_sales_chart() -> go.Figure: """Build a line chart from df_dashboard.csv.""" path = TAB_DIR / "df_dashboard.csv" if not path.exists(): return empty_chart("Monthly Overview") df = pd.read_csv(path) date_col = next((c for c in df.columns if "month" in c.lower()), None) value_cols = [c for c in df.columns if c != date_col and pd.api.types.is_numeric_dtype(df[c])] if not date_col or not value_cols: return empty_chart("Monthly Overview") df[date_col] = pd.to_datetime(df[date_col], errors="coerce") fig = go.Figure() for column in value_cols: fig.add_trace(go.Scatter( x=df[date_col], y=df[column], mode="lines+markers", name=column.replace("_", " ").title(), )) fig.update_layout( title="Monthly Overview", template="plotly_white", height=420, paper_bgcolor="white", plot_bgcolor="white", hovermode="x unified", ) return fig
def build_top_sellers_chart() -> go.Figure: """Build a horizontal bar chart from top_titles_by_units_sold.csv.""" path = TAB_DIR / "top_titles_by_units_sold.csv" if not path.exists(): return empty_chart("Top Selling Titles") df = pd.read_csv(path).head(15) title_col = next((c for c in df.columns if "title" in c.lower()), df.columns[0]) value_col = next((c for c in df.columns if "unit" in c.lower()), df.columns[-1]) fig = go.Figure(go.Bar(x=df[value_col], y=df[title_col], orientation="h")) fig.update_layout( title="Top Selling Titles", template="plotly_white", height=max(420, len(df) * 28), paper_bgcolor="white", plot_bgcolor="white", ) fig.update_yaxes(autorange="reversed") return fig
def build_sentiment_chart() -> go.Figure: """Build a stacked sentiment chart from sentiment_counts_sampled.csv.""" path = TAB_DIR / "sentiment_counts_sampled.csv" if not path.exists(): return empty_chart("Sentiment Distribution") df = pd.read_csv(path) title_col = df.columns[0] sentiment_cols = [c for c in ["negative", "neutral", "positive"] if c in df.columns] if not sentiment_cols: return empty_chart("Sentiment Distribution") fig = go.Figure() for column in sentiment_cols: fig.add_trace(go.Bar(x=df[column], y=df[title_col], name=column.title(), orientation="h")) fig.update_layout( title="Sentiment Distribution", template="plotly_white", height=max(420, len(df) * 28), barmode="stack", paper_bgcolor="white", plot_bgcolor="white", ) fig.update_yaxes(autorange="reversed") return fig
def refresh_table(choice: str) -> pd.DataFrame: """Load the selected table into the preview component.""" if not choice: return pd.DataFrame([{"hint": "Choose a table first."}]) return load_table(TAB_DIR / choice)
def refresh_dashboard() -> tuple: """Refresh every dashboard component in one click.""" choices = list_tables() default_choice = choices[0] if choices else None default_df = refresh_table(default_choice) if default_choice else pd.DataFrame() return ( kpi_cards_html(), build_sales_chart(), build_sentiment_chart(), build_top_sellers_chart(), gallery_items(), gr.update(choices=choices, value=default_choice), default_df, )
ensure_dirs()
with gr.Blocks(title="Notebook Runner Space") as demo: gr.Markdown( "# ESCP Notebook Runner\n" "Upload a notebook and two CSV files, then run the full analysis in one click." )
with gr.Tab("1. Run Notebook"): gr.Markdown( "The notebook expects these exact filenames inside the Space:\n" "`analysis.ipynb`, `synthetic_book_reviews.csv`, and `synthetic_sales_data.csv`.\n" "This app renames your uploaded files automatically before execution." ) notebook_file = gr.File(label="Notebook (.ipynb)", file_types=[".ipynb"], type="filepath") reviews_file = gr.File(label="Reviews CSV", file_types=[".csv"], type="filepath") sales_file = gr.File(label="Sales CSV", file_types=[".csv"], type="filepath") run_button = gr.Button("Run Full Pipeline", variant="primary") run_log = gr.Textbox(label="Execution Log", lines=18, interactive=False) run_button.click( run_pipeline, inputs=[notebook_file, reviews_file, sales_file], outputs=[run_log], )
with gr.Tab("2. Dashboard"): kpis = gr.HTML(value=kpi_cards_html()) refresh_button = gr.Button("Refresh Dashboard", variant="primary") chart_sales = gr.Plot(label="Monthly Overview") chart_sentiment = gr.Plot(label="Sentiment Distribution") chart_top = gr.Plot(label="Top Sellers") gallery = gr.Gallery(label="Generated Figures", columns=2, height=420) table_name = gr.Dropdown(label="Generated Tables", choices=[], interactive=True) table_preview = gr.Dataframe(label="Table Preview", interactive=False)
refresh_button.click( refresh_dashboard, outputs=[kpis, chart_sales, chart_sentiment, chart_top, gallery, table_name, table_preview], ) table_name.change(refresh_table, inputs=[table_name], outputs=[table_preview])
with gr.Tab("3. Project Files"): gr.Markdown( "Bundled defaults included in this starter project:\n" "- `analysis.ipynb`\n" "- `synthetic_book_reviews.csv`\n" "- `synthetic_sales_data.csv`\n" "- `artifacts/` for notebook outputs" )
demo.launch(css=load_css(), allowed_paths=[str(BASE_DIR)])1234567891011121314151617gradio==5.23.3pandas==2.2.3papermill==2.6.0plotly==6.0.1matplotlib==3.10.1seaborn==0.13.2numpy==2.2.4statsmodels==0.14.4vaderSentiment==3.3.2textblob==0.19.0faker==37.1.0transformers==4.49.0huggingface_hub==0.29.3requests==2.32.3nbformat==5.10.4ipykernel==6.29.5jupyter-client==8.6.312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849/* AI-Assisted Code — Academic Integrity NoticeGenerated with The App Builder. ESCP coursework.Student must be able to explain all code when asked. */
body, .gradio-container { background: #f7f9fc !important;}
.gradio-container { max-width: 1100px !important;}
#component-0, .block { border-radius: 14px;}
.kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 18px;}
.card { background: white; border: 1px solid #dbe4f0; border-radius: 14px; padding: 16px; box-shadow: 0 2px 10px rgba(15, 23, 42, 0.05);}
.empty-card { text-align: center;}
.card-title { color: #546274; font-size: 12px; font-weight: 700; text-transform: uppercase; margin-bottom: 8px; letter-spacing: 0.06em;}
.card-value { color: #152235; font-size: 24px; font-weight: 700;}README (1).mdAdded+59
app.pyAdded+352
requirements (1).txtAdded+17
style.cssAdded+49