mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
fix(speech): ship the common-word list as a 2% Bloom filter to fit the phone page budget
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
// Regenerates src/shared/dictation-english-words.ts, the common-word filter dictation's near-miss matching
|
||||
// checks before spelling a word as a dictionary term. Run: node config/scripts/dictation/build-dictation-english-words.mjs
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { wordFilterSlots } from '../../../src/shared/dictation-word-filter.ts'
|
||||
|
||||
const SOURCES = {
|
||||
scowl: [
|
||||
'https://downloads.sourceforge.net/project/wordlist/SCOWL/2020.12.07/scowl-2020.12.07.tar.gz',
|
||||
'5587667caa20c4891390c2d42dbb4d5c4c3f41bee77af1457ece3ba23fb859cc'
|
||||
],
|
||||
femaleFirst: [
|
||||
'https://www2.census.gov/topics/genealogy/1990surnames/dist.female.first',
|
||||
'bd2f310fc4e5d5e5ea122c9d4342c9821145823118eb20db1647f305ec77b358'
|
||||
],
|
||||
maleFirst: [
|
||||
'https://www2.census.gov/topics/genealogy/1990surnames/dist.male.first',
|
||||
'0a5078ef6effe3b483d15b0f7f95047662126c9bfb624ecd5e5b978fc0f2470b'
|
||||
],
|
||||
last: [
|
||||
'https://www2.census.gov/topics/genealogy/1990surnames/dist.all.last',
|
||||
'b0e2b3743ccbad641ca48b344c24cdebcd1d9a1f76dc6dbf05986f2919f0b4e1'
|
||||
]
|
||||
}
|
||||
// SCOWL sizes up to 60: everyday words plus the rarer ones ("bezel", "aslant") a term could sound like.
|
||||
const SCOWL_MAX_SIZE = 60
|
||||
const LAST_NAMES = 1000
|
||||
const FALSE_POSITIVE_RATE = 0.02
|
||||
// Matching never looks up words shorter than this.
|
||||
const MIN_WORD_LENGTH = 3
|
||||
const OUT = 'src/shared/dictation-english-words.ts'
|
||||
|
||||
async function download([url, sha256]) {
|
||||
const response = await fetch(url)
|
||||
if (!response.ok) {
|
||||
throw new Error(`${url}: HTTP ${response.status}`)
|
||||
}
|
||||
const bytes = Buffer.from(await response.arrayBuffer())
|
||||
const actual = createHash('sha256').update(bytes).digest('hex')
|
||||
if (actual !== sha256) {
|
||||
throw new Error(`${url}: sha256 ${actual}, expected ${sha256}`)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
const work = mkdtempSync(join(tmpdir(), 'dictation-english-words-'))
|
||||
try {
|
||||
const words = new Set()
|
||||
// Contractions add their stems ("doesn" of "doesn't"), since dictated text splits words at apostrophes.
|
||||
const add = (entry) => {
|
||||
for (const part of entry.split("'")) {
|
||||
if (/^[A-Za-z]+$/.test(part) && part.length >= MIN_WORD_LENGTH) {
|
||||
words.add(part.toLowerCase())
|
||||
}
|
||||
}
|
||||
}
|
||||
writeFileSync(join(work, 'scowl.tar.gz'), await download(SOURCES.scowl))
|
||||
execFileSync('tar', ['-xzf', 'scowl.tar.gz'], { cwd: work })
|
||||
const final = join(work, 'scowl-2020.12.07', 'final')
|
||||
for (const file of readdirSync(final)) {
|
||||
const list =
|
||||
/^(?:english|american|british|canadian|australian)-(?:words|upper|contractions)\.(\d+)$/.exec(
|
||||
file
|
||||
)
|
||||
if (list && Number(list[1]) <= SCOWL_MAX_SIZE) {
|
||||
readFileSync(join(final, file), 'latin1').split('\n').forEach(add)
|
||||
}
|
||||
}
|
||||
const names = async (source, limit) =>
|
||||
(await download(source))
|
||||
.toString('latin1')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.slice(0, limit)
|
||||
.map((line) => line.split(/\s+/)[0])
|
||||
for (const name of [
|
||||
...(await names(SOURCES.femaleFirst)),
|
||||
...(await names(SOURCES.maleFirst)),
|
||||
...(await names(SOURCES.last, LAST_NAMES))
|
||||
]) {
|
||||
add(name)
|
||||
}
|
||||
|
||||
const bits = Math.ceil((-words.size * Math.log(FALSE_POSITIVE_RATE)) / Math.LN2 ** 2 / 8) * 8
|
||||
const hashes = Math.round((bits / words.size) * Math.LN2)
|
||||
const bytes = new Uint8Array(bits / 8)
|
||||
for (const word of words) {
|
||||
for (const slot of wordFilterSlots(word, bits, hashes)) {
|
||||
bytes[slot >>> 3] |= 1 << (slot & 7)
|
||||
}
|
||||
}
|
||||
// The whole SCOWL notice (Atkinson, WordNet, VarCon, Ispell and the rest) rides in every bundle that keeps legal comments.
|
||||
const license = readFileSync('resources/licenses/scowl/Copyright', 'utf8').trimEnd().split('\n')
|
||||
const notice = [
|
||||
`A filter of ${words.size} common English words and names: SCOWL 2020.12.07 words, capitalized words and`,
|
||||
`contractions up to size ${SCOWL_MAX_SIZE} (english, american, british, canadian, australian), a-z only, lowercased,`,
|
||||
`plus the 1990 US census first names and ${LAST_NAMES} most common last names (public domain). Generated by`,
|
||||
'config/scripts/dictation/build-dictation-english-words.mjs from these SCOWL notices:',
|
||||
'',
|
||||
...license.map((line) => line.replaceAll('*/', '* /'))
|
||||
]
|
||||
writeFileSync(
|
||||
OUT,
|
||||
`/*! @license\n${notice.map((line) => ` * ${line}`.trimEnd()).join('\n')}\n */\n` +
|
||||
`import type { WordFilter } from './dictation-word-filter'\n\n` +
|
||||
`export const COMMON_ENGLISH_WORDS: WordFilter = {\n bits: ${bits},\n hashes: ${hashes},\n` +
|
||||
` base64:\n '${Buffer.from(bytes).toString('base64')}'\n}\n`
|
||||
)
|
||||
console.log(`${OUT}: ${words.size} words, ${bits} bits, ${hashes} hashes`)
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true })
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,16 +1,17 @@
|
||||
import { levenshtein } from './edit-distance'
|
||||
import { createWordFilterLookup } from './dictation-word-filter'
|
||||
|
||||
// Shorter terms sit too close to ordinary words ("Vite" and "vote", "Hono" and "honey").
|
||||
const MIN_TERM_KEY_LENGTH = 5
|
||||
const LATIN_LETTERS_RE = /^[a-z]+$/
|
||||
|
||||
// The list is ~850 KB, so only a dictionary with a term to near-miss loads it; until then nothing near-misses.
|
||||
let commonWords: ReadonlySet<string> | undefined
|
||||
// Only a dictionary with a term to near-miss loads the word filter; until then nothing near-misses.
|
||||
let isCommonWord: ((word: string) => boolean) | undefined
|
||||
let commonWordsLoad: Promise<void> | undefined
|
||||
function loadCommonWords(): void {
|
||||
commonWordsLoad ??= import('./dictation-english-words.js').then(
|
||||
({ COMMON_ENGLISH_WORDS }) => {
|
||||
commonWords = new Set(COMMON_ENGLISH_WORDS.split(' '))
|
||||
isCommonWord = createWordFilterLookup(COMMON_ENGLISH_WORDS)
|
||||
},
|
||||
() => {
|
||||
commonWordsLoad = undefined
|
||||
@@ -40,8 +41,8 @@ type NearMissTerm<T> = { key: string; consonants: number; term: T }
|
||||
export type NearMissMatcher<T> = (keys: readonly string[]) => (T | undefined)[] | null
|
||||
|
||||
/**
|
||||
* Matches near misses of `terms` (by word key) in text in `languages`, or in text that reads as English when
|
||||
* they are unknown; null when no term is long enough or the language is known not to be English.
|
||||
* Matches near misses of `terms` (by word key) in English text: text whose only language is English, or that
|
||||
* reads as English; null when no term is long enough or English isn't among the known `languages`.
|
||||
*/
|
||||
export function createNearMissMatcher<T>(
|
||||
terms: readonly (readonly [key: string, term: T])[],
|
||||
@@ -59,15 +60,15 @@ export function createNearMissMatcher<T>(
|
||||
return null
|
||||
}
|
||||
loadCommonWords()
|
||||
const match = (key: string, words: ReadonlySet<string>): T | undefined => {
|
||||
const match = (key: string, isCommon: (word: string) => boolean): T | undefined => {
|
||||
// An ordinary word or name is never a misheard term.
|
||||
if (!LATIN_LETTERS_RE.test(key) || words.has(key)) {
|
||||
if (!LATIN_LETTERS_RE.test(key) || isCommon(key)) {
|
||||
return undefined
|
||||
}
|
||||
let best: { term: T; distance: number } | undefined
|
||||
for (const candidate of bySound.get(soundKey(key)) ?? []) {
|
||||
// A term that is itself a word ("Drizzle") is heard right, so what sounds like it is another word.
|
||||
if (words.has(candidate.key)) {
|
||||
if (isCommon(candidate.key)) {
|
||||
continue
|
||||
}
|
||||
// Sounding the same and spelled close ("Versal" for "Vercel"), with fewer edits than the consonants
|
||||
@@ -84,18 +85,19 @@ export function createNearMissMatcher<T>(
|
||||
return best?.term
|
||||
}
|
||||
return (keys) => {
|
||||
const words = commonWords
|
||||
const found = words ? keys.map((key) => match(key, words)) : []
|
||||
if (!words || !found.some(Boolean)) {
|
||||
const isCommon = isCommonWord
|
||||
const found = isCommon ? keys.map((key) => match(key, isCommon)) : []
|
||||
if (!isCommon || !found.some(Boolean)) {
|
||||
return null
|
||||
}
|
||||
if (languages) {
|
||||
// A bilingual model ("zh-en") may have heard either language, so only an English-only one skips the check.
|
||||
if (languages?.every((language) => language === 'en')) {
|
||||
return found
|
||||
}
|
||||
// Short words ("I", "a") and the misheard words say little about the language; two thirds of the rest must
|
||||
// be English, since other languages share a few words with it ("den", "part").
|
||||
const rest = keys.filter((key, index) => key.length > 2 && !found[index])
|
||||
const english = rest.filter((key) => words.has(key)).length
|
||||
const english = rest.filter(isCommon).length
|
||||
return rest.length > 0 && english * 3 >= rest.length * 2 ? found : null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,5 +72,11 @@ describe('createDictationDictionary', () => {
|
||||
]) {
|
||||
expect(clean(text)).toBe(text)
|
||||
}
|
||||
// A bilingual model's Chinese sentence is not English, even though English is one of its languages.
|
||||
const bilingual = createDictationDictionary([{ term: 'Vercel' }], ['zh', 'en'])!
|
||||
expect(bilingual('请在 Versal 上部署预览。')).toBe('请在 Versal 上部署预览。')
|
||||
expect(bilingual('Deploy the preview to Versal before the review.')).toBe(
|
||||
'Deploy the preview to Vercel before the review.'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* A Bloom filter over lowercase a-z words: about 1 byte a word instead of the word, so a ~90k-word list fits
|
||||
* in a phone's page bundle. A false "yes" (~2%) only makes dictation leave a word alone.
|
||||
*/
|
||||
export type WordFilter = { bits: number; hashes: number; base64: string }
|
||||
|
||||
// Double hashing over two FNV-1a variants; the generator and the reader must agree on this.
|
||||
export function wordFilterSlots(word: string, bits: number, hashes: number): number[] {
|
||||
let first = 0x811c9dc5
|
||||
let second = 0x01000193
|
||||
for (let index = 0; index < word.length; index++) {
|
||||
const code = word.charCodeAt(index)
|
||||
first = Math.imul(first ^ code, 0x01000193)
|
||||
second = Math.imul(second ^ code, 0x5bd1e995) ^ (second >>> 15)
|
||||
}
|
||||
const step = (second | 1) >>> 0
|
||||
const slots: number[] = []
|
||||
for (let index = 0; index < hashes; index++) {
|
||||
slots.push(((first >>> 0) + index * step) % bits)
|
||||
}
|
||||
return slots
|
||||
}
|
||||
|
||||
/** Whether `word` may be in the filter: false is certain, true is right ~98% of the time. */
|
||||
export function createWordFilterLookup(filter: WordFilter): (word: string) => boolean {
|
||||
const bytes = Uint8Array.from(atob(filter.base64), (char) => char.charCodeAt(0))
|
||||
return (word) =>
|
||||
wordFilterSlots(word, filter.bits, filter.hashes).every(
|
||||
(slot) => (bytes[slot >>> 3] & (1 << (slot & 7))) !== 0
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user