Spaces:
Runtime error

Codex commited on
Commit
5b25e0e
·
1 Parent(s): 89e726d

Normalize Circa names with FanGraphs rosters

Browse files
Files changed (1) hide show
  1. src/market-scanner.js +284 -1
src/market-scanner.js CHANGED
@@ -60,6 +60,65 @@ const CIRCA_MARKET_ALIASES = {
60
  pitcher_strikeouts: 'pitcher_strikeouts_generic',
61
  };
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  const OCR_MARKET_PATTERNS = [
64
  { type: 'home_runs', label: 'Home Runs', pattern: /(home\s*runs?|hr\b)/i },
65
  { type: 'total_bases', label: 'Total Bases', pattern: /(total\s*bases?|tb\b)/i },
@@ -119,6 +178,228 @@ export function slugify(value) {
119
  .replace(/^-+|-+$/g, '');
120
  }
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  export function americanToImpliedProbability(oddsInput) {
123
  if (!oddsInput) {
124
  return null;
@@ -1324,11 +1605,13 @@ export async function fetchCircaEntries(config) {
1324
 
1325
  const sourceFile = await discoverCircaFileFromSharedFolder(config);
1326
  const text = await extractPdfText(sourceFile.buffer);
 
 
1327
  return {
1328
  fileName: sourceFile.fileName,
1329
  source: sourceFile.source,
1330
  text,
1331
- entries: parseCircaOcrText(text),
1332
  };
1333
  }
1334
 
 
60
  pitcher_strikeouts: 'pitcher_strikeouts_generic',
61
  };
62
 
63
+ const TEAM_ALIASES = {
64
+ KC: 'KCR',
65
+ KCR: 'KCR',
66
+ CHN: 'CHC',
67
+ CHC: 'CHC',
68
+ CHW: 'CHW',
69
+ CWS: 'CHW',
70
+ SF: 'SFG',
71
+ SFG: 'SFG',
72
+ SD: 'SDP',
73
+ SDP: 'SDP',
74
+ TB: 'TBR',
75
+ TBR: 'TBR',
76
+ WAS: 'WSN',
77
+ WSH: 'WSN',
78
+ WSN: 'WSN',
79
+ };
80
+
81
+ const FANGRAPHS_TEAM_SLUGS = {
82
+ ARI: 'd-backs',
83
+ ATL: 'braves',
84
+ ATH: 'athletics',
85
+ BAL: 'orioles',
86
+ BOS: 'red-sox',
87
+ CHC: 'cubs',
88
+ CHW: 'white-sox',
89
+ CIN: 'reds',
90
+ CLE: 'guardians',
91
+ COL: 'rockies',
92
+ DET: 'tigers',
93
+ HOU: 'astros',
94
+ KCR: 'royals',
95
+ LAA: 'angels',
96
+ LAD: 'dodgers',
97
+ MIA: 'marlins',
98
+ MIL: 'brewers',
99
+ MIN: 'twins',
100
+ NYM: 'mets',
101
+ NYY: 'yankees',
102
+ PHI: 'phillies',
103
+ PIT: 'pirates',
104
+ SDP: 'padres',
105
+ SEA: 'mariners',
106
+ SFG: 'giants',
107
+ STL: 'cardinals',
108
+ TBR: 'rays',
109
+ TEX: 'rangers',
110
+ TOR: 'blue-jays',
111
+ WSN: 'nationals',
112
+ };
113
+
114
+ const FANGRAPHS_ROSTER_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
115
+ let fanGraphsRosterCache = {
116
+ loadedAt: 0,
117
+ teams: new Map(),
118
+ allPlayers: [],
119
+ promise: null,
120
+ };
121
+
122
  const OCR_MARKET_PATTERNS = [
123
  { type: 'home_runs', label: 'Home Runs', pattern: /(home\s*runs?|hr\b)/i },
124
  { type: 'total_bases', label: 'Total Bases', pattern: /(total\s*bases?|tb\b)/i },
 
178
  .replace(/^-+|-+$/g, '');
179
  }
180
 
181
+ function normalizeTeamCode(teamCode) {
182
+ const cleaned = normalizeWhitespace(teamCode).toUpperCase();
183
+ return TEAM_ALIASES[cleaned] ?? cleaned;
184
+ }
185
+
186
+ function splitNormalizedNameParts(name) {
187
+ return normalizePlayerName(name).split(/\s+/).filter(Boolean);
188
+ }
189
+
190
+ function levenshteinDistance(left, right) {
191
+ if (left === right) {
192
+ return 0;
193
+ }
194
+
195
+ if (!left.length) {
196
+ return right.length;
197
+ }
198
+
199
+ if (!right.length) {
200
+ return left.length;
201
+ }
202
+
203
+ const previous = new Array(right.length + 1).fill(0).map((_, index) => index);
204
+ const current = new Array(right.length + 1).fill(0);
205
+
206
+ for (let i = 1; i <= left.length; i += 1) {
207
+ current[0] = i;
208
+ for (let j = 1; j <= right.length; j += 1) {
209
+ const cost = left[i - 1] === right[j - 1] ? 0 : 1;
210
+ current[j] = Math.min(
211
+ current[j - 1] + 1,
212
+ previous[j] + 1,
213
+ previous[j - 1] + cost,
214
+ );
215
+ }
216
+
217
+ for (let j = 0; j <= right.length; j += 1) {
218
+ previous[j] = current[j];
219
+ }
220
+ }
221
+
222
+ return previous[right.length];
223
+ }
224
+
225
+ function extractFanGraphsRosterPlayers(html, teamCode) {
226
+ const players = [];
227
+ const seen = new Set();
228
+ const pattern = /"dbTeam":"([^"]+)".{0,400}?"playerNameDisplay":"([^"]+)"/g;
229
+
230
+ for (const match of String(html ?? '').matchAll(pattern)) {
231
+ const dbTeam = normalizeTeamCode(match[1]);
232
+ const playerName = normalizeWhitespace(match[2]).replace(/\\u0026/g, '&');
233
+ if (dbTeam !== teamCode || !playerName) {
234
+ continue;
235
+ }
236
+
237
+ const key = normalizePlayerName(playerName);
238
+ if (!key || seen.has(key)) {
239
+ continue;
240
+ }
241
+
242
+ seen.add(key);
243
+ players.push({
244
+ team: dbTeam,
245
+ playerName,
246
+ normalizedName: key,
247
+ parts: splitNormalizedNameParts(playerName),
248
+ });
249
+ }
250
+
251
+ return players;
252
+ }
253
+
254
+ async function loadFanGraphsRosterCache(teamCodes) {
255
+ const normalizedTeamCodes = [...new Set((teamCodes ?? []).map((teamCode) => normalizeTeamCode(teamCode)).filter(Boolean))]
256
+ .filter((teamCode) => FANGRAPHS_TEAM_SLUGS[teamCode]);
257
+
258
+ const cacheIsFresh = Date.now() - fanGraphsRosterCache.loadedAt < FANGRAPHS_ROSTER_CACHE_TTL_MS;
259
+ const hasAllTeams = normalizedTeamCodes.every((teamCode) => fanGraphsRosterCache.teams.has(teamCode));
260
+ if (cacheIsFresh && hasAllTeams) {
261
+ return fanGraphsRosterCache;
262
+ }
263
+
264
+ if (fanGraphsRosterCache.promise) {
265
+ await fanGraphsRosterCache.promise;
266
+ return fanGraphsRosterCache;
267
+ }
268
+
269
+ fanGraphsRosterCache.promise = (async () => {
270
+ const nextTeams = new Map(fanGraphsRosterCache.teams);
271
+ for (const teamCode of normalizedTeamCodes) {
272
+ if (cacheIsFresh && nextTeams.has(teamCode)) {
273
+ continue;
274
+ }
275
+
276
+ const slug = FANGRAPHS_TEAM_SLUGS[teamCode];
277
+ const response = await fetch(`https://www.fangraphs.com/roster-resource/depth-charts/${slug}`);
278
+ if (!response.ok) {
279
+ continue;
280
+ }
281
+
282
+ const html = await response.text();
283
+ const players = extractFanGraphsRosterPlayers(html, teamCode);
284
+ if (players.length > 0) {
285
+ nextTeams.set(teamCode, players);
286
+ }
287
+ }
288
+
289
+ const allPlayers = dedupeBy(
290
+ [...nextTeams.values()].flat(),
291
+ (player) => `${player.team}|${player.normalizedName}`,
292
+ );
293
+
294
+ fanGraphsRosterCache = {
295
+ loadedAt: Date.now(),
296
+ teams: nextTeams,
297
+ allPlayers,
298
+ promise: null,
299
+ };
300
+ })();
301
+
302
+ try {
303
+ await fanGraphsRosterCache.promise;
304
+ } finally {
305
+ fanGraphsRosterCache.promise = null;
306
+ }
307
+
308
+ return fanGraphsRosterCache;
309
+ }
310
+
311
+ function selectBestRosterMatch(entry, candidates) {
312
+ const normalizedEntry = normalizePlayerName(entry.playerName);
313
+ const entryParts = splitNormalizedNameParts(entry.playerName);
314
+ const entryFirst = entryParts[0] ?? '';
315
+ const entryLast = entryParts.at(-1) ?? '';
316
+
317
+ let best = null;
318
+
319
+ for (const candidate of candidates) {
320
+ if (candidate.normalizedName === normalizedEntry) {
321
+ return candidate;
322
+ }
323
+
324
+ const candidateFirst = candidate.parts[0] ?? '';
325
+ const candidateLast = candidate.parts.at(-1) ?? '';
326
+ const lastDistance = levenshteinDistance(entryLast, candidateLast);
327
+ const firstDistance = levenshteinDistance(entryFirst, candidateFirst);
328
+ const fullDistance = levenshteinDistance(normalizedEntry, candidate.normalizedName);
329
+ const similarity = 1 - (fullDistance / Math.max(normalizedEntry.length, candidate.normalizedName.length, 1));
330
+ const score = (lastDistance * 5) + (firstDistance * 3) + fullDistance - (similarity * 4);
331
+
332
+ const acceptable = (
333
+ (lastDistance === 0 && firstDistance <= 3)
334
+ || (lastDistance <= 1 && similarity >= 0.72)
335
+ || (fullDistance <= 2 && similarity >= 0.7)
336
+ );
337
+
338
+ if (!acceptable) {
339
+ continue;
340
+ }
341
+
342
+ if (!best || score < best.score) {
343
+ best = { candidate, score };
344
+ }
345
+ }
346
+
347
+ return best?.candidate ?? null;
348
+ }
349
+
350
+ async function normalizeCircaEntriesWithFanGraphs(entries) {
351
+ if (!entries.length) {
352
+ return entries;
353
+ }
354
+
355
+ const teamCodes = [...new Set(entries.map((entry) => entry.team).filter(Boolean))];
356
+
357
+ try {
358
+ const rosterCache = await loadFanGraphsRosterCache(teamCodes);
359
+ return entries.map((entry) => {
360
+ const normalizedTeam = entry.team ? normalizeTeamCode(entry.team) : null;
361
+ const teamPlayers = normalizedTeam ? (rosterCache.teams.get(normalizedTeam) ?? []) : [];
362
+ const bestTeamMatch = selectBestRosterMatch(entry, teamPlayers);
363
+ const bestGlobalMatch = bestTeamMatch
364
+ ? null
365
+ : selectBestRosterMatch(entry, rosterCache.allPlayers);
366
+ const match = bestTeamMatch ?? bestGlobalMatch;
367
+
368
+ if (!match) {
369
+ return {
370
+ ...entry,
371
+ team: normalizedTeam ?? entry.team,
372
+ playerKey: normalizePlayerName(entry.playerName),
373
+ marketKey: buildMarketKey({
374
+ ...entry,
375
+ team: normalizedTeam ?? entry.team,
376
+ playerKey: normalizePlayerName(entry.playerName),
377
+ }),
378
+ };
379
+ }
380
+
381
+ const normalizedEntry = {
382
+ ...entry,
383
+ team: match.team ?? normalizedTeam ?? entry.team,
384
+ playerName: match.playerName,
385
+ playerKey: normalizePlayerName(match.playerName),
386
+ };
387
+ normalizedEntry.marketKey = buildMarketKey(normalizedEntry);
388
+ return normalizedEntry;
389
+ });
390
+ } catch (error) {
391
+ return entries.map((entry) => {
392
+ const normalizedEntry = {
393
+ ...entry,
394
+ team: entry.team ? normalizeTeamCode(entry.team) : entry.team,
395
+ playerKey: normalizePlayerName(entry.playerName),
396
+ };
397
+ normalizedEntry.marketKey = buildMarketKey(normalizedEntry);
398
+ return normalizedEntry;
399
+ });
400
+ }
401
+ }
402
+
403
  export function americanToImpliedProbability(oddsInput) {
404
  if (!oddsInput) {
405
  return null;
 
1605
 
1606
  const sourceFile = await discoverCircaFileFromSharedFolder(config);
1607
  const text = await extractPdfText(sourceFile.buffer);
1608
+ const parsedEntries = parseCircaOcrText(text);
1609
+ const normalizedEntries = await normalizeCircaEntriesWithFanGraphs(parsedEntries);
1610
  return {
1611
  fileName: sourceFile.fileName,
1612
  source: sourceFile.source,
1613
  text,
1614
+ entries: normalizedEntries,
1615
  };
1616
  }
1617