#!/usr/bin/env python3 """Reproduce los agregados de Fútbol con IA 365 con Python 3.8+. Ejecutar: python3 reproducir.py --salida ./resultados Los 20 ficheros fuente se descargan de una revisión fija de OpenFootball (CC0). No requiere bibliotecas externas ni credenciales. """ import argparse import csv import hashlib import itertools import json from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor from pathlib import Path from urllib.request import urlopen REPO = "https://github.com/openfootball/football.json" REVISION = "e6744429ee395bc86f247348c6184bb08d4eb361" RAW = f"https://raw.githubusercontent.com/openfootball/football.json/{REVISION}" LEAGUES = { "es": ("LaLiga", 20), "en": ("Premier League", 20), "it": ("Serie A", 20), "de": ("Bundesliga", 18), } SEASONS = ("2019-20", "2020-21", "2021-22", "2022-23", "2023-24") MEASURES = ("matches", "home_wins", "draws", "away_wins") def summarize(season_league): season, league_code = season_league league, expected_clubs = LEAGUES[league_code] source_url = f"{RAW}/{season}/{league_code}.1.json" with urlopen(source_url, timeout=45) as response: raw = response.read() source = json.loads(raw) pairs = set() rounds = defaultdict(list) counts = Counter() labelled_awards = [] for game in source["matches"]: home, away = game["team1"], game["team2"] pair = (home, away) if home == away or pair in pairs: raise ValueError(f"{source_url}: pareja repetida o inválida {pair}") pairs.add(pair) rounds[game["round"]].extend(pair) scores = game.get("score", {}).get("ft") if not isinstance(scores, list) or len(scores) != 2 or any( type(s) is not int or s < 0 for s in scores ): raise ValueError(f"{source_url}: marcador final inválido para {pair}") home_goals, away_goals = scores if home_goals > away_goals: counts["home_wins"] += 1 elif home_goals == away_goals: counts["draws"] += 1 else: counts["away_wins"] += 1 if game.get("status") == "awarded": labelled_awards.append({"home": home, "away": away, "score": scores}) clubs = {club for pair in pairs for club in pair} if len(clubs) != expected_clubs or pairs != set(itertools.permutations(clubs, 2)): raise ValueError(f"{source_url}: calendario incompleto") expected_rounds = {f"Matchday {i}" for i in range(1, 2*(expected_clubs-1)+1)} if rounds.keys() != expected_rounds or any( len(lineup) != expected_clubs or set(lineup) != clubs for lineup in rounds.values() ): raise ValueError(f"{source_url}: jornadas incompletas") row = {"season": season, "league": league, "matches": len(pairs), **counts} provenance = { "season": season, "league": league, "clubs": len(clubs), "rounds": len(rounds), "url": source_url, "sha256": hashlib.sha256(raw).hexdigest(), "labelled_awards": labelled_awards, } return row, provenance def total(rows): return {key: sum(row[key] for row in rows) for key in MEASURES} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--salida", type=Path, default=Path("."), help="directorio de salida") destination = parser.parse_args().salida with ThreadPoolExecutor(max_workers=5) as pool: results = list(pool.map(summarize, itertools.product(SEASONS, LEAGUES))) rows, provenance = zip(*results) dossier = { "source": {"project": REPO, "revision": REVISION, "license": "CC0-1.0"}, "seasons": list(SEASONS), "method": "Liga regular. Un registro por pareja ordenada local–visitante en cada liga y temporada. Se usa score.ft de OpenFootball, incluidos los marcadores adjudicados que publique la fuente. No se emplean la fecha diaria ni las cuotas.", "total": total(rows), "by_league": {name: total([r for r in rows if r["league"] == name]) for name, _ in LEAGUES.values()}, "by_season": {season: total([r for r in rows if r["season"] == season]) for season in SEASONS}, "league_seasons": rows, "files": provenance, } destination.mkdir(parents=True, exist_ok=True) with (destination / "datos.csv").open("w", encoding="utf-8", newline="") as out: writer = csv.DictWriter(out, ("season", "league", *MEASURES)) writer.writeheader() writer.writerows(rows) (destination / "evidencia.json").write_text( json.dumps(dossier, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) print(json.dumps(dossier["total"])) if __name__ == "__main__": main()