Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`),
Expand Down Expand Up @@ -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

Expand Down
32 changes: 15 additions & 17 deletions scripts/make-demo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -16,7 +18,6 @@ import {
assistPlayerFrom,
playerFrom,
subPlayersFrom,
synthDescription,
} from "./sanitize-fixtures.mjs";

const timeline = JSON.parse(
Expand Down Expand Up @@ -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}`,
Expand All @@ -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 } }
: {}),
Expand Down
2 changes: 1 addition & 1 deletion scripts/sanitize-fixtures.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
// ---------------------------------------------------------------------------

Expand Down
38 changes: 34 additions & 4 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand All @@ -33,6 +35,7 @@ import pkg from "../../package.json" with { type: "json" };

interface Flags {
lang?: Lang;
tone?: Tone;
speed?: number;
anim: boolean;
record: boolean;
Expand All @@ -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=")) {
Expand Down Expand Up @@ -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")}
Expand All @@ -87,9 +97,16 @@ async function main(): Promise<void> {
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<Config> = {};
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 */
}
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand Down
11 changes: 4 additions & 7 deletions src/core/digest.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
compareEvents,
type EventType,
type Lang,
type MatchPhase,
type MatchState,
type SourceName,
Expand Down Expand Up @@ -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,
};
Expand Down
63 changes: 63 additions & 0 deletions src/core/factextract.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading