Spaces:
Sleeping
Sleeping
Download fetch_fixtures.py from AnayShukla/fpl-solver: direct link, hf CLI and curl.
- Browser
- Download file 5.95 kB
-
https://huggingface.co/spaces/AnayShukla/fpl-solver/resolve/main/fetch_fixtures.py
- Command line
-
hf download hf://spaces/AnayShukla/fpl-solver/fetch_fixtures.py
-
curl -L -o fetch_fixtures.py https://huggingface.co/spaces/AnayShukla/fpl-solver/resolve/main/fetch_fixtures.py
5.95 kB
| """Fetch the full Premier League fixture list from the official Pulselive API. | |
| Replaces the Selenium scrape of fantasy.premierleague.com/my-team, which broke | |
| because /my-team now requires a signed-in session. This hits the same public API | |
| that premierleague.com/en/matches/... calls client-side, so it needs no browser, | |
| no login and no cookies, and it returns all 380 fixtures with gameweek numbers | |
| attached rather than relying on clicking a "next matchweek" button 37 times. | |
| Team names come back in the long form already used by team_ratings_dual_speed.csv | |
| and match_data.csv ("Manchester United", "AFC Bournemouth"), so only a handful of | |
| overrides are needed — see NAME_FIXUPS. | |
| Output: fixture_list.csv with columns [GW, Home team, Away team] — the shape | |
| `HybridFootballMatchPredictor.simulate_gameweeks` expects. (Note fixture.ipynb's | |
| cell 4 named that column "Number", but it wrote to fixtures_2.csv, so its output | |
| was never the file actually consumed.) | |
| Usage: | |
| python fetch_fixtures.py # auto-detects the latest season | |
| python fetch_fixtures.py --season 2026/2027 | |
| python fetch_fixtures.py --list-seasons | |
| """ | |
| import argparse | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import pandas as pd | |
| import requests | |
| API = "https://footballapi.pulselive.com/football" | |
| HEADERS = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " | |
| "(KHTML, like Gecko) Chrome/128.0 Safari/537.36", | |
| "Origin": "https://www.premierleague.com", | |
| "Referer": "https://www.premierleague.com/", | |
| } | |
| PREMIER_LEAGUE_COMP_ID = 1 | |
| OUTPUT = Path("fixture_list.csv") | |
| # Pulselive long names -> the names used across this repo's models. | |
| # Everything not listed here passes through unchanged. | |
| NAME_FIXUPS = { | |
| "Brighton & Hove Albion": "Brighton and Hove Albion", | |
| "Bournemouth": "AFC Bournemouth", | |
| "Spurs": "Tottenham Hotspur", | |
| } | |
| def _get(session: requests.Session, path: str, params: dict, attempts: int = 4) -> dict: | |
| last = None | |
| for i in range(attempts): | |
| try: | |
| r = session.get(f"{API}/{path}", params=params, timeout=30) | |
| r.raise_for_status() | |
| return r.json() | |
| except requests.RequestException as e: | |
| last = e | |
| if i < attempts - 1: | |
| time.sleep(2 * (i + 1)) | |
| raise RuntimeError(f"{path} failed after {attempts} attempts: {last}") | |
| def list_seasons(session: requests.Session) -> list[tuple[int, str]]: | |
| j = _get(session, f"competitions/{PREMIER_LEAGUE_COMP_ID}/compseasons", {"pageSize": 100}) | |
| return [(int(s["id"]), s["label"]) for s in j["content"]] | |
| def resolve_season(session: requests.Session, wanted: str | None) -> tuple[int, str]: | |
| seasons = list_seasons(session) | |
| if wanted is None: | |
| # compseasons comes back newest-first. | |
| return seasons[0] | |
| for sid, label in seasons: | |
| if wanted in label: | |
| return sid, label | |
| raise SystemExit(f"[err] no season matching {wanted!r}. Try --list-seasons.") | |
| def fetch_fixtures(session: requests.Session, season_id: int) -> pd.DataFrame: | |
| rows, page, num_pages = [], 0, 1 | |
| while page < num_pages: | |
| j = _get(session, "fixtures", { | |
| "comps": PREMIER_LEAGUE_COMP_ID, | |
| "compSeasons": season_id, | |
| "page": page, | |
| "pageSize": 40, | |
| "sort": "asc", | |
| "statuses": "U,L,C", # upcoming, live, completed | |
| }) | |
| num_pages = j["pageInfo"]["numPages"] | |
| for m in j["content"]: | |
| gw = m.get("gameweek", {}).get("gameweek") | |
| if gw is None: | |
| continue | |
| home, away = m["teams"][0]["team"], m["teams"][1]["team"] | |
| rows.append({ | |
| "GW": int(gw), | |
| "Home team": NAME_FIXUPS.get(home["name"], home["name"]), | |
| "Away team": NAME_FIXUPS.get(away["name"], away["name"]), | |
| }) | |
| page += 1 | |
| time.sleep(0.3) | |
| return pd.DataFrame(rows).sort_values("GW", kind="stable").reset_index(drop=True) | |
| def validate(df: pd.DataFrame) -> list[str]: | |
| """Non-fatal sanity checks — a rescheduled/postponed GW is legitimate.""" | |
| warnings = [] | |
| if len(df) != 380: | |
| warnings.append(f"expected 380 fixtures, got {len(df)}") | |
| gws = sorted(df["GW"].unique()) | |
| if gws != list(range(1, 39)): | |
| warnings.append(f"gameweeks are {gws[:3]}..{gws[-3:]} ({len(gws)} distinct), expected 1-38") | |
| odd = df["GW"].value_counts() | |
| odd = odd[odd != 10] | |
| if len(odd): | |
| warnings.append(f"gameweeks without 10 fixtures: {odd.to_dict()}") | |
| teams = set(df["Home team"]) | set(df["Away team"]) | |
| if len(teams) != 20: | |
| warnings.append(f"{len(teams)} distinct teams, expected 20") | |
| return warnings | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--season", help="season label substring, e.g. 2026/2027") | |
| ap.add_argument("--list-seasons", action="store_true") | |
| ap.add_argument("--out", default=str(OUTPUT)) | |
| args = ap.parse_args() | |
| session = requests.Session() | |
| session.headers.update(HEADERS) | |
| if args.list_seasons: | |
| for sid, label in list_seasons(session): | |
| print(f" {sid:>5} {label}") | |
| return | |
| season_id, label = resolve_season(session, args.season) | |
| print(f"[season] {label} (id {season_id})") | |
| df = fetch_fixtures(session, season_id) | |
| print(f"[fetched] {len(df)} fixtures across GW{df['GW'].min()}-{df['GW'].max()}") | |
| teams = sorted(set(df["Home team"]) | set(df["Away team"])) | |
| print(f"[teams] {len(teams)}: {', '.join(teams)}") | |
| for w in validate(df): | |
| print(f"[warn] {w}") | |
| out = Path(args.out) | |
| if out.exists(): | |
| backup = out.with_suffix(f".csv.bak_{time.strftime('%Y%m%d_%H%M%S')}") | |
| out.replace(backup) | |
| print(f"[backup] {backup.name}") | |
| df.to_csv(out, index=False) | |
| print(f"[wrote] {out}") | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |