"""FastAPI backend for the World Cup 2026 prediction platform. Serves everything from the SQLite store populated by services/model/pipeline.py, plus on-the-fly match predictions from the saved Dixon-Coles model.""" from __future__ import annotations import json import sys import time import httpx from pathlib import Path # make services/model importable MODEL_DIR = Path(__file__).resolve().parents[1] / "model" sys.path.insert(0, str(MODEL_DIR)) from fastapi import FastAPI, HTTPException, Query # noqa: E402 from fastapi.middleware.cors import CORSMiddleware # noqa: E402 from pydantic import BaseModel # noqa: E402 import config # noqa: E402 from db import connect # noqa: E402 from wcmodel import WorldCupModel # noqa: E402 import bracket as B # noqa: E402 import networkx as nx # noqa: E402 app = FastAPI(title="World Cup 2026 Predictor", version="1.0") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) MODEL = WorldCupModel.load() PARAMS = MODEL.model.get_params() _cache: dict = {} # generic TTL cache: key -> {"ts": float, "data": any} def attack_defence(team: str): a = PARAMS.get(f"attack_{team}") d = PARAMS.get(f"defence_{team}") return (round(float(a), 3) if a is not None else None, round(float(d), 3) if d is not None else None) def latest_run_id(conn) -> int: r = conn.execute("SELECT id FROM model_runs ORDER BY id DESC LIMIT 1").fetchone() if not r: raise HTTPException(503, "model not built yet — run pipeline.py") return r["id"] def _rows(q, *a): with connect() as conn: return [dict(r) for r in conn.execute(q, a).fetchall()] # ------------------------------------------------------------------ meta @app.get("/api/meta") def meta(): with connect() as conn: r = conn.execute( "SELECT * FROM model_runs ORDER BY id DESC LIMIT 1").fetchone() if not r: raise HTTPException(503, "model not built yet") d = dict(r) d["notes"] = json.loads(d["notes"]) if d.get("notes") else {} return d # ----------------------------------------------------------------- teams @app.get("/api/teams") def teams(): with connect() as conn: rid = latest_run_id(conn) rows = conn.execute( """SELECT t.name,t.group_label,t.confederation,t.elo,t.fifa_rank, s.p_group_win,s.p_advance,s.p_r16,s.p_qf,s.p_sf,s.p_final,s.p_win FROM teams t LEFT JOIN simulations s ON s.team=t.name AND s.run_id=? ORDER BY s.p_win DESC""", (rid,)).fetchall() out = [] for r in rows: d = dict(r) d["attack"], d["defence"] = attack_defence(d["name"]) out.append(d) return out @app.get("/api/teams/{name}") def team_detail(name: str): with connect() as conn: rid = latest_run_id(conn) t = conn.execute( """SELECT t.*,s.p_group_win,s.p_advance,s.p_r16,s.p_qf,s.p_sf, s.p_final,s.p_win FROM teams t LEFT JOIN simulations s ON s.team=t.name AND s.run_id=? WHERE t.name=?""", (rid, name)).fetchone() if not t: raise HTTPException(404, f"unknown team {name}") d = dict(t) d["attack"], d["defence"] = attack_defence(name) # recent form (last 12 played international matches) form = conn.execute( """SELECT date,home_team,away_team,home_score,away_score,tournament,neutral FROM matches WHERE home_score IS NOT NULL AND (home_team=? OR away_team=?) ORDER BY date DESC LIMIT 12""", (name, name)).fetchall() d["recent_form"] = [_form_row(dict(r), name) for r in form] # World Cup history wc = conn.execute( """SELECT COUNT(*) n, SUM(CASE WHEN (home_team=? AND home_score>away_score) OR (away_team=? AND away_score>home_score) THEN 1 ELSE 0 END) w FROM matches WHERE tournament='FIFA World Cup' AND home_score IS NOT NULL AND (home_team=? OR away_team=?)""", (name, name, name, name)).fetchone() d["wc_history"] = {"matches": wc["n"] or 0, "wins": wc["w"] or 0} # this team's 3 group fixtures + predictions fixtures = conn.execute( """SELECT m.date,m.home_team,m.away_team,m.city,m.country,m.neutral, p.p_home,p.p_draw,p.p_away,p.exp_home,p.exp_away,p.top_scores FROM matches m LEFT JOIN predictions p ON p.home_team=m.home_team AND p.away_team=m.away_team AND p.model_run_id=? WHERE m.stage='group' AND (m.home_team=? OR m.away_team=?) ORDER BY m.date""", (rid, name, name)).fetchall() d["fixtures"] = [_fixture_row(dict(r)) for r in fixtures] d["squad"] = _load_squad(name) return d def _load_squad(team: str): """Web-verified 26-man squad from data/squads.json (or [] if not yet added).""" f = config.DATA / "squads.json" if not f.exists(): return [] try: data = json.loads(f.read_text(encoding="utf-8")) return data.get("squads", {}).get(team, []) except Exception: return [] def _form_row(r: dict, team: str) -> dict: opp = r["away_team"] if r["home_team"] == team else r["home_team"] gf = r["home_score"] if r["home_team"] == team else r["away_score"] ga = r["away_score"] if r["home_team"] == team else r["home_score"] res = "W" if gf > ga else ("D" if gf == ga else "L") return {"date": r["date"], "opponent": opp, "gf": gf, "ga": ga, "result": res, "tournament": r["tournament"]} # -------------------------------------------------------------- fixtures def _fixture_row(r: dict) -> dict: r = dict(r) if r.get("top_scores"): r["top_scores"] = json.loads(r["top_scores"]) return r @app.get("/api/fixtures") def fixtures(): with connect() as conn: rid = latest_run_id(conn) rows = conn.execute( """SELECT m.date,m.home_team,m.away_team,m.city,m.country,m.neutral, p.p_home,p.p_draw,p.p_away,p.exp_home,p.exp_away,p.top_scores, p.over25,p.btts, th.group_label FROM matches m LEFT JOIN predictions p ON p.home_team=m.home_team AND p.away_team=m.away_team AND p.model_run_id=? LEFT JOIN teams th ON th.name=m.home_team WHERE m.stage='group' ORDER BY m.date,m.id""", (rid,)).fetchall() kmap = _kickoff_map() out = [] for r in rows: d = _fixture_row(dict(r)) d["kickoff"] = kmap.get(f"{d['home_team']}__{d['away_team']}") out.append(d) return out # ---------------------------------------------------------------- groups @app.get("/api/groups") def groups(): with connect() as conn: rid = latest_run_id(conn) teams = conn.execute( """SELECT t.name,t.group_label,t.confederation,t.elo, s.p_group_win,s.p_advance,s.p_win FROM teams t LEFT JOIN simulations s ON s.team=t.name AND s.run_id=?""", (rid,)).fetchall() g: dict[str, list] = {} for r in teams: d = dict(r) d["attack"], d["defence"] = attack_defence(d["name"]) g.setdefault(d["group_label"], []).append(d) out = [] for label in sorted(g): members = sorted(g[label], key=lambda x: (x["p_advance"] or 0), reverse=True) out.append({"group": label, "teams": members}) return out # -------------------------------------------------------------- predict class PredictReq(BaseModel): home: str away: str neutral: bool = True @app.get("/api/known_teams") def known_teams(): return sorted(MODEL.teams) @app.post("/api/predict") def predict(req: PredictReq): if not MODEL.can_predict(req.home): raise HTTPException(400, f"unknown team: {req.home}") if not MODEL.can_predict(req.away): raise HTTPException(400, f"unknown team: {req.away}") if req.home == req.away: raise HTTPException(400, "pick two different teams") return MODEL.match_summary(req.home, req.away, req.neutral) # ------------------------------------------------------------- simulate @app.get("/api/simulate") def simulate(): with connect() as conn: rid = latest_run_id(conn) rows = conn.execute( "SELECT * FROM simulations WHERE run_id=? ORDER BY p_win DESC", (rid,) ).fetchall() return [dict(r) for r in rows] # -------------------------------------------------------------- bracket @app.get("/api/bracket") def bracket(): """Projected bracket using each group's most-likely winner / runner-up.""" with connect() as conn: rid = latest_run_id(conn) rows = conn.execute( "SELECT team,group_label,p_group_win,p_advance,p_win FROM simulations " "WHERE run_id=?", (rid,)).fetchall() by_group: dict[str, list] = {} for r in rows: by_group.setdefault(r["group_label"], []).append(dict(r)) winner, runner = {}, {} for gl, members in by_group.items(): order = sorted(members, key=lambda x: x["p_advance"], reverse=True) winner[gl] = sorted(members, key=lambda x: x["p_group_win"], reverse=True)[0]["team"] runner[gl] = next(m["team"] for m in order if m["team"] != winner[gl]) # best-8 thirds by p_advance among 3rd-likely teams (approx: highest p_advance # teams not already winner/runner) used = set(winner.values()) | set(runner.values()) thirds = sorted((m for ms in by_group.values() for m in ms if m["team"] not in used), key=lambda x: x["p_advance"], reverse=True)[:8] third_groups = [t["group_label"] for t in thirds] third_team = {t["group_label"]: t["team"] for t in thirds} G = nx.Graph() slots = list(B.THIRD_SLOTS) for mid in slots: for grp in third_groups: if grp in B.THIRD_SLOTS[mid]: G.add_edge(("slot", mid), ("grp", grp)) match = nx.bipartite.maximum_matching(G, top_nodes={("grp", g) for g in third_groups}) \ if third_groups else {} slot_third = {mid: match[("slot", mid)][1] for mid in slots if ("slot", mid) in match} def resolve(slot, mid): kind, val = slot if kind == "W": return winner.get(val) if kind == "RU": return runner.get(val) return third_team.get(slot_third.get(mid)) r32 = [] for mid, (sa, sb) in sorted(B.R32.items()): r32.append({"match": mid, "stage": "R32", "home": resolve(sa, mid), "away": resolve(sb, mid)}) return {"round_of_32": r32, "feed": B.FEED, "winner": winner, "runner_up": runner, "thirds": third_team} # ----------------------------------------------------------- calibration @app.get("/api/calibration") def calibration(): with connect() as conn: rid = latest_run_id(conn) run = dict(conn.execute( "SELECT * FROM model_runs WHERE id=?", (rid,)).fetchone()) run["notes"] = json.loads(run["notes"]) if run.get("notes") else {} bins = [dict(r) for r in conn.execute( "SELECT bin_lo,bin_hi,predicted,observed,count FROM calibration " "WHERE run_id=? ORDER BY bin_lo", (rid,)).fetchall()] return {"run": run, "reliability": bins} def _load_site_password() -> str: import os p = os.environ.get("SITE_PASSWORD") if p: return p.strip() f = Path(__file__).resolve().parent / "site_password.txt" if f.exists(): return f.read_text(encoding="utf-8").strip() return "" class AuthReq(BaseModel): password: str @app.get("/api/auth/required") def auth_required(): return {"required": bool(_load_site_password())} @app.post("/api/auth") def auth(req: AuthReq): pw = _load_site_password() if not pw: return {"ok": True, "required": False} return {"ok": req.password == pw, "required": True} @app.get("/api/news") def news(): """Upcoming-team news, read from data/news.json (refreshed by the daily briefing cron / WebSearch). Static file so it always serves reliably.""" f = config.DATA / "news.json" if not f.exists(): return {"updated": None, "items": []} try: return json.loads(f.read_text(encoding="utf-8")) except Exception: return {"updated": None, "items": []} @app.get("/api/health") def health(): return {"ok": True, "teams_in_model": len(MODEL.teams)} @app.post("/api/reload") def reload_model(): """重训后热加载新模型 + 清缓存(无需重启后端)。""" global MODEL, PARAMS MODEL = WorldCupModel.load() PARAMS = MODEL.model.get_params() _cache.clear() _winner_cache["data"] = None _odds_cache["data"] = None return {"ok": True, "teams_in_model": len(MODEL.teams)} # --------------------------------------------------------- live scores _live_cache: dict = {"ts": 0, "data": []} LIVE_TTL = 60 # seconds @app.get("/api/live") def live(date: str | None = None): """Live / today scores via TheSportsDB (free, no key). Cached 60s.""" import datetime d = date or datetime.date.today().isoformat() now = time.time() if _live_cache["ts"] > now - LIVE_TTL and _live_cache.get("date") == d: return _live_cache["data"] try: url = f"https://www.thesportsdb.com/api/v1/json/3/eventsday.php?d={d}&s=Soccer" resp = httpx.get(url, timeout=12) events = resp.json().get("events") or [] wc = [e for e in events if "World Cup" in (e.get("strLeague") or "")] out = [] for e in wc: out.append({ "home_team": e.get("strHomeTeam", ""), "away_team": e.get("strAwayTeam", ""), "home_score": e.get("intHomeScore"), "away_score": e.get("intAwayScore"), "status": e.get("strStatus", "NS"), # NS/FT/HT/1H/2H/ET... "time": e.get("strTime", ""), "venue": e.get("strVenue", ""), "date": d, }) _live_cache.update(ts=now, data=out, date=d) return out except Exception: return _live_cache.get("data", []) # --------------------------------------------- the-odds-api 实时赔率 def _load_odds_key() -> str: import os k = os.environ.get("ODDS_API_KEY") if k: return k.strip() f = Path(__file__).resolve().parent / "odds_key.txt" if f.exists(): return f.read_text(encoding="utf-8").strip() return "" ODDS_API_KEY = _load_odds_key() # the-odds-api 队名 -> 本库队名 ODDS_NAME_MAP = { "Bosnia & Herzegovina": "Bosnia and Herzegovina", "USA": "United States", } _odds_cache: dict = {"ts": 0, "data": None} ODDS_TTL = 3 * 3600 # 3h,省配额(免费500/月) def _devig(oh, od, oa): """De-margin three decimal odds -> normalized true probabilities.""" inv = [1 / oh, 1 / od, 1 / oa] s = sum(inv) return [x / s for x in inv] @app.get("/api/odds") def odds(refresh: bool = False): """实时胜平负赔率(the-odds-api 全球庄家) + 模型对比 + EV 价值。缓存3小时。""" now = time.time() if not refresh and _odds_cache["data"] is not None and _odds_cache["ts"] > now - ODDS_TTL: return _odds_cache["data"] if not ODDS_API_KEY: return {"available": False, "note": "未配置 the-odds-api key", "matches": [], "quota": None} try: url = (f"https://api.the-odds-api.com/v4/sports/soccer_fifa_world_cup/odds/" f"?apiKey={ODDS_API_KEY}®ions=eu&markets=h2h&oddsFormat=decimal") r = httpx.get(url, timeout=15) quota = r.headers.get("x-requests-remaining") if r.status_code != 200: return {"available": False, "note": f"赔率接口返回 {r.status_code}", "matches": [], "quota": quota} raw = r.json() except Exception as e: return {"available": False, "note": f"获取失败({type(e).__name__})", "matches": [], "quota": None} out = [] for m in raw: home = ODDS_NAME_MAP.get(m["home_team"], m["home_team"]) away = ODDS_NAME_MAP.get(m["away_team"], m["away_team"]) # collect best & average odds across bookmakers bh, bd, ba, sh, sd, sa, n = 0, 0, 0, 0.0, 0.0, 0.0, 0 for bk in m.get("bookmakers", []): mk = next((x for x in bk.get("markets", []) if x["key"] == "h2h"), None) if not mk: continue od = {o["name"]: o["price"] for o in mk["outcomes"]} oh, od_, oa = od.get(m["home_team"]), od.get("Draw"), od.get(m["away_team"]) if not (oh and od_ and oa): continue bh, bd, ba = max(bh, oh), max(bd, od_), max(ba, oa) sh += oh; sd += od_; sa += oa; n += 1 if n == 0: continue avg = (sh / n, sd / n, sa / n) imp = _devig(*avg) mp = None if MODEL.can_predict(home, away): g = MODEL.predict_grid(home, away, neutral=True) mp = [float(x) for x in g.home_draw_away] ev = None if mp: ev = [round(mp[0] * bh - 1, 4), round(mp[1] * bd - 1, 4), round(mp[2] * ba - 1, 4)] out.append({ "home_team": home, "away_team": away, "commence_time": m.get("commence_time"), "best": {"home": round(bh, 2), "draw": round(bd, 2), "away": round(ba, 2)}, "avg": {"home": round(avg[0], 2), "draw": round(avg[1], 2), "away": round(avg[2], 2)}, "implied": {"home": round(imp[0], 4), "draw": round(imp[1], 4), "away": round(imp[2], 4)}, "model": None if not mp else {"home": round(mp[0], 4), "draw": round(mp[1], 4), "away": round(mp[2], 4)}, "ev": None if not ev else {"home": ev[0], "draw": ev[1], "away": ev[2]}, "n_books": n, }) data = {"available": True, "note": f"{len(out)} 场 · the-odds-api", "matches": out, "quota": quota} _odds_cache.update(ts=now, data=data) return data # ------------------------------------------- 夺冠盘(futures) & 模型×市场融合 _winner_cache: dict = {"ts": 0, "data": None} WINNER_TTL = 6 * 3600 def _fetch_winner_market(): """De-vigged champion probabilities from the-odds-api winner market.""" now = time.time() if _winner_cache["data"] is not None and _winner_cache["ts"] > now - WINNER_TTL: return _winner_cache["data"] out = {"probs": {}, "odds": {}, "quota": None, "ok": False} if not ODDS_API_KEY: return out try: url = (f"https://api.the-odds-api.com/v4/sports/soccer_fifa_world_cup_winner/" f"odds/?apiKey={ODDS_API_KEY}®ions=eu&markets=outrights&oddsFormat=decimal") r = httpx.get(url, timeout=15) out["quota"] = r.headers.get("x-requests-remaining") data = r.json() if data and data[0].get("bookmakers"): bk = data[0]["bookmakers"][0] outs = bk["markets"][0]["outcomes"] inv = {} for o in outs: name = ODDS_NAME_MAP.get(o["name"], o["name"]) inv[name] = 1.0 / o["price"] out["odds"][name] = o["price"] s = sum(inv.values()) out["probs"] = {k: v / s for k, v in inv.items()} out["ok"] = True except Exception: pass _winner_cache.update(ts=now, data=out) return out @app.get("/api/champion") def champion(weight: float = 0.5): """综合夺冠概率 = (1-w)·模型 + w·市场,按队归一化。w 默认 0.5。""" cache_key = f"champion_{weight}" now = time.time() if _cache.get(cache_key) and _cache[cache_key]["ts"] > now - 1800: return _cache[cache_key]["data"] with connect() as conn: rid = latest_run_id(conn) rows = conn.execute( "SELECT team,group_label,p_win FROM simulations WHERE run_id=?", (rid,) ).fetchall() model = {r["team"]: r["p_win"] for r in rows} grp = {r["team"]: r["group_label"] for r in rows} mk = _fetch_winner_market() w = 0.0 if not mk["ok"] else max(0.0, min(1.0, weight)) raw = {t: (1 - w) * model[t] + w * mk["probs"].get(t, 0.0) for t in model} z = sum(raw.values()) or 1.0 out = [{ "team": t, "group": grp[t], "model": round(model[t], 4), "market": round(mk["probs"].get(t, 0.0), 4) if mk["ok"] else None, "market_odds": mk["odds"].get(t), "blended": round(raw[t] / z, 4), } for t in model] out.sort(key=lambda x: x["blended"], reverse=True) result = {"weight": w, "market_available": mk["ok"], "quota": mk["quota"], "teams": out} _cache[cache_key] = {"ts": now, "data": result} return result # ------------------------------------------------- 竞彩 odds (体彩) attempt _jc_cache: dict = {"ts": 0, "data": None} JC_TTL = 1800 # 30 min @app.get("/api/jc_odds") def jc_odds(): """Attempt to pull official China Sports Lottery (竞彩足球) win/draw/loss odds. sporttery.cn is protected by a 瑞数 dynamic anti-bot WAF that blocks server-side and headless requests, so this usually returns available=False in hosted/sandboxed environments. On a real China residential network it may succeed, in which case odds auto-fill the value page. Cached 30 min.""" now = time.time() if _jc_cache["data"] is not None and _jc_cache["ts"] > now - JC_TTL: return _jc_cache["data"] result = {"available": False, "note": "官方接口受反爬保护,未能自动获取,请手动填写赔率", "matches": []} try: url = ("https://webapi.sporttery.cn/gateway/jc/football/getMatchListV1.qry" "?poolCode=had,crs&channel=c") r = httpx.get(url, timeout=8, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36", "Referer": "https://www.sporttery.cn/", "Accept": "application/json, text/plain, */*", }) if r.headers.get("content-type", "").startswith("application/json"): data = r.json() matches = [] for mi in (data.get("value", {}).get("matchInfoList") or []): for sm in (mi.get("subMatchList") or []): had = sm.get("had") or {} matches.append({ "home_team": sm.get("homeTeamAllName") or sm.get("homeTeamAbbName"), "away_team": sm.get("awayTeamAllName") or sm.get("awayTeamAbbName"), "odds_home": _f(had.get("h")), "odds_draw": _f(had.get("d")), "odds_away": _f(had.get("a")), }) if matches: result = {"available": True, "note": "已获取官方竞彩赔率", "matches": matches} except Exception as e: result["note"] = f"自动获取失败({type(e).__name__}),请手动填写赔率" _jc_cache.update(ts=now, data=result) return result def _f(x): try: return float(x) except (TypeError, ValueError): return None # ------------------------------------------------------ live standings @app.get("/api/standings") def standings(): """Per-group live standings from played matches + advancement probabilities. Before/while group stage is incomplete, rows still rank by model p_advance.""" with connect() as conn: rid = latest_run_id(conn) played = conn.execute( "SELECT home_team,away_team,home_score,away_score FROM matches " "WHERE stage='group' AND home_score IS NOT NULL").fetchall() teaminfo = {r["name"]: dict(r) for r in conn.execute( "SELECT name,group_label,confederation,elo FROM teams").fetchall()} sims = {r["team"]: dict(r) for r in conn.execute( "SELECT team,p_group_win,p_advance,p_r16,p_win FROM simulations " "WHERE run_id=?", (rid,)).fetchall()} # init rows rows: dict[str, dict] = {} for name, info in teaminfo.items(): s = sims.get(name, {}) rows[name] = { "team": name, "group": info["group_label"], "confederation": info["confederation"], "elo": info["elo"], "played": 0, "win": 0, "draw": 0, "loss": 0, "gf": 0, "ga": 0, "gd": 0, "pts": 0, "p_group_win": s.get("p_group_win"), "p_advance": s.get("p_advance"), "p_win": s.get("p_win"), } for r in played: h, a = r["home_team"], r["away_team"] if h not in rows or a not in rows: continue hs, as_ = r["home_score"], r["away_score"] for t in (h, a): rows[t]["played"] += 1 rows[h]["gf"] += hs; rows[h]["ga"] += as_ rows[a]["gf"] += as_; rows[a]["ga"] += hs if hs > as_: rows[h]["win"] += 1; rows[h]["pts"] += 3; rows[a]["loss"] += 1 elif hs < as_: rows[a]["win"] += 1; rows[a]["pts"] += 3; rows[h]["loss"] += 1 else: rows[h]["draw"] += 1; rows[a]["draw"] += 1 rows[h]["pts"] += 1; rows[a]["pts"] += 1 for t in rows: rows[t]["gd"] = rows[t]["gf"] - rows[t]["ga"] any_played = any(r["played"] for r in rows.values()) # group into 12 tables, rank groups: dict[str, list] = {} for r in rows.values(): groups.setdefault(r["group"], []).append(r) def sort_key(x): if any_played: return (x["pts"], x["gd"], x["gf"], x["p_advance"] or 0) return (x["p_advance"] or 0,) # pre-tournament: project by model # rank thirds across groups for best-8 highlight third_rows = [] out = [] for gl in sorted(groups): members = sorted(groups[gl], key=sort_key, reverse=True) for i, m in enumerate(members): m["rank"] = i + 1 m["qualify"] = "auto" if i < 2 else ("third" if i == 2 else "out") third_rows.append(members[2]) # 3rd-placed team of this group out.append({"group": gl, "teams": members}) # best-8 thirds third_sorted = sorted( third_rows, key=lambda x: ((x["pts"], x["gd"], x["gf"]) if any_played else (x["p_advance"] or 0,)), reverse=True) best8 = {t["team"] for t in third_sorted[:8]} for grp in out: for m in grp["teams"]: if m["qualify"] == "third": m["third_in8"] = m["team"] in best8 return {"groups": out, "any_played": any_played, "thirds_race": [ {"team": t["team"], "group": t["group"], "pts": t["pts"], "gd": t["gd"], "gf": t["gf"], "p_advance": t["p_advance"], "in8": t["team"] in best8} for t in third_sorted]} # ------------------------------------------------- full schedule (group+KO) STAGE_ORDER = {"group": 0, "R32": 1, "R16": 2, "QF": 3, "SF": 4, "3rd": 5, "F": 6} STAGE_LABEL = {"group": "小组赛", "R32": "32强", "R16": "16强", "QF": "四分之一决赛", "SF": "半决赛", "3rd": "三四名", "F": "决赛"} def _compute_group_standings(): """From played group-stage matches, compute standings per group.""" with connect() as conn: played = conn.execute( "SELECT home_team,away_team,home_score,away_score FROM matches " "WHERE stage='group' AND home_score IS NOT NULL" ).fetchall() team_group = {r["name"]: r["group_label"] for r in conn.execute("SELECT name,group_label FROM teams").fetchall()} tables: dict[str, dict[str, dict]] = {} for r in played: g = team_group.get(r["home_team"]) if not g: continue for t in (r["home_team"], r["away_team"]): tables.setdefault(g, {}).setdefault(t, {"pts": 0, "gf": 0, "ga": 0, "gd": 0}) hs, as_ = r["home_score"], r["away_score"] tables[g][r["home_team"]]["gf"] += hs tables[g][r["home_team"]]["ga"] += as_ tables[g][r["away_team"]]["gf"] += as_ tables[g][r["away_team"]]["ga"] += hs if hs > as_: tables[g][r["home_team"]]["pts"] += 3 elif hs < as_: tables[g][r["away_team"]]["pts"] += 3 else: tables[g][r["home_team"]]["pts"] += 1 tables[g][r["away_team"]]["pts"] += 1 for g in tables: for t in tables[g]: tables[g][t]["gd"] = tables[g][t]["gf"] - tables[g][t]["ga"] return tables def _resolve_bracket_from_standings(standings): """Given group standings, resolve R32 teams using actual results.""" winners, runners = {}, {} all_thirds = [] for g, tbl in standings.items(): order = sorted(tbl, key=lambda t: (tbl[t]["pts"], tbl[t]["gd"], tbl[t]["gf"]), reverse=True) if len(order) >= 2: winners[g] = order[0] runners[g] = order[1] if len(order) >= 3: all_thirds.append((g, order[2], tbl[order[2]])) all_thirds.sort(key=lambda x: (x[2]["pts"], x[2]["gd"], x[2]["gf"]), reverse=True) best8 = all_thirds[:8] third_team = {g: t for g, t, _ in best8} third_groups = [g for g, _, _ in best8] G = nx.Graph() slots = list(B.THIRD_SLOTS) for mid in slots: for grp in third_groups: if grp in B.THIRD_SLOTS[mid]: G.add_edge(("slot", mid), ("grp", grp)) matching = nx.bipartite.maximum_matching(G, top_nodes={("grp", g) for g in third_groups}) \ if third_groups else {} slot_third = {mid: matching[("slot", mid)][1] for mid in slots if ("slot", mid) in matching} third_for_slot = {mid: third_team.get(slot_third.get(mid)) for mid in slots} return winners, runners, third_for_slot def _kickoff_map(): """Map '{home}__{away}' -> ISO kickoff time (UTC) from the-odds-api data.""" data = _odds_cache.get("data") if not data or not data.get("matches"): try: data = odds() except Exception: data = None m = {} if data and data.get("matches"): for x in data["matches"]: ct = x.get("commence_time") if ct: m[f"{x['home_team']}__{x['away_team']}"] = ct return m @app.get("/api/schedule") def full_schedule(): """All fixtures: group-stage (with predictions) + knockout (with on-the-fly predictions once teams are determined from real results or simulation.""" now = time.time() if _cache.get("schedule") and _cache["schedule"]["ts"] > now - 1800: return _cache["schedule"]["data"] with connect() as conn: rid = latest_run_id(conn) # group-stage fixtures gs = conn.execute( """SELECT m.date,m.home_team,m.away_team,m.city,m.country,m.neutral,m.stage, m.home_score,m.away_score, p.p_home,p.p_draw,p.p_away,p.exp_home,p.exp_away,p.top_scores, p.over25,p.btts, th.group_label FROM matches m LEFT JOIN predictions p ON p.home_team=m.home_team AND p.away_team=m.away_team AND p.model_run_id=? LEFT JOIN teams th ON th.name=m.home_team WHERE m.stage='group' ORDER BY m.date,m.id""", (rid,)).fetchall() # Round-of-32 fixtures with real dates/scores. The 16 chronologically # first knockout games are the R32; later rounds are excluded so a # mis-resolved third-place slot can't borrow a later round's date. ko_rows = conn.execute( """SELECT date,home_team,away_team,home_score,away_score FROM matches WHERE stage='knockout' ORDER BY date, id LIMIT 16""").fetchall() # lookup: "{home}__{away}" -> real R32 date/score, so resolved R32 slots can # be placed on the calendar (else the dashboard's "即将开赛" section has no # dated knockout match and falls back to the last group matchday). ko_actual = {f"{r['home_team']}__{r['away_team']}": dict(r) for r in ko_rows} kmap = _kickoff_map() out = [] for r in gs: d = _fixture_row({**dict(r), "stage_label": "小组赛"}) d["kickoff"] = kmap.get(f"{d['home_team']}__{d['away_team']}") out.append(d) # Attempt to fill knockout slots from actual standings standings = _compute_group_standings() group_complete = all( len([t for t in tbl if tbl[t]["pts"] + tbl[t]["gf"] + tbl[t]["ga"] > 0]) >= 4 and sum(1 for t in tbl for _ in range(1)) >= 4 # at least 4 teams played for tbl in standings.values() ) if len(standings) == 12 else False # Knockout teams are only shown once decided by real group results. # Before that, all knockout slots stay 待定 (no projected matchups). if group_complete: winners, runners, third_for_slot = _resolve_bracket_from_standings(standings) else: winners, runners, third_for_slot = {}, {}, {} # Build KO fixtures ko_teams: dict[int, tuple[str | None, str | None]] = {} for mid, (sa, sb) in sorted(B.R32.items()): ta = _resolve_slot(sa, mid, winners, runners, third_for_slot) tb = _resolve_slot(sb, mid, winners, runners, third_for_slot) ko_teams[mid] = (ta, tb) # Propagate through bracket ko_winners: dict[int, str | None] = {} for mid in (89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 104): a, b = B.FEED[mid] ko_teams[mid] = (ko_winners.get(a), ko_winners.get(b)) # For each KO match, add on-the-fly prediction if both teams known for mid in sorted(ko_teams): ta, tb = ko_teams[mid] stage = B.STAGE_OF.get(mid, "KO") pred_data = {} if ta and tb and MODEL.can_predict(ta, tb): s = MODEL.match_summary(ta, tb, neutral=True) pred_data = { "p_home": s["p_home"], "p_draw": s["p_draw"], "p_away": s["p_away"], "exp_home": s["exp_home"], "exp_away": s["exp_away"], "top_scores": s["top_scores"], "over25": s["over25"], "btts": s["btts"], } # Once both teams are decided, attach the real fixture date/kickoff/score. kdate = khs = kas = kickoff = None if ta and tb: act = ko_actual.get(f"{ta}__{tb}") if act: kdate, khs, kas = act["date"], act["home_score"], act["away_score"] else: act = ko_actual.get(f"{tb}__{ta}") # stored other way round if act: kdate, khs, kas = act["date"], act["away_score"], act["home_score"] kickoff = kmap.get(f"{ta}__{tb}") or kmap.get(f"{tb}__{ta}") out.append({ "date": kdate, "home_team": ta, "away_team": tb, "city": None, "country": None, "neutral": 1, "stage": stage, "stage_label": STAGE_LABEL.get(stage, stage), "match_id": mid, "home_score": khs, "away_score": kas, "group_label": None, "kickoff": kickoff, **pred_data, }) _cache["schedule"] = {"ts": time.time(), "data": out} return out @app.get("/api/ko_bracket") def ko_bracket_view(): """Round-of-32 bracket with real results + score predictions, and the R16 pairings formed by the R32 winners. Built deterministically from the real knockout fixtures in the DB (authoritative pairings/scores) laid over the official bracket template — so third-place slots and penalty-shootout advancers come from actual data, not the flaky projection matching.""" now = time.time() if _cache.get("ko_bracket") and _cache["ko_bracket"]["ts"] > now - 900: return _cache["ko_bracket"]["data"] with connect() as conn: ko = conn.execute( "SELECT date,home_team,away_team,home_score,away_score FROM matches " "WHERE stage='knockout' ORDER BY date, id").fetchall() r32_rows = [dict(r) for r in ko[:16]] # 16 chronologically-first = R32 later_rows = [dict(r) for r in ko[16:]] # R16+ scheduled so far # teams appearing in a later round have, by definition, advanced past R32 — # this resolves penalty-shootout winners that a level score can't. advanced = {t for r in later_rows for t in (r["home_team"], r["away_team"])} by_team = {} # team -> its R32 fixture row for r in r32_rows: by_team.setdefault(r["home_team"], r) by_team.setdefault(r["away_team"], r) winners, runners, _ = _resolve_bracket_from_standings(_compute_group_standings()) kmap = _kickoff_map() def _slot_team(slot): kind, val = slot if kind == "W": return winners.get(val) if kind == "RU": return runners.get(val) return None # "3": resolved from the DB row def _actual_winner(row): hs, as_ = row["home_score"], row["away_score"] if hs is None or as_ is None: return None if hs != as_: return row["home_team"] if hs > as_ else row["away_team"] # level score -> decided on penalties; use who turns up in the next round h_adv, a_adv = row["home_team"] in advanced, row["away_team"] in advanced if h_adv != a_adv: return row["home_team"] if h_adv else row["away_team"] return None r32, winner_by_mid = [], {} for mid in sorted(B.R32): sA, sB = B.R32[mid] ta, tb = _slot_team(sA), _slot_team(sB) row = by_team.get(ta) or by_team.get(tb) date = kickoff = hs = as_ = winner = pred = None played = False if row: # fill an unknown (third-place) slot from the real opponent other = row["away_team"] if row["home_team"] in (ta, tb) else row["home_team"] if ta is None: ta = other if tb is None: tb = other date = row["date"] kickoff = (kmap.get(f"{row['home_team']}__{row['away_team']}") or kmap.get(f"{row['away_team']}__{row['home_team']}")) if row["home_score"] is not None: played = True hs, as_ = ((row["home_score"], row["away_score"]) if row["home_team"] == ta else (row["away_score"], row["home_score"])) winner = _actual_winner(row) if ta and tb and MODEL.can_predict(ta, tb): s = MODEL.match_summary(ta, tb, neutral=True) top = (s.get("top_scores") or [None])[0] pred = {"p_home": s["p_home"], "p_draw": s["p_draw"], "p_away": s["p_away"], "score": [top[0], top[1]] if top else None} if winner is None and not played: # project the not-yet-played winner winner = ta if s["p_home"] >= s["p_away"] else tb winner_by_mid[mid] = winner r32.append({ "match_id": mid, "home": ta, "away": tb, "home_score": hs, "away_score": as_, "date": date, "kickoff": kickoff, "played": played, "winner": winner, "pred": pred, }) r16 = [{"match_id": mid, "feeders": list(B.FEED[mid]), "home": winner_by_mid.get(B.FEED[mid][0]), "away": winner_by_mid.get(B.FEED[mid][1])} for mid in (89, 90, 91, 92, 93, 94, 95, 96)] data = {"r32": r32, "r16": r16} _cache["ko_bracket"] = {"ts": time.time(), "data": data} return data def _get_projected_bracket(): """Helper: get bracket from simulation projections.""" with connect() as conn: rid = latest_run_id(conn) rows = conn.execute( "SELECT team,group_label,p_group_win,p_advance FROM simulations " "WHERE run_id=?", (rid,)).fetchall() by_group: dict[str, list] = {} for r in rows: by_group.setdefault(r["group_label"], []).append(dict(r)) winner, runner = {}, {} for gl, members in by_group.items(): order = sorted(members, key=lambda x: x["p_advance"], reverse=True) winner[gl] = sorted(members, key=lambda x: x["p_group_win"], reverse=True)[0]["team"] runner[gl] = next(m["team"] for m in order if m["team"] != winner[gl]) used = set(winner.values()) | set(runner.values()) thirds = sorted((m for ms in by_group.values() for m in ms if m["team"] not in used), key=lambda x: x["p_advance"], reverse=True)[:8] third_groups = [t["group_label"] for t in thirds] third_team = {t["group_label"]: t["team"] for t in thirds} G = nx.Graph() slots = list(B.THIRD_SLOTS) for mid in slots: for grp in third_groups: if grp in B.THIRD_SLOTS[mid]: G.add_edge(("slot", mid), ("grp", grp)) matching = nx.bipartite.maximum_matching(G, top_nodes={("grp", g) for g in third_groups}) \ if third_groups else {} slot_third = {mid: matching[("slot", mid)][1] for mid in slots if ("slot", mid) in matching} third_for_slot = {mid: third_team.get(slot_third.get(mid)) for mid in slots} return {"winner": winner, "runner_up": runner, "thirds": third_team, "third_for_slot": third_for_slot} def _resolve_slot(slot, mid, winners, runners, third_for_slot): kind, val = slot if kind == "W": return winners.get(val) if kind == "RU": return runners.get(val) if kind == "3": return third_for_slot.get(mid) return None