// packages/core/src/text-chunking.ts // 줄바꿈이 없는 긴 텍스트를 한도 안의 조각으로 자르는 순수 정책(정본). // // 자막·파일 전사 히스토리(`segments.join(' ')`)와 폰 회의 전사(STT 결과 한 문단)는 줄바꿈이 없다. // 줄 경계로만 나누면 전체가 조각 하나가 되어 LLM 입력 한도·출력 토큰 한도를 넘는다. 그래서 // 문장 경계 → 공백 → 글자 수 순으로 내려가며 자른다. // // 순수 함수만 둔다 — Electron/Node 의존 금지. 다른 core 모듈을 import 하지 않는다(순환 방지). /** 문장을 끝내는 부호 (라틴·CJK·말줄임) */ const SENTENCE_END = new Set(['.', '?', '!', '…', '。', '?', '!']) /** 뒤에 공백이 없어도 문장 경계로 보는 전각 부호 (중국어·일본어는 띄어 쓰지 않는다) */ const FULL_WIDTH_SENTENCE_END = new Set(['。', '?', '!']) /** 문장 끝 부호 뒤에 붙을 수 있는 닫는 따옴표·괄호 */ const CLOSING_MARKS = new Set(['"', "'", '”', '’', ')', ']', '」', '』', ')']) const WHITESPACE = /\s/u /** 문장 경계를 이 비율보다 앞에서만 찾으면 너무 짧은 조각이 되므로 공백 경계를 대신 쓴다 */ const MIN_SENTENCE_FILL_RATIO = 0.5 function isHighSurrogate(code: number): boolean { return code >= 0xd800 && code <= 0xdbff } /** * window(= text 앞 maxChars 자) 안에서 마지막 문장 경계의 끝 위치를 찾는다(없으면 0). * 경계: 문장 끝 부호(+닫는 부호) 뒤가 공백이거나 텍스트 끝, 또는 전각 문장 부호. * "3.5" 처럼 부호 뒤에 바로 글자가 오면 경계가 아니다. */ function lastSentenceBoundary(text: string, limit: number): number { let best = 0 for (let i = 0; i < limit; i++) { const ch = text[i] if (!SENTENCE_END.has(ch)) continue let end = i + 1 while (end < limit && CLOSING_MARKS.has(text[end])) end++ const next = text[end] if (FULL_WIDTH_SENTENCE_END.has(ch) || next === undefined || WHITESPACE.test(next)) { best = end } } return best } function lastWhitespace(text: string, limit: number): number { for (let i = limit; i > 0; i--) { if (WHITESPACE.test(text[i] ?? '')) return i } return 0 } /** text(길이 > maxChars)의 첫 조각을 끊을 위치 — 문장 경계 → 공백 → 글자 수 순. */ function findCut(text: string, maxChars: number): number { const sentence = lastSentenceBoundary(text, maxChars) if (sentence >= Math.ceil(maxChars * MIN_SENTENCE_FILL_RATIO)) return sentence const space = lastWhitespace(text, maxChars) if (space > 0) return space if (sentence > 0) return sentence // 글자 수로 자른다 — 서로게이트 쌍(이모지 등) 가운데는 피한다 const hard = isHighSurrogate(text.charCodeAt(maxChars - 1)) ? maxChars - 1 : maxChars return Math.max(1, hard) } /** * 텍스트를 maxChars 이하 조각들로 자른다. 들어가면 [text] 그대로(앞뒤 공백만 정리). * 자른 조각의 앞뒤 공백은 버리고, 빈 조각은 내지 않는다. */ export function splitTextToFit(text: string, maxChars: number): string[] { const limit = Math.max(1, Math.floor(maxChars)) const pieces: string[] = [] let rest = text.trim() while (rest.length > limit) { const cut = findCut(rest, limit) const piece = rest.slice(0, cut).trim() if (piece) pieces.push(piece) rest = rest.slice(cut).trim() } if (rest) pieces.push(rest) return pieces }