d3ro-voice/packages/core/src/personal-ngram.ts

192 lines
8.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// packages/core/src/personal-ngram.ts
//
// 개인 n-gram 예측기 — 사용자가 직접 쓴 문장만으로 다음 어절(과 짧은 구)을 맞힌다.
//
// 왜 LLM 앞에 두는가 (재생 평가 2026-10-24, docs/evidence/2026-10-24-suggestion-accuracy-research.md):
// 같은 120건에서 gemma4:e4b 첫 어절 적중은 3~5%, 이 방식은 정확 14% · 단어 앞부분 일치 24% 였고
// 지연은 0 이다. Gmail Smart Compose 도 사용자별 n-gram 을 섞어 정확 일치를 +10% 올렸다(KDD 2019).
//
// 규칙
// - 문장을 넘지 않는다: 문장 경계(.!?… 줄바꿈)에서 끊어 센다. 새 문장의 첫 어절은 예측하지 않는다.
// - 단어를 끝냈으면(끝이 공백) 다음 어절을, 단어 중간이면 그 어절의 나머지를 낸다.
// - 지지(같은 문맥에서 나온 횟수)와 비율(문맥 전체 중 그 어절의 몫)이 기준을 넘을 때만 낸다.
// - 확신이 이어지면 최대 maxWords 어절까지 구로 늘린다(트라이그램 → 바이그램 순).
export interface PersonalNgramOptions {
/** 같은 문맥 뒤에 이 어절이 나온 최소 횟수 */
minSupport?: number
/** 문맥 뒤에 나온 어절 중 이 어절의 최소 비율 */
minConfidence?: number
/** 한 번에 내는 최대 어절 수 */
maxWords?: number
/** 두 번째 어절부터 늘릴 때의 최소 비율 — 첫 어절보다 깐깐하게 둘 수 있다(기본: minConfidence) */
extendConfidence?: number
}
export interface PersonalNgramPrediction {
/** 삽입할 글 — joint 가 'attach' 면 커서 앞 글자에 바로 붙는다(단어 중간) */
text: string
joint: 'attach' | 'separate'
/** 첫 어절의 지지 횟수 */
support: number
/** 첫 어절의 비율 (0~1) */
confidence: number
}
const DEFAULTS: Required<Omit<PersonalNgramOptions, 'extendConfidence'>> = { minSupport: 2, minConfidence: 0.25, maxWords: 3 }
/**
* 앱 기준값 — 재생 평가 격자 탐색(2026-10-24, 120건)에서 골랐다. 앱과 평가가 같은 값을 쓴다.
* - 단어 중간: 쓰던 어절을 늘이는 것은 쉽다 → 넉넉하게 (노출 53%, 첫 어절 34%, 통째로 맞음 26%)
* - 단어 끝: 처음엔 비율 0.5 로 깐깐하게 뒀다가(노출 14%) 실사용에서 "그리고만 쳐도 단어 하나는 나와야 한다"는
* 지적을 받았다(2026-10-24). 가장 흔한 다음 어절 하나는 낮은 비율로도 내고, 둘째 어절은 확신할 때만 붙인다.
* 2차 실사용(2026-10-25)에서 지지 1·비율 0.1 로 풀었더니 근거 약한 어절("구글로 로그인해서", 비율 0.14)이 떠
* "상관없는 아무말" 이 됐다. 확실한 것만 남긴다 — 단어 끝은 지지 2·비율 0.5 (평가: 노출 14%, 적중 29%).
*/
export const PERSONAL_NGRAM_SETTINGS = {
midWord: { minSupport: 1, minConfidence: 0.25, maxWords: 2, extendConfidence: 0.5 },
wordEnd: { minSupport: 2, minConfidence: 0.5, maxWords: 2, extendConfidence: 0.5 }
} as const satisfies Record<string, Required<PersonalNgramOptions>>
/**
* 앱이 쓰는 예측.
* - 끝이 공백: 다음 어절.
* - 끝이 글자: 먼저 그 어절의 나머지를 찾고, 없으면 그 어절을 이미 다 쓴 것으로 보고 다음 어절을 낸다.
* 한글은 멈춰도 마지막 음절이 조합 중이라 공백이 늦게 온다 — "그리고" 에서 멈추면 다음 어절이 필요하다.
*/
export function predictPersonalContinuation(model: PersonalNgramModel, prefix: string): PersonalNgramPrediction | null {
if (/\s$/u.test(prefix)) return model.predict(prefix, PERSONAL_NGRAM_SETTINGS.wordEnd)
return model.predict(prefix, PERSONAL_NGRAM_SETTINGS.midWord) ?? model.predict(`${prefix} `, PERSONAL_NGRAM_SETTINGS.wordEnd)
}
const SENTENCE_SPLIT = /[.!?。!?…\n]+/u
const EDGE_PUNCTUATION = /^["'“‘([]+|["'”’)\],;:~]+$/gu
/** 비교용 어절 — 앞뒤 따옴표·괄호·쉼표를 떼고 소문자로 */
function key(word: string): string {
return word.replace(EDGE_PUNCTUATION, '').toLowerCase()
}
function tokenize(sentence: string): string[] {
return sentence
.split(/\s+/u)
.map(key)
.filter((word) => word.length > 0)
}
function increment(table: Map<string, Map<string, number>>, context: string, word: string): void {
let followers = table.get(context)
if (!followers) {
followers = new Map()
table.set(context, followers)
}
followers.set(word, (followers.get(word) ?? 0) + 1)
}
interface Pick {
word: string
support: number
confidence: number
}
function best(followers: Map<string, number> | undefined, accept: (word: string) => boolean): Pick | null {
if (!followers) return null
let total = 0
let top: { word: string; support: number } | null = null
for (const [word, count] of followers) {
if (!accept(word)) continue
total += count
// 동률이면 먼저 센 어절(삽입 순서)을 둔다 — 결과가 실행마다 같아야 한다.
if (!top || count > top.support) top = { word, support: count }
}
return top ? { ...top, confidence: top.support / total } : null
}
export class PersonalNgramModel {
private readonly _bigram = new Map<string, Map<string, number>>()
private readonly _trigram = new Map<string, Map<string, number>>()
/** 단어 중간 완성용 — 문맥 없이 어절 빈도 */
private readonly _unigram = new Map<string, number>()
private _texts = 0
get textCount(): number {
return this._texts
}
addText(text: string): void {
this._texts += 1
for (const sentence of text.split(SENTENCE_SPLIT)) {
const words = tokenize(sentence)
for (let index = 0; index < words.length; index += 1) {
const word = words[index]
this._unigram.set(word, (this._unigram.get(word) ?? 0) + 1)
if (index >= 1) increment(this._bigram, words[index - 1], word)
if (index >= 2) increment(this._trigram, `${words[index - 2]} ${words[index - 1]}`, word)
}
}
}
/**
* 커서 앞 글(prefix)에 이어질 어절을 낸다. 확신이 없으면 null.
* prefix 끝이 공백이면 다음 어절, 아니면 지금 어절의 나머지부터.
*/
predict(prefix: string, options: PersonalNgramOptions = {}): PersonalNgramPrediction | null {
const settings = { ...DEFAULTS, ...options }
const extendConfidence = Math.max(settings.minConfidence, options.extendConfidence ?? settings.minConfidence)
const sentences = prefix.split(SENTENCE_SPLIT)
const current = sentences[sentences.length - 1] ?? ''
const wordFinished = /\s$/u.test(current)
const words = tokenize(current)
if (words.length === 0) return null
const passes = (pick: Pick | null): pick is Pick =>
pick !== null && pick.support >= settings.minSupport && pick.confidence >= settings.minConfidence
let context = words
let first: Pick | null
let joint: 'attach' | 'separate' = 'separate'
let partial = ''
if (wordFinished) {
first = this._next(context, () => true, passes)
} else {
// 단어 중간 — 쓰던 어절을 늘인 어절만 후보다. 앞 어절이 없으면 어절 빈도로.
partial = words[words.length - 1]
context = words.slice(0, -1)
const extends_ = (word: string) => word.length > partial.length && word.startsWith(partial)
first = context.length > 0 ? this._next(context, extends_, passes) : null
if (!first) {
const unigram = new Map([...this._unigram].filter(([word]) => extends_(word)))
const pick = best(unigram, () => true)
first = passes(pick) ? pick : null
}
joint = 'attach'
}
if (!first) return null
const output = [joint === 'attach' ? first.word.slice(partial.length) : first.word]
const chain = [...context, first.word]
// 둘째 어절부터는 한 번 쓴 것만으로는 붙이지 않는다 — 근거 1회짜리 구가 길게 붙으면 대부분 틀린다.
const extendPasses = (pick: Pick | null): pick is Pick =>
passes(pick) && pick.confidence >= extendConfidence && pick.support >= Math.max(2, settings.minSupport)
while (output.length < settings.maxWords) {
const next = this._next(chain, () => true, extendPasses)
if (!next) break
output.push(next.word)
chain.push(next.word)
}
return { text: output.join(' '), joint, support: first.support, confidence: first.confidence }
}
private _next(context: string[], accept: (word: string) => boolean, passes: (pick: Pick | null) => pick is Pick): Pick | null {
if (context.length >= 2) {
const tri = best(this._trigram.get(`${context[context.length - 2]} ${context[context.length - 1]}`), accept)
if (passes(tri)) return tri
}
if (context.length >= 1) {
const bi = best(this._bigram.get(context[context.length - 1]), accept)
if (passes(bi)) return bi
}
return null
}
}