import spaces import json import math import os from pathlib import Path from typing import Any import gradio as gr import pandas as pd import plotly.graph_objects as go from huggingface_hub import HfApi, hf_hub_download DATASET_ID = "htetmyet/correct_score" LATEST_PATH = "tips/latest.json" HISTORY_PREFIX = "tips/history/" CSS = """ :root { --ink: #15203b; --muted: #64748b; --glass: rgba(255, 255, 255, 0.72); --glass-border: rgba(255, 255, 255, 0.78); } body, .gradio-container { background: radial-gradient(circle at 8% 6%, rgba(99, 102, 241, .20), transparent 30rem), radial-gradient(circle at 92% 2%, rgba(34, 211, 238, .16), transparent 28rem), radial-gradient(circle at 50% 100%, rgba(168, 85, 247, .13), transparent 34rem), linear-gradient(145deg, #eef2ff 0%, #f8fafc 48%, #ecfeff 100%) !important; color: var(--ink); } .dark .gradio-container { color: var(--body-text-color); } .gradio-container { max-width: 1480px !important; margin: 0 auto !important; } .hero-glass { position: relative; overflow: hidden; padding: 2rem 2.2rem; border-radius: 28px; border: 1px solid rgba(255,255,255,.82); background: linear-gradient(135deg, rgba(255,255,255,.84), rgba(238,242,255,.64)); box-shadow: 0 28px 80px rgba(67,56,202,.13), inset 0 1px 0 rgba(255,255,255,.95); backdrop-filter: blur(22px) saturate(145%); } .hero-glass:after { content: ""; position: absolute; width: 260px; height: 260px; right: -70px; top: -120px; border-radius: 999px; background: linear-gradient(135deg, rgba(79,70,229,.22), rgba(34,211,238,.17)); filter: blur(4px); } .eyebrow { letter-spacing: .18em; text-transform: uppercase; font-weight: 800; color: #6366f1; font-size: .72rem; } .hero-title { margin: .35rem 0 .55rem; font-size: clamp(2rem, 5vw, 4rem); line-height: .98; letter-spacing: -.055em; color: #111b3a; } .hero-copy { max-width: 790px; margin: 0; color: #526078; font-size: 1rem; line-height: 1.7; } .live-pill { display: inline-flex; align-items: center; gap: .5rem; margin-top: 1rem; padding: .45rem .8rem; border-radius: 999px; background: rgba(16,185,129,.10); color: #047857; font-weight: 700; font-size: .78rem; } .live-dot { width: 8px; height: 8px; border-radius: 999px; background: #10b981; box-shadow: 0 0 0 5px rgba(16,185,129,.12); } .glass-panel { border-color: rgba(255,255,255,.76) !important; background: rgba(255,255,255,.69) !important; box-shadow: 0 18px 50px rgba(30,41,59,.075), inset 0 1px 0 rgba(255,255,255,.88) !important; backdrop-filter: blur(18px) saturate(135%); } .filter-panel { position: relative; z-index: 20; overflow: visible !important; padding: 1rem !important; } .filter-help { color:#64748b; font-size:.78rem; margin:.2rem 0 .7rem; } .tab-nav { margin-top:.35rem; } .kpi-grid { display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:12px; margin: 6px 0 10px; } .kpi { padding: 1rem; border-radius: 20px; background:rgba(255,255,255,.72); border:1px solid rgba(255,255,255,.86); box-shadow:0 12px 30px rgba(51,65,85,.07); } .kpi-label { color:#718096; font-size:.68rem; letter-spacing:.09em; text-transform:uppercase; font-weight:800; } .kpi-value { margin-top:.35rem; color:#17203b; font-size:1.6rem; letter-spacing:-.04em; font-weight:850; } .kpi-sub { margin-top:.22rem; color:#94a3b8; font-size:.68rem; } .section-note { color:#64748b; font-size:.82rem; } .gr-button-primary { box-shadow: 0 12px 30px rgba(79,70,229,.24) !important; } footer { display:none !important; } @media (max-width: 1100px) { .kpi-grid { grid-template-columns:repeat(3,minmax(0,1fr)); } } @media (max-width: 640px) { .kpi-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } .hero-glass { padding:1.4rem; border-radius:22px; } } """ def _token() -> str: token = os.environ.get("HF_TOKEN", "").strip() if not token: raise RuntimeError("HF_TOKEN Space secret is not configured.") return token def _read_json(path: str, force_download: bool = False) -> dict[str, Any]: local_path = hf_hub_download( repo_id=DATASET_ID, filename=path, repo_type="dataset", token=_token(), force_download=force_download, ) with Path(local_path).open("r", encoding="utf-8") as handle: payload = json.load(handle) if not isinstance(payload, dict) or not isinstance(payload.get("items"), list): raise ValueError(f"{path} is not a valid tips snapshot") return payload def _history_paths() -> list[str]: files = HfApi(token=_token()).list_repo_files(DATASET_ID, repo_type="dataset") return sorted( path for path in files if path.startswith(HISTORY_PREFIX) and path.endswith(".json") ) def _to_float(value: Any) -> float | None: try: parsed = float(value) return parsed if math.isfinite(parsed) else None except (TypeError, ValueError): return None def _prepare(items: list[dict[str, Any]]) -> pd.DataFrame: records: list[dict[str, Any]] = [] for item in items: odds = _to_float(item.get("odds")) status = str(item.get("evaluationStatus") or "pending").strip().lower() evaluated = status in {"win", "loss"} won = status == "win" if evaluated else None records.append({ "ID": str(item.get("id") or ""), "Snapshot": str(item.get("_snapshot") or ""), "Date": str(item.get("date") or ""), "League": str(item.get("div") or "Unknown"), "Team": str(item.get("team") or ""), "Opponent": str(item.get("opponent") or ""), "Actual Result": str(item.get("actualResult") or "Pending"), "Tip": str(item.get("tips") or "Unspecified"), "Status": status.title(), "Evaluated": evaluated, "Tip Win": won, "Odds": odds, "Unit P/L": (odds - 1.0 if won else -1.0) if evaluated and odds and odds > 1 else None, }) return pd.DataFrame.from_records(records) def _load(scope: str, history_count: int, force_download: bool = False) -> tuple[pd.DataFrame, int, str]: latest = _read_json(LATEST_PATH, force_download=force_download) updated_at = str(latest.get("updated_at") or "Unknown") if scope == "Latest snapshot": items = [dict(item, _snapshot="Latest") for item in latest["items"]] snapshot_count = 1 else: paths = _history_paths()[-max(1, int(history_count)):] snapshot_count = len(paths) all_items: list[dict[str, Any]] = [] for path in paths: payload = _read_json(path, force_download=force_download) label = Path(path).stem all_items.extend(dict(item, _snapshot=label) for item in payload["items"]) # Snapshots can contain the same selected tip repeatedly. Keep its newest # version so aggregate metrics never double-count the same saved tip. deduped: dict[str, dict[str, Any]] = {} for item in all_items: key = str(item.get("id") or f"{item.get('sourceFileId')}:{item.get('team')}:{item.get('tips')}") deduped[key] = item items = list(deduped.values()) return _prepare(items), snapshot_count, updated_at def _wilson_lower(hits: int, total: int, z: float = 1.96) -> float: if total <= 0: return 0.0 p = hits / total denominator = 1 + z * z / total centre = p + z * z / (2 * total) spread = z * math.sqrt((p * (1 - p) + z * z / (4 * total)) / total) return 100 * (centre - spread) / denominator def _reliability(hits: int, total: int) -> str: rate = hits / total if total else 0 lower = _wilson_lower(hits, total) / 100 if total >= 20 and rate >= .60 and lower >= .50: return "Supported" if total >= 10 and lower >= .45: return "Provisional" return "Watchlist" def _empty_figure(title: str) -> go.Figure: fig = go.Figure() fig.add_annotation(text="No matching evaluated rows", x=.5, y=.5, showarrow=False, font={"color": "#64748b"}) return _style_figure(fig, title) def _style_figure(fig: go.Figure, title: str) -> go.Figure: fig.update_layout( title={"text": title, "x": .02, "font": {"size": 17, "color": "#17203b"}}, paper_bgcolor="rgba(255,255,255,0)", plot_bgcolor="rgba(255,255,255,.35)", font={"family": "Inter, ui-sans-serif, system-ui", "color": "#526078"}, margin={"l": 48, "r": 20, "t": 58, "b": 42}, hoverlabel={"bgcolor": "#17203b", "font_color": "white"}, legend={"orientation": "h", "y": 1.08, "x": 1, "xanchor": "right"}, ) fig.update_xaxes(gridcolor="rgba(100,116,139,.10)", zeroline=False) fig.update_yaxes(gridcolor="rgba(100,116,139,.10)", zeroline=False) return fig def _kpis(filtered: pd.DataFrame, baseline: pd.DataFrame, snapshots: int) -> str: evaluated = filtered[filtered["Evaluated"]] hits = int(evaluated["Tip Win"].sum()) if len(evaluated) else 0 losses = len(evaluated) - hits hit_rate = 100 * hits / len(evaluated) if len(evaluated) else 0 baseline_eval = baseline[baseline["Evaluated"]] baseline_rate = 100 * float(baseline_eval["Tip Win"].mean()) if len(baseline_eval) else 0 priced = evaluated["Unit P/L"].dropna() roi = 100 * float(priced.mean()) if len(priced) else 0 lower = _wilson_lower(hits, len(evaluated)) cards = [ ("Evaluated tips", f"{len(evaluated):,}", f"{len(filtered):,} selected • {snapshots} snapshot(s)"), ("Winning tips", f"{hits:,}", "Saved evaluation: Win"), ("Losing tips", f"{losses:,}", "Saved evaluation: Loss"), ("Tip hit rate", f"{hit_rate:.1f}%", f"Baseline {baseline_rate:.1f}%"), ("95% lower bound", f"{lower:.1f}%", "Wilson confidence floor"), ("Unit-stake ROI", f"{roi:+.1f}%", f"{len(priced):,} priced evaluations"), ] return '
' + "".join( f'
{label}
{value}
{sub}
' for label, value, sub in cards ) + "
" def _league_table(frame: pd.DataFrame) -> pd.DataFrame: evaluated = frame[frame["Evaluated"]] rows = [] for league, group in evaluated.groupby("League", dropna=False): hits = int(group["Tip Win"].sum()) total = len(group) rows.append({ "League": league, "N": total, "Wins": hits, "Losses": total - hits, "Hit Rate": round(100 * hits / total, 1), "95% Lower": round(_wilson_lower(hits, total), 1), "Avg Odds": round(float(group["Odds"].mean()), 2), "ROI": round(100 * float(group["Unit P/L"].dropna().mean()), 1) if len(group["Unit P/L"].dropna()) else None, "Reliability": _reliability(hits, total), }) if not rows: return pd.DataFrame(columns=["League", "N", "Wins", "Losses", "Hit Rate", "95% Lower", "Avg Odds", "ROI", "Reliability"]) return pd.DataFrame(rows).sort_values(["N", "Hit Rate"], ascending=[False, False]) def _tip_table(frame: pd.DataFrame) -> pd.DataFrame: evaluated = frame[frame["Evaluated"]] rows = [] for tip, group in evaluated.groupby("Tip", dropna=False): hits = int(group["Tip Win"].sum()) total = len(group) rows.append({ "Tip": tip, "N": total, "Wins": hits, "Losses": total - hits, "Hit Rate": round(100 * hits / total, 1), "95% Lower": round(_wilson_lower(hits, total), 1), "Avg Odds": round(float(group["Odds"].mean()), 2), "ROI": round(100 * float(group["Unit P/L"].dropna().mean()), 1) if len(group["Unit P/L"].dropna()) else None, "Reliability": _reliability(hits, total), }) if not rows: return pd.DataFrame(columns=["Tip", "N", "Wins", "Losses", "Hit Rate", "95% Lower", "Avg Odds", "ROI", "Reliability"]) return pd.DataFrame(rows).sort_values(["N", "Hit Rate"], ascending=[False, False]).head(40) def _figures(frame: pd.DataFrame) -> tuple[go.Figure, go.Figure]: tips = _tip_table(frame).head(12).sort_values(["95% Lower", "N"], ascending=True) if tips.empty: tip_fig = _empty_figure("Tip performance and confidence") else: tip_fig = go.Figure() tip_fig.add_bar( y=tips["Tip"], x=tips["Hit Rate"], orientation="h", name="Hit rate", marker_color="#6366f1", customdata=tips[["N", "Wins", "Avg Odds", "ROI"]], hovertemplate="%{y}
Hit rate %{x:.1f}%
N %{customdata[0]}
Wins %{customdata[1]}
Avg odds %{customdata[2]}
ROI %{customdata[3]}%", ) tip_fig.add_scatter( y=tips["Tip"], x=tips["95% Lower"], mode="markers", name="95% lower bound", marker={"color": "#06b6d4", "size": 9}, ) tip_fig = _style_figure(tip_fig, "Tip performance and confidence") tip_fig.update_xaxes(title="Rate (%)", range=[0, 105]) tip_fig.update_layout(height=max(430, 34 * len(tips) + 150), margin={"l": 190, "r": 20, "t": 58, "b": 42}) evaluated = frame[frame["Evaluated"] & frame["Odds"].notna() & (frame["Odds"] > 1)].copy() if evaluated.empty: odds_fig = _empty_figure("Tip results by odds band") else: evaluated["Odds band"] = pd.cut( evaluated["Odds"], bins=[1, 1.5, 2, 3, float("inf")], labels=["1.01–1.49", "1.50–1.99", "2.00–2.99", "3.00+"], right=False, ) odds = evaluated.groupby("Odds band", observed=True).agg( N=("Tip Win", "size"), Wins=("Tip Win", "sum"), ROI=("Unit P/L", "mean") ).reset_index() odds["Hit Rate"] = 100 * odds["Wins"] / odds["N"] odds["ROI"] = 100 * odds["ROI"] odds_fig = go.Figure() odds_fig.add_bar(x=odds["Odds band"], y=odds["Hit Rate"], name="Hit rate", marker_color="#10b981", text=odds["N"].map(lambda n: f"N={n}"), textposition="outside") odds_fig.add_scatter(x=odds["Odds band"], y=odds["ROI"], name="ROI", mode="lines+markers", line={"color": "#f59e0b", "width": 3}) odds_fig = _style_figure(odds_fig, "Tip results by odds band") odds_fig.update_yaxes(title="Percent") return tip_fig, odds_fig def _insights(frame: pd.DataFrame) -> str: evaluated = frame[frame["Evaluated"]] if evaluated.empty: return "### Evidence note\n\nNo evaluated tips match the current filters." hits = int(evaluated["Tip Win"].sum()) rate = 100 * hits / len(evaluated) lower = _wilson_lower(hits, len(evaluated)) tip_table = _tip_table(evaluated) best = tip_table.sort_values(["95% Lower", "N"], ascending=False).iloc[0] if not tip_table.empty else None message = [ "### Evidence note", "", f"The selected evidence contains **{len(evaluated):,} evaluated tips** with a **{rate:.1f}% hit rate** and a **{lower:.1f}% Wilson 95% lower bound**.", ] if best is not None: message.append( f"The strongest tip by confidence floor is **{best['Tip']}** " f"({int(best['Wins'])}/{int(best['N'])}, {best['Hit Rate']:.1f}%, {best['Reliability']})." ) message.extend([ "", "> Use the confidence floor and sample size together. Historical hit rate and ROI are descriptive, not a guarantee of future profit.", ]) return "\n".join(message) def _render_dashboard( frame: pd.DataFrame, snapshots: int, updated_at: str, league: str, tip_filter: str, status: str, ) -> tuple[str, str, str, go.Figure, go.Figure, pd.DataFrame, pd.DataFrame, pd.DataFrame]: baseline = frame.copy() if league != "All leagues": frame = frame[frame["League"] == league] if tip_filter != "All tips": frame = frame[frame["Tip"] == tip_filter] if status != "All statuses": frame = frame[frame["Status"] == status] tip_fig, odds_fig = _figures(frame) explorer_columns = ["Date", "League", "Team", "Opponent", "Odds", "Tip", "Actual Result", "Status", "Unit P/L"] explorer = frame[explorer_columns].sort_values(["Date", "League"], ascending=[False, True]).reset_index(drop=True) source = f"Private source: `{DATASET_ID}` • updated `{updated_at}` • {snapshots} snapshot(s) loaded" return ( source, _kpis(frame, baseline, snapshots), _insights(frame), tip_fig, odds_fig, _tip_table(frame), _league_table(frame), explorer, ) def _error_outputs(exc: Exception) -> tuple[str, str, str, go.Figure, go.Figure, pd.DataFrame, pd.DataFrame, pd.DataFrame]: empty = pd.DataFrame() error = f"Dataset refresh failed: {type(exc).__name__}. Check the Space secret and dataset availability." return error, "", f"### Unable to load analytics\n\n{error}", _empty_figure("Unavailable"), _empty_figure("Unavailable"), empty, empty, empty def analyze( scope: str, history_count: int, league: str, tip_filter: str, status: str, refresh: bool = False, ) -> tuple[str, str, str, go.Figure, go.Figure, pd.DataFrame, pd.DataFrame, pd.DataFrame]: """Analyze and filter evaluated prediction tips from the private dataset.""" try: frame, snapshots, updated_at = _load(scope, history_count, force_download=refresh) return _render_dashboard(frame, snapshots, updated_at, league, tip_filter, status) except Exception as exc: # noqa: BLE001 - keep the public app alive with a safe error return _error_outputs(exc) def _dashboard_with_options( scope: str, history_count: int, league: str, tip_filter: str, status: str, force_download: bool, ) -> tuple[Any, ...]: try: frame, snapshots, updated_at = _load(scope, history_count, force_download=force_download) leagues = ["All leagues"] + sorted(frame["League"].dropna().unique().tolist()) tips = ["All tips"] + sorted(frame["Tip"].dropna().unique().tolist()) selected_league = league if league in leagues else "All leagues" selected_tip = tip_filter if tip_filter in tips else "All tips" dashboard = _render_dashboard(frame, snapshots, updated_at, selected_league, selected_tip, status) return ( gr.Dropdown(choices=leagues, value=selected_league), gr.Dropdown(choices=tips, value=selected_tip), *dashboard, ) except Exception as exc: # noqa: BLE001 - preserve usable controls on load failure return ( gr.Dropdown(value=league), gr.Dropdown(value=tip_filter), *_error_outputs(exc), ) def load_dashboard( scope: str, history_count: int, league: str, tip_filter: str, status: str, ) -> tuple[Any, ...]: """Load current dataset analytics and refresh available filter choices.""" return _dashboard_with_options(scope, history_count, league, tip_filter, status, False) def refresh_analytics( scope: str, history_count: int, league: str, tip_filter: str, status: str, ) -> tuple[Any, ...]: """Refresh the private dataset and return filtered prediction-tip analytics. Args: scope: latest snapshot or recent historical snapshots. history_count: number of recent snapshots to include. league: league filter, or All leagues. tip_filter: saved tip filter, or All tips. status: evaluation-status filter, or All statuses. """ return _dashboard_with_options(scope, history_count, league, tip_filter, status, True) def reset_dashboard() -> tuple[Any, ...]: """Reset all dashboard filters and return the latest tip analytics.""" defaults = ("Latest snapshot", 10, "All leagues", "All tips", "All statuses") league_update, tip_update, *dashboard = load_dashboard(*defaults) return (defaults[0], defaults[1], league_update, tip_update, defaults[4], *dashboard) @spaces.GPU(duration=1) def runtime_probe() -> str: """ZeroGPU compatibility probe used only by the hosting runtime.""" return "ready" try: initial_frame, _, _ = _load("Recent snapshots", 50) league_choices = ["All leagues"] + sorted(initial_frame["League"].dropna().unique().tolist()) tip_choices = ["All tips"] + sorted(initial_frame["Tip"].dropna().unique().tolist()) except Exception: league_choices = ["All leagues"] tip_choices = ["All tips"] initial = analyze("Latest snapshot", 10, "All leagues", "All tips", "All statuses") theme = gr.themes.Citrus( primary_hue="indigo", secondary_hue="cyan", neutral_hue="slate", font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui"], ) with gr.Blocks(theme=theme, css=CSS, title="Correct Score Tip Analytics") as demo: gr.HTML("""
Predictr.AI

