Download scripts/fetch_openf1.py from HiddenTerps/openf1-ml-dataset: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/datasets/HiddenTerps/openf1-ml-dataset/resolve/main/scripts/fetch_openf1.py
- Command line
-
hf download hf://datasets/HiddenTerps/openf1-ml-dataset/scripts/fetch_openf1.py
-
curl -L -o fetch_openf1.py https://huggingface.co/datasets/HiddenTerps/openf1-ml-dataset/resolve/main/scripts/fetch_openf1.py
22.4 kB
| #!/usr/bin/env python3 | |
| """Download OpenF1 historical Race and Qualifying data (2023+) into ML-ready tables. | |
| Free historical API, no auth. Rate limits (free tier, as of 2026-11-24): | |
| 3 req/s and 30 req/min. This client stays under both. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import time | |
| import traceback | |
| from collections import deque | |
| from datetime import datetime, timedelta, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| from urllib.error import HTTPError, URLError | |
| from urllib.parse import urlencode | |
| from urllib.request import Request, urlopen | |
| import pandas as pd | |
| BASE = "https://api.openf1.org/v1" | |
| OUT = Path("/workspace/openf1-dataset") | |
| CACHE = OUT / "_cache" | |
| LOG = OUT / "_fetch.log" | |
| UA = "openf1-ml-dataset-openf1-dataset/1.0 (historical research pull; respectful rate limit)" | |
| YEARS = (2023, 2024, 2025, 2026) | |
| SESSION_NAMES = ("Race", "Qualifying") | |
| ENDPOINTS = ("drivers", "laps", "stints", "pit", "position", "weather", "race_control") | |
| # Stay under 30/min and 3/s. | |
| MIN_INTERVAL = 0.45 | |
| MAX_PER_MINUTE = 28 | |
| TIMEOUT = 90 | |
| RETRIES = 6 | |
| def log(msg: str) -> None: | |
| line = f"{datetime.now(timezone.utc).isoformat(timespec='seconds')} {msg}" | |
| print(line, flush=True) | |
| with LOG.open("a") as f: | |
| f.write(line + "\n") | |
| class RateLimiter: | |
| def __init__(self) -> None: | |
| self.times: deque[float] = deque() | |
| self.last = 0.0 | |
| def wait(self) -> None: | |
| now = time.monotonic() | |
| gap = MIN_INTERVAL - (now - self.last) | |
| if gap > 0: | |
| time.sleep(gap) | |
| while True: | |
| now = time.monotonic() | |
| while self.times and now - self.times[0] >= 60: | |
| self.times.popleft() | |
| if len(self.times) < MAX_PER_MINUTE: | |
| break | |
| time.sleep(max(0.05, 60 - (now - self.times[0]) + 0.05)) | |
| self.last = time.monotonic() | |
| self.times.append(self.last) | |
| limiter = RateLimiter() | |
| def cache_path(name: str) -> Path: | |
| return CACHE / f"{name}.json" | |
| def load_cache(name: str) -> Any | None: | |
| p = cache_path(name) | |
| if p.exists(): | |
| with p.open() as f: | |
| return json.load(f) | |
| return None | |
| def save_cache(name: str, data: Any) -> None: | |
| p = cache_path(name) | |
| tmp = p.with_suffix(".json.tmp") | |
| with tmp.open("w") as f: | |
| json.dump(data, f) | |
| tmp.replace(p) | |
| def get_json(path: str, params: dict[str, Any], cache_name: str) -> list[dict]: | |
| cached = load_cache(cache_name) | |
| if cached is not None: | |
| return cached | |
| qs = urlencode(params) | |
| url = f"{BASE}/{path}?{qs}" | |
| last_err: Exception | None = None | |
| for attempt in range(1, RETRIES + 1): | |
| limiter.wait() | |
| req = Request(url, headers={"User-Agent": UA, "Accept": "application/json"}) | |
| try: | |
| with urlopen(req, timeout=TIMEOUT) as resp: | |
| raw = resp.read() | |
| data = json.loads(raw.decode("utf-8")) | |
| if data is None: | |
| data = [] | |
| if isinstance(data, dict) and data.get("detail") == "No results found.": | |
| data = [] | |
| if not isinstance(data, list): | |
| raise ValueError(f"unexpected payload type {type(data)} for {url}: {str(data)[:200]}") | |
| save_cache(cache_name, data) | |
| return data | |
| except HTTPError as e: | |
| body = e.read().decode("utf-8", errors="replace") if e.fp else "" | |
| if e.code == 404 and "No results found" in body: | |
| save_cache(cache_name, []) | |
| return [] | |
| last_err = e | |
| # 429 / 5xx: backoff | |
| sleep_s = min(90, 8 * attempt) if e.code in (429, 500, 502, 503, 504) else min(20, 3 * attempt) | |
| log(f"HTTP {e.code} {url} attempt {attempt}/{RETRIES}; sleep {sleep_s}s; body={body[:180]}") | |
| if e.code not in (429, 500, 502, 503, 504) and attempt >= 3: | |
| break | |
| time.sleep(sleep_s) | |
| except (URLError, TimeoutError, json.JSONDecodeError) as e: | |
| last_err = e | |
| sleep_s = min(90, 8 * attempt) | |
| log(f"ERR {type(e).__name__}: {e} {url} attempt {attempt}/{RETRIES}; sleep {sleep_s}s") | |
| time.sleep(sleep_s) | |
| raise RuntimeError(f"failed {url}: {last_err}") | |
| def to_dt(series: pd.Series) -> pd.Series: | |
| return pd.to_datetime(series, utc=True, errors="coerce") | |
| def write_table(name: str, df: pd.DataFrame) -> dict[str, Any]: | |
| csv_path = OUT / f"{name}.csv" | |
| pq_path = OUT / f"{name}.parquet" | |
| # Convert list/dict columns to JSON strings for CSV only; keep native in parquet. | |
| csv_df = df.copy() | |
| for col in csv_df.columns: | |
| if csv_df[col].dtype == "object": | |
| sample = csv_df[col].dropna() | |
| if not sample.empty and isinstance(sample.iloc[0], (list, dict)): | |
| csv_df[col] = csv_df[col].map(lambda x: json.dumps(x) if isinstance(x, (list, dict)) else x) | |
| csv_df.to_csv(csv_path, index=False) | |
| df.to_parquet(pq_path, index=False) | |
| return { | |
| "name": name, | |
| "rows": int(len(df)), | |
| "cols": list(df.columns), | |
| "csv_bytes": csv_path.stat().st_size, | |
| "parquet_bytes": pq_path.stat().st_size, | |
| } | |
| def flatten_sessions(sessions: list[dict]) -> pd.DataFrame: | |
| return pd.DataFrame(sessions) | |
| def build_lap_ml( | |
| laps: pd.DataFrame, | |
| stints: pd.DataFrame, | |
| weather: pd.DataFrame, | |
| drivers: pd.DataFrame, | |
| position: pd.DataFrame, | |
| pit: pd.DataFrame, | |
| sessions: pd.DataFrame, | |
| meetings: pd.DataFrame, | |
| ) -> pd.DataFrame: | |
| df = laps.copy() | |
| df["date_start"] = to_dt(df.get("date_start")) | |
| # Stint / compound / tyre age at this lap | |
| if not stints.empty: | |
| s = stints.copy() | |
| s["lap_start"] = pd.to_numeric(s["lap_start"], errors="coerce") | |
| s["lap_end"] = pd.to_numeric(s["lap_end"], errors="coerce") | |
| s["tyre_age_at_start"] = pd.to_numeric(s.get("tyre_age_at_start"), errors="coerce") | |
| keys = ["session_key", "driver_number"] | |
| parts = [] | |
| # Vectorized-ish join: merge then filter lap range | |
| merged = df.merge( | |
| s[keys + [c for c in ["stint_number", "compound", "lap_start", "lap_end", "tyre_age_at_start"] if c in s.columns]], | |
| on=keys, | |
| how="left", | |
| suffixes=("", "_stint"), | |
| ) | |
| lap = pd.to_numeric(merged["lap_number"], errors="coerce") | |
| in_range = (merged["lap_start"].isna() | (lap >= merged["lap_start"])) & ( | |
| merged["lap_end"].isna() | (lap <= merged["lap_end"]) | |
| ) | |
| # Keep the matching stint when one exists. Laps outside every recorded | |
| # stint range (often incomplete retirement laps) are kept with null stint fields. | |
| matched = merged[in_range].copy() | |
| matched = matched.sort_values(["session_key", "driver_number", "lap_number", "stint_number"], na_position="last") | |
| matched = matched.drop_duplicates(["session_key", "driver_number", "lap_number"], keep="last") | |
| matched["_k"] = list(zip(matched["session_key"], matched["driver_number"], matched["lap_number"])) | |
| leftover = df.copy() | |
| leftover["_k"] = list(zip(leftover["session_key"], leftover["driver_number"], leftover["lap_number"])) | |
| leftover = leftover[~leftover["_k"].isin(set(matched["_k"]))].copy() | |
| for c in ["stint_number", "compound", "lap_start", "lap_end", "tyre_age_at_start"]: | |
| if c in leftover.columns or True: | |
| leftover[c] = pd.NA | |
| df = pd.concat([matched, leftover], ignore_index=True) | |
| df = df.drop(columns=["_k"], errors="ignore") | |
| df["tyre_age"] = pd.to_numeric(df.get("tyre_age_at_start"), errors="coerce") + ( | |
| pd.to_numeric(df["lap_number"], errors="coerce") - pd.to_numeric(df.get("lap_start"), errors="coerce") | |
| ) | |
| else: | |
| df["stint_number"] = pd.NA | |
| df["compound"] = pd.NA | |
| df["tyre_age"] = pd.NA | |
| # Drivers / team (per session) | |
| if not drivers.empty: | |
| dcols = [c for c in ["session_key", "driver_number", "full_name", "name_acronym", "team_name", "broadcast_name", "country_code"] if c in drivers.columns] | |
| df = df.merge(drivers[dcols].drop_duplicates(["session_key", "driver_number"]), on=["session_key", "driver_number"], how="left") | |
| # Final position: last recorded position in the session | |
| if not position.empty: | |
| pos = position.copy() | |
| pos["date"] = to_dt(pos["date"]) | |
| pos = pos.sort_values(["session_key", "driver_number", "date"]) | |
| final = pos.dropna(subset=["position"]).groupby(["session_key", "driver_number"], as_index=False).tail(1) | |
| final = final.rename(columns={"position": "final_position", "date": "final_position_date"}) | |
| df = df.merge(final[["session_key", "driver_number", "final_position"]], on=["session_key", "driver_number"], how="left") | |
| # Position at / just after lap start (nearest previous or equal timestamp) | |
| pos_asof = pos.dropna(subset=["date", "position"]).sort_values("date") | |
| lap_asof = df.sort_values("date_start").reset_index() | |
| # merge_asof needs matching types and sorted keys; do per session+driver would be slow, | |
| # so merge on session_key+driver via a helper key then asof on time — pandas merge_asof | |
| # allows `by=`. | |
| try: | |
| joined_pos = pd.merge_asof( | |
| lap_asof.dropna(subset=["date_start"]).sort_values("date_start"), | |
| pos_asof.rename(columns={"date": "position_date", "position": "position_at_lap"})[ | |
| ["session_key", "driver_number", "position_date", "position_at_lap"] | |
| ].sort_values("position_date"), | |
| left_on="date_start", | |
| right_on="position_date", | |
| by=["session_key", "driver_number"], | |
| direction="backward", | |
| ) | |
| # restore rows with null date_start | |
| missing = lap_asof[lap_asof["date_start"].isna()] | |
| if not missing.empty: | |
| for c in ("position_date", "position_at_lap"): | |
| missing[c] = pd.NA | |
| joined_pos = pd.concat([joined_pos, missing], ignore_index=True) | |
| df = joined_pos.set_index("index").sort_index() | |
| except Exception: | |
| log("position_at_lap merge_asof failed; leaving column empty\n" + traceback.format_exc()) | |
| df["position_at_lap"] = pd.NA | |
| else: | |
| df["final_position"] = pd.NA | |
| df["position_at_lap"] = pd.NA | |
| # Weather nearest to lap start | |
| if not weather.empty: | |
| w = weather.copy() | |
| w["date"] = to_dt(w["date"]) | |
| wcols = [c for c in ["session_key", "date", "air_temperature", "track_temperature", "humidity", "rainfall", "pressure", "wind_speed", "wind_direction"] if c in w.columns] | |
| w = w[wcols].rename(columns={"date": "weather_date"}) | |
| try: | |
| base = df.reset_index(drop=False) | |
| # some laps have null date_start | |
| has_t = base.dropna(subset=["date_start"]).sort_values("date_start") | |
| no_t = base[base["date_start"].isna()] | |
| w_sorted = w.dropna(subset=["weather_date"]).sort_values("weather_date") | |
| joined_w = pd.merge_asof( | |
| has_t, | |
| w_sorted, | |
| left_on="date_start", | |
| right_on="weather_date", | |
| by="session_key", | |
| direction="nearest", | |
| ) | |
| if not no_t.empty: | |
| for c in [c for c in joined_w.columns if c not in no_t.columns]: | |
| no_t[c] = pd.NA | |
| joined_w = pd.concat([joined_w, no_t], ignore_index=True) | |
| if "index" in joined_w.columns: | |
| df = joined_w.set_index("index").sort_index() | |
| else: | |
| df = joined_w | |
| except Exception: | |
| log("weather merge_asof failed; leaving weather columns empty\n" + traceback.format_exc()) | |
| # Pit on this lap | |
| if not pit.empty: | |
| p = pit.copy() | |
| pcols = [c for c in ["session_key", "driver_number", "lap_number", "pit_duration", "stop_duration", "lane_duration"] if c in p.columns] | |
| p = p[pcols].copy() | |
| # multiple pits on same lap are rare; take max duration | |
| agg = {c: "max" for c in ["pit_duration", "stop_duration", "lane_duration"] if c in p.columns} | |
| p = p.groupby(["session_key", "driver_number", "lap_number"], as_index=False).agg(agg) | |
| p["pit_this_lap"] = 1 | |
| df = df.merge(p, on=["session_key", "driver_number", "lap_number"], how="left") | |
| df["pit_this_lap"] = df["pit_this_lap"].fillna(0).astype("int8") | |
| else: | |
| df["pit_this_lap"] = 0 | |
| df["pit_duration"] = pd.NA | |
| # Session / meeting metadata | |
| scols = [c for c in ["session_key", "meeting_key", "session_name", "session_type", "year", "date_start", "date_end", "circuit_short_name", "country_name", "location", "gmt_offset"] if c in sessions.columns] | |
| df = df.merge(sessions[scols].drop_duplicates("session_key"), on="session_key", how="left", suffixes=("", "_session")) | |
| if "date_start_session" in df.columns: | |
| df = df.rename(columns={"date_start_session": "session_date_start"}) | |
| mcols = [c for c in ["meeting_key", "meeting_name", "meeting_official_name", "circuit_short_name", "country_name", "year"] if c in meetings.columns] | |
| # avoid duplicate circuit/country/year if already present | |
| already = set(df.columns) | |
| extra = [c for c in mcols if c == "meeting_key" or c not in already] | |
| if extra: | |
| df = df.merge(meetings[extra].drop_duplicates("meeting_key"), on="meeting_key", how="left") | |
| # Useful derived fields | |
| if "lap_duration" in df.columns: | |
| df["lap_duration"] = pd.to_numeric(df["lap_duration"], errors="coerce") | |
| if "is_pit_out_lap" in df.columns: | |
| df["is_pit_out_lap"] = df["is_pit_out_lap"].astype("boolean") | |
| # Stable column order | |
| preferred = [ | |
| "year", | |
| "meeting_key", | |
| "meeting_name", | |
| "session_key", | |
| "session_name", | |
| "session_type", | |
| "circuit_short_name", | |
| "country_name", | |
| "location", | |
| "driver_number", | |
| "full_name", | |
| "name_acronym", | |
| "team_name", | |
| "lap_number", | |
| "date_start", | |
| "lap_duration", | |
| "duration_sector_1", | |
| "duration_sector_2", | |
| "duration_sector_3", | |
| "i1_speed", | |
| "i2_speed", | |
| "st_speed", | |
| "is_pit_out_lap", | |
| "stint_number", | |
| "compound", | |
| "tyre_age_at_start", | |
| "tyre_age", | |
| "lap_start", | |
| "lap_end", | |
| "air_temperature", | |
| "track_temperature", | |
| "humidity", | |
| "rainfall", | |
| "pressure", | |
| "wind_speed", | |
| "wind_direction", | |
| "weather_date", | |
| "position_at_lap", | |
| "final_position", | |
| "pit_this_lap", | |
| "pit_duration", | |
| "stop_duration", | |
| "lane_duration", | |
| "segments_sector_1", | |
| "segments_sector_2", | |
| "segments_sector_3", | |
| ] | |
| rest = [c for c in df.columns if c not in preferred] | |
| df = df[[c for c in preferred if c in df.columns] + rest] | |
| return df.reset_index(drop=True) | |
| def main() -> None: | |
| CACHE.mkdir(parents=True, exist_ok=True) | |
| cutoff = datetime.now(timezone.utc) - timedelta(minutes=30) | |
| meetings_rows: list[dict] = [] | |
| sessions_rows: list[dict] = [] | |
| for year in YEARS: | |
| meetings_rows.extend(get_json("meetings", {"year": year}, f"meetings_{year}")) | |
| sessions_rows.extend(get_json("sessions", {"year": year}, f"sessions_{year}")) | |
| log(f"loaded year={year} meetings={len([m for m in meetings_rows if m.get('year')==year])} sessions={len([s for s in sessions_rows if s.get('year')==year])}") | |
| meetings = pd.DataFrame(meetings_rows) | |
| all_sessions = pd.DataFrame(sessions_rows) | |
| def session_end(row: pd.Series) -> datetime | None: | |
| end = row.get("date_end") | |
| start = row.get("date_start") | |
| dt_end = pd.to_datetime(end, utc=True, errors="coerce") if end else pd.NaT | |
| dt_start = pd.to_datetime(start, utc=True, errors="coerce") if start else pd.NaT | |
| if pd.notna(dt_end): | |
| return dt_end.to_pydatetime() | |
| if pd.notna(dt_start): | |
| return dt_start.to_pydatetime() + timedelta(hours=3) | |
| return None | |
| mask_name = all_sessions["session_name"].isin(SESSION_NAMES) | |
| mask_not_cancel = all_sessions["is_cancelled"].fillna(False).eq(False) if "is_cancelled" in all_sessions.columns else True | |
| ends = all_sessions.apply(session_end, axis=1) | |
| mask_past = ends.map(lambda d: bool(d and d <= cutoff)) | |
| target = all_sessions[mask_name & mask_not_cancel & mask_past].copy() | |
| skipped_future = all_sessions[mask_name & ~mask_past] | |
| log( | |
| f"target sessions={len(target)} " | |
| f"(race={int((target.session_name=='Race').sum())}, " | |
| f"qual={int((target.session_name=='Qualifying').sum())}); " | |
| f"skipped_future_or_live={len(skipped_future)} " | |
| f"names={sorted(target.session_name.unique().tolist())} " | |
| f"years={sorted(target.year.unique().tolist())}" | |
| ) | |
| if len(skipped_future): | |
| for _, r in skipped_future.sort_values("date_start").iterrows(): | |
| log(f" skip future/live {r['year']} {r.get('circuit_short_name')} {r['session_name']} start={r.get('date_start')} end={r.get('date_end')}") | |
| gaps: list[dict] = [] | |
| buckets: dict[str, list[dict]] = {ep: [] for ep in ENDPOINTS} | |
| sessions_list = target.to_dict(orient="records") | |
| total = len(sessions_list) * len(ENDPOINTS) | |
| done = 0 | |
| t0 = time.time() | |
| for i, sess in enumerate(sessions_list, 1): | |
| sk = sess["session_key"] | |
| label = f"{sess.get('year')} {sess.get('circuit_short_name')} {sess.get('session_name')} sk={sk}" | |
| for ep in ENDPOINTS: | |
| data = get_json(ep, {"session_key": sk}, f"{ep}_{sk}") | |
| if not data: | |
| gaps.append({"endpoint": ep, "session_key": sk, "year": sess.get("year"), "circuit": sess.get("circuit_short_name"), "session_name": sess.get("session_name")}) | |
| buckets[ep].extend(data) | |
| done += 1 | |
| if i % 5 == 0 or i == len(sessions_list): | |
| elapsed = time.time() - t0 | |
| rate = done / elapsed if elapsed else 0 | |
| log(f"progress {i}/{len(sessions_list)} sessions, {done}/{total} requests, {rate:.2f} req/s, last={label}") | |
| # Sample telemetry: Abu Dhabi 2025 Race (session_key 9839), driver 1, plus location | |
| sample_sk = 9839 | |
| sample_driver = 1 | |
| if not (target["session_key"] == sample_sk).any(): | |
| # fallback: last completed race | |
| races = target[target["session_name"] == "Race"].sort_values("date_start") | |
| if not races.empty: | |
| sample_sk = int(races.iloc[-1]["session_key"]) | |
| log(f"sample session 9839 not in target; using last race sk={sample_sk}") | |
| log(f"fetching car_data + location sample session_key={sample_sk} driver_number={sample_driver}") | |
| car_data = get_json("car_data", {"session_key": sample_sk, "driver_number": sample_driver}, f"car_data_{sample_sk}_{sample_driver}") | |
| location = get_json("location", {"session_key": sample_sk, "driver_number": sample_driver}, f"location_{sample_sk}_{sample_driver}") | |
| tables = {} | |
| tables["meetings"] = write_table("meetings", meetings) | |
| tables["sessions"] = write_table("sessions", target.reset_index(drop=True)) | |
| tables["sessions_all"] = write_table("sessions_all", all_sessions) # includes FP/Sprint/future for reference | |
| frames = {} | |
| for ep, rows in buckets.items(): | |
| frames[ep] = pd.DataFrame(rows) | |
| tables[ep] = write_table(ep, frames[ep]) | |
| log(f"wrote {ep}: {tables[ep]['rows']} rows") | |
| frames["car_data_sample"] = pd.DataFrame(car_data) | |
| frames["location_sample"] = pd.DataFrame(location) | |
| tables["car_data_sample"] = write_table("car_data_sample", frames["car_data_sample"]) | |
| tables["location_sample"] = write_table("location_sample", frames["location_sample"]) | |
| log(f"wrote samples car_data={tables['car_data_sample']['rows']} location={tables['location_sample']['rows']}") | |
| log("building laps_ml join table") | |
| laps_ml = build_lap_ml( | |
| laps=frames["laps"], | |
| stints=frames["stints"], | |
| weather=frames["weather"], | |
| drivers=frames["drivers"], | |
| position=frames["position"], | |
| pit=frames["pit"], | |
| sessions=target, | |
| meetings=meetings, | |
| ) | |
| tables["laps_ml"] = write_table("laps_ml", laps_ml) | |
| log(f"wrote laps_ml: {tables['laps_ml']['rows']} rows, {len(laps_ml.columns)} cols") | |
| # Coverage stats | |
| coverage = { | |
| "source": "https://api.openf1.org/v1", | |
| "docs": "https://openf1.org/", | |
| "fetched_at_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), | |
| "years_requested": list(YEARS), | |
| "session_names": list(SESSION_NAMES), | |
| "cutoff_utc": cutoff.isoformat(), | |
| "target_sessions": int(len(target)), | |
| "sessions_by_year_name": target.groupby(["year", "session_name"]).size().astype(int).to_dict() if len(target) else {}, | |
| "empty_endpoint_calls": gaps, | |
| "empty_calls_by_endpoint": {ep: sum(1 for g in gaps if g["endpoint"] == ep) for ep in ENDPOINTS}, | |
| "tables": {k: {"rows": v["rows"], "csv_bytes": v["csv_bytes"], "parquet_bytes": v["parquet_bytes"], "columns": v["cols"]} for k, v in tables.items()}, | |
| "sample_telemetry": {"session_key": sample_sk, "driver_number": sample_driver, "car_data_rows": tables["car_data_sample"]["rows"], "location_rows": tables["location_sample"]["rows"]}, | |
| "laps_ml_nonnull": {c: int(laps_ml[c].notna().sum()) for c in laps_ml.columns}, | |
| "skipped_future_or_live": skipped_future[["year", "session_name", "circuit_short_name", "date_start", "date_end", "session_key"]].to_dict(orient="records") if len(skipped_future) else [], | |
| } | |
| # groupby tuple keys are not JSON-serializable if left as tuples — already converted via to_dict which uses tuples | |
| coverage["sessions_by_year_name"] = {f"{y}|{n}": int(v) for (y, n), v in (target.groupby(["year", "session_name"]).size().items() if len(target) else [])} | |
| with (OUT / "manifest.json").open("w") as f: | |
| json.dump(coverage, f, indent=2, default=str) | |
| log("wrote manifest.json") | |
| log("DONE") | |
| if __name__ == "__main__": | |
| main() | |