clarkkitchen22 commited on
Commit
af467a1
·
verified ·
1 Parent(s): c257d43

Add MLB 2025 ChatML matchup dataset

Browse files

Upload verified Parquet dataset, build manifest, reproducibility scripts, and a detailed dataset card for MLB 2025 ChatML matchup rows.

README.md ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - en
5
+ task_categories:
6
+ - text-generation
7
+ - question-answering
8
+ task_ids:
9
+ - chat-completion
10
+ tags:
11
+ - mlb
12
+ - baseball
13
+ - sports-analytics
14
+ - chatml
15
+ - parquet
16
+ - instruction-tuning
17
+ - matchup-analysis
18
+ - statsapi
19
+ size_categories:
20
+ - 1K<n<10K
21
+ pretty_name: MLB 2025 ChatML Matchups
22
+ configs:
23
+ - config_name: default
24
+ data_files:
25
+ - split: train
26
+ path: data/train-00000-of-00001.parquet
27
+ ---
28
+
29
+ # MLB 2025 ChatML Matchups
30
+
31
+ MLB 2025 ChatML Matchups is a compact instruction-tuning dataset built from the public MLB Stats API for the 2025 Major League Baseball regular season. It converts structured game, team offense, and team pitching information into ChatML-style rows that are ready for supervised fine-tuning, retrieval-augmented evaluation, sports analytics prototypes, or prompt engineering tests.
32
+
33
+ Each row is written from one team's perspective for one completed MLB regular-season game. A single game produces two examples: the away team's view and the home team's view. The assistant answer is a compact JSON payload containing the matchup facts needed to discuss the game without relying on hidden knowledge.
34
+
35
+ ## What This Dataset Is For
36
+
37
+ Use this dataset when you want a language model to learn how to read structured baseball context and produce grounded matchup analysis. It is especially useful for:
38
+
39
+ - Training chat models to answer MLB matchup questions from supplied facts
40
+ - Building sports analytics assistants that explain offense-versus-pitching context
41
+ - Evaluating whether a model can preserve structured sports statistics in an answer
42
+ - Prototyping retrieval flows where the retrieved record is converted into a concise analyst response
43
+ - Creating baseball examples for ChatML ingestion pipelines
44
+
45
+ This is not a betting dataset, odds dataset, or projection model output. It contains official-style game and team statistics from MLB API endpoints, not market prices or gambling recommendations.
46
+
47
+ ## Dataset Summary
48
+
49
+ | Field | Value |
50
+ |---|---:|
51
+ | Season | 2025 MLB regular season |
52
+ | Source | Public MLB Stats API |
53
+ | Completed unique games | 2,425 |
54
+ | Rows | 4,850 |
55
+ | Teams | 30 |
56
+ | Format | Parquet |
57
+ | Primary column | `messages` |
58
+ | Row shape | One team perspective per game |
59
+ | Split | `train` |
60
+
61
+ The schedule loader excludes postponed placeholders and deduplicates suspended or continued games that appear on multiple schedule dates by MLB `gamePk`.
62
+
63
+ ## Data Sources
64
+
65
+ The builder uses these MLB Stats API endpoints:
66
+
67
+ - `https://statsapi.mlb.com/api/v1/schedule`
68
+ - `https://statsapi.mlb.com/api/v1/teams/stats`
69
+ - `https://statsapi.mlb.com/api/v1/game/{gamePk}/boxscore`
70
+
71
+ The included script uses a local disk cache, sequential requests, configurable request throttling, retry/backoff, and explicit handling for HTTP `429` responses.
72
+
73
+ ## Row Format
74
+
75
+ Each example contains a `messages` column formatted as a list of ChatML-style messages:
76
+
77
+ ```json
78
+ [
79
+ {
80
+ "role": "system",
81
+ "content": "You are an MLB matchup analyst. Use only the supplied 2025 MLB Stats API facts and answer in compact JSON."
82
+ },
83
+ {
84
+ "role": "user",
85
+ "content": "Build a pitching and offense matchup brief for Los Angeles Dodgers vs Chicago Cubs on 2025-03-18."
86
+ },
87
+ {
88
+ "role": "assistant",
89
+ "content": "{\"game_date\":\"2025-03-18T10:10:00Z\", ... }"
90
+ }
91
+ ]
92
+ ```
93
+
94
+ The assistant content is JSON. It contains the team, opponent, final score, game-level batting and pitching lines, and season-level hitting and pitching context for both clubs.
95
+
96
+ ## Columns
97
+
98
+ | Column | Description |
99
+ |---|---|
100
+ | `row_id` | Stable row identifier: `mlb-2025-{game_pk}-{side}` |
101
+ | `season` | Season year, always `2025` |
102
+ | `game_pk` | MLB game identifier |
103
+ | `game_date` | UTC game date as `YYYY-MM-DD` |
104
+ | `game_datetime_utc` | Full UTC game datetime from the schedule endpoint |
105
+ | `team_id`, `team_name`, `team_side` | Team identity and home/away side for the row perspective |
106
+ | `opponent_id`, `opponent_name`, `opponent_side` | Opponent identity and side |
107
+ | `team_runs`, `opponent_runs` | Final score from the row team's perspective |
108
+ | `result` | `win`, `loss`, or `tie` from the row team's perspective |
109
+ | `messages` | ChatML-style `system`, `user`, `assistant` messages |
110
+ | `assistant_payload_json` | Full assistant JSON payload as a string |
111
+ | `team_game_batting_json` | Team game batting stats |
112
+ | `team_game_pitching_json` | Team game pitching stats |
113
+ | `opponent_game_batting_json` | Opponent game batting stats |
114
+ | `opponent_game_pitching_json` | Opponent game pitching stats |
115
+ | `team_season_hitting_json` | Team 2025 season hitting stats |
116
+ | `team_season_pitching_json` | Team 2025 season pitching stats |
117
+ | `opponent_season_hitting_json` | Opponent 2025 season hitting stats |
118
+ | `opponent_season_pitching_json` | Opponent 2025 season pitching stats |
119
+
120
+ ## How To Use
121
+
122
+ ### Hugging Face Datasets
123
+
124
+ ```python
125
+ from datasets import load_dataset
126
+
127
+ ds = load_dataset("clarkkitchen22/MLB-2025-ChatML-Matchups", split="train")
128
+ example = ds[0]
129
+
130
+ messages = example["messages"]
131
+ print(messages[0]["role"], messages[0]["content"])
132
+ ```
133
+
134
+ ### Pandas
135
+
136
+ ```python
137
+ import pandas as pd
138
+
139
+ df = pd.read_parquet(
140
+ "hf://datasets/clarkkitchen22/MLB-2025-ChatML-Matchups/data/train-00000-of-00001.parquet"
141
+ )
142
+
143
+ print(df[["team_name", "opponent_name", "team_runs", "opponent_runs", "result"]].head())
144
+ ```
145
+
146
+ ### Fine-Tuning
147
+
148
+ Most chat fine-tuning stacks can consume the `messages` column directly or after a small adapter. The dataset is designed for supervised fine-tuning where:
149
+
150
+ - `system` defines the analyst behavior and grounding rule
151
+ - `user` asks for a matchup brief
152
+ - `assistant` returns a structured JSON answer
153
+
154
+ If your trainer expects plain text, serialize each row with your model's chat template before training.
155
+
156
+ ## Why This Format
157
+
158
+ Baseball data is highly structured, but baseball questions are usually conversational. This dataset bridges those two modes. The model sees natural user requests while the target response preserves exact facts in a predictable JSON structure. That makes it useful for teaching:
159
+
160
+ - Grounded sports explanations
161
+ - Matchup framing
162
+ - Team offense versus team pitching context
163
+ - Score-aware summaries
164
+ - Structured-output discipline
165
+
166
+ The dataset intentionally keeps the assistant response compact. It is easier to inspect, easier to validate, and less likely to reward unsupported narrative claims.
167
+
168
+ ## Reproducibility
169
+
170
+ The repository includes:
171
+
172
+ - `scripts/build_dataset.py`: source scraper and Parquet builder
173
+ - `scripts/verify_dataset.py`: verifier for row counts, teams, unique row ids, ChatML roles, and pitching fields
174
+ - `mlb_2025_chatml_matchups.manifest.json`: build manifest with row count, source, and scraper metrics
175
+
176
+ The local build was verified with:
177
+
178
+ ```bash
179
+ python3 scripts/verify_dataset.py --parquet data/processed/mlb_2025_chatml_matchups.parquet
180
+ ```
181
+
182
+ Verification result:
183
+
184
+ - `rows`: 4,850
185
+ - `games`: 2,425
186
+ - `teams`: 30
187
+ - `rows_match_schedule_x2`: true
188
+ - `unique_row_ids`: true
189
+ - `all_games_present`: true
190
+ - `all_30_teams_present`: true
191
+ - `chatml_roles_valid`: true
192
+ - `pitching_fields_present`: true
193
+
194
+ ## Limitations
195
+
196
+ - The dataset reflects the public MLB Stats API responses available at build time.
197
+ - Team season stats are full-season 2025 totals, not pregame rolling statistics.
198
+ - The assistant targets are structured JSON records, not prose scouting reports.
199
+ - The dataset does not include player-level pitch-by-pitch events, betting odds, injuries, weather, umpire data, or park factors.
200
+ - Commercial usage and redistribution should be evaluated against MLB's applicable data terms and policies.
201
+
202
+ ## Responsible Use
203
+
204
+ This dataset is intended for sports analytics, education, retrieval, and model-development workflows. Do not present model outputs trained on this data as official MLB commentary, real-time predictions, medical/injury guidance, or wagering advice.
205
+
206
+ ## Attribution
207
+
208
+ Data was collected from the public MLB Stats API. This dataset is not affiliated with, endorsed by, or sponsored by Major League Baseball or its clubs.
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12cc6932624ff4611b8cef9dbdaa0ed163a1dd91af430483228d227e1fe6f8ea
3
+ size 1873108
mlb_2025_chatml_matchups.manifest.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "api_metrics": {
3
+ "cache_hits": 2427,
4
+ "network_requests": 0,
5
+ "rate_limited": 0,
6
+ "retries": 0
7
+ },
8
+ "created_at": "2026-05-14T01:16:39.965284+00:00",
9
+ "output_path": "data/processed/mlb_2025_chatml_matchups.parquet",
10
+ "regular_season_final_games": 2425,
11
+ "rows": 4850,
12
+ "season": 2025,
13
+ "source": "https://statsapi.mlb.com/api/v1"
14
+ }
scripts/build_dataset.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import hashlib
6
+ import json
7
+ import random
8
+ import time
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlencode
14
+
15
+ import pyarrow as pa
16
+ import pyarrow.parquet as pq
17
+ import requests
18
+
19
+
20
+ BASE_URL = "https://statsapi.mlb.com/api/v1"
21
+ SEASON = 2025
22
+ DEFAULT_START = "2025-03-01"
23
+ DEFAULT_END = "2025-11-30"
24
+
25
+ STAT_KEYS = [
26
+ "gamesPlayed",
27
+ "runs",
28
+ "hits",
29
+ "doubles",
30
+ "triples",
31
+ "homeRuns",
32
+ "rbi",
33
+ "baseOnBalls",
34
+ "strikeOuts",
35
+ "stolenBases",
36
+ "caughtStealing",
37
+ "avg",
38
+ "obp",
39
+ "slg",
40
+ "ops",
41
+ "era",
42
+ "whip",
43
+ "inningsPitched",
44
+ "earnedRuns",
45
+ "battersFaced",
46
+ "groundOuts",
47
+ "airOuts",
48
+ "leftOnBase",
49
+ ]
50
+
51
+
52
+ @dataclass
53
+ class ApiMetrics:
54
+ network_requests: int = 0
55
+ cache_hits: int = 0
56
+ retries: int = 0
57
+ rate_limited: int = 0
58
+
59
+
60
+ class RateLimiter:
61
+ def __init__(self, max_rps: float) -> None:
62
+ if max_rps <= 0:
63
+ raise ValueError("--max-rps must be positive")
64
+ self.min_interval = 1.0 / max_rps
65
+ self.last_request_at = 0.0
66
+
67
+ def wait(self) -> None:
68
+ elapsed = time.monotonic() - self.last_request_at
69
+ remaining = self.min_interval - elapsed
70
+ if remaining > 0:
71
+ time.sleep(remaining)
72
+ self.last_request_at = time.monotonic()
73
+
74
+
75
+ class MlbApiClient:
76
+ def __init__(
77
+ self,
78
+ cache_dir: Path,
79
+ max_rps: float,
80
+ force_refresh: bool = False,
81
+ timeout: int = 30,
82
+ max_retries: int = 5,
83
+ ) -> None:
84
+ self.cache_dir = cache_dir
85
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
86
+ self.force_refresh = force_refresh
87
+ self.timeout = timeout
88
+ self.max_retries = max_retries
89
+ self.rate_limiter = RateLimiter(max_rps=max_rps)
90
+ self.metrics = ApiMetrics()
91
+ self.session = requests.Session()
92
+ self.session.headers.update(
93
+ {
94
+ "Accept": "application/json",
95
+ "User-Agent": (
96
+ "mlb-chatml-2025-dataset/0.1 "
97
+ "(research dataset builder; contact: Clark Kitchen)"
98
+ ),
99
+ }
100
+ )
101
+
102
+ def get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
103
+ params = params or {}
104
+ url = f"{BASE_URL}{path}"
105
+ cache_path = self._cache_path(url, params)
106
+ if cache_path.exists() and not self.force_refresh:
107
+ self.metrics.cache_hits += 1
108
+ return json.loads(cache_path.read_text())
109
+
110
+ query = urlencode(sorted(params.items()))
111
+ full_url = f"{url}?{query}" if query else url
112
+ last_error: Exception | None = None
113
+ for attempt in range(self.max_retries + 1):
114
+ if attempt:
115
+ self.metrics.retries += 1
116
+ sleep_seconds = min(60.0, (2**attempt) + random.uniform(0.0, 0.5))
117
+ time.sleep(sleep_seconds)
118
+ self.rate_limiter.wait()
119
+ self.metrics.network_requests += 1
120
+ try:
121
+ response = self.session.get(full_url, timeout=self.timeout)
122
+ if response.status_code == 429:
123
+ self.metrics.rate_limited += 1
124
+ retry_after = response.headers.get("Retry-After")
125
+ if retry_after:
126
+ time.sleep(min(float(retry_after), 120.0))
127
+ continue
128
+ if response.status_code >= 500:
129
+ continue
130
+ response.raise_for_status()
131
+ data = response.json()
132
+ cache_path.write_text(json.dumps(data, sort_keys=True))
133
+ return data
134
+ except (requests.RequestException, json.JSONDecodeError) as exc:
135
+ last_error = exc
136
+ continue
137
+ raise RuntimeError(f"MLB API request failed after retries: {full_url}") from last_error
138
+
139
+ def _cache_path(self, url: str, params: dict[str, Any]) -> Path:
140
+ cache_key = json.dumps({"url": url, "params": sorted(params.items())}, sort_keys=True)
141
+ digest = hashlib.sha256(cache_key.encode("utf-8")).hexdigest()
142
+ return self.cache_dir / f"{digest}.json"
143
+
144
+
145
+ def compact_stat_dict(stats: dict[str, Any]) -> dict[str, Any]:
146
+ return {key: stats[key] for key in STAT_KEYS if key in stats}
147
+
148
+
149
+ def load_schedule(client: MlbApiClient, start_date: str, end_date: str) -> list[dict[str, Any]]:
150
+ data = client.get(
151
+ "/schedule",
152
+ {
153
+ "sportId": 1,
154
+ "season": SEASON,
155
+ "gameType": "R",
156
+ "startDate": start_date,
157
+ "endDate": end_date,
158
+ },
159
+ )
160
+ games_by_pk: dict[int, dict[str, Any]] = {}
161
+ for date_block in data.get("dates", []):
162
+ for game in date_block.get("games", []):
163
+ status = game.get("status", {})
164
+ has_scores = (
165
+ game.get("teams", {}).get("away", {}).get("score") is not None
166
+ and game.get("teams", {}).get("home", {}).get("score") is not None
167
+ )
168
+ if status.get("statusCode") == "F" and has_scores:
169
+ game_pk = int(game["gamePk"])
170
+ previous = games_by_pk.get(game_pk)
171
+ if previous is None or game["gameDate"] > previous["gameDate"]:
172
+ games_by_pk[game_pk] = game
173
+ return sorted(games_by_pk.values(), key=lambda game: (game["gameDate"], int(game["gamePk"])))
174
+
175
+
176
+ def load_season_team_stats(client: MlbApiClient) -> dict[int, dict[str, dict[str, Any]]]:
177
+ data = client.get(
178
+ "/teams/stats",
179
+ {
180
+ "season": SEASON,
181
+ "sportIds": 1,
182
+ "group": "hitting,pitching",
183
+ "stats": "season",
184
+ },
185
+ )
186
+ team_stats: dict[int, dict[str, dict[str, Any]]] = {}
187
+ for stat_block in data.get("stats", []):
188
+ group = stat_block.get("group", {}).get("displayName")
189
+ if group not in {"hitting", "pitching"}:
190
+ continue
191
+ for split in stat_block.get("splits", []):
192
+ team_id = int(split["team"]["id"])
193
+ team_stats.setdefault(team_id, {})[group] = compact_stat_dict(split.get("stat", {}))
194
+ return team_stats
195
+
196
+
197
+ def score_for_side(game: dict[str, Any], side: str) -> int | None:
198
+ value = game.get("teams", {}).get(side, {}).get("score")
199
+ return int(value) if value is not None else None
200
+
201
+
202
+ def result_for(team_runs: int | None, opponent_runs: int | None) -> str:
203
+ if team_runs is None or opponent_runs is None:
204
+ return "unknown"
205
+ if team_runs > opponent_runs:
206
+ return "win"
207
+ if team_runs < opponent_runs:
208
+ return "loss"
209
+ return "tie"
210
+
211
+
212
+ def json_dumps(data: Any) -> str:
213
+ return json.dumps(data, sort_keys=True, separators=(",", ":"))
214
+
215
+
216
+ def matchup_assistant_payload(
217
+ game: dict[str, Any],
218
+ side: str,
219
+ opponent_side: str,
220
+ team_stats: dict[int, dict[str, dict[str, Any]]],
221
+ boxscore: dict[str, Any],
222
+ ) -> dict[str, Any]:
223
+ team = game["teams"][side]["team"]
224
+ opponent = game["teams"][opponent_side]["team"]
225
+ team_id = int(team["id"])
226
+ opponent_id = int(opponent["id"])
227
+ team_box = boxscore["teams"][side]
228
+ opponent_box = boxscore["teams"][opponent_side]
229
+ team_runs = score_for_side(game, side)
230
+ opponent_runs = score_for_side(game, opponent_side)
231
+ return {
232
+ "season": SEASON,
233
+ "game_pk": game["gamePk"],
234
+ "game_date": game["gameDate"],
235
+ "team": {"id": team_id, "name": team["name"], "side": side},
236
+ "opponent": {"id": opponent_id, "name": opponent["name"], "side": opponent_side},
237
+ "score": {
238
+ "team_runs": team_runs,
239
+ "opponent_runs": opponent_runs,
240
+ "result": result_for(team_runs, opponent_runs),
241
+ },
242
+ "team_game": {
243
+ "batting": compact_stat_dict(team_box.get("teamStats", {}).get("batting", {})),
244
+ "pitching": compact_stat_dict(team_box.get("teamStats", {}).get("pitching", {})),
245
+ "fielding": compact_stat_dict(team_box.get("teamStats", {}).get("fielding", {})),
246
+ },
247
+ "opponent_game": {
248
+ "batting": compact_stat_dict(opponent_box.get("teamStats", {}).get("batting", {})),
249
+ "pitching": compact_stat_dict(opponent_box.get("teamStats", {}).get("pitching", {})),
250
+ "fielding": compact_stat_dict(opponent_box.get("teamStats", {}).get("fielding", {})),
251
+ },
252
+ "team_season": team_stats.get(team_id, {}),
253
+ "opponent_season": team_stats.get(opponent_id, {}),
254
+ }
255
+
256
+
257
+ def build_messages(payload: dict[str, Any]) -> list[dict[str, str]]:
258
+ team = payload["team"]["name"]
259
+ opponent = payload["opponent"]["name"]
260
+ game_date = payload["game_date"][:10]
261
+ return [
262
+ {
263
+ "role": "system",
264
+ "content": (
265
+ "You are an MLB matchup analyst. Use only the supplied 2025 MLB Stats API "
266
+ "facts and answer in compact JSON."
267
+ ),
268
+ },
269
+ {
270
+ "role": "user",
271
+ "content": (
272
+ f"Build a pitching and offense matchup brief for {team} vs {opponent} "
273
+ f"on {game_date}."
274
+ ),
275
+ },
276
+ {"role": "assistant", "content": json_dumps(payload)},
277
+ ]
278
+
279
+
280
+ def build_rows(
281
+ games: list[dict[str, Any]],
282
+ team_stats: dict[int, dict[str, dict[str, Any]]],
283
+ client: MlbApiClient,
284
+ limit_games: int | None,
285
+ ) -> list[dict[str, Any]]:
286
+ rows: list[dict[str, Any]] = []
287
+ selected_games = games[:limit_games] if limit_games else games
288
+ for index, game in enumerate(selected_games, start=1):
289
+ if index == 1 or index % 100 == 0 or index == len(selected_games):
290
+ print(f"fetching boxscores {index}/{len(selected_games)} gamePk={game['gamePk']}")
291
+ boxscore = client.get(f"/game/{game['gamePk']}/boxscore")
292
+ for side, opponent_side in (("away", "home"), ("home", "away")):
293
+ payload = matchup_assistant_payload(game, side, opponent_side, team_stats, boxscore)
294
+ team = payload["team"]
295
+ opponent = payload["opponent"]
296
+ team_runs = payload["score"]["team_runs"]
297
+ opponent_runs = payload["score"]["opponent_runs"]
298
+ row = {
299
+ "row_id": f"mlb-2025-{game['gamePk']}-{side}",
300
+ "season": SEASON,
301
+ "game_pk": int(game["gamePk"]),
302
+ "game_date": game["gameDate"][:10],
303
+ "game_datetime_utc": game["gameDate"],
304
+ "team_id": int(team["id"]),
305
+ "team_name": team["name"],
306
+ "team_side": side,
307
+ "opponent_id": int(opponent["id"]),
308
+ "opponent_name": opponent["name"],
309
+ "opponent_side": opponent_side,
310
+ "team_runs": team_runs,
311
+ "opponent_runs": opponent_runs,
312
+ "result": payload["score"]["result"],
313
+ "messages": build_messages(payload),
314
+ "assistant_payload_json": json_dumps(payload),
315
+ "team_game_batting_json": json_dumps(payload["team_game"]["batting"]),
316
+ "team_game_pitching_json": json_dumps(payload["team_game"]["pitching"]),
317
+ "opponent_game_batting_json": json_dumps(payload["opponent_game"]["batting"]),
318
+ "opponent_game_pitching_json": json_dumps(payload["opponent_game"]["pitching"]),
319
+ "team_season_hitting_json": json_dumps(payload["team_season"].get("hitting", {})),
320
+ "team_season_pitching_json": json_dumps(payload["team_season"].get("pitching", {})),
321
+ "opponent_season_hitting_json": json_dumps(
322
+ payload["opponent_season"].get("hitting", {})
323
+ ),
324
+ "opponent_season_pitching_json": json_dumps(
325
+ payload["opponent_season"].get("pitching", {})
326
+ ),
327
+ }
328
+ rows.append(row)
329
+ return rows
330
+
331
+
332
+ def write_parquet(rows: list[dict[str, Any]], output_path: Path) -> None:
333
+ output_path.parent.mkdir(parents=True, exist_ok=True)
334
+ schema = pa.schema(
335
+ [
336
+ ("row_id", pa.string()),
337
+ ("season", pa.int16()),
338
+ ("game_pk", pa.int64()),
339
+ ("game_date", pa.string()),
340
+ ("game_datetime_utc", pa.string()),
341
+ ("team_id", pa.int64()),
342
+ ("team_name", pa.string()),
343
+ ("team_side", pa.string()),
344
+ ("opponent_id", pa.int64()),
345
+ ("opponent_name", pa.string()),
346
+ ("opponent_side", pa.string()),
347
+ ("team_runs", pa.int16()),
348
+ ("opponent_runs", pa.int16()),
349
+ ("result", pa.string()),
350
+ (
351
+ "messages",
352
+ pa.list_(pa.struct([("role", pa.string()), ("content", pa.string())])),
353
+ ),
354
+ ("assistant_payload_json", pa.string()),
355
+ ("team_game_batting_json", pa.string()),
356
+ ("team_game_pitching_json", pa.string()),
357
+ ("opponent_game_batting_json", pa.string()),
358
+ ("opponent_game_pitching_json", pa.string()),
359
+ ("team_season_hitting_json", pa.string()),
360
+ ("team_season_pitching_json", pa.string()),
361
+ ("opponent_season_hitting_json", pa.string()),
362
+ ("opponent_season_pitching_json", pa.string()),
363
+ ]
364
+ )
365
+ table = pa.Table.from_pylist(rows, schema=schema)
366
+ pq.write_table(table, output_path, compression="zstd")
367
+
368
+
369
+ def write_manifest(
370
+ manifest_path: Path,
371
+ output_path: Path,
372
+ games: list[dict[str, Any]],
373
+ rows: list[dict[str, Any]],
374
+ client: MlbApiClient,
375
+ ) -> None:
376
+ manifest = {
377
+ "created_at": datetime.now(timezone.utc).isoformat(),
378
+ "season": SEASON,
379
+ "source": "https://statsapi.mlb.com/api/v1",
380
+ "regular_season_final_games": len(games),
381
+ "rows": len(rows),
382
+ "output_path": str(output_path),
383
+ "api_metrics": client.metrics.__dict__,
384
+ }
385
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
386
+ manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True))
387
+
388
+
389
+ def parse_args() -> argparse.Namespace:
390
+ parser = argparse.ArgumentParser(description=__doc__)
391
+ parser.add_argument("--start-date", default=DEFAULT_START)
392
+ parser.add_argument("--end-date", default=DEFAULT_END)
393
+ parser.add_argument("--cache-dir", type=Path, default=Path(".cache/mlb_api"))
394
+ parser.add_argument(
395
+ "--output",
396
+ type=Path,
397
+ default=Path("data/processed/mlb_2025_chatml_matchups.parquet"),
398
+ )
399
+ parser.add_argument(
400
+ "--manifest",
401
+ type=Path,
402
+ default=Path("data/processed/mlb_2025_chatml_matchups.manifest.json"),
403
+ )
404
+ parser.add_argument("--max-rps", type=float, default=4.0)
405
+ parser.add_argument("--force-refresh", action="store_true")
406
+ parser.add_argument("--limit-games", type=int, default=None)
407
+ return parser.parse_args()
408
+
409
+
410
+ def main() -> None:
411
+ args = parse_args()
412
+ client = MlbApiClient(
413
+ cache_dir=args.cache_dir,
414
+ max_rps=args.max_rps,
415
+ force_refresh=args.force_refresh,
416
+ )
417
+ games = load_schedule(client, args.start_date, args.end_date)
418
+ print(f"loaded {len(games)} final regular-season games")
419
+ team_stats = load_season_team_stats(client)
420
+ if len(team_stats) != 30:
421
+ raise RuntimeError(f"expected 30 teams with season stats, got {len(team_stats)}")
422
+ rows = build_rows(games, team_stats, client, args.limit_games)
423
+ if not rows:
424
+ raise RuntimeError("no rows built")
425
+ write_parquet(rows, args.output)
426
+ write_manifest(args.manifest, args.output, games, rows, client)
427
+ print(f"wrote {len(rows)} rows to {args.output}")
428
+ print(f"api metrics: {client.metrics.__dict__}")
429
+
430
+
431
+ if __name__ == "__main__":
432
+ main()
scripts/verify_dataset.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import pyarrow.parquet as pq
9
+
10
+ from build_dataset import MlbApiClient, load_schedule
11
+
12
+
13
+ def parse_args() -> argparse.Namespace:
14
+ parser = argparse.ArgumentParser(description="Verify the generated MLB ChatML parquet dataset.")
15
+ parser.add_argument(
16
+ "--parquet",
17
+ type=Path,
18
+ default=Path("data/processed/mlb_2025_chatml_matchups.parquet"),
19
+ )
20
+ parser.add_argument("--cache-dir", type=Path, default=Path(".cache/mlb_api"))
21
+ parser.add_argument("--max-rps", type=float, default=4.0)
22
+ return parser.parse_args()
23
+
24
+
25
+ def main() -> None:
26
+ args = parse_args()
27
+ if not args.parquet.exists():
28
+ raise SystemExit(f"missing parquet file: {args.parquet}")
29
+
30
+ table = pq.read_table(args.parquet)
31
+ rows = table.to_pylist()
32
+ client = MlbApiClient(cache_dir=args.cache_dir, max_rps=args.max_rps)
33
+ games = load_schedule(client, "2025-03-01", "2025-11-30")
34
+ expected_rows = len(games) * 2
35
+
36
+ row_ids = [row["row_id"] for row in rows]
37
+ game_pks = {row["game_pk"] for row in rows}
38
+ team_ids = {row["team_id"] for row in rows}
39
+ bad_messages = [
40
+ row["row_id"]
41
+ for row in rows
42
+ if [message["role"] for message in row["messages"]] != ["system", "user", "assistant"]
43
+ ]
44
+ missing_pitching = [
45
+ row["row_id"]
46
+ for row in rows
47
+ if not json.loads(row["team_game_pitching_json"])
48
+ or not json.loads(row["team_season_pitching_json"])
49
+ or not json.loads(row["opponent_game_pitching_json"])
50
+ ]
51
+
52
+ checks = {
53
+ "rows_match_schedule_x2": len(rows) == expected_rows,
54
+ "unique_row_ids": len(row_ids) == len(set(row_ids)),
55
+ "all_games_present": len(game_pks) == len(games),
56
+ "all_30_teams_present": len(team_ids) == 30,
57
+ "chatml_roles_valid": not bad_messages,
58
+ "pitching_fields_present": not missing_pitching,
59
+ }
60
+ print(
61
+ json.dumps(
62
+ {
63
+ "parquet": str(args.parquet),
64
+ "rows": len(rows),
65
+ "expected_rows": expected_rows,
66
+ "games": len(games),
67
+ "teams": len(team_ids),
68
+ "checks": checks,
69
+ "api_metrics": client.metrics.__dict__,
70
+ },
71
+ indent=2,
72
+ sort_keys=True,
73
+ )
74
+ )
75
+ failed = [name for name, passed in checks.items() if not passed]
76
+ if failed:
77
+ raise SystemExit(f"verification failed: {failed}")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()