Tip analytics,
with an evidence lens.

Evaluate saved football tips through their recorded win/loss outcomes and decimal odds. Compare markets, leagues, confidence floors and unit-stake returns without mixing tip performance with model score accuracy.

Live private-dataset connection
""") with gr.Group(elem_classes=["glass-panel", "filter-panel"]): gr.Markdown("### Filter tip evidence\nChoose the evidence window and filters, then select **Apply filters**. Use **Refresh dataset** only when new data has been published.") with gr.Row(): scope = gr.Dropdown(["Latest snapshot", "Recent snapshots"], value="Latest snapshot", label="Evidence window", info="Latest is recommended for current performance", scale=2) history_count = gr.Slider(1, 50, value=10, step=1, label="History snapshots", info="Used only with Recent snapshots", scale=2) with gr.Row(): league = gr.Dropdown(league_choices, value="All leagues", label="League", filterable=True, scale=2) tip_filter = gr.Dropdown(tip_choices, value="All tips", label="Tip", filterable=True, scale=3) status = gr.Dropdown(["All statuses", "Win", "Loss", "Pending"], value="All statuses", label="Result", scale=2) with gr.Row(): apply_button = gr.Button("Apply filters", variant="primary") reset_button = gr.Button("Reset") refresh = gr.Button("Refresh dataset") source_status = gr.Markdown(initial[0], elem_classes=["section-note"]) summary = gr.HTML(initial[1]) insights = gr.Markdown(initial[2], elem_classes=["glass-panel"]) with gr.Tabs(elem_classes=["tab-nav"]): with gr.Tab("Overview"): with gr.Row(): tip_plot = gr.Plot(initial[3], elem_classes=["glass-panel"]) odds_plot = gr.Plot(initial[4], elem_classes=["glass-panel"]) with gr.Tab("Tip evidence"): gr.Markdown("Hit rate uses only saved **Win/Loss** evaluations. **95% Lower** is the Wilson confidence floor. ROI assumes one unit staked at the saved decimal odds.") tip_table = gr.Dataframe(initial[5], interactive=False, wrap=True, elem_classes=["glass-panel"]) with gr.Tab("League evidence"): gr.Markdown("Compare tip results by league. Small groups remain Watchlist regardless of a high raw percentage.") league_table = gr.Dataframe(initial[6], interactive=False, wrap=True, elem_classes=["glass-panel"]) with gr.Tab("Fixture explorer"): gr.Markdown("A clean tip-evaluation view. Model prediction, PROB MAX, lambda features, dataset IDs and internal notes are intentionally excluded.") explorer = gr.Dataframe(initial[7], interactive=False, wrap=True, elem_classes=["glass-panel"]) with gr.Tab("How metrics work"): gr.Markdown(""" ### Tip-first evaluation - **Hit rate** = saved Win evaluations ÷ all saved Win/Loss evaluations. - **95% lower bound** = conservative Wilson confidence floor for the hit rate. - **Unit P/L** = `odds - 1` for a win and `-1` for a loss. - **ROI** = average Unit P/L across records with valid decimal odds. - Pending tips are visible in Fixture Explorer but excluded from evaluated metrics. Odds affect ROI, not whether a tip is classified as a win. The dashboard trusts the dataset's saved evaluation status. """) outputs = [source_status, summary, insights, tip_plot, odds_plot, tip_table, league_table, explorer] filters = [scope, history_count, league, tip_filter, status] synchronized_outputs = [league, tip_filter, *outputs] demo.load( fn=load_dashboard, inputs=filters, outputs=synchronized_outputs, api_name=False, show_progress="minimal", ) apply_button.click( fn=load_dashboard, inputs=filters, outputs=synchronized_outputs, api_name=False, show_progress="minimal", ) refresh.click( fn=refresh_analytics, inputs=filters, outputs=synchronized_outputs, api_name="refresh_analytics", show_progress="full", ) reset_button.click( fn=reset_dashboard, outputs=[*filters, *outputs], api_name=False, ) # Bound but hidden: ZeroGPU requires a registered decorated handler even # though this analytics workload never requests GPU compute. probe_button = gr.Button("Runtime probe", visible=False) probe_output = gr.Textbox(visible=False) probe_button.click(runtime_probe, outputs=probe_output, api_name=False) gr.Markdown("

Historical analytics only • Not betting advice • Private source credentials remain server-side

") if __name__ == "__main__": demo.launch(mcp_server=True)