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

586 lines
20 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 — 개인 그래프(관계형 개인화) 정본.
//
// 왜 그래프인가:
// n-gram 문자열 조회(1단계)는 "같은 꼬리 뒤에 이어 쓴 문장" 만 찾는다. 하지만 사용자의
// 글은 관계로 이어진다 — 어떤 문장은 늘 다른 문장 뒤에 오고("follows"), 어떤 문장들은
// 같은 용어를 공유한다("shares_terms"). 그 관계를 저장해 두면 접두가 조금 달라도
// 관련 문맥을 끌어올 수 있다.
//
// 전부 순수 함수로 두어 LLM/DB 없이 검증 가능하게 한다.
import type { PhraseSource } from './input-intelligence'
import { countLexicalWords, getWordSegmenter } from './text-segmentation'
import { detectSentenceRegister } from './writing-context'
// 렌더러/프리로드도 같은 계약을 쓴다 (main 모듈을 import 할 수 없다).
export type { PhraseSource }
/** 그래프 노드 = 사용자의 문장 하나. */
export interface GraphNode {
text: string
terms: string[]
source: PhraseSource
appName: string | null
count: number
lastUsedAt: number | null
}
export type GraphEdgeKind = 'follows' | 'shares_terms'
/** 그래프 엣지 = 두 문장의 관계. */
export interface GraphEdge {
from: string
to: string
kind: GraphEdgeKind
weight: number
}
/** 그래프 통계 (지식베이스 그래프 탭). */
export interface PersonalGraphStats {
nodes: number
followsEdges: number
sharesTermsEdges: number
/** 가장 강한 follows 엣지 (A → B) */
topEdges: Array<{ from: string; to: string; kind: string; weight: number }>
/** 최근 노드 */
recentNodes: Array<{ text: string; terms: string[]; count: number; appName: string | null }>
}
/** 특정 텍스트 주변 그래프 조회 결과. */
export interface PersonalGraphQuery {
anchors: Array<{ text: string; terms: string[]; count: number }>
neighbors: Array<{ text: string; kind: string; weight: number }>
}
export interface GraphContext {
/** 접두 꼬리 뒤에 실제로 이어 쓴 텍스트 (가장 강한 신호) */
continuations: string[]
/** 관계로 끌어온 관련 문장 (follows 우선, 그다음 용어 공유) */
related: string[]
/**
* 직전 완결 문장(또는 그와 거의 같은 문장) 뒤에 사용자가 실제로 이어 쓴 문장 — follows 엣지.
* "다음 문장" 을 고를 때 가장 강한 근거다. 없으면 생략될 수 있다(호환).
*/
followUps?: string[]
}
/** 용어 추출에서 제외할 불용어 (한/영 최소 집합). */
const STOPWORDS: ReadonlySet<string> = new Set([
'그리고',
'그러나',
'하지만',
'그래서',
'저는',
'제가',
'이거',
'그거',
'저거',
'있습니다',
'합니다',
'입니다',
'the',
'and',
'for',
'with',
'that',
'this',
'from',
'have',
'will',
'your',
'you',
'are',
'was',
'were',
'not',
'but'
])
/** 최소 길이 (1~2자 토큰은 노이즈가 많다). */
const MIN_TERM_CHARS = 2
/**
* 용어 경계 — 어떤 문자 체계든 문자(L)·숫자(N)·결합 부호(M)가 아닌 것.
*
* 예전에는 ASCII/한글/가나/한자만 허용해서 키릴·그리스·아랍·태국 문자는 통째로 사라지고
* 'Präsentation' 같은 악센트 라틴 단어는 'pr' + 'sentation' 조각으로 쪼개졌다.
*/
const TERM_SEPARATOR = /[^\p{L}\p{N}\p{M}]+/u
/** 띄어쓰기 없이 쓰는 문자 체계 — 경계 분리만으로는 문장 전체가 한 토큰이 된다. */
const UNSPACED_SCRIPT = /[\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u
/** 띄어쓰기 없는 문자 체계의 토큰을 사전 기반 단어로 나눈다. 분할기가 없으면 그대로 둔다. */
function segmentUnspacedToken(token: string): string[] {
if (!UNSPACED_SCRIPT.test(token)) return [token]
const segmenter = getWordSegmenter()
if (!segmenter) return [token]
const words: string[] = []
for (const part of segmenter.segment(token)) {
if (part.isWordLike) words.push(part.segment)
}
return words.length > 0 ? words : [token]
}
/**
* 텍스트를 비교용 토큰으로 자른다 (불용어/길이 필터 전 단계).
*
* NFC 정규화 → 소문자화 → 문자/숫자/결합 부호 경계로 분리 → 띄어쓰기 없는 문자 체계는 단어 분할.
* 한글 음절·ASCII·가나·한자로 된 토큰은 예전과 같은 결과를 낸다 (저장된 노드의 terms 와 호환).
*/
export function tokenizeTerms(text: string): string[] {
return text
.normalize('NFC')
.toLowerCase()
.split(TERM_SEPARATOR)
.filter((token) => token.length > 0)
.flatMap(segmentUnspacedToken)
}
/**
* 한국어 어절 끝의 조사·흔한 '하다' 활용을 떼어 낸 어간.
*
* 왜: "회의에서" 와 "회의는" 이 다른 용어로 잡히면 같은 주제의 문장끼리 겹치는 용어가 거의 없어
* 그래프가 관련 문장을 못 찾는다(한국어는 거의 모든 명사에 조사가 붙는다). 남는 어간이 2자 미만이면
* 떼지 않는다 — "회의"(의), "결과"(과) 같은 단어 끝 글자를 조사로 오인하지 않게.
*/
const KOREAN_SUFFIXES: readonly string[] = [
'했습니다', '하겠습니다', '드립니다', '합니다', '했어요', '해요', '했다', '하는', '하고', '해서', '하면', '하기',
'에서는', '에서도', '에서의', '에게서', '으로부터', '로부터', '으로는', '으로도', '이라는', '이라고', '에게는',
'한테서', '에서', '에게', '한테', '으로', '까지', '부터', '처럼', '보다', '만큼', '이나', '이랑', '과는', '와는',
'에는', '에도', '들은', '들이', '들을', '들의',
'은', '는', '이', '가', '을', '를', '에', '의', '도', '로', '만', '와', '과', '랑', '들', '한', '할'
].slice().sort((a, b) => b.length - a.length)
const HANGUL_WORD = /^[가-힣]+$/u
export function stemTerm(token: string): string {
if (!HANGUL_WORD.test(token)) return token
for (const suffix of KOREAN_SUFFIXES) {
if (token.endsWith(suffix) && token.length - suffix.length >= 2) return token.slice(0, -suffix.length)
}
return token
}
/**
* 문장에서 비교용 용어를 뽑는다.
*
* 토큰화 → 한국어 어간화 → 불용어/짧은 토큰 제거 → 빈도 순.
*/
export function extractTerms(text: string, limit = 8): string[] {
const tokens = tokenizeTerms(text)
.map(stemTerm)
.filter((token) => token.length >= MIN_TERM_CHARS)
.filter((token) => !STOPWORDS.has(token))
const frequency = new Map<string, number>()
for (const token of tokens) {
frequency.set(token, (frequency.get(token) ?? 0) + 1)
}
return [...frequency.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, limit)
.map(([token]) => token)
}
/**
* 문장 단위로 쪼갠다 (종결 부호 + 개행). 2단어 이상만 남긴다.
*
* 단어 수는 countLexicalWords 로 센다 — 공백으로만 세면 띄어쓰기 없는 중국어·일본어·태국어
* 문장이 모두 1단어가 되어 그 언어 사용자의 문장이 하나도 학습되지 않는다.
*/
export function splitSentences(text: string): string[] {
return text
.split(/[.!?。!?…\n]+/u)
.map((segment) => segment.replace(/\s+/gu, ' ').trim())
.filter((segment) => segment.length >= 4 && countLexicalWords(segment) >= 2)
}
/** 한 텍스트 안에서 인접한 문장 쌍 (follows 엣지의 근거). */
export function buildSequenceEdges(sentences: readonly string[]): Array<{ from: string; to: string }> {
const edges: Array<{ from: string; to: string }> = []
for (let index = 0; index + 1 < sentences.length; index += 1) {
const from = sentences[index]
const to = sentences[index + 1]
if (from === to) continue
edges.push({ from, to })
}
return edges
}
/** 자카드 유사도 — 두 용어 집합이 얼마나 겹치는가 (0~1). */
export function jaccard(a: readonly string[], b: readonly string[]): number {
if (a.length === 0 || b.length === 0) return 0
const setA = new Set(a)
const setB = new Set(b)
let intersection = 0
for (const term of setA) {
if (setB.has(term)) intersection += 1
}
const union = setA.size + setB.size - intersection
return union === 0 ? 0 : intersection / union
}
/** 용어 공유 엣지로 볼 최소 자카드. */
export const SHARES_TERMS_MIN_SIMILARITY = 0.34
/**
* 접두 꼬리 뒤에 실제로 이어 쓴 텍스트를 뽑는다.
*
* `texts` 는 꼬리를 포함하는 후보 문장들(최신순)이다.
*/
export function continuationsFrom(
texts: readonly string[],
tail: string,
limit = 3,
maxChars = 60
): string[] {
const needle = tail.trim()
if (needle.length < 4) return []
const out: string[] = []
for (const text of texts) {
const index = text.indexOf(needle)
if (index < 0) continue
const continuation = text
.slice(index + needle.length)
.replace(/\s+/gu, ' ')
.trim()
if (continuation.length < 3) continue
const clipped = continuation.slice(0, maxChars)
if (out.includes(clipped)) continue
out.push(clipped)
if (out.length >= limit) break
}
return out
}
const EDGE_PUNCT = /^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu
function normalizeWordStem(rawWord: string): string {
const cleaned = rawWord.normalize('NFC').replace(EDGE_PUNCT, '').toLowerCase()
return cleaned ? stemTerm(cleaned) : ''
}
/**
* 조사가 달라 정확한 부분 문자열(`continuationsFrom`)이 어긋날 때 어간(stem) 열이 일치하는 지점 뒤의 이어쓰기를 뽑는다.
* 예: 저장 문장 "회의록 정리해서 내일 오전까지 공유드리겠습니다" ← 입력 꼬리 "회의록을 정리해서" → "내일 오전까지 공유드리겠습니다"
*/
export function stemContinuationsFrom(
texts: readonly string[],
tail: string,
limit = 3,
maxChars = 60
): string[] {
const rawTailWords = tail
.trim()
.split(/\s+/u)
.map(normalizeWordStem)
.filter((w) => w.length >= 2)
if (rawTailWords.length === 0) return []
const tailStems = rawTailWords.slice(-3)
if (tailStems.length === 1 && tailStems[0].length < 2) return []
const out: string[] = []
for (const text of texts) {
const spans: Array<{ stem: string; end: number }> = []
const wordRegex = /\S+/gu
for (let match = wordRegex.exec(text); match !== null; match = wordRegex.exec(text)) {
const stem = normalizeWordStem(match[0])
if (stem.length > 0) {
spans.push({ stem, end: match.index + match[0].length })
}
}
if (spans.length <= tailStems.length) continue
for (let len = tailStems.length; len >= Math.min(2, tailStems.length); len -= 1) {
const needleStems = tailStems.slice(-len)
for (let i = 0; i <= spans.length - len - 1; i += 1) {
let matched = true
for (let k = 0; k < len; k += 1) {
if (spans[i + k].stem !== needleStems[k]) {
matched = false
break
}
}
if (!matched) continue
const sliceStart = spans[i + len - 1].end
const continuation = text
.slice(sliceStart)
.replace(/^[,.:;!?~\s]+/u, '')
.replace(/\s+/gu, ' ')
.trim()
if (continuation.length < 3) continue
const clipped = continuation.slice(0, maxChars)
if (!out.includes(clipped)) {
out.push(clipped)
if (out.length >= limit) return out
}
break
}
}
}
return out
}
export interface RelatedCandidate {
text: string
terms: readonly string[]
/** 엣지 가중치 합 (follows 가중치가 더 크게 반영된다) */
weight: number
lastUsedAt: number | null
}
/**
* 관련 문장 순위를 매긴다.
*
* 점수 = 엣지 가중치 + 용어 유사도 + 최근성 보너스.
* 이미 접두에 포함된 문장(후보 자신)은 제외한다.
*/
export function rankRelated(
anchorTerms: readonly string[],
candidates: readonly RelatedCandidate[],
limit = 4
): string[] {
const scored = candidates
.map((candidate) => {
const similarity = jaccard(anchorTerms, candidate.terms)
const recency = candidate.lastUsedAt
? Math.max(0, 1 - (Date.now() - candidate.lastUsedAt) / (7 * 86400000))
: 0
return { text: candidate.text, score: candidate.weight * 1.0 + similarity * 2.0 + recency * 0.5 }
})
.sort((a, b) => b.score - a.score)
const out: string[] = []
for (const item of scored) {
if (out.includes(item.text)) continue
out.push(item.text)
if (out.length >= limit) break
}
return out
}
// ============================================================
// 관련 문장 점수 (IDF 가중 용어 겹침)
// ============================================================
/** 관련 문장 후보 노드 — 저장소에서 읽은 그대로(용어는 어간화 전일 수 있다). */
export interface GraphNodeSample {
text: string
terms: readonly string[]
count: number
lastUsedAt: number | null
appName: string | null
}
export interface RelatedNodeQuery {
/** 질의 용어 → 가중치 (지금 문장 용어를 앞 문맥보다 무겁게) */
terms: ReadonlyMap<string, number>
appName?: string | null
now?: number
/** 이미 접두에 들어 있는 문장 등 제외할 텍스트 */
exclude?: (text: string) => boolean
}
export interface ScoredNode {
text: string
score: number
sharedTerms: number
}
/**
* 질의 용어와 노드 용어의 겹침을 IDF 로 가중해 순위를 매긴다.
*
* 자카드는 긴 문장일수록 점수가 희석되고, "합니다" 같은 흔한 어절과 "배포" 같은 주제어를 같게
* 센다. 여기서는 훑은 노드 집합에서 드문 용어일수록 무겁게, 노드 길이는 제곱근으로만 나눈다.
* 같은 앱에서 쓴 문장, 최근 문장, 자주 쓴 문장에 가산점을 준다.
*/
export function scoreRelatedNodes(
query: RelatedNodeQuery,
nodes: readonly GraphNodeSample[],
limit = 6
): ScoredNode[] {
if (query.terms.size === 0 || nodes.length === 0) return []
const now = query.now ?? Date.now()
const nodeTerms = nodes.map((node) => new Set(node.terms.map(stemTerm)))
const documentFrequency = new Map<string, number>()
for (const terms of nodeTerms) {
for (const term of terms) documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1)
}
const total = nodes.length
const idf = (term: string): number => Math.log(1 + total / (1 + (documentFrequency.get(term) ?? 0)))
const requestedApp = query.appName?.trim().toLowerCase() || null
const scored: ScoredNode[] = []
nodes.forEach((node, index) => {
if (query.exclude?.(node.text)) return
const terms = nodeTerms[index]
if (terms.size === 0) return
let overlap = 0
let shared = 0
for (const [term, weight] of query.terms) {
if (!terms.has(term)) continue
overlap += weight * idf(term)
shared += 1
}
if (shared === 0) return
const recency = node.lastUsedAt ? Math.max(0, 1 - (now - node.lastUsedAt) / (14 * 86400000)) : 0
const sameApp = requestedApp !== null && node.appName?.trim().toLowerCase() === requestedApp
const score =
(overlap / Math.sqrt(terms.size)) * (sameApp ? 1.3 : 1) +
recency * 0.3 +
Math.log2(1 + Math.max(0, node.count)) * 0.1
scored.push({ text: node.text, score, sharedTerms: shared })
})
scored.sort((a, b) => b.score - a.score || b.sharedTerms - a.sharedTerms)
const out: ScoredNode[] = []
for (const item of scored) {
if (out.some((existing) => existing.text === item.text)) continue
out.push(item)
if (out.length >= limit) break
}
return out
}
/**
* 질의 용어 가중치 — 지금 쓰는 문장 2, 직전 문장 1.5, 앞 문맥 1.
* 같은 용어가 여러 곳에 나오면 가장 큰 가중치를 쓴다.
*/
export function buildQueryTerms(parts: ReadonlyArray<{ text: string; weight: number }>): Map<string, number> {
const terms = new Map<string, number>()
for (const part of parts) {
if (!part.text) continue
for (const term of extractTerms(part.text, 12)) {
terms.set(term, Math.max(terms.get(term) ?? 0, part.weight))
}
}
return terms
}
export interface TwoHopGraphEdge {
from: string
to: string
kind: GraphEdgeKind
weight: number
}
/**
* 2-hop 그래프 경로 탐색 (A --shares_terms--> B --follows--> C 또는 A --follows--> B --follows--> C).
*
* 직전 문장(또는 지금 문장)과 직접 이어진 follows 엣지가 없더라도,
* 같은 주제를 공유하는 이웃 문장(shares_terms) 뒤에 실제로 이어 썼던 문장(follows)을
* 경로 가중치와 질의 용어 겹침으로 점수화해 끌어온다.
*/
export function rankTwoHopGraphTargets(params: {
firstHopEdges: readonly TwoHopGraphEdge[]
secondHopFollowEdges: readonly TwoHopGraphEdge[]
queryTerms: ReadonlyMap<string, number>
exclude?: (text: string) => boolean
limit?: number
}): string[] {
const { firstHopEdges, secondHopFollowEdges, queryTerms, exclude, limit = 4 } = params
if (firstHopEdges.length === 0 || secondHopFollowEdges.length === 0) return []
const firstHopScores = new Map<string, number>()
for (const edge of firstHopEdges) {
const kindMultiplier = edge.kind === 'follows' ? 1.5 : 1.0
const score = Math.log2(1 + Math.max(1, edge.weight)) * kindMultiplier
firstHopScores.set(edge.to, Math.max(firstHopScores.get(edge.to) ?? 0, score))
}
const targetScores = new Map<string, number>()
for (const edge of secondHopFollowEdges) {
if (edge.kind !== 'follows') continue
if (exclude?.(edge.to)) continue
const hop1 = firstHopScores.get(edge.from)
if (hop1 === undefined) continue
const hop2 = Math.log2(1 + Math.max(1, edge.weight)) * 1.4
const targetTerms = extractTerms(edge.to, 8)
let termBonus = 0
for (const term of targetTerms) {
termBonus += (queryTerms.get(term) ?? 0) * 0.6
}
const totalScore = hop1 * hop2 + termBonus
targetScores.set(edge.to, (targetScores.get(edge.to) ?? 0) + totalScore)
}
return [...targetScores.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([text]) => text)
}
export interface CandidatePersonalizationContext {
prefix: string
continuationHints?: readonly string[]
followUpHints?: readonly string[]
relatedHints?: readonly string[]
phraseHints?: readonly string[]
}
/**
* 생성된 제안 후보가 사용자의 개인 그래프(이어쓰기·직후 문장·관련 문장·자주 쓰는 표현) 및 현재 어투와
* 얼마나 잘 맞는지 점수화한다 (후보 재정렬용).
*/
export function scoreCandidatePersonalization(
candidateText: string,
context: CandidatePersonalizationContext
): number {
const normalizedCandidate = candidateText.replace(/\s+/gu, ' ').trim()
if (!normalizedCandidate) return 0
let score = 0
const candidateTerms = new Set(extractTerms(normalizedCandidate, 10))
for (const hint of context.continuationHints ?? []) {
const normHint = hint.replace(/\s+/gu, ' ').trim()
if (!normHint) continue
if (normalizedCandidate === normHint || normalizedCandidate.startsWith(normHint) || normHint.startsWith(normalizedCandidate)) {
score += 4.0
break
}
}
for (const hint of context.followUpHints ?? []) {
const normHint = hint.replace(/\s+/gu, ' ').trim()
if (!normHint) continue
if (normalizedCandidate === normHint || normalizedCandidate.startsWith(normHint) || normHint.startsWith(normalizedCandidate)) {
score += 3.5
break
}
}
const addOverlapScore = (hints: readonly string[] | undefined, weightPerTerm: number): void => {
if (!hints || hints.length === 0 || candidateTerms.size === 0) return
let matched = 0
for (const hint of hints) {
for (const term of extractTerms(hint, 8)) {
if (candidateTerms.has(term)) matched += 1
}
}
score += Math.min(matched, 5) * weightPerTerm
}
addOverlapScore(context.continuationHints, 1.8)
addOverlapScore(context.followUpHints, 1.6)
addOverlapScore(context.relatedHints, 1.0)
addOverlapScore(context.phraseHints, 0.8)
const prefixRegister = detectSentenceRegister(context.prefix)
const candidateRegister = detectSentenceRegister(normalizedCandidate)
if (prefixRegister && candidateRegister) {
if (prefixRegister === candidateRegister) {
score += 0.8
} else if (
(prefixRegister === 'casual' && (candidateRegister === 'formal' || candidateRegister === 'polite')) ||
((prefixRegister === 'formal' || prefixRegister === 'polite') && candidateRegister === 'casual')
) {
score -= 1.5
}
}
return score
}