Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/skills

Store, retrieve, edit, version, and revert reusable agent skill documents via skill_list then skill_get.

FollowFork

Files

promo-text.ts

155 lines · 4.8 KB · TypeScript
/**
 * Shared, deterministic text helpers for narration alignment and speech QA.
 * Internal module (not a package export): imported by narration-align and final-qa.
 */

export type Aliases = Record<string, string>

/** Spoken-form aliases every promo needs. Callers add product names (e.g. `{ "cody kodi": "kody" }`). */
export const DEFAULT_ALIASES: Aliases = { 'git hub': 'github' }

const NUMBERS: Record<string, string> = {
	'0': 'zero',
	'1': 'one',
	'2': 'two',
	'3': 'three',
	'4': 'four',
	'5': 'five',
	'6': 'six',
	'7': 'seven',
	'8': 'eight',
	'9': 'nine',
	'10': 'ten',
	'11': 'eleven',
	'12': 'twelve',
}

function escapeRegExp(text: string) {
	return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

/**
 * Normalize alias keys. A key is either one phrase (`"git hub"`) or several
 * single-word spellings separated by `|` (`"cody|kodi|kogi"`), all mapped to the value.
 */
export function expandAliases(aliases: Aliases = {}): Array<[string, string]> {
	const out: Array<[string, string]> = []
	for (const [key, value] of Object.entries({ ...DEFAULT_ALIASES, ...aliases })) {
		for (const variant of key.split('|')) {
			const phrase = variant.trim().toLowerCase()
			if (phrase) out.push([phrase, value.toLowerCase()])
		}
	}
	// Longest phrases first so "git hub" wins over any single-word alias.
	return out.sort((a, b) => b[0].split(' ').length - a[0].split(' ').length || a[0].localeCompare(b[0]))
}

/**
 * Tokenize script or ASR text for comparison: split run-together camelCase,
 * lowercase, drop apostrophes, hyphens and punctuation, apply aliases, spell small numbers.
 */
export function tokenize(text: string, aliases: Aliases = {}): string[] {
	let x = text.replace(/(?<=[a-z])(?=[A-Z])/g, ' ')
	x = x.toLowerCase().replace(/-/g, ' ').replace(/[’']/g, '')
	x = x.replace(/[^a-z0-9 ]/g, ' ')
	for (const [from, to] of expandAliases(aliases)) {
		x = x.replace(new RegExp(`\\b${escapeRegExp(from).replace(/ /g, '\\s+')}\\b`, 'g'), to)
	}
	return x
		.split(/\s+/)
		.filter(Boolean)
		.map((t) => NUMBERS[t] ?? t)
}

/** Strict tokens: lowercase words only, no aliases or number spelling. */
export function strictTokens(text: string): string[] {
	return text
		.toLowerCase()
		.replace(/-/g, ' ')
		.replace(/[’']/g, '')
		.replace(/[^a-z0-9 ]/g, ' ')
		.split(/\s+/)
		.filter(Boolean)
}

export type MatchBlock = { a: number; b: number; size: number }

/**
 * Matching blocks between two token arrays: a port of Python difflib
 * SequenceMatcher(autojunk=False).get_matching_blocks(), so results are
 * deterministic and match the reference Python tools.
 */
export function matchingBlocks(a: string[], b: string[]): MatchBlock[] {
	const b2j = new Map<string, number[]>()
	b.forEach((token, j) => {
		const list = b2j.get(token)
		if (list) list.push(j)
		else b2j.set(token, [j])
	})
	const longest = (alo: number, ahi: number, blo: number, bhi: number) => {
		let besti = alo
		let bestj = blo
		let bestsize = 0
		let j2len = new Map<number, number>()
		for (let i = alo; i < ahi; i++) {
			const next = new Map<number, number>()
			for (const j of b2j.get(a[i]) ?? []) {
				if (j < blo) continue
				if (j >= bhi) break
				const k = (j2len.get(j - 1) ?? 0) + 1
				next.set(j, k)
				if (k > bestsize) {
					besti = i - k + 1
					bestj = j - k + 1
					bestsize = k
				}
			}
			j2len = next
		}
		while (besti > alo && bestj > blo && a[besti - 1] === b[bestj - 1]) {
			besti--
			bestj--
			bestsize++
		}
		while (besti + bestsize < ahi && bestj + bestsize < bhi && a[besti + bestsize] === b[bestj + bestsize]) {
			bestsize++
		}
		return { a: besti, b: bestj, size: bestsize }
	}
	const queue: Array<[number, number, number, number]> = [[0, a.length, 0, b.length]]
	const blocks: MatchBlock[] = []
	while (queue.length) {
		const [alo, ahi, blo, bhi] = queue.pop()!
		const m = longest(alo, ahi, blo, bhi)
		if (m.size) {
			blocks.push(m)
			if (alo < m.a && blo < m.b) queue.push([alo, m.a, blo, m.b])
			if (m.a + m.size < ahi && m.b + m.size < bhi) queue.push([m.a + m.size, ahi, m.b + m.size, bhi])
		}
	}
	blocks.sort((x, y) => x.a - y.a || x.b - y.b)
	const merged: MatchBlock[] = []
	for (const blk of blocks) {
		const last = merged[merged.length - 1]
		if (last && last.a + last.size === blk.a && last.b + last.size === blk.b) last.size += blk.size
		else merged.push({ ...blk })
	}
	return merged
}

/** Word recall of `ref` inside `hyp` (matched tokens / ref tokens) plus ref words never heard. */
export function wordRecall(ref: string[], hyp: string[]) {
	const matched = matchingBlocks(ref, hyp).reduce((n, blk) => n + blk.size, 0)
	const heard = new Set(hyp)
	return {
		scriptWords: ref.length,
		matchedWords: matched,
		recall: ref.length ? round(matched / ref.length) : 1,
		notHeard: ref.filter((w) => !heard.has(w)),
	}
}

export function round(value: number, digits = 3) {
	const f = 10 ** digits
	return Math.round(value * f) / f
}