Spaces:
Sleeping
Sleeping
Upload 10 files
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600"""AIBDM 2026 - AI & Big Data Management | ESCP Business SchoolGradio App Template for Hugging Face SpacesThis app executes student Jupyter notebooks (data creation + analysis),displays results in a gallery, and provides an AI-powered dashboardfor exploring the generated artifacts.Usage:1. Place your two notebooks in the repo root.2. Set environment variables (or use defaults).3. Deploy to Hugging Face Spaces."""# βββββββββββββββββββββββββββββββββββββββββββββ# Imports# βββββββββββββββββββββββββββββββββββββββββββββimport os, json, glob, time, re, textwrap, traceback, subprocess, sysfrom pathlib import Pathfrom functools import lru_cacheimport gradio as grimport pandas as pd# βββββββββββββββββββββββββββββββββββββββββββββ# Configuration (all via environment variables)# βββββββββββββββββββββββββββββββββββββββββββββNB1 = os.getenv("NB1", "datacreation.ipynb")NB2 = os.getenv("NB2", "pythonanalysis.ipynb")HF_API_KEY = os.getenv("HF_API_KEY", "")MODEL_NAME = os.getenv("MODEL_NAME", "mistralai/Mistral-7B-Instruct-v0.3")FIG_DIR = Path("artifacts/py/figures")TABLE_DIR = Path("artifacts/py/tables")KERNEL_NAME = "python3"# βββββββββββββββββββββββββββββββββββββββββββββ# Directory & kernel helpers# βββββββββββββββββββββββββββββββββββββββββββββdef ensure_dirs():"""Create artifact output directories if they don't exist."""FIG_DIR.mkdir(parents=True, exist_ok=True)TABLE_DIR.mkdir(parents=True, exist_ok=True)def ensure_python_kernelspec():"""Register the current Python interpreter as a Jupyter kernel soPapermill can find it. Safe to call repeatedly."""try:subprocess.check_call([sys.executable, "-m", "ipykernel", "install","--user", "--name", KERNEL_NAME],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,)except Exception as exc:print(f"[WARN] Could not install kernelspec: {exc}")# Run once at import timeensure_dirs()ensure_python_kernelspec()# βββββββββββββββββββββββββββββββββββββββββββββ# Notebook execution via Papermill# βββββββββββββββββββββββββββββββββββββββββββββdef run_notebook(nb_name: str) -> str:"""Execute a notebook with Papermill. Returns a log string."""import papermill as pmnb_path = Path(nb_name)if not nb_path.exists():return f"ERROR Notebook not found: {nb_name}"out_path = Path(f"artifacts/{nb_path.stem}_output.ipynb")out_path.parent.mkdir(parents=True, exist_ok=True)t0 = time.time()try:pm.execute_notebook(str(nb_path),str(out_path),kernel_name=KERNEL_NAME,progress_bar=False,)elapsed = time.time() - t0return f"OK {nb_name} finished in {elapsed:.1f}s\n Output -> {out_path}"except Exception:elapsed = time.time() - t0tb = traceback.format_exc()return f"FAIL {nb_name} failed after {elapsed:.1f}s\n{tb}"# Pipeline runner wrappers (return status dict + log)_step_status = {"step1": "READY", "step2": "READY"}def _log_block(title: str, body: str) -> str:return f"\n{'='*60}\n {title}\n{'='*60}\n{body}\n"def run_datacreation():_step_status["step1"] = "RUNNING"log = _log_block("Step 1: Data Creation", run_notebook(NB1))_step_status["step1"] = "DONE" if "OK" in log else "ERROR"return render_status_html(), logdef run_pythonanalysis():_step_status["step2"] = "RUNNING"log = _log_block("Step 2: Python Analysis", run_notebook(NB2))_step_status["step2"] = "DONE" if "OK" in log else "ERROR"return render_status_html(), logdef run_full_pipeline():all_log = ""status, log = run_datacreation()all_log += logstatus, log = run_pythonanalysis()all_log += logreturn status, all_log# βββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββ# Artifact indexing# βββββββββββββββββββββββββββββββββββββββββββββdef artifacts_index():"""Return (list_of_figure_paths, list_of_table_paths)."""figs = sorted(glob.glob(str(FIG_DIR / "*.png")))tables = (sorted(glob.glob(str(TABLE_DIR / "*.csv")))+ sorted(glob.glob(str(TABLE_DIR / "*.json"))))return figs, tables# βββββββββββββββββββββββββββββββββββββββββββββ# KPI helpers# βββββββββββββββββββββββββββββββββββββββββββββdef load_kpis() -> dict:"""Load KPIs from artifacts/py/tables/kpis.json (or return empty)."""kpi_path = TABLE_DIR / "kpis.json"if not kpi_path.exists():return {}try:with open(kpi_path) as f:return json.load(f)except Exception:return {}_KPI_META = {"n_titles": ("π", "Book Titles", "#a48de8"),"n_months": ("π ", "Time Periods", "#7aa6f8"),"total_units_sold": ("π¦", "Units Sold", "#6ee7c7"),"total_revenue": ("π°", "Total Revenue", "#3dcba8"),}def render_kpi_cards(kpis: dict | None = None) -> str:"""Return glassmorphism HTML cards for each KPI."""if kpis is None:kpis = load_kpis()if not kpis:return ('<div style="background:rgba(255,255,255,0.65);backdrop-filter:blur(16px);''border-radius:20px;padding:28px;text-align:center;''border:1px solid rgba(197,180,240,0.3);''box-shadow:0 8px 32px rgba(124,92,191,0.08);">''<div style="font-size:36px;margin-bottom:10px;">π</div>''<div style="color:#6b5b8e;font-size:14px;font-weight:700;">No data yet</div>''<div style="color:#9d8fc4;font-size:12px;margin-top:4px;">''Run the pipeline to populate these cards.</div></div>')def _card(icon, label, value, colour):if isinstance(value, (int, float)):value = f"{value:,.0f}" if value > 100 else str(value)return (f'<div style="background:rgba(255,255,255,0.72);backdrop-filter:blur(16px);'f'border-radius:20px;padding:18px 14px 16px;text-align:center;'f'border:1px solid rgba(255,255,255,0.8);'f'box-shadow:0 4px 16px rgba(124,92,191,0.08);'f'border-top:3px solid {colour};">'f'<div style="font-size:26px;margin-bottom:7px;">{icon}</div>'f'<div style="color:#9d8fc4;font-size:10px;text-transform:uppercase;'f'letter-spacing:1.8px;font-weight:800;margin-bottom:7px;">{label}</div>'f'<div style="color:#2d1f4e;font-size:18px;font-weight:800;">{value}</div>'f'</div>')cards_html = ""for key, val in kpis.items():icon, label, colour = _KPI_META.get(key, ("π", key.replace("_", " ").title(), "#a48de8"))cards_html += _card(icon, label, val, colour)return (f'<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));'f'gap:12px;margin-bottom:20px;">{cards_html}</div>')# βββββββββββββββββββββββββββββββββββββββββββββ# Status badges# βββββββββββββββββββββββββββββββββββββββββββββ_BADGE_COLORS = {"READY": ("#888", "rgba(255,255,255,0.08)"),"RUNNING": ("#e8a835", "rgba(232,168,53,0.12)"),"DONE": ("#3eca6e", "rgba(62,202,110,0.12)"),"ERROR": ("#e84f4f", "rgba(232,79,79,0.12)"),}def render_status_html() -> str:"""Render pipeline status badges as HTML."""badge_css = ("display:inline-flex;align-items:center;gap:8px;""padding:8px 18px;border-radius:12px;margin:6px;""font-family:system-ui,sans-serif;font-size:0.9em;""backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,0.15);")badges = []for label, key in [("Data Creation", "step1"), ("Python Analysis", "step2")]:st = _step_status.get(key, "READY")color, bg = _BADGE_COLORS.get(st, _BADGE_COLORS["READY"])dot = f"<span style='width:10px;height:10px;border-radius:50%;background:{color};display:inline-block;'></span>"badges.append(f"<div style='{badge_css}background:{bg};color:{color};'>"f"{dot}<strong>{label}</strong> — {st}</div>")return f"<div style='display:flex;flex-wrap:wrap;justify-content:center;'>{''.join(badges)}</div>"# βββββββββββββββββββββββββββββββββββββββββββββ# Gallery / table helpers# βββββββββββββββββββββββββββββββββββββββββββββdef refresh_gallery():"""Return (gallery_images, table_dropdown_choices)."""figs, tables = artifacts_index()table_names = [Path(t).name for t in tables]gallery = figs if figs else []return gallery, gr.update(choices=table_names, value=table_names[0] if table_names else None)def on_table_select(choice: str | None):"""Load the selected table and return a DataFrame (or message)."""if not choice:return pd.DataFrame({"info": ["Select a table from the dropdown."]})for ext_dir in [TABLE_DIR]:path = ext_dir / choiceif path.exists():if choice.endswith(".csv"):try:return pd.read_csv(path)except Exception as exc:return pd.DataFrame({"error": [str(exc)]})elif choice.endswith(".json"):try:with open(path) as f:data = json.load(f)if isinstance(data, list):return pd.DataFrame(data)return pd.DataFrame([data])except Exception as exc:return pd.DataFrame({"error": [str(exc)]})return pd.DataFrame({"error": [f"File not found: {choice}"]})# βββββββββββββββββββββββββββββββββββββββββββββ# AI Dashboard# βββββββββββββββββββββββββββββββββββββββββββββ_SYSTEM_PROMPT = textwrap.dedent("""\You are a data-analysis assistant for an ESCP Business School project.The student has generated the following artifacts:FIGURES: {figures}TABLES: {tables}KPIs: {kpis}Answer the student's question conversationally. When relevant, end yourresponse with a JSON directive on its own line so the UI can display theright artifact:{{"show_figure": "filename.png"}} OR {{"show_table": "filename.csv"}}Only include the directive when an artifact is directly relevant.""")def _build_system_prompt() -> str:figs, tables = artifacts_index()fig_names = [Path(f).name for f in figs]tbl_names = [Path(t).name for t in tables]kpis = load_kpis()return _SYSTEM_PROMPT.format(figures=", ".join(fig_names) or "none yet",tables=", ".join(tbl_names) or "none yet",kpis=json.dumps(kpis) if kpis else "none yet",)def _call_hf_api(messages: list[dict]) -> str:"""Call Hugging Face Inference API (returns assistant text)."""from huggingface_hub import InferenceClientclient = InferenceClient(model=MODEL_NAME, token=HF_API_KEY)resp = client.chat_completion(messages=messages, max_tokens=512)return resp.choices[0].message.contentdef _keyword_fallback(msg: str, idx: dict, kpis: dict) -> str:"""Simple keyword matcher when no LLM is available."""msg_lower = msg.lower()figs, tables = idx# Try to match a figurefor f in figs:name = Path(f).stem.lower().replace("_", " ")if any(w in msg_lower for w in name.split()):return (f"Here is the **{Path(f).stem}** chart I found for you.\n\n"f'{{"show_figure": "{Path(f).name}"}}')# Try to match a tablefor t in tables:name = Path(t).stem.lower().replace("_", " ")if any(w in msg_lower for w in name.split()):return (f"Here is the **{Path(t).stem}** table.\n\n"f'{{"show_table": "{Path(t).name}"}}')# KPI summaryif any(k in msg_lower for k in ("kpi", "metric", "summary", "overview")):if kpis:lines = [f"- **{k.replace('_',' ').title()}**: {v}" for k, v in kpis.items()]return "Here are the current KPIs:\n\n" + "\n".join(lines)return "No KPIs have been generated yet. Please run the pipeline first."# Sentiment / review keywordsif any(k in msg_lower for k in ("sentiment", "review", "opinion")):match = [f for f in figs if "sentiment" in Path(f).name.lower()]if match:return f'The sentiment analysis is shown in this chart.\n\n{{"show_figure": "{Path(match[0]).name}"}}'# Forecast / ARIMAif any(k in msg_lower for k in ("forecast", "arima", "predict", "future")):match = [f for f in figs if any(w in Path(f).name.lower() for w in ("forecast", "arima"))]if match:return f'Here is the forecast chart.\n\n{{"show_figure": "{Path(match[0]).name}"}}'# Price / pricingif any(k in msg_lower for k in ("price", "pricing", "cost")):match = [f for f in figs if "pric" in Path(f).name.lower()]if match:return f'Here is the pricing chart.\n\n{{"show_figure": "{Path(match[0]).name}"}}'return ("I can help you explore your project data. Try asking about ""**sentiment**, **forecasts**, **pricing**, **KPIs**, or mention ""a specific chart/table name.")def _parse_directive(text: str):"""Extract a JSON directive from the assistant response."""match = re.search(r'\{[^{}]*"show_(?:figure|table)"[^{}]*\}', text)if not match:return None, Nonetry:d = json.loads(match.group())if "show_figure" in d:return "figure", d["show_figure"]if "show_table" in d:return "table", d["show_table"]except json.JSONDecodeError:passreturn None, Nonedef ai_chat(user_msg: str, history: list):"""Process a user message and return (history, viz_image, viz_table)."""if not user_msg.strip():return history, None, pd.DataFrame()figs, tables = artifacts_index()kpis = load_kpis()# Build assistant responseif HF_API_KEY:try:api_msgs = [{"role": "system", "content": _build_system_prompt()}]for entry in (history or []):api_msgs.append(entry)api_msgs.append({"role": "user", "content": user_msg})assistant_text = _call_hf_api(api_msgs)except Exception as exc:assistant_text = f"LLM error ({exc}). Falling back to keyword mode.\n\n"assistant_text += _keyword_fallback(user_msg, (figs, tables), kpis)else:assistant_text = _keyword_fallback(user_msg, (figs, tables), kpis)# Parse directivekind, name = _parse_directive(assistant_text)# Strip the JSON directive from the displayed messageclean_text = re.sub(r'\{[^{}]*"show_(?:figure|table)"[^{}]*\}', "", assistant_text).strip()viz_img = Noneviz_tbl = pd.DataFrame()if kind == "figure":fig_path = FIG_DIR / nameif fig_path.exists():viz_img = str(fig_path)elif kind == "table":tbl_path = TABLE_DIR / nameif tbl_path.exists():viz_tbl = on_table_select(name)# Gradio 6 uses messages format: [{"role": ..., "content": ...}]history = (history or []) + [{"role": "user", "content": user_msg},{"role": "assistant", "content": clean_text},]return history, viz_img, viz_tbl# βββββββββββββββββββββββββββββββββββββββββββββ# CSS# βββββββββββββββββββββββββββββββββββββββββββββBASE = Path(__file__).resolve().parentdef _load_css() -> str:"""Load external CSS and inject background image paths as CSS variables."""css_path = BASE / "style.css"css = css_path.read_text(encoding="utf-8") if css_path.exists() else ""# Inject CSS custom properties for background images (served via /file=)bg_vars = (":root {\n"f" --bg-top: url('/file={BASE / 'background_top.png'}');\n"f" --bg-mid: url('/file={BASE / 'background_mid.png'}');\n"f" --bg-bottom: url('/file={BASE / 'background_bottom.png'}');\n""}\n")return bg_vars + css# βββββββββββββββββββββββββββββββββββββββββββββ# Build the Gradio UI# βββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(title="AIBDM 2026 Dashboard") as demo:gr.Markdown("# AIBDM 2026 — AI & Big Data Management Dashboard\n""*ESCP Business School • Hugging Face Spaces*",elem_id="escp_title",)# ββ Tab 1: Pipeline Runner ββββββββββββοΏ½οΏ½οΏ½βwith gr.Tab("Pipeline Runner"):status_html = gr.HTML(value=render_status_html, every=None)with gr.Row():btn_step1 = gr.Button("Step 1: Data Creation", variant="secondary")btn_step2 = gr.Button("Step 2: Python Analysis", variant="secondary")btn_full = gr.Button("Run Full Pipeline", variant="primary")log_box = gr.Textbox(label="Execution Log",lines=18,max_lines=40,interactive=False,elem_id="log-box",)btn_step1.click(fn=run_datacreation, outputs=[status_html, log_box])btn_step2.click(fn=run_pythonanalysis, outputs=[status_html, log_box])btn_full.click(fn=run_full_pipeline, outputs=[status_html, log_box])# ββ Tab 2: Results Gallery ββββββββββββββwith gr.Tab("Results Gallery"):kpi_html = gr.HTML(value=render_kpi_cards)refresh_btn = gr.Button("Refresh Results", variant="secondary")gallery = gr.Gallery(label="Generated Figures",columns=3,height="auto",object_fit="contain",)table_dd = gr.Dropdown(label="Select a data table", choices=[], interactive=True)table_view = gr.Dataframe(label="Table Preview", wrap=True)def _on_refresh():imgs, dd_update = refresh_gallery()khtml = render_kpi_cards()return imgs, dd_update, khtmlrefresh_btn.click(fn=_on_refresh, outputs=[gallery, table_dd, kpi_html])table_dd.change(fn=on_table_select, inputs=[table_dd], outputs=[table_view])# ββ Tab 3: AI Dashboard βββββββββββββββββwith gr.Tab("AI Dashboard"):_llm_note = ("*LLM active.*" if HF_API_KEYelse "*No API key detected. Using keyword matching. ""Set `HF_API_KEY` in Space secrets for full AI support.*")gr.Markdown("Ask questions about your generated data and the AI will "f"pick the best chart or table to show you.\n\n{_llm_note}")with gr.Row(equal_height=True):with gr.Column(scale=1):chatbot = gr.Chatbot(label="Chat", height=420)with gr.Row():chat_input = gr.Textbox(placeholder="e.g. Show me the sentiment distribution",show_label=False,scale=4,)send_btn = gr.Button("Send", variant="primary", scale=1)gr.Examples(examples=["Show me the sentiment analysis results","What do the sales forecasts look like?","Give me a KPI summary","Show the pricing analysis","Which books have the best reviews?",],inputs=chat_input,)with gr.Column(scale=1):viz_image = gr.Image(label="Visualization", height=350)viz_table = gr.Dataframe(label="Data Table", wrap=True)def _send(msg, hist):return ai_chat(msg, hist)send_btn.click(fn=_send,inputs=[chat_input, chatbot],outputs=[chatbot, viz_image, viz_table],).then(fn=lambda: "", outputs=[chat_input])chat_input.submit(fn=_send,inputs=[chat_input, chatbot],outputs=[chatbot, viz_image, viz_table],).then(fn=lambda: "", outputs=[chat_input])# ββ Tab 4: About ββββββββββββββββββββββββwith gr.Tab("About"):gr.Markdown(textwrap.dedent("""\## About This DashboardThis interactive dashboard was built for the **AI & Big Data Management**(AIBDM) course at **ESCP Business School** (2026 cohort).### How It Works1. **Data Creation** notebook scrapes the web and generates syntheticdata (books, sales, reviews).2. **Python Analysis** notebook runs sentiment analysis, createsvisualizations, builds ARIMA forecasts, and computes pricingdecisions.3. All outputs are saved to `artifacts/py/figures/` and`artifacts/py/tables/`.4. This Gradio app displays the results and lets you explore themwith an AI assistant.### How to Customize- Replace `datacreation.ipynb` and `pythonanalysis.ipynb` with yourown notebooks.- Make sure your notebooks write PNGs to `artifacts/py/figures/`and CSVs/JSONs to `artifacts/py/tables/`.- Optionally export a `kpis.json` file to `artifacts/py/tables/`for the KPI cards.- Set the `HF_API_KEY` secret in your Space settings to enable theAI chat (otherwise keyword fallback is used).### Environment Variables| Variable | Default | Description ||----------|---------|-------------|| `NB1` | `datacreation.ipynb` | Path to data-creation notebook || `NB2` | `pythonanalysis.ipynb` | Path to analysis notebook || `HF_API_KEY` | *(empty)* | HF Inference API token || `MODEL_NAME` | `mistralai/Mistral-7B-Instruct-v0.3` | LLM model ID |### CreditsBuilt with [Gradio](https://gradio.app) and deployed on[Hugging Face Spaces](https://huggingface.co/spaces).*ESCP Business School — AIBDM 2026*"""))# βββββββββββββββββββββββββββββββββββββββββββββ# Launch (HF Spaces handles host/port)# βββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__":demo.launch(server_name="0.0.0.0",server_port=7860,css=_load_css(),allowed_paths=[str(BASE)],)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763import osimport reimport jsonimport timeimport tracebackfrom pathlib import Pathfrom typing import Dict, Any, List, Tupleimport pandas as pdimport gradio as grimport papermill as pmimport plotly.express as pximport plotly.graph_objects as go# Optional LLM (HuggingFace Inference API)try:from huggingface_hub import InferenceClientexcept Exception:InferenceClient = None# =========================================================# CONFIG# =========================================================BASE_DIR = Path(__file__).resolve().parentNB1 = os.environ.get("NB1", "datacreation.ipynb").strip()NB2 = os.environ.get("NB2", "pythonanalysis.ipynb").strip()RUNS_DIR = BASE_DIR / "runs"ART_DIR = BASE_DIR / "artifacts"PY_FIG_DIR = ART_DIR / "py" / "figures"PY_TAB_DIR = ART_DIR / "py" / "tables"PAPERMILL_TIMEOUT = int(os.environ.get("PAPERMILL_TIMEOUT", "1800"))MAX_PREVIEW_ROWS = int(os.environ.get("MAX_FILE_PREVIEW_ROWS", "50"))MAX_LOG_CHARS = int(os.environ.get("MAX_LOG_CHARS", "8000"))HF_API_KEY = os.environ.get("HF_API_KEY", "").strip()MODEL_NAME = os.environ.get("MODEL_NAME", "deepseek-ai/DeepSeek-R1").strip()HF_PROVIDER = os.environ.get("HF_PROVIDER", "novita").strip()LLM_ENABLED = bool(HF_API_KEY) and InferenceClient is not Nonellm_client = (InferenceClient(provider=HF_PROVIDER, api_key=HF_API_KEY)if LLM_ENABLEDelse None)# =========================================================# HELPERS# =========================================================def ensure_dirs():for p in [RUNS_DIR, ART_DIR, PY_FIG_DIR, PY_TAB_DIR]:p.mkdir(parents=True, exist_ok=True)def stamp():return time.strftime("%Y%m%d-%H%M%S")def tail(text: str, n: int = MAX_LOG_CHARS) -> str:return (text or "")[-n:]def _ls(dir_path: Path, exts: Tuple[str, ...]) -> List[str]:if not dir_path.is_dir():return []return sorted(p.name for p in dir_path.iterdir() if p.is_file() and p.suffix.lower() in exts)def _read_csv(path: Path) -> pd.DataFrame:return pd.read_csv(path, nrows=MAX_PREVIEW_ROWS)def _read_json(path: Path):with path.open(encoding="utf-8") as f:return json.load(f)def artifacts_index() -> Dict[str, Any]:return {"python": {"figures": _ls(PY_FIG_DIR, (".png", ".jpg", ".jpeg")),"tables": _ls(PY_TAB_DIR, (".csv", ".json")),},}# =========================================================# PIPELINE RUNNERS# =========================================================def run_notebook(nb_name: str) -> str:ensure_dirs()nb_in = BASE_DIR / nb_nameif not nb_in.exists():return f"ERROR: {nb_name} not found."nb_out = RUNS_DIR / f"run_{stamp()}_{nb_name}"pm.execute_notebook(input_path=str(nb_in),output_path=str(nb_out),cwd=str(BASE_DIR),log_output=True,progress_bar=False,request_save_on_cell_execute=True,execution_timeout=PAPERMILL_TIMEOUT,)return f"Executed {nb_name}"def run_datacreation() -> str:try:log = run_notebook(NB1)csvs = [f.name for f in BASE_DIR.glob("*.csv")]return f"OK {log}\n\nCSVs now in /app:\n" + "\n".join(f" - {c}" for c in sorted(csvs))except Exception as e:return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"def run_pythonanalysis() -> str:try:log = run_notebook(NB2)idx = artifacts_index()figs = idx["python"]["figures"]tabs = idx["python"]["tables"]return (f"OK {log}\n\n"f"Figures: {', '.join(figs) or '(none)'}\n"f"Tables: {', '.join(tabs) or '(none)'}")except Exception as e:return f"FAILED {e}\n\n{traceback.format_exc()[-2000:]}"def run_full_pipeline() -> str:logs = []logs.append("=" * 50)logs.append("STEP 1/2: Data Creation (web scraping + synthetic data)")logs.append("=" * 50)logs.append(run_datacreation())logs.append("")logs.append("=" * 50)logs.append("STEP 2/2: Python Analysis (sentiment, ARIMA, dashboard)")logs.append("=" * 50)logs.append(run_pythonanalysis())return "\n".join(logs)# =========================================================# GALLERY LOADERS# =========================================================def _load_all_figures() -> List[Tuple[str, str]]:"""Return list of (filepath, caption) for Gallery."""items = []for p in sorted(PY_FIG_DIR.glob("*.png")):items.append((str(p), p.stem.replace('_', ' ').title()))return itemsdef _load_table_safe(path: Path) -> pd.DataFrame:try:if path.suffix == ".json":obj = _read_json(path)if isinstance(obj, dict):return pd.DataFrame([obj])return pd.DataFrame(obj)return _read_csv(path)except Exception as e:return pd.DataFrame([{"error": str(e)}])def refresh_gallery():"""Called when user clicks Refresh on Gallery tab."""figures = _load_all_figures()idx = artifacts_index()table_choices = []for name in idx["python"]["tables"]:table_choices.append(name)default_df = pd.DataFrame()if table_choices:default_df = _load_table_safe(PY_TAB_DIR / table_choices[0])return (figures if figures else [],gr.update(choices=table_choices, value=table_choices[0] if table_choices else None),default_df,render_kpi_cards(),)def on_table_select(choice: str):if not choice:return pd.DataFrame([{"hint": "Select a table above."}])path = PY_TAB_DIR / choiceif not path.exists():return pd.DataFrame([{"error": f"File not found: {choice}"}])return _load_table_safe(path)# =========================================================# KPI CARDS (BubbleBusters style)# =========================================================def load_kpis() -> Dict[str, Any]:for candidate in [PY_TAB_DIR / "kpis.json", PY_FIG_DIR / "kpis.json"]:if candidate.exists():try:return _read_json(candidate)except Exception:passreturn {}def render_kpi_cards() -> str:kpis = load_kpis()if not kpis:return ('<div style="background:rgba(255,255,255,.65);backdrop-filter:blur(16px);''border-radius:20px;padding:28px;text-align:center;''border:1.5px solid rgba(255,255,255,.7);''box-shadow:0 8px 32px rgba(124,92,191,.08);">''<div style="font-size:36px;margin-bottom:10px;">π</div>''<div style="color:#a48de8;font-size:14px;''font-weight:800;margin-bottom:6px;">No data yet</div>''<div style="color:#9d8fc4;font-size:12px;">''Run the pipeline to populate these cards.</div>''</div>')def card(icon, label, value, colour):return f"""<div style="background:rgba(255,255,255,.72);backdrop-filter:blur(16px);border-radius:20px;padding:18px 14px 16px;text-align:center;border:1.5px solid rgba(255,255,255,.8);box-shadow:0 4px 16px rgba(124,92,191,.08);border-top:3px solid {colour};"><div style="font-size:26px;margin-bottom:7px;line-height:1;">{icon}</div><div style="color:#9d8fc4;font-size:9.5px;text-transform:uppercase;letter-spacing:1.8px;margin-bottom:7px;font-weight:800;">{label}</div><div style="color:#2d1f4e;font-size:16px;font-weight:800;">{value}</div></div>"""# Map KPI keys to display configkpi_config = [("n_titles", "π", "Book Titles", "#a48de8"),("n_months", "π ", "Time Periods", "#7aa6f8"),("total_units_sold", "π¦", "Units Sold", "#6ee7c7"),("total_revenue", "π°", "Revenue", "#3dcba8"),]html = ('<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));''gap:12px;margin-bottom:24px;">')for key, icon, label, colour in kpi_config:val = kpis.get(key)if val is None:continueif isinstance(val, (int, float)) and val > 100:val = f"{val:,.0f}"html += card(icon, label, str(val), colour)# Add any extra KPIs not in the configknown = {k for k, *_ in kpi_config}for key, val in kpis.items():if key not in known:label = key.replace("_", " ").title()if isinstance(val, (int, float)) and val > 100:val = f"{val:,.0f}"html += card("π", label, str(val), "#8fa8f8")html += "</div>"return html# =========================================================# AI DASHBOARD (Tab 3) -- LLM picks what to display# =========================================================DASHBOARD_SYSTEM = """You are an AI dashboard assistant for a book-sales analytics app.The user asks questions or requests about their data. You have access to pre-computedartifacts from a Python analysis pipeline.AVAILABLE ARTIFACTS (only reference ones that exist):{artifacts_json}KPI SUMMARY: {kpis_json}YOUR JOB:1. Answer the user's question conversationally using the KPIs and your knowledge of the artifacts.2. At the END of your response, output a JSON block (fenced with ```json ... ```) that tellsthe dashboard which artifact to display. The JSON must have this shape:{{"show": "figure"|"table"|"none", "scope": "python", "filename": "..."}}- Use "show": "figure" to display a chart image.- Use "show": "table" to display a CSV/JSON table.- Use "show": "none" if no artifact is relevant.RULES:- If the user asks about sales trends or forecasting by title, show sales_trends or arima figures.- If the user asks about sentiment, show sentiment figure or sentiment_counts table.- If the user asks about forecast accuracy or model comparison, show arima figures.- If the user asks about top sellers, show top_titles_by_units_sold.csv.- If the user asks a general data question, pick the most relevant artifact.- Keep your answer concise (2-4 sentences), then the JSON block."""JSON_BLOCK_RE = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL)FALLBACK_JSON_RE = re.compile(r"\{[^{}]*\"show\"[^{}]*\}", re.DOTALL)def _parse_display_directive(text: str) -> Dict[str, str]:m = JSON_BLOCK_RE.search(text)if m:try:return json.loads(m.group(1))except json.JSONDecodeError:passm = FALLBACK_JSON_RE.search(text)if m:try:return json.loads(m.group(0))except json.JSONDecodeError:passreturn {"show": "none"}def _clean_response(text: str) -> str:"""Strip the JSON directive block from the displayed response."""return JSON_BLOCK_RE.sub("", text).strip()def ai_chat(user_msg: str, history: list):"""Chat function for the AI Dashboard tab."""if not user_msg or not user_msg.strip():return history, "", None, Noneidx = artifacts_index()kpis = load_kpis()if not LLM_ENABLED:reply, directive = _keyword_fallback(user_msg, idx, kpis)else:system = DASHBOARD_SYSTEM.format(artifacts_json=json.dumps(idx, indent=2),kpis_json=json.dumps(kpis, indent=2) if kpis else "(no KPIs yet, run the pipeline first)",)msgs = [{"role": "system", "content": system}]for entry in (history or [])[-6:]:msgs.append(entry)msgs.append({"role": "user", "content": user_msg})try:r = llm_client.chat_completion(model=MODEL_NAME,messages=msgs,temperature=0.3,max_tokens=600,stream=False,)raw = (r["choices"][0]["message"]["content"]if isinstance(r, dict)else r.choices[0].message.content)directive = _parse_display_directive(raw)reply = _clean_response(raw)except Exception as e:reply = f"LLM error: {e}. Falling back to keyword matching."reply_fb, directive = _keyword_fallback(user_msg, idx, kpis)reply += "\n\n" + reply_fb# Resolve artifact pathsfig_out = Nonetab_out = Noneshow = directive.get("show", "none")fname = directive.get("filename", "")if show == "figure" and fname:fp = PY_FIG_DIR / fnameif fp.exists():fig_out = str(fp)else:reply += f"\n\n*(Could not find figure: {fname})*"if show == "table" and fname:fp = PY_TAB_DIR / fnameif fp.exists():tab_out = _load_table_safe(fp)else:reply += f"\n\n*(Could not find table: {fname})*"new_history = (history or []) + [{"role": "user", "content": user_msg},{"role": "assistant", "content": reply},]return new_history, "", fig_out, tab_outdef _keyword_fallback(msg: str, idx: Dict, kpis: Dict) -> Tuple[str, Dict]:"""Simple keyword matcher when LLM is unavailable."""msg_lower = msg.lower()if not idx["python"]["figures"] and not idx["python"]["tables"]:return ("No artifacts found yet. Please run the pipeline first (Tab 1), ""then come back here to explore the results.",{"show": "none"},)kpi_text = ""if kpis:total = kpis.get("total_units_sold", 0)kpi_text = (f"Quick summary: **{kpis.get('n_titles', '?')}** book titles across "f"**{kpis.get('n_months', '?')}** months, with **{total:,.0f}** total units sold.")if any(w in msg_lower for w in ["trend", "sales trend", "monthly sale"]):return (f"Here are the sales trends for sampled titles. {kpi_text}",{"show": "figure", "scope": "python", "filename": "sales_trends_sampled_titles.png"},)if any(w in msg_lower for w in ["sentiment", "review", "positive", "negative"]):return (f"Here is the sentiment distribution across sampled book titles. {kpi_text}",{"show": "figure", "scope": "python", "filename": "sentiment_distribution_sampled_titles.png"},)if any(w in msg_lower for w in ["arima", "forecast", "predict"]):return (f"Here are the ARIMA forecasts for sampled titles. {kpi_text}",{"show": "figure", "scope": "python", "filename": "arima_forecasts_sampled_titles.png"},)if any(w in msg_lower for w in ["top", "best sell", "popular", "rank"]):return (f"Here are the top-selling titles by units sold. {kpi_text}",{"show": "table", "scope": "python", "filename": "top_titles_by_units_sold.csv"},)if any(w in msg_lower for w in ["price", "pricing", "decision"]):return (f"Here are the pricing decisions. {kpi_text}",{"show": "table", "scope": "python", "filename": "pricing_decisions.csv"},)if any(w in msg_lower for w in ["dashboard", "overview", "summary", "kpi"]):return (f"Dashboard overview: {kpi_text}\n\nAsk me about sales trends, sentiment, forecasts, ""pricing, or top sellers to see specific visualizations.",{"show": "table", "scope": "python", "filename": "df_dashboard.csv"},)# Defaultreturn (f"I can show you various analyses. {kpi_text}\n\n""Try asking about: **sales trends**, **sentiment**, **ARIMA forecasts**, ""**pricing decisions**, **top sellers**, or **dashboard overview**.",{"show": "none"},)# =========================================================# INTERACTIVE PLOTLY CHARTS (built from CSV artifacts)# =========================================================CHART_PALETTE = ["#7c5cbf", "#2ec4a0", "#e8537a", "#e8a230", "#5e8fef","#c45ea8", "#3dbacc", "#a0522d", "#6aaa3a", "#d46060"]def _styled_layout(**kwargs) -> dict:defaults = dict(template="plotly_white",paper_bgcolor="rgba(255,255,255,0.95)",plot_bgcolor="rgba(255,255,255,0.98)",font=dict(family="system-ui, sans-serif", color="#2d1f4e", size=12),margin=dict(l=60, r=20, t=70, b=70),legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1,bgcolor="rgba(255,255,255,0.92)",bordercolor="rgba(124,92,191,0.35)", borderwidth=1,),title=dict(font=dict(size=15, color="#4b2d8a")),)defaults.update(kwargs)return defaultsdef _empty_chart(title: str) -> go.Figure:fig = go.Figure()fig.update_layout(title=title, height=420,template="plotly_white",paper_bgcolor="rgba(255,255,255,0.95)",annotations=[dict(text="Run the pipeline to generate data",x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False,font=dict(size=14, color="rgba(124,92,191,0.5)"),)],)return figdef build_sales_chart() -> go.Figure:"""Interactive sales trends from the dashboard CSV."""path = PY_TAB_DIR / "df_dashboard.csv"if not path.exists():return _empty_chart("Sales Trends β run the pipeline first")df = pd.read_csv(path)# Try to find a month/date column and a value columndate_col = next((c for c in df.columns if "month" in c.lower() or "date" in c.lower()), None)val_cols = [c for c in df.columns if c != date_col and df[c].dtype in ("float64", "int64")]if not date_col or not val_cols:return _empty_chart("Could not auto-detect columns in df_dashboard.csv")df[date_col] = pd.to_datetime(df[date_col], errors="coerce")fig = go.Figure()for i, col in enumerate(val_cols):fig.add_trace(go.Scatter(x=df[date_col], y=df[col], name=col.replace("_", " ").title(),mode="lines+markers", line=dict(color=CHART_PALETTE[i % len(CHART_PALETTE)], width=2),marker=dict(size=4),hovertemplate=f"<b>{col.replace('_',' ').title()}</b><br>%{{x|%b %Y}}: %{{y:,.0f}}<extra></extra>",))fig.update_layout(**_styled_layout(height=450, hovermode="x unified",title=dict(text="Monthly Overview")))fig.update_xaxes(gridcolor="rgba(124,92,191,0.15)", showgrid=True)fig.update_yaxes(gridcolor="rgba(124,92,191,0.15)", showgrid=True)return figdef build_sentiment_chart() -> go.Figure:"""Interactive sentiment distribution from sentiment_counts CSV."""path = PY_TAB_DIR / "sentiment_counts_sampled.csv"if not path.exists():return _empty_chart("Sentiment Distribution β run the pipeline first")df = pd.read_csv(path)# Expect columns like: grouped_title, negative, neutral, positivetitle_col = df.columns[0]sent_cols = [c for c in ["negative", "neutral", "positive"] if c in df.columns]if not sent_cols:return _empty_chart("No sentiment columns found in CSV")colors = {"negative": "#e8537a", "neutral": "#5e8fef", "positive": "#2ec4a0"}fig = go.Figure()for col in sent_cols:fig.add_trace(go.Bar(name=col.title(), y=df[title_col], x=df[col],orientation="h", marker_color=colors.get(col, "#888"),hovertemplate=f"<b>{col.title()}</b>: %{{x}}<extra></extra>",))fig.update_layout(**_styled_layout(height=max(400, len(df) * 28),barmode="stack",title=dict(text="Sentiment Distribution by Book"),))fig.update_xaxes(title="Number of Reviews")fig.update_yaxes(autorange="reversed")return figdef build_top_sellers_chart() -> go.Figure:"""Interactive bar chart of top sellers."""path = PY_TAB_DIR / "top_titles_by_units_sold.csv"if not path.exists():return _empty_chart("Top Sellers β run the pipeline first")df = pd.read_csv(path).head(15)title_col = next((c for c in df.columns if "title" in c.lower()), df.columns[0])val_col = next((c for c in df.columns if "unit" in c.lower() or "sold" in c.lower()), df.columns[-1])fig = go.Figure(go.Bar(y=df[title_col], x=df[val_col],orientation="h",marker=dict(color=df[val_col],colorscale=[[0, "#c5b4f0"], [1, "#7c5cbf"]],),hovertemplate="<b>%{y}</b><br>Units: %{x:,.0f}<extra></extra>",))fig.update_layout(**_styled_layout(height=max(400, len(df) * 30),title=dict(text="Top Selling Titles"),showlegend=False,))fig.update_yaxes(autorange="reversed")fig.update_xaxes(title="Total Units Sold")return figdef refresh_charts():"""Rebuild all interactive charts from latest CSV data."""return build_sales_chart(), build_sentiment_chart(), build_top_sellers_chart()# =========================================================# UI# =========================================================ensure_dirs()def load_css() -> str:css_path = BASE_DIR / "style.css"return css_path.read_text(encoding="utf-8") if css_path.exists() else ""with gr.Blocks(title="AIBDM 2026 Workshop App") as demo:gr.Markdown("# AIBDM 2026 - AI & Big Data Management - Workshop App\n""*Run notebooks, explore results, and chat with your data*",elem_id="escp_title",)# ===========================================================# TAB 1 -- Pipeline Runner# ===========================================================with gr.Tab("Pipeline Runner"):gr.Markdown()with gr.Row():with gr.Column(scale=1):btn_nb1 = gr.Button("Step 1: Data Creation",variant="secondary",)with gr.Column(scale=1):btn_nb2 = gr.Button("Step 2: Python Analysis",variant="secondary",)with gr.Row():btn_all = gr.Button("Run Full Pipeline (Both Steps)",variant="primary",)run_log = gr.Textbox(label="Execution Log",lines=18,max_lines=30,interactive=False,)btn_nb1.click(run_datacreation, outputs=[run_log])btn_nb2.click(run_pythonanalysis, outputs=[run_log])btn_all.click(run_full_pipeline, outputs=[run_log])# ===========================================================# TAB 2 -- Results Gallery# ===========================================================with gr.Tab("Results Gallery"):kpi_html = gr.HTML(value=render_kpi_cards)gr.Markdown("After running the pipeline, click **Refresh** to load all figures and tables.")refresh_btn = gr.Button("Refresh Gallery", variant="primary")gr.Markdown("#### Figures")gallery = gr.Gallery(label="Generated Figures",columns=2,height=480,object_fit="contain",)gr.Markdown("#### Tables")table_dropdown = gr.Dropdown(label="Select a table to view",choices=[],interactive=True,)table_display = gr.Dataframe(label="Table Preview",interactive=False,)refresh_btn.click(refresh_gallery,outputs=[gallery, table_dropdown, table_display, kpi_html],)table_dropdown.change(on_table_select,inputs=[table_dropdown],outputs=[table_display],)# ===========================================================# TAB 3 -- Interactive Charts# ===========================================================with gr.Tab("Interactive Charts"):gr.Markdown("### Live interactive charts built from your pipeline data\n\n""These charts are generated from the CSV artifacts. ""Click **Refresh Charts** after running the pipeline.")refresh_charts_btn = gr.Button("Refresh Charts", variant="primary")chart_sales = gr.Plot(label="Monthly Overview", value=build_sales_chart)chart_sentiment = gr.Plot(label="Sentiment Distribution", value=build_sentiment_chart)chart_top = gr.Plot(label="Top Sellers", value=build_top_sellers_chart)refresh_charts_btn.click(refresh_charts,outputs=[chart_sales, chart_sentiment, chart_top],)# ===========================================================# TAB 4 -- AI Dashboard# ===========================================================with gr.Tab('"AI" Dashboard'):gr.Markdown("### Ask questions, get visualisations\n\n""Describe what you want to see and the AI will pick the right chart or table. "+ ("*LLM is active.*"if LLM_ENABLEDelse "*No API key detected \u2014 using keyword matching. ""Set `HF_API_KEY` in Space secrets for full LLM support.*"))with gr.Row(equal_height=True):with gr.Column(scale=1):chatbot = gr.Chatbot(label="Conversation",height=380,)user_input = gr.Textbox(label="Ask about your data",placeholder="e.g. Show me sales trends / What are the top sellers? / Sentiment analysis",lines=1,)gr.Examples(examples=["Show me the sales trends","What does the sentiment look like?","Which titles sell the most?","Show the ARIMA forecasts","What are the pricing decisions?","Give me a dashboard overview",],inputs=user_input,)with gr.Column(scale=1):ai_figure = gr.Image(label="Visualisation",height=350,)ai_table = gr.Dataframe(label="Data Table",interactive=False,)user_input.submit(ai_chat,inputs=[user_input, chatbot],outputs=[chatbot, user_input, ai_figure, ai_table],)demo.launch(css=load_css(), allowed_paths=[str(BASE_DIR)])
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455566 unmodified lines636465666768691 unmodified line717273747576771 unmodified line7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411 unmodified line1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522531 unmodified line2552562572582592602612 unmodified lines2642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293309 unmodified lines340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384/* ============================================================ESCP Business School β AI for Business Decision MakingGradio 5.x Custom Theme | ESCP Deep Purple + Glass Cards============================================================ *//* ---------- design tokens ---------- */:root {--escp-purple: rgb(40, 9, 109);--escp-purple-light: rgb(60, 20, 140);--escp-gold: rgb(242, 198, 55);--bg-card: rgba(255, 255, 255, 0.95);--bg-card-glass: rgba(255, 255, 255, 0.88);--lavender: #c5b4f0;--lavender-mid: #a48de8;--violet: #7c5cbf;--violet-deep: #4b2d8a;--mint: #6ee7c7;--blush: #ffb3c8;--red: #ff6b8a;--text: #2d1f4e;--text-mid: #6b5b8e;--text-muted: #9d8fc4;--font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;--font-mono: 'SF Mono', 'Cascadia Code', Consolas, 'Liberation Mono', monospace;--radius-sm: 10px;--radius-md: 16px;--radius-lg: 20px;--radius-pill: 50px;--shadow-card: 0 4px 24px rgba(0, 0, 0, 0.12);--shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.18);--transition: 0.2s ease;}/* ---------- ESCP deep purple background (extends infinitely) ---------- */html, body {background-color: var(--escp-purple) !important;margin: 0 !important;padding: 0 !important;min-height: 100vh !important;}/* Background images: top (once at top) + mid (repeats to fill all remaining space) *//* NOTE: __BG_TOP__, __BG_MID__, __BG_BOTTOM__ are replaced at runtime by app.pywith the correct Gradio file-serving paths. */gradio-app,.gradio-app,.main,#app,[data-testid="app"] {background-color: var(--escp-purple) !important;background-image:var(--bg-top),var(--bg-mid) !important;background-position:top center,0 913px !important;6 unmodified linesmin-height: 100vh !important;}/* Fixed bottom banner β stays pinned to viewport bottom */body::after {content: '' !important;position: fixed !important;1 unmodified lineleft: 0 !important;right: 0 !important;height: 130px !important;background-image: var(--bg-bottom) !important;background-size: 100% 100% !important;background-repeat: no-repeat !important;background-position: bottom center !important;1 unmodified linez-index: 9999 !important;}/* ---------- container: transparent so purple shows through ---------- */.gradio-container {max-width: 1400px !important;width: 94vw !important;margin: 0 auto !important;padding-top: 200px !important;padding-bottom: 160px !important;background: transparent !important;font-family: var(--font-sans) !important;}/* ---------- animations ---------- */@keyframes popIn {0% { opacity: 0; transform: scale(0.94) translateY(10px); }100% { opacity: 1; transform: scale(1) translateY(0); }}@keyframes shimmerSlide {0% { background-position: -200% center; }100% { background-position: 200% center; }}/* ---------- title: ESCP gold ---------- */#escp_title h1,.gradio-container > .main > div:first-child h1 {color: var(--escp-gold) !important;font-size: 2.8rem !important;font-weight: 800 !important;text-align: center !important;margin: 0 0 8px 0 !important;text-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);}/* subtitle / italic text */#escp_title p, #escp_title em,.gradio-container > .main > div:first-child p,.gradio-container > .main > div:first-child em {color: rgba(255, 255, 255, 0.85) !important;text-align: center !important;}/* ---------- tab bar ---------- */.tabs > .tab-nav,.tab-nav,div[role="tablist"] {background: rgba(40, 9, 109, 0.6) !important;backdrop-filter: blur(14px) !important;-webkit-backdrop-filter: blur(14px) !important;border-radius: var(--radius-sm) var(--radius-sm) 0 0 !important;padding: 4px !important;gap: 2px !important;border: none !important;}.tabs > .tab-nav > button,.tab-nav button,button[role="tab"] {color: #ffffff !important;font-weight: 600 !important;border: none !important;1 unmodified linepadding: 10px 20px !important;border-radius: 8px 8px 0 0 !important;opacity: 1 !important;font-family: var(--font-sans) !important;font-size: 0.9rem !important;transition: all var(--transition) !important;}.tabs > .tab-nav > button.selected,.tab-nav button.selected,button[role="tab"][aria-selected="true"] {color: var(--escp-gold) !important;background: rgba(255, 255, 255, 0.12) !important;}.tabs > .tab-nav > button:hover:not(.selected),.tab-nav button:hover:not(.selected) {background: rgba(255, 255, 255, 0.08) !important;}/* ---------- tab content area (white cards on purple) ---------- */.tabitem, .gradio-tabitem {background: var(--bg-card) !important;border-radius: 0 0 var(--radius-sm) var(--radius-sm) !important;padding: 20px !important;animation: popIn 0.35s ease both;border: none !important;box-shadow: none !important;}/* ---------- white card panels inside tabs ---------- */.gradio-container .gr-block,.gradio-container .gr-box,.gradio-container .gr-panel,.gradio-container .gr-group {background: #ffffff !important;border-radius: var(--radius-sm) !important;}/* ---------- buttons: primary (ESCP purple) ---------- */.primary, button.primary,.gr-button-primary, .gr-button.primary {background-color: var(--escp-purple) !important;color: #ffffff !important;border: none !important;border-radius: var(--radius-sm) !important;padding: 10px 20px !important;font-weight: 600 !important;box-shadow: 0 3px 12px rgba(40, 9, 109, 0.3) !important;transition: all var(--transition) !important;}.primary:hover, button.primary:hover {background-color: var(--escp-purple-light) !important;transform: translateY(-1px) !important;box-shadow: 0 5px 18px rgba(40, 9, 109, 0.4) !important;}/* ---------- buttons: secondary ---------- */.secondary, button.secondary,.gr-button-secondary, .gr-button.secondary {background-color: #ffffff !important;color: var(--escp-purple) !important;border: 2px solid var(--escp-purple) !important;border-radius: var(--radius-sm) !important;padding: 10px 20px !important;font-weight: 600 !important;transition: all var(--transition) !important;}.secondary:hover, button.secondary:hover {background-color: rgb(240, 238, 250) !important;transform: translateY(-1px) !important;}/* ---------- inputs / textareas ---------- */.gradio-container input,.gradio-container textarea,.gradio-container select {background: #ffffff !important;border: 1px solid #d1d5db !important;border-radius: 8px !important;font-family: var(--font-sans) !important;color: var(--text) !important;transition: all var(--transition) !important;}.gradio-container input:focus,.gradio-container textarea:focus,.gradio-container select:focus {outline: none !important;border-color: var(--lavender-mid) !important;box-shadow: 0 0 0 3px rgba(164, 141, 232, 0.25) !important;}/* ---------- pipeline log (dark terminal) ---------- */#log-box textarea {background: #1a0e2e !important;color: var(--lavender) !important;font-family: var(--font-mono) !important;font-size: 0.82rem !important;line-height: 1.7 !important;border-radius: var(--radius-md) !important;border: 1px solid rgba(197, 180, 240, 0.2) !important;box-shadow: inset 0 2px 12px rgba(0, 0, 0, 0.2) !important;}/* ---------- chatbot ---------- */.gr-chatbot {min-height: 380px !important;background-color: #ffffff !important;1 unmodified line}.gr-chatbot .message.user {background-color: rgb(232, 225, 250) !important;border-radius: 12px !important;}2 unmodified linesborder-radius: 12px !important;}/* ---------- headings inside tabs ---------- */.tabitem h3, .gradio-tabitem h3 {color: var(--escp-purple) !important;font-weight: 700 !important;}.tabitem h4, .gradio-tabitem h4 {color: #374151 !important;}/* ---------- gallery ---------- */.gallery {background: #ffffff !important;border-radius: var(--radius-sm) !important;}/* ---------- dataframe / table ---------- */[data-testid="dataframe"] {background-color: #ffffff !important;border-radius: var(--radius-sm) !important;}table {font-size: 0.85rem !important;}/* ---------- example prompts ---------- */.examples-row button {background: rgb(240, 238, 250) !important;color: var(--escp-purple) !important;border: 1px solid var(--escp-purple) !important;border-radius: 8px !important;font-size: 0.85rem !important;}.examples-row button:hover {background: rgb(232, 225, 250) !important;}/* ---------- scrollbars ---------- */* {scrollbar-width: thin;scrollbar-color: var(--lavender) transparent;}::-webkit-scrollbar { width: 6px; height: 6px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb {background: linear-gradient(180deg, var(--lavender), var(--mint));border-radius: 3px;}/* ---------- plotly charts ---------- */.js-plotly-plot .plot-container,.js-plotly-plot .main-svg,.js-plotly-plot .bg {fill: transparent !important;background: transparent !important;}/* ---------- header / footer: transparent ---------- */header, header *,footer, footer * {background: transparent !important;9 unmodified linessection footer,section footer button,section footer a,section footer button *,section footer a * {background: transparent !important;background-color: transparent !important;box-shadow: none !important;border: none !important;color: white !important;}/* ---------- responsive ---------- */@media (max-width: 768px) {.gradio-container {padding-top: 120px !important;padding-bottom: 160px !important;width: 98vw !important;}.tabs > .tab-nav > button,.tab-nav button {padding: 8px 14px !important;font-size: 0.82rem !important;}}@media (max-width: 480px) {.gradio-container {padding-top: 80px !important;}#escp_title h1,.gradio-container > .main > div:first-child h1 {font-size: 1.8rem !important;}}/* ---------- smooth transitions ---------- */button, a, input, textarea, select {transition-property: background, border-color, box-shadow, color, opacity, transform;transition-duration: 0.2s;transition-timing-function: ease;}12345678910111213146 unmodified lines212223242526272829303132331 unmodified line353637383940411 unmodified line43444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788891 unmodified line9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771 unmodified line1791801811821831841852 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282299 unmodified lines239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292/* ββ ESCP Background: top (once) + mid (repeats) + bottom (fixed) ββ */gradio-app,.gradio-app,.main,#app,[data-testid="app"] {background-color: rgb(40,9,109) !important;background-image:url('file=background_top.png'),url('file=background_mid.png') !important;background-position:top center,0 913px !important;6 unmodified linesmin-height: 100vh !important;}html, body {background-color: rgb(40,9,109) !important;margin: 0 !important;padding: 0 !important;min-height: 100vh !important;}body::after {content: '' !important;position: fixed !important;1 unmodified lineleft: 0 !important;right: 0 !important;height: 130px !important;background-image: url('file=background_bottom.png') !important;background-size: 100% 100% !important;background-repeat: no-repeat !important;background-position: bottom center !important;1 unmodified linez-index: 9999 !important;}/* ββ Container ββ */.gradio-container {max-width: 1400px !important;width: 94vw !important;margin: 0 auto !important;padding-top: 220px !important;padding-bottom: 150px !important;background: transparent !important;}/* ββ Title: ESCP gold ββ */#escp_title h1 {color: rgb(242,198,55) !important;font-size: 3rem !important;font-weight: 800 !important;text-align: center !important;margin: 0 0 12px 0 !important;}#escp_title p, #escp_title em {color: rgba(255,255,255,0.85) !important;text-align: center !important;}/* ββ Tab bar ββ */.tabs > .tab-nav,.tab-nav,div[role="tablist"],.svelte-tabs > .tab-nav {background: rgba(40,9,109,0.6) !important;border-radius: 10px 10px 0 0 !important;padding: 4px !important;}.tabs > .tab-nav button,.tab-nav button,div[role="tablist"] button,button[role="tab"],.svelte-tabs button,.tab-nav > button,.tabs button {color: #ffffff !important;font-weight: 600 !important;border: none !important;1 unmodified linepadding: 10px 20px !important;border-radius: 8px 8px 0 0 !important;opacity: 1 !important;}.tabs > .tab-nav button.selected,.tab-nav button.selected,button[role="tab"][aria-selected="true"],button[role="tab"].selected,div[role="tablist"] button[aria-selected="true"],.svelte-tabs button.selected {color: rgb(242,198,55) !important;background: rgba(255,255,255,0.12) !important;}.tabs > .tab-nav button:not(.selected),.tab-nav button:not(.selected),button[role="tab"][aria-selected="false"],button[role="tab"]:not(.selected),div[role="tablist"] button:not([aria-selected="true"]) {color: #ffffff !important;opacity: 1 !important;}/* ββ White card panels ββ */.gradio-container .gr-block,.gradio-container .gr-box,.gradio-container .gr-panel,.gradio-container .gr-group {background: #ffffff !important;border-radius: 10px !important;}.tabitem {background: rgba(255,255,255,0.95) !important;border-radius: 0 0 10px 10px !important;padding: 16px !important;}/* ββ Inputs ββ */.gradio-container input,.gradio-container textarea,.gradio-container select {background: #ffffff !important;border: 1px solid #d1d5db !important;border-radius: 8px !important;}/* ββ Buttons ββ */.gradio-container button:not([role="tab"]) {font-weight: 600 !important;padding: 10px 16px !important;border-radius: 10px !important;}button.primary {background-color: rgb(40,9,109) !important;color: #ffffff !important;border: none !important;}button.primary:hover {background-color: rgb(60,20,140) !important;}button.secondary {background-color: #ffffff !important;color: rgb(40,9,109) !important;border: 2px solid rgb(40,9,109) !important;}button.secondary:hover {background-color: rgb(240,238,250) !important;}/* ββ Dataframes ββ */[data-testid="dataframe"] {background-color: #ffffff !important;border-radius: 10px !important;}table { font-size: 0.85rem !important; }/* ββ Chatbot ββ */.gr-chatbot {min-height: 380px !important;background-color: #ffffff !important;1 unmodified line}.gr-chatbot .message.user {background-color: rgb(232,225,250) !important;border-radius: 12px !important;}2 unmodified linesborder-radius: 12px !important;}/* ββ Gallery ββ */.gallery {background: #ffffff !important;border-radius: 10px !important;}/* ββ Log textbox ββ */textarea {font-family: monospace !important;font-size: 0.8rem !important;}/* ββ Headings inside tabs ββ */.tabitem h3 {color: rgb(40,9,109) !important;font-weight: 700 !important;}.tabitem h4 {color: #374151 !important;}/* ββ Examples row ββ */.examples-row button {background: rgb(240,238,250) !important;color: rgb(40,9,109) !important;border: 1px solid rgb(40,9,109) !important;border-radius: 8px !important;font-size: 0.85rem !important;}.examples-row button:hover {background: rgb(232,225,250) !important;}/* ββ Header / footer: transparent ββ */header, header *,footer, footer * {background: transparent !important;9 unmodified linessection footer,section footer button,section footer a {background: transparent !important;background-color: transparent !important;border: none !important;box-shadow: none !important;color: white !important;}section footer button *,section footer a * {background: transparent !important;background-color: transparent !important;box-shadow: none !important;}section footer button::before,section footer button::after {background: transparent !important;background-color: transparent !important;background-image: none !important;box-shadow: none !important;filter: none !important;}.gradio-container footer button,.gradio-container footer button *,.gradio-container .footer button,.gradio-container .footer button * {background: transparent !important;background-color: transparent !important;background-image: none !important;box-shadow: none !important;}.gradio-container footer button::before,.gradio-container footer button::after,.gradio-container .footer button::before,.gradio-container .footer button::after {background: transparent !important;background-color: transparent !important;background-image: none !important;box-shadow: none !important;}/* ββ Responsive ββ */@media (max-width: 768px) {.gradio-container {padding-top: 120px !important;width: 98vw !important;}}
app.py+662-499
style.css+146-238