feat(input): upgrade graph personalization, english morphology detection, and atomic SendInput replacement
This commit is contained in:
parent
52eef21bab
commit
cd4a452148
21 changed files with 1098 additions and 110 deletions
|
|
@ -16,8 +16,10 @@ import {
|
|||
continuationsFrom,
|
||||
extractTerms,
|
||||
jaccard,
|
||||
rankTwoHopGraphTargets,
|
||||
scoreRelatedNodes,
|
||||
splitSentences,
|
||||
stemContinuationsFrom,
|
||||
type GraphContext,
|
||||
type PersonalGraphQuery,
|
||||
type PersonalGraphStats,
|
||||
|
|
@ -40,13 +42,20 @@ export type { PersonalGraphQuery, PersonalGraphStats }
|
|||
const MAINTENANCE_NODE_LIMIT = 300
|
||||
/** 관계 조회에서 최근 노드를 훑는 수. */
|
||||
const TERM_SCAN_LIMIT = 400
|
||||
/** 같은 앱에서 단문 메시지를 연속으로 보낼 때 follows 엣지로 잇는 최대 세션 간격 (10분). */
|
||||
const SESSION_FOLLOWS_WINDOW_MS = 10 * 60_000
|
||||
/** 새 문장을 넣을 때 즉시 shares_terms 엣지를 연결할 최근 노드 수. */
|
||||
const INCREMENTAL_SHARES_SCAN_LIMIT = 40
|
||||
|
||||
class PersonalGraphService {
|
||||
/** 앱별 마지막 학습 문장 — 카카오톡·슬랙 등 단문 메시지 사이의 follows 사슬을 잇는다. */
|
||||
private readonly _lastIndexedByScope = new Map<string, { phrase: string; at: number }>()
|
||||
|
||||
/**
|
||||
* 텍스트를 그래프에 반영한다.
|
||||
*
|
||||
* 문장마다 노드를 upsert 하고, 연속한 문장 쌍을 follows 엣지로, 용어를 충분히
|
||||
* 공유하는 쌍을 shares_terms 엣지로 남긴다.
|
||||
* 문장마다 노드를 upsert 하고, 연속한 문장 쌍(같은 앱의 직전 메시지 포함)을 follows 엣지로,
|
||||
* 용어를 충분히 공유하는 쌍을 shares_terms 엣지로 남긴다.
|
||||
*/
|
||||
indexText(
|
||||
text: string,
|
||||
|
|
@ -56,9 +65,17 @@ class PersonalGraphService {
|
|||
if (sentences.length === 0) return
|
||||
|
||||
const at = meta.at ?? Date.now()
|
||||
const scopeKey = meta.appName?.trim().toLowerCase() || null
|
||||
try {
|
||||
const db = getDatabase()
|
||||
|
||||
const recentExisting = db
|
||||
.select({ phrase: personalPhrases.phrase, terms: personalPhrases.terms })
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.lastUsedAt))
|
||||
.limit(INCREMENTAL_SHARES_SCAN_LIMIT)
|
||||
.all()
|
||||
|
||||
for (const sentence of sentences) {
|
||||
const terms = extractTerms(sentence)
|
||||
db.insert(personalPhrases)
|
||||
|
|
@ -82,9 +99,36 @@ class PersonalGraphService {
|
|||
}
|
||||
})
|
||||
.run()
|
||||
|
||||
if (terms.length > 0) {
|
||||
for (const existing of recentExisting) {
|
||||
if (existing.phrase === sentence) continue
|
||||
const existingTerms = parseTerms(existing.terms)
|
||||
if (existingTerms.length === 0) continue
|
||||
if (jaccard(terms, existingTerms) >= SHARES_TERMS_MIN_SIMILARITY) {
|
||||
this._upsertEdge(existing.phrase, sentence, 'shares_terms')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// follows 엣지
|
||||
// 같은 앱에서 직전 세션(10분 이내)에 쓴 문장과 첫 문장을 follows 로 연결
|
||||
if (scopeKey) {
|
||||
const previousInScope = this._lastIndexedByScope.get(scopeKey)
|
||||
if (
|
||||
previousInScope &&
|
||||
previousInScope.phrase !== sentences[0] &&
|
||||
Math.abs(at - previousInScope.at) <= SESSION_FOLLOWS_WINDOW_MS
|
||||
) {
|
||||
this._upsertEdge(previousInScope.phrase, sentences[0], 'follows')
|
||||
}
|
||||
this._lastIndexedByScope.set(scopeKey, {
|
||||
phrase: sentences[sentences.length - 1],
|
||||
at
|
||||
})
|
||||
}
|
||||
|
||||
// follows 엣지 (같은 텍스트 내 인접 문장)
|
||||
for (const edge of buildSequenceEdges(sentences)) {
|
||||
this._upsertEdge(edge.from, edge.to, 'follows')
|
||||
}
|
||||
|
|
@ -135,7 +179,11 @@ class PersonalGraphService {
|
|||
* 3) related — 지금 문장·직전 문장·앞 문맥의 용어를 IDF 로 가중해 고른 관련 문장과,
|
||||
* 그 문장들 뒤에 이어 쓴 문장(follows 1단계 확장).
|
||||
*/
|
||||
retrieveContext(prefix: string, limit = 4, options: { appName?: string | null } = {}): GraphContext {
|
||||
retrieveContext(
|
||||
prefix: string,
|
||||
limit = 4,
|
||||
options: { appName?: string | null; recentWrites?: readonly string[] } = {}
|
||||
): GraphContext {
|
||||
const empty: GraphContext = { continuations: [], related: [], followUps: [] }
|
||||
const normalizedPrefix = prefix.replace(/\s+/gu, ' ').trim()
|
||||
if (normalizedPrefix.length < 2) return empty
|
||||
|
|
@ -143,19 +191,26 @@ class PersonalGraphService {
|
|||
try {
|
||||
const db = getDatabase()
|
||||
const context = analyzeWritingContext(prefix)
|
||||
const recentWriteSentences =
|
||||
options.recentWrites && options.recentWrites.length > 0
|
||||
? splitSentences(options.recentWrites[options.recentWrites.length - 1] ?? '')
|
||||
: []
|
||||
const anchorLastSentence =
|
||||
context.lastSentence ||
|
||||
(recentWriteSentences.length > 0 ? recentWriteSentences[recentWriteSentences.length - 1] : '')
|
||||
const inPrefix = (text: string): boolean => normalizedPrefix.includes(text)
|
||||
|
||||
// (1) 직전 문장 뒤에 이어 쓴 문장
|
||||
const followUps = this._followUpsAfter(context.lastSentence, context.currentSentence ? 2 : 3, inPrefix)
|
||||
// (1) 직전 문장(또는 방금 보낸 채팅 메시지) 뒤에 이어 쓴 문장
|
||||
const followUps = this._followUpsAfter(anchorLastSentence, context.currentSentence ? 2 : 3, inPrefix)
|
||||
|
||||
// (2) 꼬리 이어쓰기 — 지금 문장 안에서만 찾는다 (앞 문장 끝과 섞이지 않게)
|
||||
const tailSource = context.currentSentence || context.lastSentence
|
||||
const continuations = this._continuationsForTail(tailSource)
|
||||
|
||||
// (3) 관련 문장 — IDF 가중 용어 겹침 + follows 1단계 확장
|
||||
// (3) 관련 문장 — IDF 가중 용어 겹침 + 1-hop follows + 2-hop (shares_terms -> follows) 경로 확장
|
||||
const queryTerms = buildQueryTerms([
|
||||
{ text: context.currentSentence, weight: 2 },
|
||||
{ text: context.lastSentence, weight: 1.5 },
|
||||
{ text: anchorLastSentence, weight: 1.5 },
|
||||
{ text: context.earlierText.slice(-200), weight: 1 }
|
||||
])
|
||||
const recentNodes = db
|
||||
|
|
@ -185,22 +240,66 @@ class PersonalGraphService {
|
|||
if (related.length >= limit || related.includes(text) || followUps.includes(text) || inPrefix(text)) return
|
||||
related.push(text)
|
||||
}
|
||||
// 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 2개만 확장한다.
|
||||
const anchors = scored.slice(0, 2).map((item) => item.text)
|
||||
const hops = anchors.length
|
||||
// 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 확장 + 2-hop 경로 탐색
|
||||
const anchors = scored.slice(0, 3).map((item) => item.text)
|
||||
const firstHopEdges = anchors.length
|
||||
? db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(and(inArray(phraseEdges.fromPhrase, anchors), eq(phraseEdges.kind, 'follows')))
|
||||
.where(or(inArray(phraseEdges.fromPhrase, anchors), inArray(phraseEdges.toPhrase, anchors)))
|
||||
.orderBy(desc(phraseEdges.weight))
|
||||
.limit(6)
|
||||
.limit(12)
|
||||
.all()
|
||||
: []
|
||||
const directFollowHops = firstHopEdges.filter(
|
||||
(edge) => edge.kind === 'follows' && anchors.includes(edge.fromPhrase)
|
||||
)
|
||||
const normalizedFirstHop = firstHopEdges.flatMap((edge) => {
|
||||
if (edge.kind === 'follows' && anchors.includes(edge.fromPhrase)) {
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'follows' as const, weight: edge.weight }]
|
||||
}
|
||||
if (edge.kind === 'shares_terms') {
|
||||
if (anchors.includes(edge.fromPhrase)) {
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'shares_terms' as const, weight: edge.weight }]
|
||||
}
|
||||
if (anchors.includes(edge.toPhrase)) {
|
||||
return [{ from: edge.toPhrase, to: edge.fromPhrase, kind: 'shares_terms' as const, weight: edge.weight }]
|
||||
}
|
||||
}
|
||||
return []
|
||||
})
|
||||
const midNodes = [...new Set(normalizedFirstHop.map((edge) => edge.to))]
|
||||
const secondHopFollows = midNodes.length
|
||||
? db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(and(inArray(phraseEdges.fromPhrase, midNodes), eq(phraseEdges.kind, 'follows')))
|
||||
.orderBy(desc(phraseEdges.weight))
|
||||
.limit(12)
|
||||
.all()
|
||||
.map((edge) => ({
|
||||
from: edge.fromPhrase,
|
||||
to: edge.toPhrase,
|
||||
kind: 'follows' as const,
|
||||
weight: edge.weight
|
||||
}))
|
||||
: []
|
||||
const twoHopTargets = rankTwoHopGraphTargets({
|
||||
firstHopEdges: normalizedFirstHop,
|
||||
secondHopFollowEdges: secondHopFollows,
|
||||
queryTerms,
|
||||
exclude: (text) => inPrefix(text) || followUps.includes(text),
|
||||
limit: 2
|
||||
})
|
||||
|
||||
for (const item of scored) {
|
||||
push(item.text)
|
||||
const hop = hops.find((edge) => edge.fromPhrase === item.text)
|
||||
const hop = directFollowHops.find((edge) => edge.fromPhrase === item.text)
|
||||
if (hop) push(hop.toPhrase)
|
||||
}
|
||||
for (const target of twoHopTargets) {
|
||||
push(target)
|
||||
}
|
||||
return { continuations, related, followUps }
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
|
|
@ -305,7 +404,16 @@ class PersonalGraphService {
|
|||
)
|
||||
if (found.length > 0) return found
|
||||
}
|
||||
return []
|
||||
|
||||
// 정확한 문자열 꼬리가 어긋나도("회의록을 정리해서" vs "회의록 정리해서") 어간 열이 일치하면 이어쓰기를 뽑는다.
|
||||
const recentPhrases = db
|
||||
.select({ phrase: personalPhrases.phrase })
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt))
|
||||
.limit(120)
|
||||
.all()
|
||||
.map((row) => row.phrase)
|
||||
return stemContinuationsFrom(recentPhrases, normalized, 3)
|
||||
}
|
||||
|
||||
/** 용어 공유 엣지를 백필한다 (기존 노드들 사이 관계 보강). */
|
||||
|
|
@ -469,6 +577,7 @@ class PersonalGraphService {
|
|||
|
||||
clearAll(): void {
|
||||
try {
|
||||
this._lastIndexedByScope.clear()
|
||||
const db = getDatabase()
|
||||
db.delete(phraseEdges).run()
|
||||
logger.info('개인 그래프 엣지 전체 삭제')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue