Spaces:
Sleeping
Sleeping
| from __future__ import annotations | |
| import pandas as pd | |
| import gradio as gr | |
| import plotly.express as px | |
| from data import read_events, aggregate | |
| from bandit import EmpiricalBayesHierarchicalThompson | |
| from causal import fit_uplift_binary | |
| BANDIT = EmpiricalBayesHierarchicalThompson(min_explore=0.05, margin=0.0, n_draws=10000) | |
| def ui_refresh_tables(): | |
| df = read_events() | |
| agg = aggregate() | |
| return df, agg | |
| def ui_recommend(): | |
| agg = aggregate() | |
| if agg.empty: | |
| return {"message": "No data yet. Upload or POST /api/ingest first."} | |
| rec = BANDIT.recommend(agg) | |
| return rec | |
| def ui_plot_posteriors(medium: str): | |
| agg = aggregate() | |
| if agg.empty: | |
| return gr.update(visible=False), "No data" | |
| g = agg[agg["medium"].astype(str) == str(medium)].copy() | |
| if g.empty: | |
| return gr.update(visible=False), f"No data for medium={medium}" | |
| # 事後平均の棒グラフ(Laplace 平滑 CTR) | |
| g["ctr"] = (g["clicks"] + 1) / (g["impressions"] + 2) | |
| fig = px.bar(g, x="creative", y="ctr", color="is_control", barmode="group", title=f"CTR (Laplace) by creative @ {medium}") | |
| return gr.Plot(fig), "" | |
| def ui_fit_uplift(): | |
| agg = aggregate() | |
| if agg.empty: | |
| return {"message": "No data"} | |
| res = fit_uplift_binary(agg) | |
| return res | |
| def build_ui(): | |
| with gr.Blocks(title="AdCopy MAB Optimizer Pro") as demo: | |
| gr.Markdown("# AdCopy MAB Optimizer Pro — Hierarchical TS + Uplift") | |
| with gr.Tab("Data"): | |
| btn = gr.Button("Refresh") | |
| grid = gr.Dataframe(headers=["ts","date","medium","creative","is_control","impressions","clicks","conversions","cost","features_json"], wrap=True) | |
| grid_agg = gr.Dataframe() | |
| btn.click(ui_refresh_tables, outputs=[grid, grid_agg]) | |
| with gr.Tab("Bandit"): | |
| bbtn = gr.Button("Suggest Allocation (TS)") | |
| jout = gr.JSON() | |
| bbtn.click(ui_recommend, outputs=jout) | |
| with gr.Row(): | |
| medium = gr.Textbox(label="Medium for Plot", value="FB") | |
| plot = gr.Plot(visible=False) | |
| msg = gr.Markdown() | |
| plot_btn = gr.Button("Plot CTR by Creative") | |
| plot_btn.click(ui_plot_posteriors, inputs=[medium], outputs=[plot, msg]) | |
| with gr.Tab("Uplift (Causal)"): | |
| cbtn = gr.Button("Fit Uplift Model") | |
| cout = gr.JSON() | |
| cbtn.click(ui_fit_uplift, outputs=cout) | |
| return demo | |