Spaces:
Running
Running
File size: 8,478 Bytes
d5ea29f ddd0be5 d5ea29f ddd0be5 d5ea29f ddd0be5 d5ea29f d8a5132 d5ea29f 79b74e3 2c641ec d5ea29f ddd0be5 d5ea29f 35cf803 ddd0be5 35cf803 d5ea29f 35cf803 d5ea29f 35cf803 d5ea29f 35cf803 2c641ec d5ea29f 2c641ec d8a5132 35cf803 d5ea29f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | export type Kind = "pass" | "route" | "carry"
export const KIND_LABEL: Record<Kind, string> = { pass: "Passing", route: "Receiving", carry: "Rushing" }
export const KIND_NOUN: Record<Kind, [string, string]> = {
pass: ["pass", "passes"],
route: ["route", "routes"],
carry: ["carry", "carries"],
}
/** what a search entry / dataset is about: one charted player, a receiver's targets from his QBs' pass charts,
* a team's plays, or the plays a defense faced (service/views.py) */
export type Subject = "player" | "rec" | "team" | "def"
export function subjectOf(p: { position?: string | null }, kind: Kind): Subject {
const pos = (p.position ?? "").toUpperCase()
if (pos === "TEAM") return "team"
if (pos === "DEF") return "def"
return kind === "pass" && pos !== "QB" ? "rec" : "player"
}
export function kindLabel(subject: Subject, kind: Kind): string {
if (subject === "rec") return "Targets"
if (subject === "def") return kind === "pass" ? "Pass D" : "Run D"
if (subject === "team" && kind === "route") return "Routes"
return KIND_LABEL[kind]
}
export interface PlayerKindStats {
games: number
[stat: string]: number
}
export interface Player {
esb_id: string
name: string
position?: string
team: string
headshot?: string | null
kinds: Partial<Record<Kind, PlayerKindStats>>
/** league-table entries (no NGS charts): a one-line summary and a volume rank for ordering */
line?: string
rank?: number
}
export type JobStatus = "queued" | "running" | "ready" | "refining" | "done" | "error"
export interface Job {
id: string
kind: Kind
name: string
season: number
status: JobStatus
stage: string
done: number
total: number
version: number
error: string | null
}
// One pass / route / carry. Matched plays carry every curated pbp field; unmatched ones only the chart's own.
export interface Play {
id: string
matched: boolean
week?: number | string | null
[field: string]: any
}
export interface Game {
week: string
game_id: number
opponent: string | null
season_type: string
[stat: string]: any
}
export interface Dataset {
kind: Kind
table: string
season: number
player: { esb_id: string; name: string; position?: string; team: string; headshot?: string | null }
games: Game[]
plays: Play[]
notes: string[]
pending?: { week: string; game_id: number; plays: number }[] // charted games nflverse hasn't published yet
counts: { charts: number; matched: number; unmatched: number; undrawn?: number }
version: number
subject?: Subject
/** views: how much of the subject's season the charts cover (games, and plays in play-by-play) */
coverage?: { games: number; charted_games: number; plays: number; charted_plays: number; drawn: number }
}
export type FilterKind = "choice" | "select" | "bool" | "range"
export interface FilterSpec {
col: string
label: string
group: string
kind: FilterKind
tables: string[]
choices: [string | number, string][] | null
since: string | null
step: number | null
help: string | null
/** false: an Ask-bar-only filter - not in the panel, and its column comes from api.columns when used */
panel?: boolean
}
export interface AskResult {
dataset: string | null
seasons: number[]
weeks: number[]
team: string | null
name: string | null
esb_id?: string | null
params: Record<string, string>
understood: { text: string; meaning: string }[]
ignored: string[]
notes: string[]
engine: string
refused?: string | null
llm_prompt?: string | null
llm_schema?: object | null
llm_messages?: { role: string; content: string }[] | null
llm_ft?: { role: string; content: string }[] | null
}
export async function json<T>(r: Response): Promise<T> {
if (!r.ok) {
let msg = r.statusText
try {
msg = (await r.json()).detail ?? msg
} catch {
/* not json */
}
throw new Error(msg)
}
return r.json() as Promise<T>
}
/** fetch for /api: the deployed server answers only this page's session; if that has expired (a tab left open,
* the server restarted), get a new one and try once more. */
export async function apiFetch(url: string, init?: RequestInit): Promise<Response> {
const r = await fetch(url, { credentials: "same-origin", ...init })
if (r.status !== 401) return r
await fetch("/session", { credentials: "same-origin" })
return fetch(url, { credentials: "same-origin", ...init })
}
export const api = {
seasons: () => apiFetch("/api/seasons").then(json<{ seasons: number[]; current: number }>),
players: (season: number) => apiFetch(`/api/players?season=${season}`).then(json<{ players: Player[] }>),
load: (kind: Kind, esb_id: string, season: number) =>
apiFetch("/api/load", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ kind, esb_id, season }),
}).then(json<Job>),
job: (id: string) => apiFetch(`/api/jobs/${id}`).then(json<Job>),
data: (id: string) => apiFetch(`/api/data/${id}`).then(json<Dataset>),
filters: (kind: Kind) => apiFetch(`/api/filters?kind=${kind}`).then(json<{ groups: string[]; filters: FilterSpec[] }>),
// llm="client": words the rules can't place come back as a prompt for the in-browser model (lib/llm.ts), whose
// answer goes to refine(); "server" asks Gemini instead
ask: (q: string, kind: Kind, season: number, job?: string, llm: "client" | "server" = "client") =>
apiFetch(`/api/ask?${new URLSearchParams({ q, kind, season: String(season), llm, ...(job ? { job } : {}) })}`).then(
json<AskResult>
),
refine: (q: string, kind: Kind, season: number, answer: Record<string, unknown>, job?: string) =>
apiFetch("/api/ask/refine", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ q, kind, season, answer, ...(job ? { job } : {}) }),
}).then(json<AskResult>),
columns: (job: string, cols: string[]) =>
apiFetch(`/api/columns/${job}?cols=${encodeURIComponent(cols.join(","))}`).then(json<Record<string, Record<string, unknown>>>),
play: (job: string, id: string) => apiFetch(`/api/play/${job}/${encodeURIComponent(id)}`).then(json<PlayDetailData>),
}
export interface Person { id: string; role: string; name?: string | null; position?: string | null; headshot?: string | null; jersey?: number | null; team?: string | null }
export interface DrivePlay { play_id: number; qtr?: number; time?: string; down?: number; ydstogo?: number; yrdln?: string; play_type?: string; yards?: number; epa?: number; desc?: string; current: boolean }
/** Everything about one play (GET /api/play/{job}/{id}); sections are absent when unknown. */
export interface PlayDetailData {
id: string
kind: Kind
matched: boolean
week?: string
chart: Record<string, any>
game?: Record<string, any>
situation?: Record<string, any>
result?: Record<string, any>
scheme?: Record<string, any>
charting?: Record<string, any>
gamecenter?: Record<string, any>
match?: Record<string, any>
people?: Person[]
drive?: { number?: number; result?: string; plays_count?: number; time?: string; first_downs?: number; start?: string; end?: string; plays: DrivePlay[] }
}
export function kindFromDataset(ds: string | null | undefined): Kind | null {
return ds === "passes" ? "pass" : ds === "routes" ? "route" : ds === "carries" ? "carry" : null
}
/** "1".."18" for the regular season; NGS labels playoff games post-19 (wild card) .. post-23 (Super Bowl). */
export function weekLabel(w: string | number | null | undefined, long = false): string {
const s = String(w ?? "")
if (!s.startsWith("post")) return long ? `Week ${s}` : s
const n = Number(s.split("-")[1])
const name = n <= 19 ? "WC" : n === 20 ? "DIV" : n === 21 ? "CONF" : "SB"
return long ? { WC: "Wild Card", DIV: "Divisional", CONF: "Conference", SB: "Super Bowl" }[name]! : name
}
/** Why a drawn line has no play: never matched, or matched to nothing that fits (likely a misread line). */
export function unmatchedText(play: Play) {
if (play.reason !== "no_fit") return "Drawn on the chart, but no play-by-play row could be matched to it."
const end = Array.isArray(play.path_y) && play.path_y.length ? play.path_y[play.path_y.length - 1] : null
return `No run in play-by-play fits this line${end != null ? ` (it ends ${Number(end).toFixed(1)} yds past the line of scrimmage)` : ""} - most likely a misread chart: a short run hidden under a longer one, read as a branch of it.`
}
|