// The frame scan's first profile: an online poker client on a stream // (release 30, lane P). A vision model reads each kept frame into a POKER // READING — what the client shows, every field optional and never invented — // and pure code derives the rest: the series per tournament (chips, big // blinds, players left, level), the events (a double-up, a bust, the final // table…), the phase segments, and the flags where a spoken number disagrees // with what a frame read. // // The model reads a frame; code derives everything else (the brief's rule). // Counts, ranges and enums are enforced here, in `coercePokerReading`, never // trusted from the prompt. import { pokerSpoken } from "./pokerSpoken"; import { agree, changesOnly, dropExcursions, dropMisreads, ratioOf, type AgreeRule, type Pt } from "./series"; import { clock, fmtNum, type Derived, type DerivedEvent, type DerivedFlag, type DerivedSegment, type DerivedTournament, type FrameProfile, type SeriesPoint, type SpokenReading, } from "./types"; export const POKER_PHASES = ["lobby", "table", "break", "other"] as const; export type PokerPhase = (typeof POKER_PHASES)[number]; export const POKER_FRAME_EVENTS = ["all-in", "bust", "double-up", "final-table", "eliminated", "won"] as const; export type PokerFrameEvent = (typeof POKER_FRAME_EVENTS)[number]; export type PokerReading = { phase: PokerPhase; tournament?: { name?: string; level?: number; blinds?: { sb?: number; bb?: number; ante?: number }; playersLeft?: number; totalPlayers?: number; prizePool?: number; position?: number; payout?: number; averageStack?: number; }; hero?: { stack?: number; bb?: number; seat?: number; cards?: string[]; bounty?: number }; hand?: { number?: number; pot?: number; board?: string[]; action?: string }; // The client's dealer/chat log lines as shown, oldest first (code reads // the hero's pots, knockouts, a bust and the blinds out of them). log?: string[]; event?: PokerFrameEvent; }; // ─── The ask ─── const num = { type: ["number", "null"] } as const; const int = { type: ["integer", "null"] } as const; const str = { type: ["string", "null"] } as const; const cards = { type: ["array", "null"], items: { type: "string" } } as const; const READING_SCHEMA = { type: "object", properties: { frame: { type: "integer" }, phase: { type: "string", enum: [...POKER_PHASES] }, tournament: { type: "object", properties: { name: str, level: int, smallBlind: num, bigBlind: num, ante: num, playersLeft: int, totalPlayers: int, prizePool: num, position: int, payout: num, averageStack: num, }, }, hero: { type: "object", properties: { stack: num, stackInBigBlinds: num, seat: int, cards, bounty: num }, }, hand: { type: "object", properties: { number: int, pot: num, board: cards, action: str }, }, log: { type: ["array", "null"], items: { type: "string" } }, event: { type: ["string", "null"], enum: [...POKER_FRAME_EVENTS, null] }, }, required: ["frame", "phase"], } as const; export function pokerSchema(n: number): object { return { type: "object", properties: { frames: { type: "array", items: READING_SCHEMA, minItems: n, maxItems: n } }, required: ["frames"], }; } // Rules only (Q0): no worked examples, no sample readings. export function pokerSystem(hints: { hero?: string } = {}): string { return [ "You read screenshots from a livestream of online poker and report what the poker client shows, as data.", "Rules:", "- Report only what is legible in that frame. A field that is not shown, cut off or unreadable is null. Never guess, never carry a value over from another frame, never compute a value the screen does not show.", "- Numbers are plain numbers: chips as whole chips (expand K and M suffixes), money in dollars, no separators.", "- phase: table when a poker table in play is the main picture; lobby for a tournament lobby, a tournament list, a registration or a results screen; break when the table shows a break or a resume countdown, or a paused or starting-soon screen; other for anything else (a camera, a desktop, a browser, a chat).", `- The hero is the streamer's own player: the seat whose hole cards are shown face up, usually at the bottom of the table.${hints.hero ? ` The hero's screen name is "${hints.hero}".` : ""}`, "- A seat's name box may show the player's last action (FOLD, CHECK, CALL) in place of the name for a moment; the seat is still that player's.", "- hero.stack is the hero's chip count; hero.stackInBigBlinds only when the client itself shows the stack in big blinds; hero.cards the hero's hole cards.", "- Cards are rank then suit, one character each: ranks 2-9, T, J, Q, K, A; suits s, h, d, c.", "- tournament.name is the tournament's title as the client shows it (a lobby title, a stats header, or the name printed on the table felt); level the blind level's number; smallBlind, bigBlind and ante the current blinds; position the hero's rank and playersLeft the players remaining, as in a \"position N of M\" display; totalPlayers the field at the start, when shown apart; averageStack the average stack when shown; payout the money the hero has won or is guaranteed, when shown; prizePool when shown.", "- hero.bounty is the bounty shown on the hero's own seat (a knockout tournament), in dollars.", "- log is the client's dealer or chat log as shown on screen, one string per line, oldest first, copied as written (names, numbers and punctuation); null when no log is shown.", "- hand.pot is the pot in chips; hand.board the community cards; hand.action a few words for the action shown (a bet, a raise, an all-in), or null.", "- event is set only when the screen shows it in words or a banner: all-in, bust or eliminated (the hero is out), double-up, final-table, won (the hero won the tournament). Otherwise null.", "- Frames come in time order, numbered from 1. Answer one reading per frame, in order, each read on its own.", ].join("\n"); } export function pokerUser(frames: { t: number }[]): string { return `${frames.length} frame${frames.length === 1 ? "" : "s"}, in order: ${frames.map((f, i) => `frame ${i + 1} at ${clock(f.t)}`).join("; ")}. Read each.`; } // ─── The reading, cleaned ─── const isObj = (v: unknown): v is Record => !!v && typeof v === "object" && !Array.isArray(v); const nonNeg = (v: unknown, max = 1e12): number | undefined => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= max ? v : undefined; const whole = (v: unknown, max = 1e12): number | undefined => { const n = nonNeg(v, max); return n === undefined ? undefined : Math.round(n); }; const CARD = /^(?:[2-9TJQKA])[shdc]$/; function cardList(v: unknown, max: number): string[] | undefined { if (!Array.isArray(v)) return undefined; const out = v .filter((c): c is string => typeof c === "string") .map((c) => c.trim().replace(/^10/, "T")) .map((c) => (c.length === 2 ? c[0].toUpperCase() + c[1].toLowerCase() : c)) .filter((c) => CARD.test(c)); return out.length && out.length <= max && new Set(out).size === out.length ? out : undefined; } const prune = >(o: T): T | undefined => { for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k]; return Object.keys(o).length ? o : undefined; }; /** A model's reading as a PokerReading, every field checked; null when it is not a reading. */ const logLines = (v: unknown): string[] | undefined => { if (!Array.isArray(v)) return undefined; const out = v .filter((l): l is string => typeof l === "string") .map((l) => l.replace(/\s+/g, " ").trim().slice(0, 200)) .filter(Boolean) .slice(-8); return out.length ? out : undefined; }; export function coercePokerReading(raw: unknown): PokerReading | null { if (!isObj(raw)) return null; const phase = typeof raw.phase === "string" && (POKER_PHASES as readonly string[]).includes(raw.phase) ? (raw.phase as PokerPhase) : null; if (!phase) return null; const out: PokerReading = { phase }; const t = isObj(raw.tournament) ? raw.tournament : null; if (t) { const blinds = prune({ sb: nonNeg(t.smallBlind), bb: nonNeg(t.bigBlind), ante: nonNeg(t.ante) }); // A big blind under the small one is a misread pair: neither is kept. const okBlinds = blinds && !(blinds.sb !== undefined && blinds.bb !== undefined && blinds.bb < blinds.sb) ? blinds : undefined; const name = typeof t.name === "string" ? t.name.replace(/\s+/g, " ").trim().slice(0, 120) : ""; const tour = prune({ name: name || undefined, level: whole(t.level, 500), blinds: okBlinds, playersLeft: whole(t.playersLeft, 10_000_000), totalPlayers: whole(t.totalPlayers, 10_000_000), prizePool: nonNeg(t.prizePool), position: whole(t.position, 10_000_000), payout: nonNeg(t.payout), averageStack: whole(t.averageStack), }); // Players left over the field is a misread pair: the field is dropped. if (tour && tour.playersLeft !== undefined && tour.totalPlayers !== undefined && tour.playersLeft > tour.totalPlayers) delete tour.totalPlayers; if (tour) out.tournament = tour; } const h = isObj(raw.hero) ? raw.hero : null; if (h) { const hero = prune({ stack: whole(h.stack), bb: nonNeg(h.stackInBigBlinds ?? h.bb, 1_000_000), seat: whole(h.seat, 12), cards: cardList(h.cards, 6), bounty: nonNeg(h.bounty, 1e9) }); if (hero) out.hero = hero; } const hd = isObj(raw.hand) ? raw.hand : null; if (hd) { const action = typeof hd.action === "string" ? hd.action.replace(/\s+/g, " ").trim().slice(0, 80) : ""; const hand = prune({ number: whole(hd.number), pot: whole(hd.pot), board: cardList(hd.board, 5), action: action || undefined }); if (hand) out.hand = hand; } const log = logLines(raw.log); if (log) out.log = log; if (typeof raw.event === "string" && (POKER_FRAME_EVENTS as readonly string[]).includes(raw.event)) out.event = raw.event as PokerFrameEvent; return out; } // ─── Derivation (pure) ─── type R = PokerReading & { t: number }; // How two readings of a field must agree to call a third a misread, and a // spoken number a frame's. const MISREAD: Record = { stack: { ratio: 3 }, stackBB: { ratio: 3 }, playersLeft: { ratio: 1.5, absolute: 3 }, level: { ratio: 1.5, absolute: 1 }, position: { ratio: 2, absolute: 5 }, averageStack: { ratio: 2 }, bigBlind: { ratio: 2.5 }, }; const SPOKEN_AGREE: Record = { stack: { ratio: 1.3 }, stackBB: { ratio: 1.3, absolute: 2 }, playersLeft: { ratio: 1.15, absolute: 2 }, level: { ratio: 1, absolute: 1 }, position: { ratio: 1.2, absolute: 3 }, averageStack: { ratio: 1.3 }, bigBlind: { ratio: 1.01 }, }; // Spoken fields that are series; the rest are facts. const SPOKEN_SERIES = new Set(["stack", "stackBB", "playersLeft", "level", "position", "averageStack", "bigBlind"]); const SPOKEN_WINDOW_S = 90; /** Players left at or under which the hero is at the final table. */ export const FINAL_TABLE = 9; /** * The players-left milestones (release 31), crossed once each per * tournament: the first header reading at or under one after the LAST * reading over it (players left never rise, so a reading over it later * means the earlier crossing was a misread). The final table is the last. */ export const PLAYERS_LEFT_MILESTONES = [100, 50, 27, 18] as const; /** A pot the hero takes of this many big blinds or more is a `big-pot`. */ export const BIG_POT_BB = 25; /** A hero pot line within this window, its size within SAME_POT_RATIO of an earlier one, is that line misread. */ const SAME_POT = { windowS: 180, ratio: 1.01 }; /** How long after an all-in the stack readings are looked at for its outcome. */ export const ALL_IN_OUTCOME_WINDOW_S = 180; /** All-in signals this close together are one all-in (the same hand). */ const ALL_IN_SAME_HAND_S = 60; const normName = (s: string) => s.toLowerCase().replace(/[^a-z0-9$]+/g, " ").trim(); const squash = (s: string) => normName(s).replace(/ /g, ""); // ─── Which tournament a reading is in ─── // // A name read off the screen is NOT evidence of another tournament: the model // puts a hand description from the log ("Three of a Kind Eights"), a seat's // name or a misread of the title ("VENOM NLH10", "NLHKAO") in the field now // and then. So a tournament changes only where the hero's own chips say so — // after a CONFIRMED bust (a stack of 0 held, or with a bust banner or the // hero's "has finished the tournament" line beside it), a screen away from the // table, and chips in front of the hero again. Between two such points every // reading is one tournament, and its name is the title most of its readings // agree on (below). const HAND_WORDS = /\b(pair|two pair|three of a kind|four of a kind|full house|flush|straight|royal|high card|kicker|high|with|takes|pot|wins|chips?)\b/i; /** Levenshtein distance (small strings). */ function editDistance(a: string, b: string): number { const row = Array.from({ length: b.length + 1 }, (_, j) => j); for (let i = 1; i <= a.length; i++) { let prev = row[0]; row[0] = i; for (let j = 1; j <= b.length; j++) { const cur = row[j]; row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = cur; } } return row[b.length]; } /** How alike two names are, 0..1 (1 − edit distance over the longer, on letters and digits only). */ export function nameSimilarity(a: string, b: string): number { const x = squash(a); const y = squash(b); if (!x || !y) return 0; return 1 - editDistance(x, y) / Math.max(x.length, y.length); } // Every player name a log shows ("Dealer: X takes the pot…", "X has finished // the tournament…", "X knocked out Y"): a name read as the title that matches // one of them is a seat, not the tournament. function speakersOf(rs: readonly R[]): string[] { const out = new Set(); for (const r of rs) for (const line of r.log ?? []) { const m = /^(?:dealer:\s*)?(.+?) (?:takes the|has finished the tournament|knocked out|knocks out|wins|is eliminated|was eliminated)\b/i.exec(line); if (m && m[1].length <= 40) out.add(m[1]); } return [...out]; } /** Whether a name read as the tournament's could be a title: not a hand, a seat or the hero. */ export function looksLikeTitle(name: string, o: { hero?: string; speakers?: readonly string[] } = {}): boolean { const n = normName(name); if (!/[a-z]/.test(n) || n.length < 2) return false; if (HAND_WORDS.test(name)) return false; if (o.hero && nameSimilarity(name, o.hero) >= 0.75) return false; if ((o.speakers ?? []).some((sp) => nameSimilarity(name, sp) >= 0.75)) return false; return true; } /** * The title a set of names agrees on: names clustered (one's words the start * of the other's — "VENOM" and "VENOM NLH PKO" — or 75% alike as letters), * the cluster read most often wins if read at least `min` times (or it is the * only one), and it is named by its most frequent spelling. Null when no * cluster is read enough. */ export function canonicalTitle(names: readonly string[], min = 3): string | null { // Spellings that differ only in case and punctuation are one name, shown // as its most frequent spelling. const counts = new Map(); const spellings = new Map>(); for (const n of names) { const k = normName(n); counts.set(k, (counts.get(k) ?? 0) + 1); const sp = spellings.get(k) ?? new Map(); sp.set(n, (sp.get(n) ?? 0) + 1); spellings.set(k, sp); } const shown = (k: string) => [...(spellings.get(k) ?? new Map())].sort((a, b) => b[1] - a[1])[0]?.[0] ?? k; const byCount = [...counts].sort((a, b) => b[1] - a[1] || a[0].length - b[0].length); const clusters: { members: [string, number][] }[] = []; const joins = (a: string, b: string) => { const x = normName(a); const y = normName(b); return x === y || x.startsWith(`${y} `) || y.startsWith(`${x} `) || nameSimilarity(a, b) >= 0.75; }; for (const [n, c] of byCount) { const home = clusters.find((cl) => cl.members.some(([m]) => joins(m, n))); if (home) home.members.push([n, c]); else clusters.push({ members: [[n, c]] }); } const scored = clusters.map((cl) => ({ total: cl.members.reduce((s, [, c]) => s + c, 0), top: cl.members[0][0] })).sort((a, b) => b.total - a.total); // Read enough times, or the only title read at all. return scored[0] && (scored[0].total >= min || scored.length === 1) ? shown(scored[0].top) : null; } const HERO_FINISHED = (hero: string) => new RegExp(`^(?:dealer:\\s*)?${hero.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} has finished the tournament`, "i"); // The confirmed busts: the index of the reading where the hero is out. function confirmedBusts(rs: readonly R[], hero?: string): Set { const out = new Set(); const finished = hero ? HERO_FINISHED(hero) : null; rs.forEach((r, i) => { if (r.hero?.stack !== 0) return; // The readings either side: a 0 held on the next or the last, or a bust // banner on it or beside it; or the hero's own finishing line within a minute. const beside = [rs[i - 1], rs[i + 1]].filter((x): x is R => !!x); const held = beside.some((x) => x.hero?.stack === 0); const banner = [r, ...beside].some((x) => x.event === "bust" || x.event === "eliminated"); const said = finished ? rs.some((x) => Math.abs(x.t - r.t) <= 60 && (x.log ?? []).some((l) => finished.test(l))) : false; if (held || banner || said) out.add(i); }); return out; } function keyReadings(rs: readonly R[], hero?: string): { keys: (string | null)[]; names: Map } { const busts = confirmedBusts(rs, hero); // Generations: a new one after a confirmed bust, a screen away from the // table, and chips in front of the hero again. const gen: (number | null)[] = []; let g = 1; let out = false; let away = false; rs.forEach((r, i) => { if (r.phase !== "table") away = true; if (out && away && r.phase === "table" && (r.hero?.stack ?? 0) > 0) { g++; out = false; } if (busts.has(i)) { out = true; away = false; } gen.push(r.phase === "table" || r.phase === "lobby" ? g : null); }); const speakers = speakersOf(rs); const names = new Map(); const keyOfGen = new Map(); const used = new Set(); for (const n of [...new Set(gen.filter((x): x is number => x !== null))]) { const titles = rs.filter((_, i) => gen[i] === n).map((r) => r.tournament?.name).filter((x): x is string => !!x && looksLikeTitle(x, { hero, speakers })); const title = canonicalTitle(titles); let key = title ? normName(title) : "tournament"; if (used.has(key)) { let k = 2; while (used.has(`${key}#${k}`)) k++; key = `${key}#${k}`; } used.add(key); keyOfGen.set(n, key); if (title) names.set(key, title); } return { keys: gen.map((n) => (n === null ? null : keyOfGen.get(n)!)), names }; } // ─── What a reading's fields may be taken as ─── // Players left is the tournament's only from the stats header ("Your position // N of M": both numbers on one reading, the position within the field) or from // the log's finishing places. A count beside a table's seats ("7 of 7") or a // number with no position beside it is not the field. function headerPlayersLeft(r: R): number | undefined { const t = r.tournament; if (t?.playersLeft === undefined || t.position === undefined) return undefined; if (t.position > t.playersLeft) return undefined; if (t.totalPlayers !== undefined && t.totalPlayers <= 10 && t.playersLeft <= 10) return undefined; return t.playersLeft; } function finishedPlayersLeft(r: R): number | undefined { const places = (r.log ?? []).map((l) => FINISHED_LINE.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => Number(m[1])); const low = places.length ? Math.min(...places) : 0; return low > 1 ? low - 1 : undefined; } const logBlindsOf = (r: R): { sb: number; bb: number } | null => { for (let i = (r.log?.length ?? 0) - 1; i >= 0; i--) { const m = BLINDS_LINE.exec(r.log![i]); if (!m) continue; const sb = digits(m[1]); const bb = digits(m[2]); return sb > 0 && bb >= sb ? { sb, bb } : null; } return null; }; // Players left never rise (a late registration adds a few, not half the // field): a reading followed within ten minutes by one more than 1.5× and 3 // larger is a misread (a table's seats, a rank read as the field). function fieldOnlyFalls(points: readonly Pt[], misreads: Derived["misreads"]): Pt[] { return points.filter((p, i) => { const later = points.slice(i + 1).some((q) => q.t - p.t <= 600 && q.v > p.v * 1.5 && q.v - p.v > 3); if (later) misreads.push({ t: p.t, field: "playersLeft", value: p.v }); return !later; }); } // Stack changes judged against: a level left and returned to within this // window is not a change (a mid-hand reading, a misread). const EXCURSION = { returnRatio: 1.1, windowS: 90 }; // A double-up's or a big loss's new level is held by the reading after it. const HELD: AgreeRule = { ratio: 1.25 }; /** * Readings (and spoken numbers) to tournaments with series, events, phase * segments and flags. Pure; heavily tested (poker.test.ts, pokerDerive.test.ts). */ export function derivePoker(readingsIn: readonly R[], spoken: readonly SpokenReading[], o: { everySeconds: number; durationSeconds?: number; hero?: string }): Derived { const rs = [...readingsIn].sort((a, b) => a.t - b.t); const segments = phaseSegments(rs, o); const { keys, names } = keyReadings(rs, o.hero); const misreads: Derived["misreads"] = []; const byKey = new Map(); rs.forEach((_, i) => { const k = keys[i]; if (!k) return; if (!byKey.has(k)) byKey.set(k, []); byKey.get(k)!.push(i); }); const tournaments: DerivedTournament[] = []; // Every kept point per tournament and field (not collapsed to changes): the // events judge a change by the reading after it. const full = new Map>(); for (const [key, idx] of byKey) { const list = idx.map((i) => rs[i]); const raw: Record = { stack: [], playersLeft: [], level: [], position: [], averageStack: [], bigBlind: [], shownBB: [] }; // THE BLINDS: the log's "Blinds are now a/b" is the truth and holds until // the next one; a big blind read off the table that disagrees with it by // more than 2× is a misread. Before the log has said any, the reads. // Blinds only go up within a tournament: before the log has said any, a // read lower than the last one kept, or higher than the first the log // will say, is a misread (an ante or a small blind read as the big). // A logged big blind that a LATER line puts lower is that line misread // (blinds only go up; release 31): set aside, the last good one held. const read = list.map(logBlindsOf); const lines = read.map((b, j) => (b && read.slice(j + 1).some((x) => x !== null && x.bb < b.bb) ? null : b)); // Recorded once per run of the line (it scrolls on the next readings). read.forEach((b, j) => { if (b && !lines[j] && read[j - 1]?.bb !== b.bb) misreads.push({ t: list[j].t, field: "bigBlind", value: b.bb }); }); let logged: { sb: number; bb: number } | null = null; const firstLogged = lines.find((b) => b !== null)?.bb; let lastRead = 0; for (const [j, r] of list.entries()) { logged = lines[j] ?? logged; const read = r.tournament?.blinds?.bb; if (logged) { if (read !== undefined && ratioOf(read, logged.bb) > 2) misreads.push({ t: r.t, field: "bigBlind", value: read }); raw.bigBlind.push({ t: r.t, v: logged.bb }); } else if (read !== undefined) { if (read < lastRead || (firstLogged !== undefined && read > firstLogged)) misreads.push({ t: r.t, field: "bigBlind", value: read }); else { raw.bigBlind.push({ t: r.t, v: read }); lastRead = read; } } if (r.hero?.stack !== undefined) raw.stack.push({ t: r.t, v: r.hero.stack }); if (r.hero?.bb !== undefined) raw.shownBB.push({ t: r.t, v: r.hero.bb }); const left = headerPlayersLeft(r) ?? finishedPlayersLeft(r); if (left !== undefined) raw.playersLeft.push({ t: r.t, v: left }); if (r.tournament?.level !== undefined) raw.level.push({ t: r.t, v: r.tournament.level }); if (r.tournament?.position !== undefined && headerPlayersLeft(r) !== undefined) raw.position.push({ t: r.t, v: r.tournament.position }); if (r.tournament?.averageStack !== undefined) raw.averageStack.push({ t: r.t, v: r.tournament.averageStack }); } const points: Record = {}; const keep = (field: string, ps: Pt[], excursions = false) => { let cur = ps; if (excursions) { const ex = dropExcursions(cur, EXCURSION); for (const d of ex.dropped) misreads.push({ t: d.t, field, value: d.v }); cur = ex.kept; } const { kept, dropped } = dropMisreads(cur, MISREAD[field]); for (const d of dropped) misreads.push({ t: d.t, field, value: d.v }); points[field] = kept; }; keep("stack", raw.stack, true); keep("bigBlind", raw.bigBlind); keep("playersLeft", fieldOnlyFalls(raw.playersLeft, misreads)); keep("level", raw.level); keep("position", raw.position); keep("averageStack", raw.averageStack); // Stack in big blinds: the client's own figure where it shows one, else // the kept stack over the big blind of its moment. const shown = new Map(raw.shownBB.map((p) => [p.t, p.v])); points.stackBB = points.stack .map((p) => { const s = shown.get(p.t); if (s !== undefined) return { t: p.t, v: s }; const bb = nearestBefore(points.bigBlind, p.t); return bb ? { t: p.t, v: Math.round((p.v / bb) * 10) / 10 } : null; }) .filter((p): p is Pt => p !== null); const series: Record = {}; for (const f of ["stack", "stackBB", "playersLeft", "level", "position", "averageStack", "bigBlind"]) series[f] = changesOnly(points[f] ?? []).map((p) => [p.t, p.v] as SeriesPoint); full.set(key, points); const facts: Record = {}; for (const r of list) { const t = r.tournament; // The field at the start, when shown apart and larger than a table. if (t?.totalPlayers !== undefined && t.totalPlayers > 10) facts.totalPlayers = t.totalPlayers; if (t?.prizePool !== undefined) facts.prizePool = t.prizePool; if (t?.payout !== undefined) facts.payout = t.payout; if (t?.position !== undefined && headerPlayersLeft(r) !== undefined) facts.position = t.position; } const tour: DerivedTournament = { key, from: list[0].t, to: list[list.length - 1].t + o.everySeconds, series, facts }; const name = names.get(key); if (name) tour.name = name; tournaments.push(tour); } tournaments.sort((a, b) => a.from - b.from); const { flags, flagged } = crossCheck(tournaments, full, spoken); // Segments say which tournament they are in, when one covers them. for (const s of segments) { const tour = tournaments.find((t) => s.from >= t.from && s.from < t.to); if (tour && (s.phase === "table" || s.phase === "lobby")) s.tournament = tour.key; } const events = [ ...frameEvents(rs, keys, full), ...seriesEvents(tournaments, full, flagged), ...milestoneEvents(tournaments, full, flagged), ...logEvents(rs, keys, full, o.hero), ...levelEvents(rs, keys, full), ...allInEvents(rs, keys, full, flagged, o.hero), ...spokenEvents(spoken), ].sort((a, b) => a.t - b.t || a.kind.localeCompare(b.kind)); return { tournaments, events, segments, flags, misreads: misreads.sort((a, b) => a.t - b.t || a.field.localeCompare(b.field)) }; } // Phase segments: a phase seen on ONE frame between two frames of another // (the same both sides) is that other phase — a transition frame, a misread. function phaseSegments(rs: readonly R[], o: { everySeconds: number; durationSeconds?: number }): DerivedSegment[] { const phases = rs.map((r) => r.phase as string); for (let i = 1; i < phases.length - 1; i++) if (phases[i - 1] === phases[i + 1] && phases[i] !== phases[i - 1]) phases[i] = phases[i - 1]; const out: DerivedSegment[] = []; rs.forEach((r, i) => { const last = out[out.length - 1]; if (last && last.phase === phases[i]) return; if (last) last.to = r.t; out.push({ from: r.t, to: r.t, phase: phases[i] }); }); if (out.length) { const end = rs[rs.length - 1].t + o.everySeconds; out[out.length - 1].to = o.durationSeconds !== undefined ? Math.min(o.durationSeconds, end) : end; } return out; } // The model's own events (a banner on screen), checked against the rest of // what was read, one per run (the same kind within a minute is one moment): // - `won` is dropped: the model says it for any player's hand. A hand the // hero takes is the log's `pot`/`big-pot`; the tournament won is the // players-left series reaching one. // - `bust` / `eliminated` stand only when no table frame in the next two // minutes shows chips in front of the hero. // - `final-table` stands only beside a stats header of 9 or fewer left. function frameEvents(rs: readonly R[], keys: readonly (string | null)[], full: ReadonlyMap>): DerivedEvent[] { const out: DerivedEvent[] = []; const headerLeft = [...full.values()].flatMap((p) => p.playersLeft ?? []); rs.forEach((r, i) => { const kind = r.event; // `all-in` is judged with the log and the action text (allInEvents): the // model says it for any player's shove, as it says `won`. if (!kind || kind === "won" || kind === "all-in") return; if ((kind === "bust" || kind === "eliminated") && rs.some((x) => x.t > r.t && x.t - r.t <= 120 && x.phase === "table" && (x.hero?.stack ?? 0) > 0)) return; if (kind === "final-table" && !headerLeft.some((p) => Math.abs(p.t - r.t) <= 120 && p.v <= FINAL_TABLE)) return; const prev = out.filter((e) => e.kind === kind).pop(); if (prev && r.t - prev.t <= 60) return; const e: DerivedEvent = { t: r.t, kind, detail: `shown on screen at ${clock(r.t)}`, source: "frame" }; if (keys[i]) e.tournament = keys[i]!; out.push(e); }); return out; } // Events the series show, on the kept points (excursions and misreads set // aside) and never on a flagged point: // - a double-up (×1.8 or more) or a big loss (half or more gone), its new // level held by the reading after it (two readings at least); // - a bust (the stack at 0 and no later chips in that tournament); // - a win: one player left, the hero with chips. // (The final table is a players-left milestone since release 31: below.) function seriesEvents(tournaments: readonly DerivedTournament[], full: ReadonlyMap>, flagged: ReadonlySet): DerivedEvent[] { const out: DerivedEvent[] = []; const ok = (field: string) => (p: Pt) => !flagged.has(`${field}@${p.t}`); for (const tour of tournaments) { const stack = (full.get(tour.key)?.stack ?? []).filter(ok("stack")); for (let i = 1; i < stack.length; i++) { const a = stack[i - 1]; const b = stack[i]; if (a.v === b.v) continue; const after = stack[i + 1]; if (!after || !agree(after.v, b.v, HELD)) continue; if (a.v > 0 && b.v / a.v >= 1.8) { out.push({ t: b.t, kind: "double-up", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips (${(b.v / a.v).toFixed(1)}×)`, source: "series", tournament: tour.key }); } else if (a.v > 0 && b.v > 0 && b.v / a.v <= 0.5) { out.push({ t: b.t, kind: "big-loss", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips`, source: "series", tournament: tour.key }); } } const zero = stack.findIndex((p) => p.v === 0); if (zero >= 0 && !stack.slice(zero + 1).some((p) => p.v > 0)) { const before = stack[zero - 1]; out.push({ t: stack[zero].t, kind: "bust", detail: before ? `out from ${fmtNum(before.v)} chips` : "out", source: "series", tournament: tour.key }); } const left = (full.get(tour.key)?.playersLeft ?? []).filter(ok("playersLeft")); const one = left.find((p) => p.v === 1); const lastStack = stack[stack.length - 1]; if (one && lastStack && lastStack.v > 0 && lastStack.t >= one.t - 120) out.push({ t: one.t, kind: "won", detail: "one player left", source: "series", tournament: tour.key }); } return out; } // ─── The client's log ─── const digits = (s: string) => Number(s.replace(/,/g, "")); // An "INFO" or "Dealer:" prefix the client puts before the line is allowed. const BLINDS_LINE = /^(?:(?:info|dealer):?\s*)?blinds are now ([\d,]+)\s*\/\s*([\d,]+)/i; const POT_LINE = /^dealer:\s*(.+?) takes the (?:(main|side) )?pot ([\d,]+)(?: with (.+?))?\.?$/i; const FINISHED_LINE = /\bhas finished the tournament in (\d+)(?:st|nd|rd|th)?\b/i; const ALL_IN = /\ball[\s-]?in\b/i; const sameName = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase(); const withoutDealer = (line: string) => line.replace(/^dealer:\s*/i, ""); // The kept stack points of a tournament, flagged ones left out. const stackOf = (full: ReadonlyMap>, key: string | undefined, flagged: ReadonlySet = new Set()) => (key ? (full.get(key)?.stack ?? []) : []).filter((p) => !flagged.has(`stack@${p.t}`)); // The hero's moments in the log (rule `log-pot`, `log-knockout`, // `log-bust`), each line once: a line seen again within three minutes is the // same line scrolling, not a second pot, and a hero pot line within three // minutes of an earlier one whose size is within 1% of it is that line // misread ("60,025" then "60,026"). A pot the hero takes is `pot`, or // `big-pot` at BIG_POT_BB big blinds or more; it is `confirmed` when the // hero's kept stack after it is above the stack before it. A line naming the // hero beside a knockout word is a `knockout` (the hero knocked someone out) // or a `bust` (someone knocked the hero out, or the hero finished). function logEvents(rs: readonly R[], keys: readonly (string | null)[], full: ReadonlyMap>, hero?: string): DerivedEvent[] { if (!hero) return []; const out: DerivedEvent[] = []; const seen = new Map(); const pots: { t: number; v: number }[] = []; rs.forEach((r, i) => { for (const line of r.log ?? []) { const at = seen.get(line); seen.set(line, r.t); if (at !== undefined && r.t - at <= 180) continue; const key = keys[i] ?? undefined; const pot = POT_LINE.exec(line); if (pot) { if (!sameName(pot[1], hero)) continue; const v = digits(pot[3]); if (pots.some((p) => r.t - p.t <= SAME_POT.windowS && ratioOf(p.v, v) <= SAME_POT.ratio)) continue; pots.push({ t: r.t, v }); const bb = key ? nearestBefore(full.get(key)?.bigBlind ?? [], r.t) : null; const potBB = bb ? Math.round((v / bb) * 10) / 10 : null; const big = potBB !== null && potBB >= BIG_POT_BB; const stack = stackOf(full, key); const before = [...stack].reverse().find((p) => p.t < r.t); const after = stack.find((p) => p.t >= r.t && p.t - r.t <= 120); const evidence: Record = { pot: v, line }; if (bb) evidence.bigBlind = bb; if (potBB !== null) evidence.potBB = potBB; if (before) evidence.stackBefore = before.v; if (after) evidence.stackAfter = after.v; out.push({ t: r.t, kind: big ? "big-pot" : "pot", detail: `takes the ${pot[2] ? `${pot[2]} ` : ""}pot ${fmtNum(v)}${bb ? ` (${Math.round(v / bb)} BB)` : ""}${pot[4] ? ` with ${pot[4]}` : ""}`, source: "log", ...(key ? { tournament: key } : {}), rule: "log-pot", evidence, confidence: before && after && after.v > before.v ? "confirmed" : "unconfirmed", }); continue; } if (!/\b(knocked out|knocks out|eliminated|eliminates|busted|finished|bounty)\b/i.test(line) || !line.toLowerCase().includes(hero.toLowerCase())) continue; const heroFirst = withoutDealer(line).toLowerCase().startsWith(hero.toLowerCase()); const kind = heroFirst && !/\bfinished\b|\bbusted\b|\bis eliminated\b|\bwas eliminated\b|\bhas been eliminated\b/i.test(line) ? "knockout" : "bust"; out.push({ t: r.t, kind, detail: line, source: "log", ...(key ? { tournament: key } : {}), rule: `log-${kind}`, evidence: { line } }); } }); return out; } // LEVEL-UPS (rule `log-blinds`): the log's "Blinds are now a/b", once per new // big blind per tournament, at the first reading that shows it. A logged big // blind that a LATER line in the same tournament puts lower is a misread of // that line and makes no event (blinds only go up). It is `confirmed` when the // big blind before it — the last line's, else the last read off the table — // is lower; with nothing before it to compare, `unconfirmed`. The level's // number rides along when a reading within two minutes shows one. function levelEvents(rs: readonly R[], keys: readonly (string | null)[], full: ReadonlyMap>): DerivedEvent[] { const byKey = new Map(); rs.forEach((r, i) => { const key = keys[i]; if (!key) return; for (let j = (r.log?.length ?? 0) - 1; j >= 0; j--) { const m = BLINDS_LINE.exec(r.log![j]); if (!m) continue; const sb = digits(m[1]); const bb = digits(m[2]); if (sb > 0 && bb >= sb) { const list = byKey.get(key) ?? []; if (list[list.length - 1]?.bb !== bb) list.push({ t: r.t, sb, bb, line: r.log![j] }); byKey.set(key, list); } break; } }); const out: DerivedEvent[] = []; for (const [key, lines] of byKey) { // Kept: a line no later line undercuts; then each new big blind once. const kept = lines.filter((l, i) => !lines.slice(i + 1).some((x) => x.bb < l.bb)); const seen = new Set(); let prev: number | null = null; const reads = full.get(key)?.bigBlind ?? []; const levels = full.get(key)?.level ?? []; for (const l of kept) { if (seen.has(l.bb)) continue; seen.add(l.bb); // Before the first line, the big blind read off the table (the series' last point before it). const from = prev ?? [...reads].reverse().find((p) => p.t < l.t && p.v !== l.bb)?.v ?? null; prev = l.bb; if (from !== null && from >= l.bb) continue; const level = levels.find((p) => Math.abs(p.t - l.t) <= 120)?.v; const evidence: Record = { smallBlind: l.sb, bigBlind: l.bb, line: l.line }; if (from !== null) evidence.from = from; if (level !== undefined) evidence.level = level; out.push({ t: l.t, kind: "level-up", detail: `blinds ${fmtNum(l.sb)}/${fmtNum(l.bb)}${from !== null ? ` (from ${fmtNum(from)})` : ""}${level !== undefined ? `, level ${fmtNum(level)}` : ""}`, source: "log", tournament: key, rule: "log-blinds", evidence, confidence: from !== null ? "confirmed" : "unconfirmed", }); } } return out; } // PLAYERS-LEFT MILESTONES (rule `players-left-milestone`), on the kept // players-left points (the stats header, or the log's finishing places — // never a table's seats, never a spoken number) with flagged points left // out: each of PLAYERS_LEFT_MILESTONES and the final table crossed once per // tournament, at the first point after the LAST point over it (players left // never rise: a point over it later means an earlier crossing was a misread). // A point that crosses several at once is one event, the lowest. The final // table is its own kind (`final-table`, not at 1 left); the rest are // `players-left`. `confirmed` when the next point holds it. function milestoneEvents(tournaments: readonly DerivedTournament[], full: ReadonlyMap>, flagged: ReadonlySet): DerivedEvent[] { const out: DerivedEvent[] = []; for (const tour of tournaments) { const left = (full.get(tour.key)?.playersLeft ?? []).filter((p) => !flagged.has(`playersLeft@${p.t}`)); const at = new Map(); for (const x of [...PLAYERS_LEFT_MILESTONES, FINAL_TABLE]) { let last = -1; left.forEach((p, i) => { if (p.v > x) last = i; }); const i = last + 1; if (last < 0 || i >= left.length) continue; if (x === FINAL_TABLE && left[i].v <= 1) continue; // The lowest milestone a point crosses names it. if (!at.has(i) || x < at.get(i)!) at.set(i, x); } for (const [i, x] of [...at].sort((a, b) => a[0] - b[0])) { const p = left[i]; const before = left[i - 1]; const next = left[i + 1]; const ft = x === FINAL_TABLE; out.push({ t: p.t, kind: ft ? "final-table" : "players-left", detail: ft ? `${p.v} players left` : `${p.v} players left (under ${x})`, source: "series", tournament: tour.key, rule: "players-left-milestone", evidence: { milestone: x, playersLeft: p.v, before: before.v, beforeT: before.t }, confidence: next && next.v <= x ? "confirmed" : "unconfirmed", }); } } return out; } // ALL-INS (rule `all-in`): the hero's, from what was read — // - a log line naming the hero first with "all in" (a call when it says // "call"; else the hero shoved); // - the action text naming the hero with "all in"; // - the action text or the model's all-in banner with no name, only when // the same reading shows the hero's cards and the hero's stack read as 0 // (every chip in the middle). The model says "all-in" for any player's // shove, so a banner with the hero's chips still in front of them is not // the hero's. // Signals within a minute are one all-in. Its OUTCOME is read off the kept // stack (flagged points left out) within ALL_IN_OUTCOME_WINDOW_S after it, // against the last kept stack before it: `busted` (a bust event of the series // or the log follows within the window, or the stack reads 0 and stays), // `doubled` (×1.8 or more), `won` (×1.1 or more), `lost` (under ×0.9), // `unclear` (about level), `unknown` (no reading). `confirmed` with an // outcome other than unclear/unknown. const ALL_IN_OUTCOME: Record = { doubled: "doubles up", won: "wins it", lost: "loses chips", busted: "busts", unclear: "no clear change", unknown: "outcome not read" }; function allInEvents(rs: readonly R[], keys: readonly (string | null)[], full: ReadonlyMap>, flagged: ReadonlySet, hero?: string): DerivedEvent[] { const signals: { t: number; i: number; via: string; role: "shove" | "call"; text: string }[] = []; const names = (text: string) => !!hero && withoutDealer(text).toLowerCase().startsWith(hero.toLowerCase()); const mentions = (text: string) => !!hero && text.toLowerCase().includes(hero.toLowerCase()); const chipsIn = (r: R) => r.phase === "table" && r.hero?.stack === 0 && (r.hero?.cards?.length ?? 0) > 0; const roleOf = (text: string): "shove" | "call" => (/\bcall(?:s|ed)?\b/i.test(text) ? "call" : "shove"); // "Villain is all in, SynthHero calls": the hero called an all-in. const heroCalls = hero ? new RegExp(`\\b${hero.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} call(?:s|ed)\\b`, "i") : null; rs.forEach((r, i) => { for (const line of r.log ?? []) { if (ALL_IN.test(line) && (names(line) || heroCalls?.test(line))) signals.push({ t: r.t, i, via: "log", role: roleOf(line), text: line }); } const action = r.hand?.action; if (action && ALL_IN.test(action) && (mentions(action) || chipsIn(r))) signals.push({ t: r.t, i, via: "action", role: roleOf(action), text: action }); if (r.event === "all-in" && chipsIn(r)) signals.push({ t: r.t, i, via: "banner", role: "shove", text: "all-in shown on screen" }); }); signals.sort((a, b) => a.t - b.t); // The hero out in the log: " has finished…", " is eliminated", " knocked out ". const outLine = (l: string) => mentions(l) && ((names(l) && /\b(has finished the tournament|is eliminated|was eliminated|has been eliminated|busted)\b/i.test(l)) || (!names(l) && /\b(knocked out|knocks out|eliminates|eliminated)\b/i.test(l))); const out: DerivedEvent[] = []; let lastT = -Infinity; for (const s of signals) { if (s.t - lastT <= ALL_IN_SAME_HAND_S) continue; lastT = s.t; const key = keys[s.i] ?? undefined; const stack = stackOf(full, key, flagged); const before = [...stack].reverse().find((p) => p.t < s.t && p.v > 0); const after = stack.filter((p) => p.t > s.t && p.t - s.t <= ALL_IN_OUTCOME_WINDOW_S); const firstAfter = after.find((p) => p.v > 0) ?? after[0]; const zeroStays = after.length > 0 && after[after.length - 1].v === 0 && !stack.some((p) => p.t > s.t && p.v > 0); const heroOut = rs.some((r) => r.t >= s.t && r.t - s.t <= ALL_IN_OUTCOME_WINDOW_S && (r.log ?? []).some(outLine)); let outcome: string; if (zeroStays || heroOut) outcome = "busted"; else if (!before || !firstAfter) outcome = "unknown"; else if (firstAfter.v >= before.v * 1.8) outcome = "doubled"; else if (firstAfter.v >= before.v * 1.1) outcome = "won"; // A 0 with chips again later (past the window) is a dip, not a result. else if (firstAfter.v === 0) outcome = "unknown"; else if (firstAfter.v < before.v * 0.9) outcome = "lost"; else outcome = "unclear"; const evidence: Record = { via: s.via, role: s.role, text: s.text, outcome }; if (before) evidence.stackBefore = before.v; if (firstAfter) { evidence.stackAfter = firstAfter.v; evidence.afterT = firstAfter.t; } out.push({ t: s.t, kind: "all-in", detail: `${s.role === "call" ? "calls all in" : "all in"}${before ? ` with ${fmtNum(before.v)}` : ""}: ${ALL_IN_OUTCOME[outcome]}${firstAfter && ["doubled", "won", "lost"].includes(outcome) ? ` (${fmtNum(firstAfter.v)})` : ""}`, source: s.via === "log" ? "log" : "frame", ...(key ? { tournament: key } : {}), rule: "all-in", evidence, confidence: outcome === "unknown" || outcome === "unclear" ? "unconfirmed" : "confirmed", }); } return out; } function nearestBefore(points: readonly Pt[], t: number): number | null { let v: number | null = null; for (const p of points) { if (p.t > t) break; v = p.v; } return v ?? points[0]?.v ?? null; } // What the streamer said that is an event in itself: none of the numbers is, // but a buy-in or a prize said marks the start of talk about a tournament. function spokenEvents(spoken: readonly SpokenReading[]): DerivedEvent[] { return spoken .filter((s) => s.field === "buyIn") .map((s) => ({ t: s.t, kind: "buy-in", detail: `$${fmtNum(s.value)} buy-in said: "${s.text}"`, source: "spoken" as const })); } // A spoken number beside the frame readings of its field: when no frame point // within the window agrees with it, every one of them is FLAGGED (and makes no // event); the flag names the nearest. With no frame point within the window, // the number fills the series of the tournament the moment is in (marked // "spoken") when it fits the readings either side, else it is flagged. Facts // (buy-in, prize, field) go to the tournament's facts when no frame read them. function crossCheck(tournaments: DerivedTournament[], full: ReadonlyMap>, spoken: readonly SpokenReading[]): { flags: DerivedFlag[]; flagged: Set } { const flags: DerivedFlag[] = []; const flagged = new Set(); const at = (t: number) => tournaments.find((x) => t >= x.from - SPOKEN_WINDOW_S && t <= x.to + SPOKEN_WINDOW_S) ?? null; const fills: { tour: DerivedTournament; field: string; t: number; v: number }[] = []; for (const s of spoken) { const tour = at(s.t); if (!SPOKEN_SERIES.has(s.field)) { if (tour && tour.facts[s.field] === undefined) tour.facts[s.field] = s.value; continue; } if (!tour) continue; const all = full.get(tour.key)?.[s.field] ?? []; const near = all.filter((p) => Math.abs(p.t - s.t) <= SPOKEN_WINDOW_S); if (!near.length) { // A gap is filled only by a number that fits the readings either side // of it (within 2×): one that fits neither is about something else (the // other tournament, a hand) — flagged against the nearer, not drawn. const before = [...all].reverse().find((p) => p.t < s.t); const after = all.find((p) => p.t > s.t); const sides = [before, after].filter((p): p is Pt => !!p); if (sides.length && sides.every((p) => ratioOf(s.value, p.v) > 2)) { const n = [...sides].sort((a, b) => Math.abs(a.t - s.t) - Math.abs(b.t - s.t))[0]; flags.push({ t: s.t, field: s.field, spoken: s.value, frame: n.v, frameT: n.t, tournament: tour.key }); } else fills.push({ tour, field: s.field, t: s.t, v: s.value }); continue; } // One frame in the window that agrees settles it (the number moved // before or after); none agreeing flags every one of them. if (near.some((p) => agree(s.value, p.v, SPOKEN_AGREE[s.field]))) continue; const bad = near; for (const p of bad) flagged.add(`${s.field}@${p.t}`); const nearest = [...bad].sort((a, b) => Math.abs(a.t - s.t) - Math.abs(b.t - s.t))[0]; if (nearest) flags.push({ t: s.t, field: s.field, spoken: s.value, frame: nearest.v, frameT: nearest.t, tournament: tour.key }); } for (const f of fills) { const list = (f.tour.series[f.field] ??= []); list.push([f.t, f.v, "spoken"]); list.sort((a, b) => a[0] - b[0]); } return { flags, flagged }; } export const POKER_PROFILE: FrameProfile = { id: "poker", // 2: the stats header, the dealer log, the hero's bounty, the break countdown. promptVersion: 2, // Wide enough for a client's small numbers on a 1080p stream. width: 1280, dupMaxBits: 2, rereadEvery: 6, framesPerAsk: { api: 4, local: 1 }, system: pokerSystem, user: pokerUser, schema: pokerSchema, coerce: coercePokerReading, spoken: pokerSpoken, derive: derivePoker, };