diff --git a/README.md b/README.md index 9201143..78fbe9c 100644 --- a/README.md +++ b/README.md @@ -48,18 +48,28 @@ termfc replay [file] replay a recorded match (no arg: list recordings) termfc demo bundled offline demo match --lang ko|en commentary language (default: ko, persisted) +--tone official|community|brief + commentary tone, Korean only (persisted) --speed N replay/demo speed multiplier --no-anim skip entrance/goal animations --no-record don't record watched matches ``` -While watching: `q` quit · `s` skip animation. +While watching: `q` quit · `t` cycle tone · `s` skip animation. ## What you get - **Live commentary** — every shot, save, corner, foul, card, VAR call and - goal, timestamped with the match clock (`90'+1'`), in Korean (FIFA's - official Korean feed) or English. + goal, timestamped with the match clock (`90'+1'`), in Korean or English. + Sentences are generated locally from the structured match facts. +- **Tone presets (Korean)** — pick how the commentary talks and switch live + with the `t` key, re-rendering the whole log: `official` (방송 문어체, + `골! Mikel Merino! 스페인이 앞서갑니다 0:1`), `community` (커뮤니티 순한맛, + `메리노 골!!! 이 시간에 터지네요`), `brief` (위젯 미니멀, `⚽ 메리노 (0:1)`). + Community/brief transliterate player names to Hangul (rule engine + a + curated table for well-known names). All templates pass a banned-lexicon + test gate: no profanity, no mockery, sensitive moments (own goals, missed + penalties, red cards) stay neutral in every tone. - **Readable over 90 minutes** — routine events older than ~15 match-minutes fold away automatically (goals, cards, subs and VAR always stay), a highlight strip under the score pins the key moments (`⚽90'+1' Merino`), @@ -94,11 +104,13 @@ espn.com use in the browser. It is **not affiliated with or endorsed by FIFA or ESPN**. These endpoints are undocumented and may change or disappear at any time — the adapter layer isolates that risk, and polling is deliberately polite (~10s intervals, identified User-Agent). Match facts (scores, times, -events) are not copyrightable, and no FIFA/ESPN prose ships with this -package or repo: ESPN-fallback sentences are always generated locally from -structured event data, and the bundled demo match and recorded test fixtures -carry locally synthesized sentences too (`scripts/sanitize-fixtures.mjs`). -FIFA's own feed text only appears live on screen while you watch. +events) are not copyrightable, and no FIFA/ESPN prose is displayed, +recorded or shipped anywhere: every sentence you see — live, replay or +demo, in any tone — is generated locally from structured event data. Feed +text is used only as a parse source for facts (player names, substitutions) +inside the adapters; recordings and the bundled demo store structured facts, +never prose (`scripts/sanitize-fixtures.mjs` keeps the test fixtures clean +the same way). ## Development diff --git a/scripts/make-demo.mjs b/scripts/make-demo.mjs index 67f2fea..bf23806 100644 --- a/scripts/make-demo.mjs +++ b/scripts/make-demo.mjs @@ -4,10 +4,12 @@ * FIFA fixtures: Portugal 0-1 Spain, Round of 16, 2026-07-06. * Normalization mirrors src/data/fifa.ts (kept minimal on purpose). * - * Event sentences are NOT copied from the source feed — they are synthesized - * from structured facts via the shared templates in sanitize-fixtures.mjs, - * so the npm package never redistributes FIFA prose. If fixtures were - * re-recorded, run `node scripts/sanitize-fixtures.mjs` first. + * As of v0.4 demo events carry NO text at all — sentences are rendered from + * the structured facts at view time (per the active tone preset), so the + * npm package never redistributes FIFA prose. This script's job is to + * extract those facts (player, sub in/out, assist taker) from the fixture + * prose and bake them as structured fields. If fixtures were re-recorded, + * run `node scripts/sanitize-fixtures.mjs` first. * * Usage: node scripts/make-demo.mjs */ @@ -16,7 +18,6 @@ import { assistPlayerFrom, playerFrom, subPlayersFrom, - synthDescription, } from "./sanitize-fixtures.mjs"; const timeline = JSON.parse( @@ -99,16 +100,13 @@ const events = timeline.Event.map((e, i) => { const srcText = e.EventDescription?.[0]?.Description ?? ""; const teamSide = String(e.IdTeam) === homeId ? "home" : String(e.IdTeam) === awayId ? "away" : undefined; - const teamName = teamSide ? match[teamSide].name : undefined; - const player = PLAYER_TYPES.has(type) || type === "CORNER" - ? playerFrom(srcText) - : undefined; - const text = synthDescription(type, "ko", { - period: e.Period, - team: teamName, - player: type === "ASSIST" ? assistPlayerFrom(srcText) : player, - ...(type === "SUBSTITUTION" ? subPlayersFrom(srcText) : {}), - }); + const player = + type === "ASSIST" + ? assistPlayerFrom(srcText) + : PLAYER_TYPES.has(type) || type === "CORNER" + ? playerFrom(srcText) + : undefined; + const sub = type === "SUBSTITUTION" ? subPlayersFrom(srcText) : {}; const isGoal = type === "GOAL" || type === "OWN_GOAL" || type === "PENALTY_GOAL"; return { id: `fifa:${e.EventId ?? i}`, @@ -117,8 +115,8 @@ const events = timeline.Event.map((e, i) => { ...(injury !== undefined ? { injury } : {}), period: e.Period, ...(teamSide ? { teamSide, teamCode: match[teamSide].code } : {}), - ...(player && PLAYER_TYPES.has(type) ? { player } : {}), - text, + ...(player ? { player } : {}), + ...(sub.inP ? { playerIn: sub.inP, playerOut: sub.outP } : {}), ...(isGoal && typeof e.HomeGoals === "number" ? { scoreAfter: { home: e.HomeGoals, away: e.AwayGoals } } : {}), diff --git a/scripts/sanitize-fixtures.mjs b/scripts/sanitize-fixtures.mjs index 6a9366a..5769441 100644 --- a/scripts/sanitize-fixtures.mjs +++ b/scripts/sanitize-fixtures.mjs @@ -52,7 +52,7 @@ export function assistPlayerFrom(text) { // --------------------------------------------------------------------------- // Sentence synthesis — our own wording, generated from structured facts. -// Mirrors the spirit of eventSentence() in src/core/i18n.ts, extended with +// Mirrors the spirit of the tone templates in src/core/tone.ts, extended with // the facts a recorded fixture can carry (player, sub in/out, period). // --------------------------------------------------------------------------- diff --git a/src/cli/index.ts b/src/cli/index.ts index f70d830..06bfc2a 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -7,6 +7,7 @@ import { type Match, type TimelineEvent, } from "../core/model.js"; +import { isTone, type Tone } from "../core/tone.js"; import { EspnProvider } from "../data/espn.js"; import { FailoverProvider, linkSourceRefs } from "../data/failover.js"; import { FifaProvider } from "../data/fifa.js"; @@ -22,6 +23,7 @@ import { REPLAY_DIR, writeConfig, writeScheduleCache, + type Config, type Coverage, } from "../store/store.js"; import { bold, cyan, dim, red, yellow } from "../ui/ansi.js"; @@ -33,6 +35,7 @@ import pkg from "../../package.json" with { type: "json" }; interface Flags { lang?: Lang; + tone?: Tone; speed?: number; anim: boolean; record: boolean; @@ -49,6 +52,12 @@ function parseArgv(argv: string[]): { cmd?: string; args: string[]; flags: Flags } else if (a.startsWith("--lang=")) { const v = a.slice(7); if (v === "ko" || v === "en") flags.lang = v; + } else if (a === "--tone") { + const v = argv[++i]; + if (isTone(v)) flags.tone = v; + } else if (a.startsWith("--tone=")) { + const v = a.slice(7); + if (isTone(v)) flags.tone = v; } else if (a === "--speed") { flags.speed = Number(argv[++i]); } else if (a.startsWith("--speed=")) { @@ -78,6 +87,7 @@ const HELP = ` ${bold("options")} --lang ko|en ${dim("commentary language (default: ko, persisted)")} + --tone official|community|brief ${dim("commentary tone, ko only (persisted; t key toggles)")} --speed N ${dim("replay/demo speed multiplier")} --no-anim ${dim("skip entrance/goal animations")} --no-record ${dim("don't record watched matches for replay")} @@ -87,9 +97,16 @@ async function main(): Promise { const { cmd, args, flags } = parseArgv(process.argv.slice(2)); const config = readConfig(); const lang: Lang = flags.lang ?? config.lang ?? "ko"; - if (flags.lang && flags.lang !== config.lang) { + // Unknown stored values (edited by hand / written by a future version) + // degrade to the default instead of leaking into rendering. + flags.tone = + flags.tone ?? (isTone(config.tone) ? config.tone : undefined) ?? "official"; + const persist: Partial = {}; + if (flags.lang && flags.lang !== config.lang) persist.lang = flags.lang; + if (flags.tone !== (config.tone ?? "official")) persist.tone = flags.tone; + if (Object.keys(persist).length > 0) { try { - writeConfig({ ...config, lang: flags.lang }); + writeConfig({ ...config, ...persist }); } catch { /* non-fatal */ } @@ -307,11 +324,23 @@ async function enterMatch( lang, mode: "live", animations: flags.anim, + tone: flags.tone, lambdas, sourceLabel: () => provider.activeSource.toUpperCase(), onEvents: (events: TimelineEvent[]) => recorder?.append(events), }); - await screen.run(); + persistTone(await screen.run()); +} + +/** A tone settled on via the t toggle survives into the next run. */ +function persistTone(finalTone: Tone): void { + try { + const cfg = readConfig(); + if ((cfg.tone ?? "official") === finalTone) return; + writeConfig({ ...cfg, tone: finalTone }); + } catch { + /* non-fatal */ + } } async function replayCommand( @@ -368,12 +397,13 @@ async function runReplay( lang, mode: "replay", animations: flags.anim, + tone: flags.tone, clockRate: speed, speedLabel: String(speed), lambdas: null, sourceLabel: () => `${parsed.events[0]?.source ?? "fifa"} replay`, }); - await screen.run(); + persistTone(await screen.run()); } main() diff --git a/src/core/digest.ts b/src/core/digest.ts index 78a9b4c..507fafb 100644 --- a/src/core/digest.ts +++ b/src/core/digest.ts @@ -1,7 +1,6 @@ import { compareEvents, type EventType, - type Lang, type MatchPhase, type MatchState, type SourceName, @@ -131,22 +130,20 @@ export function deriveHighlights( export function synthesizeAddedTime( prev: MatchState | null, next: MatchState, - opts: { lang: Lang; source: SourceName }, + opts: { source: SourceName }, ): TimelineEvent | null { if (!next.injury || next.injury <= 0) return null; const samePhaseAlreadyAnnounced = prev !== null && prev.phase === next.phase && !!prev.injury; if (samePhaseAlreadyAnnounced) return null; - const text = - opts.lang === "ko" - ? `추가시간 +${next.injury}분` - : `+${next.injury} minutes added`; return { id: `local:added-time-${next.phase}`, type: "ADDED_TIME", minute: next.minute, + // the announced amount rides the injury field — sentences are rendered + // from it at view time (and recordings keep the structured fact) + injury: next.injury, period: fifaPeriodOf(next.phase), - text, source: opts.source, seq: 0, }; diff --git a/src/core/factextract.ts b/src/core/factextract.ts new file mode 100644 index 0000000..3db5f14 --- /dev/null +++ b/src/core/factextract.ts @@ -0,0 +1,63 @@ +/** + * Fact extraction from event sentence text. The FIFA feed carries some facts + * (substitution in/out, assist taker, added-time amount) only inside its + * prose sentence — these helpers pull the facts out so events can be + * rendered from structure alone. Patterns cover both the live FIFA feed + * (ko/en) and the synthetic sentences written by pre-v0.4 termfc (recordings + * and fixtures), so old replay files can be enriched on load. + * + * The prose itself is never displayed; it is a parse source only. + */ + +const SUB_PATTERNS: readonly RegExp[] = [ + /^(.+?) \(in\) comes off the bench to replace (.+?) \(out\)/, // FIFA en + /^(.+?) \(in\) 선수가 (.+?)\s*\(교체\)/, // FIFA ko + /^(?:선수 교체|Substitution)(?: \(.+?\))?: (.+?) (?:IN|in), (.+?) (?:OUT|out)$/, // v0.3 synthetic +]; + +export function subPlayersFrom( + text: string | undefined, +): { playerIn: string; playerOut: string } | undefined { + for (const re of SUB_PATTERNS) { + const m = re.exec(text ?? ""); + if (m) return { playerIn: m[1]!.trim(), playerOut: m[2]!.trim() }; + } + return undefined; +} + +const ASSIST_PATTERNS: readonly RegExp[] = [ + /^Assisted by (.+?)\.?$/, // FIFA en + /^(.+?) 선수의 어시스트/, // FIFA ko + /^(?:어시스트|Assist): (.+)$/, // v0.3 synthetic +]; + +export function assistPlayerFrom(text: string | undefined): string | undefined { + for (const re of ASSIST_PATTERNS) { + const m = re.exec(text ?? ""); + if (m) return m[1]!.trim(); + } + return undefined; +} + +/** Added-time amount from a stored ADDED_TIME sentence ("추가시간 +4분", "+4 minutes added"). */ +export function addedTimeFrom(text: string | undefined): number | undefined { + const m = /\+\s*(\d+)\s*(?:분|minute)/.exec(text ?? ""); + return m ? Number(m[1]) : undefined; +} + +/** Leading "PLAYER (TEAM)" name — the shape FIFA prose uses for actor events. */ +export function leadingPlayerFrom(text: string | undefined): string | undefined { + if (!text) return undefined; + // FIFA-ko booking sentences lead with the referee, not the player + // ("주심이 X (팀) 에게 경고…") — drop that prefix before matching. + const cleaned = text.replace(/^(?:주심|부심|심판)이\s*/, ""); + const m = /^(.{2,40}?)\s*\(/.exec(cleaned); + return m?.[1]?.trim() || undefined; +} + +/** Strip the referee prefix old recordings baked into extracted player names. */ +export function cleanPlayerFact(player: string | undefined): string | undefined { + if (!player) return undefined; + const cleaned = player.replace(/^(?:주심|부심|심판)이\s*/, "").trim(); + return cleaned || undefined; +} diff --git a/src/core/hangul.ts b/src/core/hangul.ts new file mode 100644 index 0000000..9ce1346 --- /dev/null +++ b/src/core/hangul.ts @@ -0,0 +1,271 @@ +/** + * Roman-to-Hangul transliteration for player names (community/brief tones). + * Rule engine follows the spirit of 외래어 표기법 for Latin-script names: + * CV pairs become syllables, trailing m/n/l/ng/k/p become batchim, other + * trailing consonants get an ㅡ vowel (트/스/드), r before a consonant + * becomes 르. Language-specific pronunciation (Spanish j, Portuguese nh…) + * cannot be inferred from spelling — well-known names are pinned in + * data/hangul-names.json and everything else degrades to a deterministic, + * harmless approximation (the requirement gate is determinism + harmlessness, + * not perfect accuracy). + */ +import exceptionsJson from "../data/hangul-names.json" with { type: "json" }; + +const EXCEPTIONS = exceptionsJson as Record; + +// Choseong (onset) indices in the Hangul syllable block. +const CHO = { + g: 0, n: 2, d: 3, r: 5, m: 6, b: 7, s: 9, ng: 11, j: 12, ch: 14, + k: 15, t: 16, p: 17, h: 18, +} as const; +// Jungseong (vowel) indices. +const JUNG = { + a: 0, ya: 2, e: 5, ye: 7, o: 8, wa: 9, yo: 12, u: 13, wo: 14, we: 15, + wi: 16, yu: 17, eu: 18, i: 20, +} as const; +// Jongseong (batchim) codes for consonants allowed to close a syllable. +const JONG = { k: 1, n: 4, l: 8, m: 16, p: 17, s: 19, ng: 21 } as const; + +type Cho = number; +interface Syllable { + cho: Cho; + jung: number; + jong?: number; +} + +const compose = (s: Syllable): string => + String.fromCharCode(0xac00 + (s.cho * 21 + s.jung) * 28 + (s.jong ?? 0)); + +/** Non-decomposable Latin letters NFD cannot strip. */ +const LETTER_FIXES: Record = { + ø: "o", đ: "d", ł: "l", ß: "ss", æ: "ae", œ: "oe", ð: "d", þ: "th", +}; + +function normalizeRoman(word: string): string { + return word + .normalize("NFD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/[øđłßæœðþ]/g, (ch) => LETTER_FIXES[ch] ?? "") + .replace(/[^a-z'-]/g, ""); +} + +const VOWELS = new Set(["a", "e", "i", "o", "u", "y"]); + +interface Token { + kind: "c" | "v" | "ngEnd"; + /** consonant: choseong index; vowel: jungseong index */ + code: number; + /** consonant carries a y-glide onto the next vowel (nh, sh) */ + palatal?: boolean; + /** consonant carries a w-glide onto the next vowel (qu) */ + labial?: boolean; + /** letter this consonant came from (batchim eligibility) */ + letter?: string; + /** geminate l (ll) — closes the previous syllable with ㄹ too */ + geminateL?: boolean; +} + +function consonantToken(letter: string, next: string): Token | null { + const soft = next === "e" || next === "i" || next === "y"; + switch (letter) { + case "b": case "v": return { kind: "c", code: CHO.b, letter: "b" }; + case "c": return soft + ? { kind: "c", code: CHO.s, letter: "s" } + : { kind: "c", code: CHO.k, letter: "k" }; + case "d": return { kind: "c", code: CHO.d, letter: "d" }; + case "f": case "p": return { kind: "c", code: CHO.p, letter: "p" }; + case "g": return { kind: "c", code: CHO.g, letter: "k" }; + case "h": return { kind: "c", code: CHO.h, letter: "h" }; + case "j": return { kind: "c", code: CHO.j, letter: "j" }; + case "k": case "q": return { kind: "c", code: CHO.k, letter: "k" }; + case "l": return { kind: "c", code: CHO.r, letter: "l" }; + case "m": return { kind: "c", code: CHO.m, letter: "m" }; + case "n": return { kind: "c", code: CHO.n, letter: "n" }; + case "r": return { kind: "c", code: CHO.r, letter: "r" }; + case "s": case "z": return { kind: "c", code: CHO.s, letter: "s" }; + case "t": return { kind: "c", code: CHO.t, letter: "t" }; + case "w": return { kind: "c", code: CHO.ng, labial: true, letter: "w" }; + default: return null; + } +} + +/** Tokenize one normalized word into consonant/vowel tokens. */ +function tokenize(word: string): Token[] { + const out: Token[] = []; + let i = 0; + while (i < word.length) { + const ch = word[i]!; + const nx = word[i + 1] ?? ""; + const nx2 = word[i + 2] ?? ""; + if (ch === "'" || ch === "-") { + i++; + continue; + } + // consonant digraphs + if (ch === "c" && nx === "h") { out.push({ kind: "c", code: CHO.ch, letter: "t" }); i += 2; continue; } + if (ch === "s" && nx === "h") { out.push({ kind: "c", code: CHO.s, palatal: true, letter: "s" }); i += 2; continue; } + if (ch === "t" && nx === "h") { out.push({ kind: "c", code: CHO.t, letter: "t" }); i += 2; continue; } + if (ch === "p" && nx === "h") { out.push({ kind: "c", code: CHO.p, letter: "p" }); i += 2; continue; } + if (ch === "k" && nx === "h") { out.push({ kind: "c", code: CHO.k, letter: "k" }); i += 2; continue; } + if (ch === "g" && nx === "h") { out.push({ kind: "c", code: CHO.g, letter: "k" }); i += 2; continue; } + if ((ch === "n" || ch === "l") && nx === "h") { + out.push({ kind: "c", code: ch === "n" ? CHO.n : CHO.r, palatal: true, letter: ch }); + i += 2; + continue; + } + if (ch === "c" && nx === "k") { out.push({ kind: "c", code: CHO.k, letter: "k" }); i += 2; continue; } + if (ch === "q" && nx === "u") { out.push({ kind: "c", code: CHO.k, labial: true, letter: "k" }); i += 2; continue; } + if (ch === "x") { // k + s cluster (Felix → 펠릭스) + out.push({ kind: "c", code: CHO.k, letter: "k" }, { kind: "c", code: CHO.s, letter: "s" }); + i++; + continue; + } + // ng closing a syllable (before a consonant or at word end) + if (ch === "n" && nx === "g" && (nx2 === "" || !VOWELS.has(nx2))) { + out.push({ kind: "ngEnd", code: JONG.ng }); + i += 2; + continue; + } + // geminate l → ㄹㄹ; other doubled consonants collapse to one + if (ch === "l" && nx === "l") { + out.push({ kind: "c", code: CHO.r, letter: "l", geminateL: true }); + i += 2; + continue; + } + if (!VOWELS.has(ch) && ch === nx) { + i++; + continue; + } + if (!VOWELS.has(ch)) { + const tok = consonantToken(ch, nx); + if (tok) out.push(tok); + i++; + continue; + } + // vowels — digraphs first + if ((ch === "o" && (nx === "o" || nx === "u")) ) { out.push({ kind: "v", code: JUNG.u }); i += 2; continue; } + if (ch === "e" && nx === "e") { out.push({ kind: "v", code: JUNG.i }); i += 2; continue; } + if (ch === "y" && VOWELS.has(nx) && nx !== "y") { + const base = { a: JUNG.ya, e: JUNG.ye, o: JUNG.yo, u: JUNG.yu, i: JUNG.i }[nx as "a" | "e" | "o" | "u" | "i"]; + out.push({ kind: "v", code: base }); + i += 2; + continue; + } + const single = { a: JUNG.a, e: JUNG.e, i: JUNG.i, o: JUNG.o, u: JUNG.u, y: JUNG.i }[ch as "a" | "e" | "i" | "o" | "u" | "y"]; + out.push({ kind: "v", code: single }); + i++; + continue; + } + return out; +} + +const glideVowel = (v: number, tok: Token): number => { + if (tok.palatal) { + const map: Record = { + [JUNG.a]: JUNG.ya, [JUNG.e]: JUNG.ye, [JUNG.o]: JUNG.yo, [JUNG.u]: JUNG.yu, + }; + return map[v] ?? v; + } + if (tok.labial) { + const map: Record = { + [JUNG.a]: JUNG.wa, [JUNG.e]: JUNG.we, [JUNG.i]: JUNG.wi, [JUNG.o]: JUNG.wo, + }; + return map[v] ?? v; + } + return v; +}; + +/** Batchim code for a consonant letter closing a syllable, if allowed. */ +const batchimOf = (letter: string | undefined): number | undefined => + letter && letter in JONG && letter !== "s" // s before a consonant → 스, not ㅅ batchim + ? JONG[letter as keyof typeof JONG] + : undefined; + +/** Rule-convert one normalized word. Deterministic; Hangul-only output. */ +export function romanWordToHangul(word: string): string { + const tokens = tokenize(normalizeRoman(word)); + const syls: Syllable[] = []; + let pending: Token | null = null; + + const flushPendingAsSyllable = () => { + if (!pending) return; + // r before a consonant / at end → 르; others → consonant + ㅡ + syls.push({ cho: pending.code, jung: JUNG.eu }); + pending = null; + }; + const flushPendingAsBatchim = (): boolean => { + if (!pending) return true; + const last = syls[syls.length - 1]; + const jong = pending.letter === "r" ? undefined : batchimOf(pending.letter); + if (last && last.jong === undefined && jong !== undefined) { + last.jong = jong; + pending = null; + return true; + } + return false; + }; + + for (const tok of tokens) { + if (tok.kind === "ngEnd") { + if (!flushPendingAsBatchim()) flushPendingAsSyllable(); + const last = syls[syls.length - 1]; + if (last && last.jong === undefined) last.jong = JONG.ng; + else syls.push({ cho: CHO.ng, jung: JUNG.eu, jong: JONG.ng }); + continue; + } + if (tok.kind === "c") { + if (pending) { + // stop consonants split with ㅡ before l/r clusters (gl → 글, tr → 트르) + const cluster = + (pending.letter === "k" || pending.letter === "p" || pending.letter === "t" || pending.letter === "d") && + tok.letter === "l"; + if (cluster || !flushPendingAsBatchim()) flushPendingAsSyllable(); + } + pending = tok; + continue; + } + // vowel + const cho = pending?.code ?? CHO.ng; + const jung = pending ? glideVowel(tok.code, pending) : tok.code; + // intervocalic [l] is written ㄹㄹ (표기법) — close the previous open + // syllable with ㄹ before starting the new one (Felix → 펠릭스) + if (pending?.letter === "l") { + const last = syls[syls.length - 1]; + if (last && last.jong === undefined) last.jong = JONG.l; + } + pending = null; + syls.push({ cho, jung }); + } + if (pending) { + if (!flushPendingAsBatchim()) flushPendingAsSyllable(); + } + const out = syls.map(compose).join(""); + return out || word; +} + +const exceptionKey = (s: string): string => normalizeRoman(s).replace(/['-]/g, ""); + +/** + * Transliterate a (possibly multi-word) player name. Exception table wins — + * full name first, then per word — and the rule engine covers the rest. + */ +export function hangulPlayerName(name: string): string { + const trimmed = name.trim(); + if (!trimmed) return trimmed; + if (/[가-힣]/.test(trimmed)) return trimmed; // already Korean + const full = EXCEPTIONS[exceptionKey(trimmed)]; + if (full) return full; + return trimmed + .split(/\s+/) + .map((w) => EXCEPTIONS[exceptionKey(w)] ?? romanWordToHangul(w)) + .join(" "); +} + +/** Surname-style short form used by community/brief tones ("메리노"). */ +export function hangulSurname(name: string): string { + const words = name.trim().split(/\s+/); + const last = words[words.length - 1] ?? ""; + // "De Bruyne" style particles keep the two final words when the last is short + return hangulPlayerName(last); +} diff --git a/src/core/i18n.ts b/src/core/i18n.ts index 17e4566..dea1bb3 100644 --- a/src/core/i18n.ts +++ b/src/core/i18n.ts @@ -24,7 +24,7 @@ export const LABELS = { sourceSwitched: "데이터 소스 전환 — 백업 소스로 중계를 계속합니다", corrected: "정정", goalCancelled: "골 취소", - quitHint: "q 종료 · s 애니메이션 건너뛰기", + quitHint: "q 종료 · t 말투 · s 애니메이션 건너뛰기", pickPrompt: "번호를 입력해 경기에 입장하세요 (q 종료): ", schedule: "경기 일정", liveNow: "진행 중", @@ -128,96 +128,48 @@ interface SentenceCtx { } /** - * Template sentence generator. Used for events that carry no source-provided - * text in the requested language (i.e. the ESPN fallback source — we do not - * redistribute ESPN's verbatim commentary; we generate our own from the - * structured event data). + * English sentence generator, applied at render time for en sessions. + * (Korean sentences come from the tone presets in core/tone.ts — the tone + * feature is ko-only, en keeps this single register.) Generated from + * structured facts; no source prose is ever displayed or redistributed. */ -export function eventSentence( - e: Pick, - lang: Lang, +export function enEventSentence( + e: Pick, ctx: SentenceCtx = {}, ): string { - const who = ctx.player; + const who = ctx.player + ? `${ctx.player}${ctx.team ? ` (${ctx.team})` : ""}` + : (ctx.team ?? ""); const team = ctx.team; - const koWho = who ? `${who}${team ? ` (${team})` : ""}` : (team ?? ""); - const enWho = who ? `${who}${team ? ` (${team})` : ""}` : (team ?? ""); - - if (lang === "ko") { - switch (e.type) { - case "GOAL": - return koWho ? `골! ${koWho} 득점!` : "골!"; - case "OWN_GOAL": - return koWho ? `자책골! ${koWho}` : "자책골!"; - case "PENALTY_GOAL": - return koWho ? `${koWho} 페널티킥 성공!` : "페널티킥 성공!"; - case "PENALTY_MISS": - return koWho ? `${koWho} 페널티킥 실축` : "페널티킥 실축"; - case "ASSIST": - return koWho ? `${koWho} 어시스트` : "어시스트"; - case "SHOT": - return koWho ? `${koWho} 슈팅 시도` : "슈팅 시도"; - case "SAVE": - return team ? `${team} 골키퍼 선방` : "골키퍼 선방"; - case "FOUL": - return koWho ? `${koWho} 파울` : "파울"; - case "YELLOW": - return koWho ? `${koWho} 경고 (옐로카드)` : "경고 (옐로카드)"; - case "RED": - return koWho ? `${koWho} 퇴장! (레드카드)` : "퇴장! (레드카드)"; - case "CORNER": - return team ? `${team} 코너킥` : "코너킥"; - case "OFFSIDE": - return koWho ? `${koWho} 오프사이드` : "오프사이드"; - case "SUBSTITUTION": - return team ? `${team} 선수 교체` : "선수 교체"; - case "VAR": - return "VAR 판독 중"; - case "PERIOD_START": - return "경기 시작 휘슬"; - case "PERIOD_END": - return "종료 휘슬"; - case "FULLTIME": - return "경기 종료"; - case "COIN_TOSS": - return "동전 던지기"; - case "BREAK": - return "경기 일시 중단"; - case "RESUMED": - return "경기 재개"; - case "ADDED_TIME": - return "추가시간 표시"; - default: - return "경기 상황"; - } - } switch (e.type) { case "GOAL": - return enWho ? `Goal! ${enWho} scores!` : "Goal!"; + return who ? `Goal! ${who} scores!` : "Goal!"; case "OWN_GOAL": - return enWho ? `Own goal by ${enWho}` : "Own goal"; + return who ? `Own goal by ${who}` : "Own goal"; case "PENALTY_GOAL": - return enWho ? `${enWho} converts the penalty!` : "Penalty scored!"; + return who ? `${who} converts the penalty!` : "Penalty scored!"; case "PENALTY_MISS": - return enWho ? `${enWho} misses the penalty` : "Penalty missed"; + return who ? `${who} misses the penalty` : "Penalty missed"; case "ASSIST": - return enWho ? `Assisted by ${enWho}` : "Assist"; + return who ? `Assisted by ${who}` : "Assist"; case "SHOT": - return enWho ? `${enWho} attempts a shot` : "Shot attempt"; + return who ? `${who} attempts a shot` : "Shot attempt"; case "SAVE": return team ? `Save by the ${team} goalkeeper` : "Goalkeeper save"; case "FOUL": - return enWho ? `Foul by ${enWho}` : "Foul"; + return who ? `Foul by ${who}` : "Foul"; case "YELLOW": - return enWho ? `${enWho} is booked` : "Yellow card"; + return who ? `${who} is booked` : "Yellow card"; case "RED": - return enWho ? `${enWho} is sent off!` : "Red card!"; + return who ? `${who} is sent off!` : "Red card!"; case "CORNER": return team ? `Corner kick for ${team}` : "Corner kick"; case "OFFSIDE": - return enWho ? `${enWho} is offside` : "Offside"; + return who ? `${who} is offside` : "Offside"; case "SUBSTITUTION": + if (e.playerIn && e.playerOut) + return `Substitution${team ? ` (${team})` : ""}: ${e.playerIn} in, ${e.playerOut} out`; return team ? `Substitution for ${team}` : "Substitution"; case "VAR": return "VAR review"; @@ -234,7 +186,7 @@ export function eventSentence( case "RESUMED": return "Match resumed"; case "ADDED_TIME": - return "Added time signalled"; + return e.injury ? `+${e.injury} minutes added` : "Added time signalled"; default: return "Match event"; } diff --git a/src/core/model.ts b/src/core/model.ts index 96bdfb9..446ea1b 100644 --- a/src/core/model.ts +++ b/src/core/model.ts @@ -48,6 +48,40 @@ export type EventType = | "ADDED_TIME" | "UNKNOWN"; +/** Runtime enumeration of every EventType (kept in sync via `satisfies`). */ +export const ALL_EVENT_TYPES = [ + "GOAL", + "OWN_GOAL", + "PENALTY_GOAL", + "PENALTY_MISS", + "ASSIST", + "SHOT", + "SAVE", + "FOUL", + "YELLOW", + "RED", + "CORNER", + "OFFSIDE", + "SUBSTITUTION", + "VAR", + "PERIOD_START", + "PERIOD_END", + "FULLTIME", + "COIN_TOSS", + "BREAK", + "RESUMED", + "ADDED_TIME", + "UNKNOWN", +] as const satisfies readonly EventType[]; + +// Compile-time exhaustiveness: fails to build when EventType gains a member +// that is missing from ALL_EVENT_TYPES. +true satisfies [Exclude] extends [ + never, +] + ? true + : never; + export type Salience = "high" | "low"; const HIGH_SALIENCE: ReadonlySet = new Set([ @@ -137,7 +171,15 @@ export interface TimelineEvent { teamSide?: "home" | "away"; /** Best-effort player name extracted from source data. */ player?: string; - /** Localized display sentence (source-provided or template-generated). */ + /** Substitution facts (player coming on / going off), when known. */ + playerIn?: string; + playerOut?: string; + /** + * Display sentence. As of v0.4 events are rendered from structure at view + * time and adapters no longer fill this; it survives on the model so + * pre-v0.4 recordings (which stored it) still parse. Never render it + * directly — it may contain source-feed prose. + */ text?: string; /** Score right after this event, when the source provides it (goals). */ scoreAfter?: { home: number; away: number }; diff --git a/src/core/text.ts b/src/core/text.ts index 5752228..08e229d 100644 --- a/src/core/text.ts +++ b/src/core/text.ts @@ -1,9 +1,9 @@ /** - * Display-time cleanup for source-provided commentary text. FIFA's feed - * carries artifacts we don't want on screen: doubled spaces, a detached - * genitive particle ("포르투갈 의 골키퍼"), and player names in ALL CAPS - * ("JOAO CANCELO", "Lamine YAMAL"). Applied when rendering, so live, - * replay and demo paths (including already-recorded files) all benefit. + * Player-name normalization. The FIFA feed carries names in ALL CAPS + * ("JOAO CANCELO", "Mikel MERINO") — normalize before display or + * transliteration. (Sentence-level cleanup for feed prose was removed in + * v0.4: sentences are generated locally from structure, so there is no feed + * prose to clean.) */ const ALL_CAPS_WORD = /^[A-Z]{2,}$/; @@ -14,30 +14,6 @@ function titleCaseWord(w: string): string { .replace(/(^|[-'’])([a-z])/g, (_, sep: string, ch: string) => sep + ch.toUpperCase()); } -/** - * Title-case ALL-CAPS latin words, but only inside runs of 2+ latin words — - * standalone acronyms (VAR, PSO) must survive. - */ -function normalizeNamesInText(s: string): string { - return s.replace( - /[A-Za-z][A-Za-z'’-]*(?: [A-Za-z][A-Za-z'’-]*)+/g, - (run) => - run - .split(" ") - .map((w) => (ALL_CAPS_WORD.test(w.replace(/['’-]/g, "")) ? titleCaseWord(w) : w)) - .join(" "), - ); -} - -export function normalizeEventText(s: string): string { - let t = s.replace(/\s{2,}/g, " ").trim(); - t = t.replace(/(\S) (의|에게) /g, "$1$2 "); - t = normalizeNamesInText(t); - // Standalone single-name players ("RODRI"). 4+ letters so short acronyms - // (VAR, PSO, GK) survive. - return t.replace(/(?; + +const OFFICIAL: ToneTable = { + GOAL: { full: ["골! {p}![ {sp}]"], bare: ["골이 들어갑니다![ {sp}]"] }, + OWN_GOAL: { full: ["{p}의 자책골입니다[ {sp}]"], bare: ["자책골입니다[ {sp}]"] }, + PENALTY_GOAL: { full: ["{p}, 페널티킥을 성공시킵니다[ {sp}]"], bare: ["페널티킥 성공[ {sp}]"] }, + PENALTY_MISS: { full: ["{p}, 페널티킥을 성공시키지 못합니다"], bare: ["페널티킥 실패"] }, + ASSIST: { full: ["어시스트: {p}"], bare: ["어시스트가 기록됩니다"] }, + SHOT: { full: ["{p}의 슈팅"], team: ["{t}의 슈팅 시도"], bare: ["슈팅 시도"] }, + SAVE: { team: ["{t} 골키퍼가 막아냅니다"], bare: ["골키퍼 선방"] }, + FOUL: { full: ["{p}의 파울"], team: ["{t}의 파울"], bare: ["파울"] }, + YELLOW: { full: ["{p}, 경고를 받습니다"], team: ["{t}에 경고가 나옵니다"], bare: ["경고 (옐로카드)"] }, + RED: { full: ["{p}, 퇴장당합니다 (레드카드)"], team: ["{t}에서 퇴장자가 나옵니다"], bare: ["퇴장 (레드카드)"] }, + CORNER: { full: ["{p}의 코너킥"], team: ["{t} 코너킥"], bare: ["코너킥"] }, + OFFSIDE: { full: ["{p}, 오프사이드입니다"], team: ["{t} 오프사이드"], bare: ["오프사이드"] }, + SUBSTITUTION: { + full: ["교체 ({t}): {in} 투입, {out} 아웃", "교체: {in} 투입, {out} 아웃"], + team: ["{t} 선수 교체"], + bare: ["선수 교체"], + }, + VAR: { bare: ["VAR 판독이 진행됩니다"] }, + PERIOD_START: { bare: ["{per} 시작"] }, + PERIOD_END: { bare: ["{per} 종료"] }, + FULLTIME: { bare: ["경기 종료"] }, + COIN_TOSS: { team: ["동전 던지기 — {t} 선축"], bare: ["동전 던지기"] }, + BREAK: { bare: ["경기가 잠시 중단됩니다 (수분 섭취)"] }, + RESUMED: { bare: ["경기 재개"] }, + ADDED_TIME: { full: ["추가시간 +{n}분"], bare: ["추가시간이 표시됩니다"] }, + UNKNOWN: { bare: ["경기 상황"] }, +}; + +/** + * Sensitive events stay neutral in every tone — no exclamation at a person, + * no mockery (content policy §3-3). Community draws these from this table + * only; the lexicon test pins that structurally. + */ +export const SENSITIVE_TYPES: ReadonlySet = new Set([ + "OWN_GOAL", + "PENALTY_MISS", + "RED", +]); + +export const COMMUNITY_NEUTRAL: Partial> = { + OWN_GOAL: { + full: ["{p}의 자책골이 나왔습니다... 이런 장면은 아프네요"], + bare: ["자책골이 나왔습니다..."], + }, + PENALTY_MISS: { + full: ["{p} 페널티킥 실축... 아쉽습니다"], + bare: ["페널티킥 실축... 아쉽네요"], + }, + RED: { + full: ["{p} 퇴장입니다... 남은 시간 수적 열세네요"], + team: ["{t}에서 퇴장이 나왔습니다..."], + bare: ["퇴장이 나왔습니다..."], + }, +}; + +const COMMUNITY: ToneTable = { + GOAL: { + full: [ + "{p} 골!!! 이 시간에 터지네요", + "{p} 골!!! 드디어 터집니다", + "{p} 골!!! 제대로 꽂아넣습니다", + ], + bare: ["골!!! 터졌습니다"], + }, + OWN_GOAL: COMMUNITY_NEUTRAL.OWN_GOAL!, + PENALTY_GOAL: { + full: ["{p} 페널티킥 성공! 침착했습니다"], + bare: ["페널티킥 성공! 침착하네요"], + }, + PENALTY_MISS: COMMUNITY_NEUTRAL.PENALTY_MISS!, + ASSIST: { full: ["어시스트는 {p}"], bare: ["어시스트까지 깔끔했네요"] }, + SHOT: { + full: ["{p} 슛! 아깝네요", "{p} 때려봅니다!", "{p} 슛! 이번엔 빗나갑니다"], + team: ["{t} 슈팅 기회!"], + bare: ["슛! 아깝습니다"], + }, + SAVE: { + team: ["{t} 골키퍼 선방! 좋았습니다", "{t} 골키퍼가 잘 막아냅니다"], + bare: ["키퍼 선방! 좋네요"], + }, + FOUL: { + full: ["{p} 파울이네요", "{p} 파울, 성급했습니다"], + team: ["{t} 파울"], + bare: ["파울이네요"], + }, + YELLOW: { + full: ["{p} 카드 받았네요, 급했습니다", "{p} 옐로카드, 조심해야겠는데요"], + team: ["{t}에 카드가 나옵니다"], + bare: ["옐로카드 나옵니다"], + }, + RED: COMMUNITY_NEUTRAL.RED!, + CORNER: { + full: ["{p} 코너킥 준비합니다"], + team: ["{t} 코너킥 기회!"], + bare: ["코너킥 기회"], + }, + OFFSIDE: { + full: ["{p} 오프사이드네요, 타이밍이 빨랐습니다"], + team: ["{t} 오프사이드"], + bare: ["오프사이드네요"], + }, + SUBSTITUTION: { + full: ["교체 카드 ({t}) — {in} 들어가고 {out} 나옵니다", "교체 카드 — {in} 들어가고 {out} 나옵니다"], + team: ["{t} 교체 카드 꺼냅니다"], + bare: ["선수 교체입니다"], + }, + VAR: { bare: ["VAR 봅니다... 떨리네요"] }, + PERIOD_START: { bare: ["{per} 시작합니다!"] }, + PERIOD_END: { bare: ["{per} 끝! 잠시 쉬어갑니다"] }, + FULLTIME: { bare: ["경기 끝! 수고하셨습니다"] }, + COIN_TOSS: { team: ["동전 던지기는 {t} — 선축 가져갑니다"], bare: ["동전 던지기"] }, + BREAK: { bare: ["수분 타임! 잠시 쉬어갑니다"] }, + RESUMED: { bare: ["다시 갑니다!"] }, + ADDED_TIME: { full: ["추가시간 +{n}분! 끝까지 갑니다"], bare: ["추가시간 들어갑니다"] }, + UNKNOWN: { bare: ["경기 상황"] }, +}; + +const BRIEF: ToneTable = { + GOAL: { full: ["{p}[ ({s})]"], bare: ["골[ ({s})]"] }, + OWN_GOAL: { full: ["{p} 자책골[ ({s})]"], bare: ["자책골[ ({s})]"] }, + PENALTY_GOAL: { full: ["{p} PK골[ ({s})]"], bare: ["PK골[ ({s})]"] }, + PENALTY_MISS: { full: ["{p} PK 실축"], bare: ["PK 실축"] }, + ASSIST: { full: ["도움 {p}"], bare: ["도움"] }, + SHOT: { full: ["{p} 슛"], team: ["{t} 슛"], bare: ["슛"] }, + SAVE: { team: ["{t} 선방"], bare: ["선방"] }, + FOUL: { full: ["{p} 파울"], team: ["{t} 파울"], bare: ["파울"] }, + YELLOW: { full: ["{p}"], team: ["{t} 경고"], bare: ["경고"] }, + RED: { full: ["{p} 퇴장"], team: ["{t} 퇴장"], bare: ["퇴장"] }, + CORNER: { full: ["{p} CK"], team: ["{t} CK"], bare: ["CK"] }, + OFFSIDE: { full: ["{p} 오프사이드"], team: ["{t} 오프사이드"], bare: ["오프사이드"] }, + SUBSTITUTION: { full: ["{in} ↔ {out}"], team: ["{t} 교체"], bare: ["교체"] }, + VAR: { bare: ["VAR"] }, + PERIOD_START: { bare: ["{per} 시작"] }, + PERIOD_END: { bare: ["{per} 종료"] }, + FULLTIME: { full: ["FT {s}"], bare: ["FT"] }, + COIN_TOSS: { team: ["{t} 선축"], bare: ["동전 던지기"] }, + BREAK: { bare: ["중단"] }, + RESUMED: { bare: ["재개"] }, + ADDED_TIME: { full: ["+{n}'"], bare: ["추가시간"] }, + UNKNOWN: { bare: ["경기 상황"] }, +}; + +export const TONE_TEMPLATES: Record = { + official: OFFICIAL, + community: COMMUNITY, + brief: BRIEF, +}; + +/** Official-tone goal score phrases, keyed by the scorer's standing. */ +export const SCORE_PHRASES = { + lead: "{t:이가} 앞서갑니다 {s}", + tie: "동점입니다 {s}", + behind: "{t:이가} 추격합니다 {s}", + plain: "스코어 {s}", +} as const; + +/** FIFA period code → Korean label. */ +export function periodLabel(period: number | undefined): string | undefined { + switch (period) { + case 3: return "전반"; + case 5: return "후반"; + case 7: return "연장 전반"; + case 9: return "연장 후반"; + default: return undefined; + } +} + +/** Deterministic variant pick — FNV-1a over the stable event id. */ +function fnv1a(s: string): number { + let h = 0x811c9dc5; + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +/** 받침 유무에 따른 조사 선택. Latin/unknown endings take the vowel form. */ +function josa(word: string, withBatchim: string, without: string): string { + const ch = word.charCodeAt(word.length - 1); + if (ch >= 0xac00 && ch <= 0xd7a3) { + return (ch - 0xac00) % 28 > 0 ? withBatchim : without; + } + return without; +} + +type Facts = Record; + +const PLACEHOLDER = /\{(p|t|s|in|out|n|per|sp)(?::(.)(.))?\}/g; + +/** Fill a template; null when a mandatory placeholder has no fact. */ +function fill(tpl: string, facts: Facts): string | null { + // optional groups: kept only when everything inside resolves + const withOptionals = tpl.replace(/\[([^\]]*)\]/g, (_, inner: string) => { + const resolved = fill(inner, facts); + return resolved ?? ""; + }); + let missing = false; + const out = withOptionals.replace( + PLACEHOLDER, + (_, key: string, j1?: string, j2?: string) => { + const v = facts[key]; + if (v === undefined || v === "") { + missing = true; + return ""; + } + return j1 && j2 ? v + josa(v, j1, j2) : v; + }, + ); + return missing ? null : out; +} + +export interface ToneCtx { + /** Display name of the event's team (already localized). */ + team?: string; + /** Score at the moment of the event (for goal/full-time sentences). */ + score?: Score; +} + +function displayPlayer(raw: string | undefined, tone: Tone): string | undefined { + if (!raw) return undefined; + const norm = normalizePlayerName(raw); + return tone === "official" ? norm : hangulSurname(norm); +} + +function scorePhrase( + e: Pick, + ctx: ToneCtx, +): string | undefined { + const s = ctx.score; + if (!s) return undefined; + const scoreStr = `${s.home}:${s.away}`; + const facts: Facts = { t: ctx.team, s: scoreStr }; + if (!e.teamSide || !ctx.team) return fill(SCORE_PHRASES.plain, facts) ?? undefined; + const mine = e.teamSide === "home" ? s.home : s.away; + const theirs = e.teamSide === "home" ? s.away : s.home; + const tpl = + mine > theirs + ? SCORE_PHRASES.lead + : mine === theirs + ? SCORE_PHRASES.tie + : SCORE_PHRASES.behind; + return fill(tpl, facts) ?? undefined; +} + +/** + * Render one event as a sentence in the given tone. Pure and deterministic: + * the same event + tone + ctx always produce the same sentence (variant + * choice hashes the stable event id). + */ +export function toneSentence( + e: Pick< + TimelineEvent, + "type" | "id" | "teamSide" | "player" | "playerIn" | "playerOut" | "injury" | "period" + >, + tone: Tone, + ctx: ToneCtx = {}, +): string { + const forms = TONE_TEMPLATES[tone][e.type] ?? TONE_TEMPLATES[tone].UNKNOWN; + const facts: Facts = { + p: displayPlayer(e.player, tone), + t: ctx.team, + s: ctx.score ? `${ctx.score.home}:${ctx.score.away}` : undefined, + in: displayPlayer(e.playerIn, tone), + out: displayPlayer(e.playerOut, tone), + n: e.type === "ADDED_TIME" && e.injury ? String(e.injury) : undefined, + per: periodLabel(e.period), + sp: tone === "official" ? scorePhrase(e, ctx) : undefined, + }; + const hash = fnv1a(e.id); + for (const pool of [forms.full, forms.team, forms.bare]) { + if (!pool || pool.length === 0) continue; + const start = hash % pool.length; + for (let i = 0; i < pool.length; i++) { + const s = fill(pool[(start + i) % pool.length]!, facts); + if (s !== null) return s.replace(/\s{2,}/g, " ").trim(); + } + } + return "경기 진행"; +} diff --git a/src/data/demo-match.json b/src/data/demo-match.json index ca425f5..a832dc7 100644 --- a/src/data/demo-match.json +++ b/src/data/demo-match.json @@ -35,7 +35,6 @@ "period": 2, "teamSide": "away", "teamCode": "ESP", - "text": "동전 던지기 — 스페인 선축", "source": "fifa", "seq": 0 }, @@ -44,7 +43,6 @@ "type": "PERIOD_START", "minute": 0, "period": 3, - "text": "전반 시작", "source": "fifa", "seq": 1 }, @@ -56,7 +54,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 파울", "source": "fifa", "seq": 2 }, @@ -68,7 +65,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Mikel OYARZABAL", - "text": "Mikel OYARZABAL (스페인) 슈팅 시도", "source": "fifa", "seq": 3 }, @@ -79,7 +75,6 @@ "period": 3, "teamSide": "home", "teamCode": "POR", - "text": "포르투갈 골키퍼 선방", "source": "fifa", "seq": 4 }, @@ -91,7 +86,6 @@ "teamSide": "home", "teamCode": "POR", "player": "JOAO CANCELO", - "text": "JOAO CANCELO (포르투갈) 슈팅 시도", "source": "fifa", "seq": 5 }, @@ -103,7 +97,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Mikel OYARZABAL", - "text": "Mikel OYARZABAL (스페인) 슈팅 시도", "source": "fifa", "seq": 6 }, @@ -114,7 +107,7 @@ "period": 3, "teamSide": "home", "teamCode": "POR", - "text": "BRUNO FERNANDES (포르투갈) 코너킥", + "player": "BRUNO FERNANDES", "source": "fifa", "seq": 7 }, @@ -126,7 +119,6 @@ "teamSide": "home", "teamCode": "POR", "player": "PEDRO NETO", - "text": "PEDRO NETO (포르투갈) 슈팅 시도", "source": "fifa", "seq": 8 }, @@ -138,7 +130,6 @@ "teamSide": "home", "teamCode": "POR", "player": "JOAO FELIX", - "text": "JOAO FELIX (포르투갈) 파울", "source": "fifa", "seq": 9 }, @@ -150,7 +141,6 @@ "teamSide": "home", "teamCode": "POR", "player": "CRISTIANO RONALDO", - "text": "CRISTIANO RONALDO (포르투갈) 슈팅 시도", "source": "fifa", "seq": 10 }, @@ -161,7 +151,6 @@ "period": 3, "teamSide": "away", "teamCode": "ESP", - "text": "스페인 골키퍼 선방", "source": "fifa", "seq": 11 }, @@ -172,7 +161,7 @@ "period": 3, "teamSide": "home", "teamCode": "POR", - "text": "NUNO MENDES (포르투갈) 코너킥", + "player": "NUNO MENDES", "source": "fifa", "seq": 12 }, @@ -184,7 +173,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Alex BAENA", - "text": "Alex BAENA (스페인) 슈팅 시도", "source": "fifa", "seq": 13 }, @@ -196,7 +184,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 슈팅 시도", "source": "fifa", "seq": 14 }, @@ -207,7 +194,6 @@ "period": 3, "teamSide": "home", "teamCode": "POR", - "text": "포르투갈 골키퍼 선방", "source": "fifa", "seq": 15 }, @@ -219,7 +205,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Alex BAENA", - "text": "Alex BAENA (스페인) 슈팅 시도", "source": "fifa", "seq": 16 }, @@ -230,7 +215,6 @@ "period": 3, "teamSide": "home", "teamCode": "POR", - "text": "포르투갈 골키퍼 선방", "source": "fifa", "seq": 17 }, @@ -241,7 +225,7 @@ "period": 3, "teamSide": "away", "teamCode": "ESP", - "text": "Alex BAENA (스페인) 코너킥", + "player": "Alex BAENA", "source": "fifa", "seq": 18 }, @@ -253,7 +237,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Alex BAENA", - "text": "Alex BAENA (스페인) 파울", "source": "fifa", "seq": 19 }, @@ -265,7 +248,6 @@ "teamSide": "home", "teamCode": "POR", "player": "BRUNO FERNANDES", - "text": "BRUNO FERNANDES (포르투갈) 오프사이드", "source": "fifa", "seq": 20 }, @@ -277,7 +259,6 @@ "teamSide": "home", "teamCode": "POR", "player": "JOAO CANCELO", - "text": "JOAO CANCELO (포르투갈) 파울", "source": "fifa", "seq": 21 }, @@ -289,7 +270,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Pedro PORRO", - "text": "Pedro PORRO (스페인) 슈팅 시도", "source": "fifa", "seq": 22 }, @@ -298,7 +278,6 @@ "type": "BREAK", "minute": 23, "period": 3, - "text": "수분 섭취 휴식 — 경기 일시 중단", "source": "fifa", "seq": 23 }, @@ -307,7 +286,6 @@ "type": "RESUMED", "minute": 26, "period": 3, - "text": "경기 재개", "source": "fifa", "seq": 24 }, @@ -319,7 +297,6 @@ "teamSide": "home", "teamCode": "POR", "player": "PEDRO NETO", - "text": "PEDRO NETO (포르투갈) 파울", "source": "fifa", "seq": 25 }, @@ -330,7 +307,7 @@ "period": 3, "teamSide": "away", "teamCode": "ESP", - "text": "Alex BAENA (스페인) 코너킥", + "player": "Alex BAENA", "source": "fifa", "seq": 26 }, @@ -342,7 +319,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Dani OLMO", - "text": "Dani OLMO (스페인) 슈팅 시도", "source": "fifa", "seq": 27 }, @@ -354,7 +330,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Aymeric LAPORTE", - "text": "Aymeric LAPORTE (스페인) 파울", "source": "fifa", "seq": 28 }, @@ -366,7 +341,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 파울", "source": "fifa", "seq": 29 }, @@ -378,7 +352,6 @@ "teamSide": "home", "teamCode": "POR", "player": "CRISTIANO RONALDO", - "text": "CRISTIANO RONALDO (포르투갈) 슈팅 시도", "source": "fifa", "seq": 30 }, @@ -389,7 +362,6 @@ "period": 3, "teamSide": "away", "teamCode": "ESP", - "text": "스페인 골키퍼 선방", "source": "fifa", "seq": 31 }, @@ -401,7 +373,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Pedro PORRO", - "text": "Pedro PORRO (스페인) 파울", "source": "fifa", "seq": 32 }, @@ -412,7 +383,7 @@ "period": 3, "teamSide": "home", "teamCode": "POR", - "text": "NUNO MENDES (포르투갈) 코너킥", + "player": "NUNO MENDES", "source": "fifa", "seq": 33 }, @@ -424,7 +395,6 @@ "teamSide": "home", "teamCode": "POR", "player": "NUNO MENDES", - "text": "NUNO MENDES (포르투갈) 슈팅 시도", "source": "fifa", "seq": 34 }, @@ -436,7 +406,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "RODRI", - "text": "RODRI (스페인) 슈팅 시도", "source": "fifa", "seq": 35 }, @@ -449,7 +418,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 오프사이드", "source": "fifa", "seq": 36 }, @@ -462,7 +430,6 @@ "teamSide": "home", "teamCode": "POR", "player": "RUBEN DIAS", - "text": "RUBEN DIAS (포르투갈) 파울", "source": "fifa", "seq": 37 }, @@ -475,7 +442,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Pau CUBARSI", - "text": "Pau CUBARSI (스페인) 파울", "source": "fifa", "seq": 38 }, @@ -488,7 +454,6 @@ "teamSide": "home", "teamCode": "POR", "player": "JOAO FELIX", - "text": "JOAO FELIX (포르투갈) 파울", "source": "fifa", "seq": 39 }, @@ -498,7 +463,6 @@ "minute": 45, "injury": 7, "period": 3, - "text": "전반 종료", "source": "fifa", "seq": 40 }, @@ -507,7 +471,6 @@ "type": "PERIOD_START", "minute": 45, "period": 5, - "text": "후반 시작", "source": "fifa", "seq": 41 }, @@ -519,7 +482,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Dani OLMO", - "text": "Dani OLMO (스페인) 파울", "source": "fifa", "seq": 42 }, @@ -531,7 +493,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 파울", "source": "fifa", "seq": 43 }, @@ -542,7 +503,8 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "선수 교체 (포르투갈): NELSON SEMEDO IN, NUNO MENDES OUT", + "playerIn": "NELSON SEMEDO", + "playerOut": "NUNO MENDES", "source": "fifa", "seq": 44 }, @@ -554,7 +516,6 @@ "teamSide": "home", "teamCode": "POR", "player": "CRISTIANO RONALDO", - "text": "CRISTIANO RONALDO (포르투갈) 오프사이드", "source": "fifa", "seq": 45 }, @@ -566,7 +527,6 @@ "teamSide": "home", "teamCode": "POR", "player": "CRISTIANO RONALDO", - "text": "CRISTIANO RONALDO (포르투갈) 슈팅 시도", "source": "fifa", "seq": 46 }, @@ -578,7 +538,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 파울", "source": "fifa", "seq": 47 }, @@ -590,7 +549,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "PEDRI", - "text": "PEDRI (스페인) 슈팅 시도", "source": "fifa", "seq": 48 }, @@ -601,7 +559,7 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "Alex BAENA (스페인) 코너킥", + "player": "Alex BAENA", "source": "fifa", "seq": 49 }, @@ -613,7 +571,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 슈팅 시도", "source": "fifa", "seq": 50 }, @@ -624,7 +581,7 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "Alex BAENA (스페인) 코너킥", + "player": "Alex BAENA", "source": "fifa", "seq": 51 }, @@ -636,7 +593,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "PEDRI", - "text": "PEDRI (스페인) 파울", "source": "fifa", "seq": 52 }, @@ -648,7 +604,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Alex BAENA", - "text": "Alex BAENA (스페인) 슈팅 시도", "source": "fifa", "seq": 53 }, @@ -659,7 +614,6 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "포르투갈 골키퍼 선방", "source": "fifa", "seq": 54 }, @@ -668,7 +622,6 @@ "type": "BREAK", "minute": 68, "period": 5, - "text": "수분 섭취 휴식 — 경기 일시 중단", "source": "fifa", "seq": 55 }, @@ -679,7 +632,8 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "선수 교체 (포르투갈): RAFAEL LEAO IN, JOAO FELIX OUT", + "playerIn": "RAFAEL LEAO", + "playerOut": "JOAO FELIX", "source": "fifa", "seq": 56 }, @@ -690,7 +644,8 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "선수 교체 (포르투갈): DIOGO DALOT IN, JOAO CANCELO OUT", + "playerIn": "DIOGO DALOT", + "playerOut": "JOAO CANCELO", "source": "fifa", "seq": 57 }, @@ -699,7 +654,6 @@ "type": "RESUMED", "minute": 72, "period": 5, - "text": "경기 재개", "source": "fifa", "seq": 58 }, @@ -711,7 +665,6 @@ "teamSide": "home", "teamCode": "POR", "player": "NELSON SEMEDO", - "text": "NELSON SEMEDO (포르투갈) 파울", "source": "fifa", "seq": 59 }, @@ -723,7 +676,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 슈팅 시도", "source": "fifa", "seq": 60 }, @@ -734,7 +686,6 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "포르투갈 골키퍼 선방", "source": "fifa", "seq": 61 }, @@ -745,7 +696,7 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "Alex BAENA (스페인) 코너킥", + "player": "Alex BAENA", "source": "fifa", "seq": 62 }, @@ -756,7 +707,8 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "선수 교체 (스페인): Ferran TORRES IN, Alex BAENA OUT", + "playerIn": "Ferran TORRES", + "playerOut": "Alex BAENA", "source": "fifa", "seq": 63 }, @@ -768,7 +720,6 @@ "teamSide": "home", "teamCode": "POR", "player": "VITINHA", - "text": "VITINHA (포르투갈) 슈팅 시도", "source": "fifa", "seq": 64 }, @@ -780,7 +731,6 @@ "teamSide": "home", "teamCode": "POR", "player": "BRUNO FERNANDES", - "text": "BRUNO FERNANDES (포르투갈) 슈팅 시도", "source": "fifa", "seq": 65 }, @@ -792,7 +742,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Ferran TORRES", - "text": "Ferran TORRES (스페인) 슈팅 시도", "source": "fifa", "seq": 66 }, @@ -804,7 +753,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Dani OLMO", - "text": "Dani OLMO (스페인) 슈팅 시도", "source": "fifa", "seq": 67 }, @@ -815,7 +763,7 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "Lamine YAMAL (스페인) 코너킥", + "player": "Lamine YAMAL", "source": "fifa", "seq": 68 }, @@ -826,7 +774,7 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "Lamine YAMAL (스페인) 코너킥", + "player": "Lamine YAMAL", "source": "fifa", "seq": 69 }, @@ -838,7 +786,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "RODRI", - "text": "RODRI (스페인) 파울", "source": "fifa", "seq": 70 }, @@ -849,7 +796,8 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "선수 교체 (포르투갈): BERNARDO SILVA IN, VITINHA OUT", + "playerIn": "BERNARDO SILVA", + "playerOut": "VITINHA", "source": "fifa", "seq": 71 }, @@ -860,7 +808,8 @@ "period": 5, "teamSide": "home", "teamCode": "POR", - "text": "선수 교체 (포르투갈): FRANCISCO CONCEICAO IN, PEDRO NETO OUT", + "playerIn": "FRANCISCO CONCEICAO", + "playerOut": "PEDRO NETO", "source": "fifa", "seq": 72 }, @@ -872,7 +821,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Lamine YAMAL", - "text": "Lamine YAMAL (스페인) 파울", "source": "fifa", "seq": 73 }, @@ -883,7 +831,8 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "선수 교체 (스페인): Mikel MERINO IN, Dani OLMO OUT", + "playerIn": "Mikel MERINO", + "playerOut": "Dani OLMO", "source": "fifa", "seq": 74 }, @@ -894,7 +843,8 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "선수 교체 (스페인): Fabian RUIZ IN, PEDRI OUT", + "playerIn": "Fabian RUIZ", + "playerOut": "PEDRI", "source": "fifa", "seq": 75 }, @@ -906,7 +856,6 @@ "teamSide": "home", "teamCode": "POR", "player": "BERNARDO SILVA", - "text": "BERNARDO SILVA (포르투갈) 경고 (옐로카드)", "source": "fifa", "seq": 76 }, @@ -918,7 +867,6 @@ "teamSide": "home", "teamCode": "POR", "player": "BERNARDO SILVA", - "text": "BERNARDO SILVA (포르투갈) 파울", "source": "fifa", "seq": 77 }, @@ -930,7 +878,7 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "어시스트: Ferran TORRES", + "player": "Ferran TORRES", "source": "fifa", "seq": 78 }, @@ -943,7 +891,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Mikel MERINO", - "text": "Mikel MERINO (스페인) 슈팅 시도", "source": "fifa", "seq": 79 }, @@ -956,7 +903,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Mikel MERINO", - "text": "Mikel MERINO (스페인) 득점!", "scoreAfter": { "home": 0, "away": 1 @@ -973,7 +919,6 @@ "teamSide": "home", "teamCode": "POR", "player": "RENATO VEIGA", - "text": "RENATO VEIGA (포르투갈) 경고 (옐로카드)", "source": "fifa", "seq": 81 }, @@ -986,7 +931,6 @@ "teamSide": "home", "teamCode": "POR", "player": "BERNARDO SILVA", - "text": "BERNARDO SILVA (포르투갈) 슈팅 시도", "source": "fifa", "seq": 82 }, @@ -998,7 +942,8 @@ "period": 5, "teamSide": "away", "teamCode": "ESP", - "text": "선수 교체 (스페인): Borja IGLESIAS IN, Mikel OYARZABAL OUT", + "playerIn": "Borja IGLESIAS", + "playerOut": "Mikel OYARZABAL", "source": "fifa", "seq": 83 }, @@ -1011,7 +956,6 @@ "teamSide": "away", "teamCode": "ESP", "player": "Ferran TORRES", - "text": "Ferran TORRES (스페인) 경고 (옐로카드)", "source": "fifa", "seq": 84 }, @@ -1024,7 +968,6 @@ "teamSide": "home", "teamCode": "POR", "player": "JOAO NEVES", - "text": "JOAO NEVES (포르투갈) 슈팅 시도", "source": "fifa", "seq": 85 }, @@ -1034,7 +977,6 @@ "minute": 90, "injury": 9, "period": 5, - "text": "후반 종료", "source": "fifa", "seq": 86 }, @@ -1043,7 +985,6 @@ "type": "FULLTIME", "minute": 99, "period": 10, - "text": "경기 종료", "source": "fifa", "seq": 87 } diff --git a/src/data/espn.ts b/src/data/espn.ts index 3d6d93a..8b20227 100644 --- a/src/data/espn.ts +++ b/src/data/espn.ts @@ -1,4 +1,3 @@ -import { eventSentence } from "../core/i18n.js"; import { parseMatchMinute, type EventType, @@ -227,10 +226,6 @@ export class EspnProvider implements MatchDataProvider { ? { teamSide, teamCode: match[teamSide].code } : {}), ...(player ? { player } : {}), - text: eventSentence({ type }, lang, { - player, - team: teamSide ? match[teamSide].name : teamName, - }), source: "espn", seq: i, }; diff --git a/src/data/fifa.ts b/src/data/fifa.ts index 3d25f83..1504a86 100644 --- a/src/data/fifa.ts +++ b/src/data/fifa.ts @@ -1,4 +1,8 @@ -import { eventSentence } from "../core/i18n.js"; +import { + assistPlayerFrom, + leadingPlayerFrom, + subPlayersFrom, +} from "../core/factextract.js"; import { parseMatchMinute, type EventType, @@ -129,6 +133,7 @@ function normalizeMatch(m: any): Match { return match; } +/** Types whose FIFA prose leads with "PLAYER (TEAM)" — actor extractable. */ const PLAYER_TYPES: ReadonlySet = new Set([ "GOAL", "OWN_GOAL", @@ -139,14 +144,9 @@ const PLAYER_TYPES: ReadonlySet = new Set([ "SHOT", "OFFSIDE", "FOUL", + "CORNER", ]); -function extractPlayer(text: string | undefined): string | undefined { - if (!text) return undefined; - const m = /^(.{2,40}?)\s*\(/.exec(text); - return m?.[1]?.trim() || undefined; -} - export class FifaProvider implements MatchDataProvider { readonly name = "fifa" as const; @@ -234,6 +234,9 @@ export class FifaProvider implements MatchDataProvider { return data.Event.map((e: any, i: number): TimelineEvent => { const type = (map[String(e.Type)] ?? "UNKNOWN") as EventType; const { minute, injury } = parseMatchMinute(e.MatchMinute); + // Feed prose is a parse source only: facts are extracted here and the + // sentence never leaves this function — display text is rendered from + // structure at view time (and recordings stay prose-free). const text: string | undefined = e.EventDescription?.[0]?.Description || undefined; const teamSide = @@ -244,6 +247,13 @@ export class FifaProvider implements MatchDataProvider { : undefined; const isGoal = type === "GOAL" || type === "OWN_GOAL" || type === "PENALTY_GOAL"; + const player = + type === "ASSIST" + ? assistPlayerFrom(text) + : PLAYER_TYPES.has(type) + ? leadingPlayerFrom(text) + : undefined; + const sub = type === "SUBSTITUTION" ? subPlayersFrom(text) : undefined; return { id: `fifa:${e.EventId ?? `${e.Type}-${e.MatchMinute}-${i}`}`, type, @@ -254,14 +264,8 @@ export class FifaProvider implements MatchDataProvider { ? { teamCode: teamSide ? match[teamSide].code : String(e.IdTeam) } : {}), ...(teamSide ? { teamSide } : {}), - ...(PLAYER_TYPES.has(type) - ? { player: extractPlayer(text) } - : {}), - text: - text ?? - eventSentence({ type }, lang, { - team: teamSide ? match[teamSide].name : undefined, - }), + ...(player ? { player } : {}), + ...(sub ? { playerIn: sub.playerIn, playerOut: sub.playerOut } : {}), ...(isGoal && typeof e.HomeGoals === "number" ? { scoreAfter: { home: e.HomeGoals, away: e.AwayGoals } } : {}), diff --git a/src/data/hangul-names.json b/src/data/hangul-names.json new file mode 100644 index 0000000..114096b --- /dev/null +++ b/src/data/hangul-names.json @@ -0,0 +1,106 @@ +{ + "__comment": "Roman→Hangul overrides where the rule engine's spelling-based guess is wrong. Keys are lowercase with diacritics/apostrophes/hyphens stripped (see exceptionKey in core/hangul.ts). Seeded with the 2026 QF-onward squads (FRA/MAR/ESP/BEL/NOR/ENG/ARG/SUI) plus the bundled POR-ESP demo corpus.", + + "joao": "주앙", + "cancelo": "칸셀루", + "ronaldo": "호날두", + "bernardo": "베르나르두", + "semedo": "세메두", + "leao": "레앙", + "conceicao": "콘세이상", + "felix": "펠릭스", + "vitinha": "비티냐", + "dalot": "달로", + "goncalo": "곤살루", + "ramos": "하무스", + "rafael": "하파엘", + "veiga": "베이가", + + "oyarzabal": "오야르사발", + "ruiz": "루이스", + "carvajal": "카르바할", + "laporte": "라포르트", + "williams": "윌리엄스", + "cucurella": "쿠쿠레야", + "iglesias": "이글레시아스", + "unai simon": "우나이 시몬", + "baena": "바에나", + "cubarsi": "쿠바르시", + "fabian": "파비안", + "lamine": "라민", + + "mbappe": "음바페", + "griezmann": "그리즈만", + "dembele": "뎀벨레", + "tchouameni": "추아메니", + "camavinga": "카마빙가", + "maignan": "메냥", + "kounde": "쿤데", + "hernandez": "에르난데스", + "giroud": "지루", + "upamecano": "우파메카노", + "thuram": "튀랑", + "barcola": "바르콜라", + + "hakimi": "하키미", + "ziyech": "지예흐", + "ennesyri": "엔네시리", + "bounou": "부누", + "amrabat": "암라바트", + "aguerd": "아게르드", + "ounahi": "우나히", + "adli": "아들리", + + "de bruyne": "더 브라위너", + "bruyne": "브라위너", + "lukaku": "루카쿠", + "doku": "도쿠", + "courtois": "쿠르투아", + "trossard": "트로사르", + "de ketelaere": "더 케텔라러", + "ketelaere": "케텔라러", + "onana": "오나나", + "bakayoko": "바카요코", + + "haaland": "홀란드", + "odegaard": "외데고르", + "sorloth": "쇠를로트", + "nusa": "누사", + "berge": "베르게", + "ajer": "아예르", + "nyland": "닐란", + + "kane": "케인", + "bellingham": "벨링엄", + "saka": "사카", + "foden": "포든", + "rice": "라이스", + "palmer": "파머", + "pickford": "픽포드", + "stones": "스톤스", + "walker": "워커", + "gordon": "고든", + "watkins": "왓킨스", + + "messi": "메시", + "martinez": "마르티네스", + "alvarez": "알바레스", + "de paul": "데 파울", + "paul": "파울", + "mac allister": "맥 알리스터", + "allister": "알리스터", + "fernandez": "페르난데스", + "di maria": "디 마리아", + "maria": "마리아", + "romero": "로메로", + "otamendi": "오타멘디", + + "xhaka": "자카", + "shaqiri": "샤키리", + "sommer": "조머", + "embolo": "엠볼로", + "akanji": "아칸지", + "vargas": "바르가스", + "rieder": "리더", + "elvedi": "엘베디" +} diff --git a/src/engine/polling.ts b/src/engine/polling.ts index 479d275..65ca02f 100644 --- a/src/engine/polling.ts +++ b/src/engine/polling.ts @@ -182,7 +182,6 @@ export class PollingEngine extends EventEmitter { // from the injury field, once per phase (bypasses the differ: local // events are never subject to source-switch cancellation). const addedTime = synthesizeAddedTime(this.prevState, state, { - lang: this.lang, source: this.provider.name, }); this.prevState = state; diff --git a/src/replay/player.ts b/src/replay/player.ts index a0ee2ed..377a3b0 100644 --- a/src/replay/player.ts +++ b/src/replay/player.ts @@ -1,4 +1,11 @@ import { EventEmitter } from "node:events"; +import { + addedTimeFrom, + assistPlayerFrom, + cleanPlayerFact, + leadingPlayerFrom, + subPlayersFrom, +} from "../core/factextract.js"; import { CELEBRATION_TYPES, compareEvents, @@ -14,6 +21,38 @@ export interface ParsedReplay { events: TimelineEvent[]; } +/** + * Pre-v0.4 recordings carried some facts (sub in/out, assist taker, + * added-time amount) only inside the stored prose sentence — promote them + * to structured fields on load so tone rendering can use them. The stored + * prose itself is never displayed (it may be source-feed text). + */ +function enrichFromStoredText(raw: TimelineEvent): TimelineEvent { + const e = { ...raw }; + const cleaned = cleanPlayerFact(e.player); // strips the "주심이 " wart + if (cleaned) e.player = cleaned; + else if (e.player) delete e.player; + const text = e.text; + if (!text) return e; + if (e.type === "SUBSTITUTION" && (!e.playerIn || !e.playerOut)) { + const sub = subPlayersFrom(text); + if (sub) { + e.playerIn = e.playerIn ?? sub.playerIn; + e.playerOut = e.playerOut ?? sub.playerOut; + } + } else if (e.type === "ASSIST" && !e.player) { + const p = assistPlayerFrom(text); + if (p) e.player = p; + } else if (e.type === "CORNER" && !e.player) { + const p = leadingPlayerFrom(text); + if (p) e.player = p; + } else if (e.type === "ADDED_TIME" && e.injury === undefined) { + const n = addedTimeFrom(text); + if (n !== undefined) e.injury = n; + } + return e; +} + export function parseReplay(content: string): ParsedReplay { const lines = content.split("\n").filter((l) => l.trim().length > 0); if (lines.length === 0) throw new Error("empty replay file"); @@ -26,7 +65,7 @@ export function parseReplay(content: string): ParsedReplay { const e = JSON.parse(line) as TimelineEvent; if (seen.has(e.id)) continue; // re-watch sessions may duplicate lines seen.add(e.id); - events.push(e); + events.push(enrichFromStoredText(e)); } events.sort(compareEvents); return { match: header.match, events }; diff --git a/src/store/store.ts b/src/store/store.ts index b8c229f..dd45562 100644 --- a/src/store/store.ts +++ b/src/store/store.ts @@ -39,6 +39,8 @@ export function atomicWrite(file: string, data: string): void { export interface Config { lang?: Lang; + /** Commentary tone preset (v0.4+). Consumers validate with isTone(). */ + tone?: string; } export function readConfig(): Config { diff --git a/src/ui/matchScreen.ts b/src/ui/matchScreen.ts index 9f1ee0f..889f292 100644 --- a/src/ui/matchScreen.ts +++ b/src/ui/matchScreen.ts @@ -1,7 +1,7 @@ import { EventEmitter } from "node:events"; import * as readline from "node:readline"; import { ClockInterpolator, formatClock } from "../core/clock.js"; -import { EVENT_ICON, labels, type Labels } from "../core/i18n.js"; +import { enEventSentence, EVENT_ICON, labels, type Labels } from "../core/i18n.js"; import { BOUNDARY_PHASES, boundaryPhaseOf, @@ -19,9 +19,11 @@ import { type TimelineEvent, } from "../core/model.js"; import { phaseLabel } from "../core/state.js"; +import { hangulSurname } from "../core/hangul.js"; +import { TONES, toneSentence, type Tone } from "../core/tone.js"; import { liveWinProb, type WinProb } from "../core/winprob.js"; import type { NetInfo } from "../engine/polling.js"; -import { normalizeEventText, normalizePlayerName } from "../core/text.js"; +import { normalizePlayerName } from "../core/text.js"; import { bgYellow, bold, @@ -62,9 +64,13 @@ const SYSTEM_TYPES: ReadonlySet = new Set([ ]); /** Log entries are stored structured and formatted at render time, so - * alignment follows the current terminal width (and resizes). */ + * alignment follows the current terminal width (and resizes) and the whole + * log re-renders in a new tone when the user toggles it. `score` captures + * the score at receive time for events whose sentence quotes it (goals, + * full-time) — ESPN goals carry no scoreAfter of their own. */ type LogLine = - | { kind: "event"; e: TimelineEvent } + | { kind: "event"; e: TimelineEvent; score?: Score } + | { kind: "cancelled"; e: TimelineEvent } | { kind: "text"; text: string; align?: "left" | "center" } | { kind: "sep" } | { kind: "boundary"; phase: MatchPhase; score: Score }; @@ -73,6 +79,7 @@ export interface MatchScreenOptions { lang: Lang; mode: "live" | "replay"; animations: boolean; + tone?: Tone; clockRate?: number; speedLabel?: string; lambdas?: { lh: number; la: number } | null; @@ -103,6 +110,7 @@ export class MatchScreen { private cancelledIds = new Set(); private boundariesMarked = new Set(); private lastPhase: MatchPhase | null = null; + private tone: Tone; constructor( private readonly match: Match, @@ -110,6 +118,7 @@ export class MatchScreen { private readonly opts: MatchScreenOptions, ) { this.l = labels(opts.lang); + this.tone = opts.tone ?? "official"; this.clock = new ClockInterpolator(undefined, opts.clockRate ?? 1); this.controller = new AnimationController((frame) => { const pad = Math.max(0, Math.floor((this.t.rows() - frame.length) / 2)); @@ -120,7 +129,8 @@ export class MatchScreen { } } - async run(): Promise { + /** Resolves with the tone in effect at exit (caller may persist it). */ + async run(): Promise { const { out } = this.t; enterAltScreen(out); const input = process.stdin; @@ -137,6 +147,10 @@ export class MatchScreen { resolveDone(); } else if (name === "s") { this.controller.skip(); + } else if (name === "t" && this.opts.lang === "ko") { + // cycle the tone and repaint the whole log in it (ko-only feature) + this.tone = TONES[(TONES.indexOf(this.tone) + 1) % TONES.length]!; + this.render(); } else if (this.finished) { resolveDone(); } @@ -165,6 +179,7 @@ export class MatchScreen { input.pause(); this.feed.stop(); leaveAltScreen(out); + return this.tone; } private subscribe(): void { @@ -189,11 +204,16 @@ export class MatchScreen { this.opts.onEvents?.(events); const entries: LogLine[] = []; for (const e of events) { - if (e.type === "ASSIST" && !e.text) continue; // assists render as text lines too const isGoal = e.type === "GOAL" || e.type === "PENALTY_GOAL" || e.type === "OWN_GOAL"; + // capture the score for sentences that quote it — deterministic + // across re-renders and tone toggles + const score = + isGoal || e.type === "FULLTIME" + ? (e.scoreAfter ?? this.state?.score ?? this.match.score) + : undefined; if (isGoal) entries.push({ kind: "sep" }); - entries.push({ kind: "event", e }); + entries.push({ kind: "event", e, ...(score ? { score: { ...score } } : {}) }); if (isGoal) entries.push({ kind: "sep" }); } this.keyEvents.push(...events); @@ -241,8 +261,7 @@ export class MatchScreen { this.feed.on("cancelled", (e: TimelineEvent) => { this.cancelledIds.add(e.id); // strip drops the disallowed goal - const line = `${dim(formatEventClock(e).padStart(7))} ${red(`📺 ${this.l.goalCancelled} (${this.l.corrected})`)} ${dim(e.text ? normalizeEventText(e.text) : "")}`; - this.pushLine({ kind: "text", text: line }); + this.pushLine({ kind: "cancelled", e }); }); this.feed.on("sourceSwitched", () => { @@ -288,9 +307,19 @@ export class MatchScreen { } } - private formatEvent(e: TimelineEvent, cols: number): string { + /** Render-time sentence: ko follows the active tone, en keeps one register. */ + private sentence(e: TimelineEvent, score?: Score): string { + const team = e.teamSide ? this.match[e.teamSide].name : undefined; + if (this.opts.lang === "ko") return toneSentence(e, this.tone, { team, score }); + return enEventSentence(e, { + player: e.player ? normalizePlayerName(e.player) : undefined, + team, + }); + } + + private formatEvent(e: TimelineEvent, cols: number, score?: Score): string { const icon = EVENT_ICON[e.type] ?? "·"; - let text = e.text ? normalizeEventText(e.text) : ""; + let text = this.sentence(e, score); if (e.type === "GOAL" || e.type === "PENALTY_GOAL" || e.type === "OWN_GOAL") text = bold(yellow(text)); else if (e.type === "RED") text = bold(red(text)); @@ -326,7 +355,11 @@ export class MatchScreen { ); } if (l.kind === "text") return l.align === "center" ? center(l.text, cols) : l.text; - return this.formatEvent(l.e, cols); + if (l.kind === "cancelled") { + const detail = this.sentence(l.e); + return `${dim(formatEventClock(l.e).padStart(7))} ${red(`📺 ${this.l.goalCancelled} (${this.l.corrected})`)} ${dim(detail)}`; + } + return this.formatEvent(l.e, cols, l.score); } /** @@ -338,8 +371,13 @@ export class MatchScreen { if (items.length === 0) return ""; const parts = items.map((e) => { const icon = EVENT_ICON[e.type] ?? ""; - const who = e.player + const surname = e.player ? (normalizePlayerName(e.player).split(" ").pop() ?? "") + : ""; + const who = surname + ? this.tone === "official" + ? surname + : hangulSurname(surname) : (e.teamCode ?? ""); return `${icon}${formatEventClock(e)} ${who}`.trim(); }); diff --git a/test/digest.test.ts b/test/digest.test.ts index 6e6fdb6..4303af1 100644 --- a/test/digest.test.ts +++ b/test/digest.test.ts @@ -43,22 +43,21 @@ const eventOf = (l: Line) => (l.kind === "event" ? l.e : null); describe("synthesizeAddedTime", () => { it("emits once when injury first appears in a phase", () => { const e = synthesizeAddedTime(st({}), st({ injury: 4 }), { - lang: "ko", source: "fifa", }); expect(e).not.toBeNull(); expect(e!.type).toBe("ADDED_TIME"); expect(e!.id).toBe("local:added-time-FIRST_HALF"); - expect(e!.text).toBe("추가시간 +4분"); + expect(e!.injury).toBe(4); // structured fact — sentences render from it + expect(e!.text).toBeUndefined(); // no prose is baked into the event expect(e!.period).toBe(3); // sorts correctly in replay files }); it("emits on the very first state when injury is already set", () => { const e = synthesizeAddedTime(null, st({ injury: 3 }), { - lang: "en", source: "espn", }); - expect(e!.text).toBe("+3 minutes added"); + expect(e!.injury).toBe(3); expect(e!.source).toBe("espn"); }); @@ -66,14 +65,12 @@ describe("synthesizeAddedTime", () => { const announced = st({ injury: 4 }); expect( synthesizeAddedTime(announced, st({ injury: 4 }), { - lang: "ko", source: "fifa", }), ).toBeNull(); // revised upwards mid-stoppage — still the same phase, still silent expect( synthesizeAddedTime(announced, st({ injury: 6 }), { - lang: "ko", source: "fifa", }), ).toBeNull(); @@ -83,21 +80,16 @@ describe("synthesizeAddedTime", () => { const e = synthesizeAddedTime( st({ injury: 4 }), st({ phase: "SECOND_HALF", minute: 90, injury: 5 }), - { lang: "ko", source: "fifa" }, + { source: "fifa" }, ); expect(e!.id).toBe("local:added-time-SECOND_HALF"); expect(e!.period).toBe(5); }); it("stays silent without injury time", () => { + expect(synthesizeAddedTime(null, st({}), { source: "fifa" })).toBeNull(); expect( - synthesizeAddedTime(null, st({}), { lang: "ko", source: "fifa" }), - ).toBeNull(); - expect( - synthesizeAddedTime(null, st({ injury: 0 }), { - lang: "ko", - source: "fifa", - }), + synthesizeAddedTime(null, st({ injury: 0 }), { source: "fifa" }), ).toBeNull(); }); }); diff --git a/test/espn-adapter.test.ts b/test/espn-adapter.test.ts index 1c9de41..8629ab4 100644 --- a/test/espn-adapter.test.ts +++ b/test/espn-adapter.test.ts @@ -33,22 +33,19 @@ const match: Match = { }; describe("EspnProvider.fetchTimeline (real summary fixture)", () => { - it("generates template sentences instead of redistributing ESPN prose", async () => { + it("emits structured events and never redistributes ESPN prose", async () => { mockFetch([[/summary/, fixture("espn-summary.json")]]); const events = await new EspnProvider().fetchTimeline(match, "ko"); expect(events.length).toBeGreaterThan(50); const goal = events.find((e) => e.type === "GOAL")!; expect(goal.player).toBe("Mikel Merino"); - expect(goal.text).toContain("득점"); // our Korean template - expect(goal.text).not.toContain("Synthetic sample"); // fixture text never passes through expect(goal.second).toBeDefined(); // ESPN gives second precision expect(goal.id).toMatch(/^espn:/); - const en = await new EspnProvider().fetchTimeline(match, "en"); - const goalEn = en.find((e) => e.type === "GOAL")!; - expect(goalEn.text).toMatch(/scores/i); - expect(goalEn.text).not.toContain("Synthetic sample"); + // license guard: the fixture's commentary text must never reach events + // (sentences are rendered from structure at view time) + expect(events.every((e) => e.text === undefined)).toBe(true); }); }); diff --git a/test/factextract.test.ts b/test/factextract.test.ts new file mode 100644 index 0000000..f7fa8e2 --- /dev/null +++ b/test/factextract.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import { + addedTimeFrom, + assistPlayerFrom, + leadingPlayerFrom, + subPlayersFrom, +} from "../src/core/factextract.js"; + +describe("subPlayersFrom", () => { + it("parses the live FIFA ko sentence", () => { + expect( + subPlayersFrom( + "NELSON SEMEDO (in) 선수가 NUNO MENDES(교체)(포르투갈) 선수 대신 교체되어 경기장에 들어갑니다.", + ), + ).toEqual({ playerIn: "NELSON SEMEDO", playerOut: "NUNO MENDES" }); + }); + + it("parses the live FIFA en sentence", () => { + expect( + subPlayersFrom( + "NELSON SEMEDO (in) comes off the bench to replace NUNO MENDES (out) (Portugal)", + ), + ).toEqual({ playerIn: "NELSON SEMEDO", playerOut: "NUNO MENDES" }); + }); + + it("parses the v0.3 synthetic sentence (old recordings)", () => { + expect( + subPlayersFrom("선수 교체 (포르투갈): NELSON SEMEDO IN, NUNO MENDES OUT"), + ).toEqual({ playerIn: "NELSON SEMEDO", playerOut: "NUNO MENDES" }); + }); + + it("returns undefined for unrelated text", () => { + expect(subPlayersFrom("파울")).toBeUndefined(); + expect(subPlayersFrom(undefined)).toBeUndefined(); + }); +}); + +describe("assistPlayerFrom", () => { + it("parses ko/en/synthetic shapes", () => { + expect(assistPlayerFrom("Ferran TORRES 선수의 어시스트입니다.")).toBe( + "Ferran TORRES", + ); + expect(assistPlayerFrom("Assisted by Ferran TORRES.")).toBe("Ferran TORRES"); + expect(assistPlayerFrom("어시스트: Ferran TORRES")).toBe("Ferran TORRES"); + }); + + it("returns undefined otherwise", () => { + expect(assistPlayerFrom("골!")).toBeUndefined(); + }); +}); + +describe("addedTimeFrom", () => { + it("parses ko and en added-time sentences", () => { + expect(addedTimeFrom("추가시간 +4분")).toBe(4); + expect(addedTimeFrom("+3 minutes added")).toBe(3); + expect(addedTimeFrom("경기 재개")).toBeUndefined(); + }); +}); + +describe("leadingPlayerFrom", () => { + it("extracts the leading PLAYER (TEAM) name", () => { + expect(leadingPlayerFrom("Lamine YAMAL (스페인) 파울")).toBe("Lamine YAMAL"); + expect(leadingPlayerFrom("골!")).toBeUndefined(); + }); +}); diff --git a/test/fifa-adapter.test.ts b/test/fifa-adapter.test.ts index a710d9b..6753bef 100644 --- a/test/fifa-adapter.test.ts +++ b/test/fifa-adapter.test.ts @@ -55,22 +55,35 @@ describe("FifaProvider.fetchTimeline (real 2026 fixture)", () => { expect(goal!.injury).toBe(1); expect(goal!.teamSide).toBe("away"); // Spain scored expect(goal!.player).toBe("Mikel MERINO"); - expect(goal!.text).toContain("득점"); expect(goal!.scoreAfter).toEqual({ home: 0, away: 1 }); expect(goal!.id).toMatch(/^fifa:/); + }); + + it("never emits feed prose — text is absent, facts are structured", async () => { + mockFetch([[/timelines/, fixture("fifa-timeline-ko.json")]]); + const events = await new FifaProvider().fetchTimeline(match, "ko"); + // sentences are rendered from structure at view time; the adapter must + // not leak the feed's prose into events (or, via them, into recordings) + expect(events.every((e) => e.text === undefined)).toBe(true); + + const sub = events.find((e) => e.type === "SUBSTITUTION"); + expect(sub!.playerIn).toBe("NELSON SEMEDO"); + expect(sub!.playerOut).toBe("NUNO MENDES"); + + const assist = events.find((e) => e.type === "ASSIST"); + expect(assist!.player).toBe("Ferran TORRES"); - // Source-provided text passes through as-is (never re-templated) - const shot = events.find((e) => e.type === "SHOT"); - expect(shot!.text).toContain("슈팅"); + const corner = events.find((e) => e.type === "CORNER"); + expect(corner!.player).toBe("BRUNO FERNANDES"); }); - it("passes unknown type codes through as UNKNOWN with text", async () => { + it("passes unknown type codes through as UNKNOWN without text", async () => { const doc = JSON.parse(fixture("fifa-timeline-ko.json")); doc.Event[0].Type = 9999; mockFetch([[/timelines/, JSON.stringify(doc)]]); const events = await new FifaProvider().fetchTimeline(match, "ko"); expect(events[0]!.type).toBe("UNKNOWN"); - expect(events[0]!.text).toBeTruthy(); + expect(events[0]!.text).toBeUndefined(); }); it("maps VAR review events via the data-file map", async () => { diff --git a/test/fixtures/banned-lexicon.ts b/test/fixtures/banned-lexicon.ts new file mode 100644 index 0000000..811cb32 --- /dev/null +++ b/test/fixtures/banned-lexicon.ts @@ -0,0 +1,33 @@ +/** + * Content-policy gate data (requirements §3): expressions that must never + * appear in any tone's output — profanity, personal disparagement, mockery + * markers. Lives under test/ ON PURPOSE: this list must never be bundled + * into the published CLI (a banned-word list inside dist/cli.js is its own + * reputational risk). + * + * The community tone is the 순한맛 (mild) register by decision — laughter + * markers (ㅋ/ㄷㄷ) are banned globally, not just for sensitive events. + */ + +/** Substrings banned in every tone, every event type, every context. */ +export const BANNED_EVERYWHERE: readonly string[] = [ + // profanity / slurs + "시발", "씨발", "ㅅㅂ", "ㅆㅂ", "병신", "ㅄ", "ㅂㅅ", "존나", "ㅈㄴ", + "새끼", "지랄", "닥쳐", "꺼져", "엿같", "좆", + // personal disparagement (실력 폄하·인신) + "멍청", "바보", "호구", "쓰레기", "노답", "발컨", "한심", "형편없", + "역겹", "재수없", "찐따", "루저", "허접", "구리다", "구려", + // mockery / meme markers (banned by the 순한맛 decision) + "ㅋ", "ㄷㄷ", "ㅉ", "극혐", "노잼", "눈물바다", "조롱", + // english equivalents (player names pass through in official tone) + "idiot", "loser", "trash", "stupid", "suck", +]; + +/** + * Additionally banned in sensitive-event sentences (자책골·PK 실축·퇴장): + * celebration/exclamation at a person's failure reads as mockery even in + * mild wording. + */ +export const BANNED_IN_SENSITIVE: readonly string[] = [ + "!!", "이득", "개이득", "꿀잼", "저럴거면", "덕분에", +]; diff --git a/test/hangul.test.ts b/test/hangul.test.ts new file mode 100644 index 0000000..1e05b48 --- /dev/null +++ b/test/hangul.test.ts @@ -0,0 +1,73 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { + hangulPlayerName, + hangulSurname, + romanWordToHangul, +} from "../src/core/hangul.js"; + +describe("romanWordToHangul (rule engine)", () => { + it("converts common Latin-name shapes", () => { + expect(romanWordToHangul("Merino")).toBe("메리노"); + expect(romanWordToHangul("Silva")).toBe("실바"); + expect(romanWordToHangul("Torres")).toBe("토레스"); + expect(romanWordToHangul("Yamal")).toBe("야말"); + expect(romanWordToHangul("Olmo")).toBe("올모"); + expect(romanWordToHangul("Pedri")).toBe("페드리"); + expect(romanWordToHangul("Felix")).toBe("펠릭스"); + expect(romanWordToHangul("Mendes")).toBe("멘데스"); + }); + + it("is deterministic", () => { + for (const w of ["Merino", "Xhaka", "Nusa", "Bernardo"]) { + expect(romanWordToHangul(w)).toBe(romanWordToHangul(w)); + } + }); + + it("strips diacritics before converting", () => { + expect(romanWordToHangul("Conceição")).toBe(romanWordToHangul("Conceicao")); + }); +}); + +describe("exception table", () => { + it("pins well-known names the rules would get wrong", () => { + expect(hangulPlayerName("João Cancelo")).toBe("주앙 칸셀루"); + expect(hangulSurname("Cristiano Ronaldo")).toBe("호날두"); + expect(hangulSurname("Kylian Mbappé")).toBe("음바페"); + expect(hangulSurname("Harry Kane")).toBe("케인"); + expect(hangulSurname("Granit Xhaka")).toBe("자카"); + }); + + it("passes through names that are already Korean", () => { + expect(hangulPlayerName("손흥민")).toBe("손흥민"); + }); +}); + +describe("harmlessness over the demo corpus", () => { + const demo = JSON.parse( + readFileSync(join(__dirname, "..", "src", "data", "demo-match.json"), "utf8"), + ) as { events: Array<{ player?: string; text?: string }> }; + + const names = new Set(); + for (const e of demo.events) if (e.player) names.add(e.player); + + it("covers every demo player name deterministically with Hangul-only output", () => { + expect(names.size).toBeGreaterThan(10); + for (const name of names) { + const out = hangulSurname(name); + expect(out.length).toBeGreaterThan(0); + expect(out).toBe(hangulSurname(name)); + expect(/^[가-힣 ]+$/.test(out), `${name} → ${out}`).toBe(true); + } + }); +}); + +describe("arbitrary latin input never throws and yields non-empty output", () => { + it("handles odd shapes", () => { + for (const w of ["N'Golo", "Saint-Maximin", "Ødegaard", "McTominay", "Van Dijk", "O'Riley"]) { + const out = hangulPlayerName(w); + expect(out.length).toBeGreaterThan(0); + } + }); +}); diff --git a/test/i18n.test.ts b/test/i18n.test.ts index f3b5c7d..f7408bc 100644 --- a/test/i18n.test.ts +++ b/test/i18n.test.ts @@ -1,27 +1,32 @@ import { describe, expect, it } from "vitest"; -import { eventSentence } from "../src/core/i18n.js"; +import { enEventSentence } from "../src/core/i18n.js"; -describe("eventSentence templates", () => { - it("generates Korean sentences with player and team", () => { +// Korean sentences are owned by the tone presets (see tone.test.ts / +// lexicon.test.ts) — i18n keeps the English single-register generator. +describe("enEventSentence templates", () => { + it("generates English sentences with player and team", () => { expect( - eventSentence({ type: "GOAL" }, "ko", { - player: "손흥민", - team: "대한민국", - }), - ).toBe("골! 손흥민 (대한민국) 득점!"); - expect(eventSentence({ type: "CORNER" }, "ko", { team: "대한민국" })).toBe( - "대한민국 코너킥", - ); + enEventSentence({ type: "RED" }, { player: "Ramos" }), + ).toContain("sent off"); + expect( + enEventSentence({ type: "GOAL" }, { player: "Son", team: "Korea Republic" }), + ).toBe("Goal! Son (Korea Republic) scores!"); }); - it("generates English sentences", () => { + it("uses structured substitution and added-time facts", () => { expect( - eventSentence({ type: "RED" }, "en", { player: "Ramos" }), - ).toContain("sent off"); + enEventSentence( + { type: "SUBSTITUTION", playerIn: "Semedo", playerOut: "Mendes" }, + { team: "Portugal" }, + ), + ).toBe("Substitution (Portugal): Semedo in, Mendes out"); + expect(enEventSentence({ type: "ADDED_TIME", injury: 4 })).toBe( + "+4 minutes added", + ); }); it("degrades gracefully without context", () => { - expect(eventSentence({ type: "GOAL" }, "ko")).toBe("골!"); - expect(eventSentence({ type: "UNKNOWN" }, "en")).toBe("Match event"); + expect(enEventSentence({ type: "GOAL" })).toBe("Goal!"); + expect(enEventSentence({ type: "UNKNOWN" })).toBe("Match event"); }); }); diff --git a/test/lexicon.test.ts b/test/lexicon.test.ts new file mode 100644 index 0000000..58e882d --- /dev/null +++ b/test/lexicon.test.ts @@ -0,0 +1,135 @@ +/** + * Content-policy gate (requirements §3-4). Three layers: + * 1. static scan of every template string in the exported tables + * 2. rendered-output matrix: every tone × every event type × representative + * fact contexts, scanned AFTER transliteration (final sentences) + * 3. structural gate: community sentences for sensitive events must come + * from COMMUNITY_NEUTRAL and carry no exclamation/mockery + * + * ANY template edit in src/core/tone.ts must keep this file green — that is + * the mechanism by which future template additions inherit the policy. + */ +import { describe, expect, it } from "vitest"; +import { ALL_EVENT_TYPES, type Score, type TimelineEvent } from "../src/core/model.js"; +import { + COMMUNITY_NEUTRAL, + SCORE_PHRASES, + SENSITIVE_TYPES, + TONES, + TONE_TEMPLATES, + toneSentence, + type ToneForms, +} from "../src/core/tone.js"; +import { BANNED_EVERYWHERE, BANNED_IN_SENSITIVE } from "./fixtures/banned-lexicon.js"; + +const allTemplateStrings = (): string[] => { + const out: string[] = []; + const collect = (forms: ToneForms | undefined) => { + if (!forms) return; + for (const pool of [forms.full, forms.team, forms.bare]) + if (pool) out.push(...pool); + }; + for (const tone of TONES) + for (const type of ALL_EVENT_TYPES) collect(TONE_TEMPLATES[tone][type]); + for (const type of Object.keys(COMMUNITY_NEUTRAL)) + collect(COMMUNITY_NEUTRAL[type as keyof typeof COMMUNITY_NEUTRAL]); + out.push(...Object.values(SCORE_PHRASES)); + return out; +}; + +describe("layer 1 — every template string is clean", () => { + it("contains no banned expression", () => { + for (const tpl of allTemplateStrings()) { + for (const banned of BANNED_EVERYWHERE) { + expect(tpl.includes(banned), `template "${tpl}" contains "${banned}"`).toBe( + false, + ); + } + } + }); +}); + +// Representative fact contexts: with/without player (roman names that +// transliterate), team names with/without 받침, score lead/tie/behind, +// substitution facts, added-time amount, period codes. +const PLAYERS = [undefined, "Mikel MERINO", "Harry KANE", "N'Golo KANTE"]; +const TEAMS = [undefined, "스페인", "독일", "잉글랜드", "포르투갈"]; +const SCORES: Array = [ + undefined, + { home: 0, away: 1 }, + { home: 1, away: 1 }, + { home: 3, away: 1 }, +]; + +const contextsFor = (type: (typeof ALL_EVENT_TYPES)[number]) => { + const events: Array<{ e: TimelineEvent; team?: string; score?: Score }> = []; + let n = 0; + for (const player of PLAYERS) + for (const team of TEAMS) + for (const score of SCORES) + for (const teamSide of ["home", "away"] as const) { + events.push({ + e: { + id: `t:${n++}`, + type, + minute: 90, + period: [3, 5, 7, 9, undefined][n % 5], + teamSide, + player, + ...(type === "SUBSTITUTION" + ? { playerIn: "Fabian RUIZ", playerOut: "PEDRI" } + : {}), + ...(type === "ADDED_TIME" ? { injury: (n % 6) + 1 } : {}), + source: "fifa", + seq: 0, + }, + team, + score, + }); + } + return events; +}; + +describe("layer 2 — rendered output matrix is clean and non-empty", () => { + for (const tone of TONES) { + it(`tone=${tone}: every type × context`, () => { + for (const type of ALL_EVENT_TYPES) { + for (const { e, team, score } of contextsFor(type)) { + const s = toneSentence(e, tone, { team, score }); + expect(s.length, `${tone}/${type} produced empty output`).toBeGreaterThan(0); + for (const banned of BANNED_EVERYWHERE) { + expect( + s.includes(banned), + `${tone}/${type} → "${s}" contains "${banned}"`, + ).toBe(false); + } + } + } + }); + } +}); + +describe("layer 3 — sensitive events stay neutral in community tone", () => { + it("community table entries for sensitive types ARE the neutral subset", () => { + for (const type of SENSITIVE_TYPES) { + expect( + TONE_TEMPLATES.community[type], + `community[${type}] must reference COMMUNITY_NEUTRAL`, + ).toBe(COMMUNITY_NEUTRAL[type]); + } + }); + + it("sensitive community output carries no exclamation burst or mockery", () => { + for (const type of SENSITIVE_TYPES) { + for (const { e, team, score } of contextsFor(type)) { + const s = toneSentence(e, "community", { team, score }); + for (const banned of [...BANNED_EVERYWHERE, ...BANNED_IN_SENSITIVE]) { + expect( + s.includes(banned), + `community/${type} → "${s}" contains "${banned}"`, + ).toBe(false); + } + } + } + }); +}); diff --git a/test/matchscreen.test.ts b/test/matchscreen.test.ts index f66fc76..92e42c8 100644 --- a/test/matchscreen.test.ts +++ b/test/matchscreen.test.ts @@ -81,3 +81,65 @@ describe("MatchScreen period-boundary blocks (readability c)", () => { expect(marks[1].score).toEqual({ home: 2, away: 1 }); }); }); + +describe("MatchScreen tone rendering (v0.4)", () => { + beforeEach(() => { + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + }); + afterEach(() => { + vi.restoreAllMocks(); + }); + + const goal: TimelineEvent = { + id: "fifa:g1", + type: "GOAL", + minute: 45, + teamSide: "home", + player: "Kylian MBAPPE", + source: "fifa", + seq: 1, + }; + + it("captures the receive-time score on goal lines (ESPN goals lack scoreAfter)", () => { + const { feed, screen } = makeScreen(); + feed.emit("state", state({ score: { home: 1, away: 0 } })); + feed.emit("events", [goal]); + const line = (screen as any).lines.find( + (l: { kind: string }) => l.kind === "event", + ); + expect(line.score).toEqual({ home: 1, away: 0 }); + }); + + it("re-renders the same stored line in the toggled tone", () => { + const { feed, screen } = makeScreen(); + feed.emit("state", state({ score: { home: 1, away: 0 } })); + feed.emit("events", [goal]); + const line = (screen as any).lines.find( + (l: { kind: string }) => l.kind === "event", + ); + const official = (screen as any).renderLine(line, 100) as string; + expect(official).toContain("Kylian Mbappe"); + expect(official).toContain("프랑스가 앞서갑니다 1:0"); + + (screen as any).tone = "community"; + const community = (screen as any).renderLine(line, 100) as string; + expect(community).toContain("음바페"); + expect(community).not.toContain("Mbappe"); + + (screen as any).tone = "brief"; + const brief = (screen as any).renderLine(line, 100) as string; + expect(brief).toContain("음바페 (1:0)"); + }); + + it("keeps cancelled-goal notices structured and tone-rendered", () => { + const { feed, screen } = makeScreen(); + feed.emit("state", state({})); + feed.emit("cancelled", goal); + const line = (screen as any).lines.find( + (l: { kind: string }) => l.kind === "cancelled", + ); + expect(line).toBeDefined(); + const rendered = (screen as any).renderLine(line, 120) as string; + expect(rendered).toContain("골 취소"); + }); +}); diff --git a/test/polling.test.ts b/test/polling.test.ts index 944b078..57c4145 100644 --- a/test/polling.test.ts +++ b/test/polling.test.ts @@ -161,7 +161,7 @@ describe("PollingEngine waiting mode", () => { await vi.advanceTimersByTimeAsync(12_000); // second live tick const added = batches.flat().filter((e) => e.type === "ADDED_TIME"); expect(added).toHaveLength(1); // once per phase, recorded via onEvents - expect(added[0]!.text).toContain("+4"); + expect(added[0]!.injury).toBe(4); engine.stop(); }); diff --git a/test/replay.test.ts b/test/replay.test.ts index 674be85..8c16d77 100644 --- a/test/replay.test.ts +++ b/test/replay.test.ts @@ -29,6 +29,42 @@ const ev = ( ...over, }); +describe("parseReplay enriches pre-v0.4 recordings from stored prose", () => { + const header = JSON.stringify({ kind: "termfc-replay", v: 1, match }); + const line = (e: object) => JSON.stringify(e); + + it("promotes sub/assist/added-time facts and cleans the referee wart", () => { + const content = [ + header, + line({ + ...ev("s1", { type: "SUBSTITUTION", minute: 56, teamSide: "home" }), + text: "NELSON SEMEDO (in) 선수가 NUNO MENDES(교체)(포르투갈) 선수 대신 교체되어 경기장에 들어갑니다.", + }), + line({ + ...ev("a1", { type: "ASSIST", minute: 90 }), + text: "Ferran TORRES 선수의 어시스트입니다.", + }), + line({ + ...ev("y1", { type: "YELLOW", minute: 89, teamSide: "home" }), + player: "주심이 BERNARDO SILVA", + text: "주심이 BERNARDO SILVA (포르투갈) 에게 경고 조치를 합니다.", + }), + line({ + ...ev("t1", { type: "ADDED_TIME", minute: 90 }), + text: "추가시간 +4분", + }), + ].join("\n"); + + const parsed = parseReplay(content); + const byType = (t: string) => parsed.events.find((e) => e.type === t)!; + expect(byType("SUBSTITUTION").playerIn).toBe("NELSON SEMEDO"); + expect(byType("SUBSTITUTION").playerOut).toBe("NUNO MENDES"); + expect(byType("ASSIST").player).toBe("Ferran TORRES"); + expect(byType("YELLOW").player).toBe("BERNARDO SILVA"); + expect(byType("ADDED_TIME").injury).toBe(4); + }); +}); + describe("recorder + player round-trip", () => { it("records JSONL and replays events in clock order", async () => { const dir = mkdtempSync(join(tmpdir(), "termfc-test-")); diff --git a/test/text.test.ts b/test/text.test.ts index 07c7d14..dc2cfc5 100644 --- a/test/text.test.ts +++ b/test/text.test.ts @@ -1,56 +1,20 @@ import { describe, expect, it } from "vitest"; -import { normalizeEventText, normalizePlayerName } from "../src/core/text.js"; - -describe("normalizeEventText", () => { - it("collapses doubled spaces", () => { - expect( - normalizeEventText("BRUNO FERNANDES (포르투갈) 코너킥을 준비합니다."), - ).toBe("Bruno Fernandes (포르투갈) 코너킥을 준비합니다."); - }); - - it("reattaches detached particles", () => { - expect(normalizeEventText("포르투갈 의 골키퍼가 공을 쳐냅니다.")).toBe( - "포르투갈의 골키퍼가 공을 쳐냅니다.", - ); - expect( - normalizeEventText("주심이 Bernardo Silva (포르투갈) 에게 카드를 보여줍니다."), - ).toBe("주심이 Bernardo Silva (포르투갈)에게 카드를 보여줍니다."); - }); - - it("title-cases all-caps names inside multi-word runs", () => { - expect(normalizeEventText("Lamine YAMAL (스페인) 선수의 반칙 장면입니다.")).toBe( - "Lamine Yamal (스페인) 선수의 반칙 장면입니다.", - ); - expect(normalizeEventText("JOAO CANCELO, 문전에서 슈팅했습니다.")).toBe( - "Joao Cancelo, 문전에서 슈팅했습니다.", - ); - }); - - it("keeps standalone short acronyms untouched", () => { - expect(normalizeEventText("VAR 판독 중")).toBe("VAR 판독 중"); - expect(normalizeEventText("(PSO 4-3)")).toBe("(PSO 4-3)"); - }); - - it("title-cases standalone single-name players of 4+ letters", () => { - expect(normalizeEventText("RODRI (스페인), 중거리 슈팅입니다.")).toBe( - "Rodri (스페인), 중거리 슈팅입니다.", - ); - }); - - it("handles hyphenated and apostrophe names", () => { - expect(normalizeEventText("Saad AL-OWAIS 심판이 경고를 줍니다")).toBe( - "Saad Al-Owais 심판이 경고를 줍니다", - ); - }); -}); +import { normalizePlayerName } from "../src/core/text.js"; describe("normalizePlayerName", () => { - it("title-cases even single all-caps words", () => { + it("title-cases all-caps words, including single names", () => { expect(normalizePlayerName("RONALDO")).toBe("Ronaldo"); expect(normalizePlayerName("JOAO CANCELO")).toBe("Joao Cancelo"); + expect(normalizePlayerName("Mikel MERINO")).toBe("Mikel Merino"); + }); + + it("handles hyphenated and apostrophe names", () => { + expect(normalizePlayerName("Saad AL-OWAIS")).toBe("Saad Al-Owais"); + expect(normalizePlayerName("N'GOLO KANTE")).toBe("N'Golo Kante"); }); - it("leaves already-cased names alone", () => { + it("collapses doubled spaces and leaves cased names alone", () => { + expect(normalizePlayerName("Lamine Yamal")).toBe("Lamine Yamal"); expect(normalizePlayerName("Lamine Yamal")).toBe("Lamine Yamal"); }); }); diff --git a/test/tone.test.ts b/test/tone.test.ts new file mode 100644 index 0000000..5de300d --- /dev/null +++ b/test/tone.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from "vitest"; +import type { TimelineEvent } from "../src/core/model.js"; +import { isTone, toneSentence } from "../src/core/tone.js"; + +const ev = (over: Partial): TimelineEvent => ({ + id: "fifa:1", + type: "GOAL", + minute: 90, + source: "fifa", + seq: 0, + ...over, +}); + +describe("toneSentence — official", () => { + it("renders a goal with roman name and score phrase", () => { + const s = toneSentence( + ev({ player: "Mikel MERINO", teamSide: "away" }), + "official", + { team: "스페인", score: { home: 0, away: 1 } }, + ); + expect(s).toBe("골! Mikel Merino! 스페인이 앞서갑니다 0:1"); + }); + + it("marks an equaliser as 동점", () => { + const s = toneSentence( + ev({ player: "Mikel MERINO", teamSide: "away" }), + "official", + { team: "스페인", score: { home: 1, away: 1 } }, + ); + expect(s).toContain("동점입니다 1:1"); + }); + + it("degrades gracefully without score or player", () => { + expect(toneSentence(ev({ player: "Mikel MERINO" }), "official")).toBe( + "골! Mikel Merino!", + ); + expect(toneSentence(ev({}), "official")).toBe("골이 들어갑니다!"); + }); + + it("uses josa by batchim (팀명 받침)", () => { + const s = toneSentence( + ev({ player: "Harry KANE", teamSide: "home" }), + "official", + { team: "잉글랜드", score: { home: 1, away: 0 } }, + ); + expect(s).toContain("잉글랜드가 앞서갑니다"); + const s2 = toneSentence( + ev({ player: "Lionel MESSI", teamSide: "home" }), + "official", + { team: "아르헨티나", score: { home: 1, away: 0 } }, + ); + expect(s2).toContain("아르헨티나가 앞서갑니다"); + const s3 = toneSentence( + ev({ player: "Kylian MBAPPE", teamSide: "home" }), + "official", + { team: "독일", score: { home: 1, away: 0 } }, + ); + expect(s3).toContain("독일이 앞서갑니다"); + }); + + it("renders substitutions from structured in/out facts", () => { + const s = toneSentence( + ev({ + type: "SUBSTITUTION", + player: undefined, + playerIn: "NELSON SEMEDO", + playerOut: "NUNO MENDES", + }), + "official", + { team: "포르투갈" }, + ); + expect(s).toBe("교체 (포르투갈): Nelson Semedo 투입, Nuno Mendes 아웃"); + }); + + it("renders added time from the injury fact", () => { + expect( + toneSentence(ev({ type: "ADDED_TIME", player: undefined, injury: 4 }), "official"), + ).toBe("추가시간 +4분"); + expect( + toneSentence(ev({ type: "ADDED_TIME", player: undefined }), "official"), + ).toBe("추가시간이 표시됩니다"); + }); +}); + +describe("toneSentence — community", () => { + it("uses hangul surnames", () => { + const s = toneSentence( + ev({ player: "Mikel MERINO", teamSide: "away" }), + "community", + { team: "스페인", score: { home: 0, away: 1 } }, + ); + expect(s).toContain("메리노"); + expect(s).toContain("골!!!"); + expect(s).not.toContain("Merino"); + }); + + it("keeps sensitive events neutral (no laughter, no mockery)", () => { + for (const type of ["OWN_GOAL", "PENALTY_MISS", "RED"] as const) { + const s = toneSentence( + ev({ type, player: "Joao FELIX", teamSide: "home" }), + "community", + { team: "포르투갈" }, + ); + expect(s).not.toMatch(/ㅋ|ㄷ|!{2,}/); + } + }); +}); + +describe("toneSentence — brief", () => { + it("is minimal with score", () => { + expect( + toneSentence(ev({ player: "Mikel MERINO", teamSide: "away" }), "brief", { + team: "스페인", + score: { home: 0, away: 1 }, + }), + ).toBe("메리노 (0:1)"); + expect( + toneSentence( + ev({ type: "YELLOW", player: "Bernardo SILVA", teamSide: "home" }), + "brief", + ), + ).toBe("실바"); + expect( + toneSentence( + ev({ + type: "SUBSTITUTION", + player: undefined, + playerIn: "Fabian RUIZ", + playerOut: "PEDRI", + }), + "brief", + ), + ).toBe("루이스 ↔ 페드리"); + }); +}); + +describe("isTone (config/flag validation)", () => { + it("accepts only the three known tones — unknown values degrade upstream", () => { + expect(isTone("official")).toBe(true); + expect(isTone("community")).toBe(true); + expect(isTone("brief")).toBe(true); + expect(isTone("spicy")).toBe(false); + expect(isTone("")).toBe(false); + expect(isTone(undefined)).toBe(false); + }); +}); + +describe("determinism", () => { + it("same event id → same variant, different ids may differ", () => { + const base = ev({ player: "Mikel OYARZABAL", type: "SHOT", teamSide: "away" }); + const a1 = toneSentence(base, "community", { team: "스페인" }); + const a2 = toneSentence(base, "community", { team: "스페인" }); + expect(a1).toBe(a2); + + const ids = ["fifa:1", "fifa:2", "fifa:3", "fifa:4", "fifa:5", "fifa:6"]; + const outs = new Set( + ids.map((id) => + toneSentence({ ...base, id }, "community", { team: "스페인" }), + ), + ); + expect(outs.size).toBeGreaterThan(1); // variant pool actually used + }); +});