// packages/core — 화면 OCR 정본 (순수 함수만: Electron/Node/DOM 의존 금지). // // 담는 것: // 1) OCR 결과 표현 — OcrResult / OcrLine / OcrWord (좌표는 캡처 이미지의 **물리 픽셀**) // 2) 엔진 출력 해석 — parseOcrEngineOutput (엔진이 준 JSON 을 검증해 정본 표현으로) // 3) 선택 계산 — 사각형 선택(wordsInRect) · 글 흐름 선택(flowSelection) · 단어/줄 선택 // 4) 선택 → 텍스트 — selectionText (줄바꿈 유지 / 한 줄, CJK 는 공백 없이 잇기) // 5) 강조 사각형 — selectionHighlightRects (줄 단위로 이어 붙인 사각형) // 6) 검색 가능한 PDF 문서 — buildSearchablePdfHtml (그림 아래에 실제 글자를 깐다) // 7) 부가 판정 — chooseOcrScale · detectLinks · pickTranslationTarget // // 오버레이(Vanilla JS 팝업)와 메인 프로세스가 같은 계산을 쓰도록 여기에 둔다. export interface OcrRect { x: number y: number width: number height: number } export interface OcrPoint { x: number y: number } /** 인식된 단어 하나. 좌표는 캡처 이미지의 물리 픽셀. */ export interface OcrWord extends OcrRect { text: string /** 속한 줄의 번호 (OcrResult.lines 의 인덱스) */ line: number /** 읽는 순서대로 매긴 전체 단어 번호 (OcrResult.words 의 인덱스) */ index: number } export interface OcrLine extends OcrRect { /** 이 줄의 첫 단어 번호 */ start: number /** 이 줄의 단어 수 */ count: number } export interface OcrResult { /** 인식에 쓴 언어 태그 (예: 'ko', 'en-US') */ language: string lines: OcrLine[] /** 읽는 순서로 편 전체 단어 */ words: OcrWord[] } // ============================================================ // 엔진 출력 해석 // ============================================================ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } function finiteNumber(value: unknown): number | null { return typeof value === 'number' && Number.isFinite(value) ? value : null } function unionRect(rects: readonly OcrRect[]): OcrRect { let left = Infinity let top = Infinity let right = -Infinity let bottom = -Infinity for (const r of rects) { left = Math.min(left, r.x) top = Math.min(top, r.y) right = Math.max(right, r.x + r.width) bottom = Math.max(bottom, r.y + r.height) } return { x: left, y: top, width: right - left, height: bottom - top } } /** * 엔진이 준 `{ lang, lines: [{ words: [{ t, x, y, w, h }] }] }` 를 정본 표현으로 옮긴다. * 모양이 어긋난 단어(글자 없음 · 좌표가 수가 아님 · 크기 0)는 버리고, 단어가 하나도 안 남은 줄도 버린다. * 최상위 모양이 틀리면 null — 호출자는 인식 실패로 다룬다(빈 결과로 꾸미지 않는다). */ export function parseOcrEngineOutput(raw: unknown): OcrResult | null { if (!isRecord(raw) || !Array.isArray(raw.lines)) return null const language = typeof raw.lang === 'string' ? raw.lang : '' const lines: OcrLine[] = [] const words: OcrWord[] = [] for (const rawLine of raw.lines) { if (!isRecord(rawLine) || !Array.isArray(rawLine.words)) continue const start = words.length for (const rawWord of rawLine.words) { if (!isRecord(rawWord)) continue const text = typeof rawWord.t === 'string' ? rawWord.t : '' const x = finiteNumber(rawWord.x) const y = finiteNumber(rawWord.y) const width = finiteNumber(rawWord.w) const height = finiteNumber(rawWord.h) if (text.length === 0 || x === null || y === null || width === null || height === null) continue if (width <= 0 || height <= 0) continue words.push({ text, x, y, width, height, line: lines.length, index: words.length }) } const count = words.length - start if (count === 0) continue lines.push({ ...unionRect(words.slice(start)), start, count }) } return { language, lines, words } } // ============================================================ // 기하 // ============================================================ /** 두 점으로 사각형을 만든다 (끌기 방향과 무관하게 양수 크기). */ export function rectFromPoints(a: OcrPoint, b: OcrPoint): OcrRect { return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(a.x - b.x), height: Math.abs(a.y - b.y) } } /** 사각형을 경계 안으로 자르고 정수 픽셀로 맞춘다. 남는 면적이 없으면 null. */ export function clampRect(rect: OcrRect, bounds: { width: number; height: number }): OcrRect | null { const left = Math.max(0, Math.floor(rect.x)) const top = Math.max(0, Math.floor(rect.y)) const right = Math.min(bounds.width, Math.ceil(rect.x + rect.width)) const bottom = Math.min(bounds.height, Math.ceil(rect.y + rect.height)) if (right - left < 1 || bottom - top < 1) return null return { x: left, y: top, width: right - left, height: bottom - top } } function containsPoint(rect: OcrRect, point: OcrPoint, pad = 0): boolean { return ( point.x >= rect.x - pad && point.x <= rect.x + rect.width + pad && point.y >= rect.y - pad && point.y <= rect.y + rect.height + pad ) } // ============================================================ // 선택 계산 // ============================================================ /** * 사각형 선택 — 중심이 사각형 안에 있거나 면적의 절반 이상이 걸친 단어. * 살짝 스친 옆 줄까지 딸려 오지 않게 "닿기만 하면 선택"으로 하지 않는다. */ export function wordsInRect(result: OcrResult, rect: OcrRect): number[] { const out: number[] = [] const right = rect.x + rect.width const bottom = rect.y + rect.height for (const word of result.words) { const cx = word.x + word.width / 2 const cy = word.y + word.height / 2 if (cx >= rect.x && cx <= right && cy >= rect.y && cy <= bottom) { out.push(word.index) continue } const overlapW = Math.min(right, word.x + word.width) - Math.max(rect.x, word.x) const overlapH = Math.min(bottom, word.y + word.height) - Math.max(rect.y, word.y) if (overlapW > 0 && overlapH > 0 && overlapW * overlapH >= word.width * word.height * 0.5) { out.push(word.index) } } return out } /** 점 바로 아래(여유 pad 픽셀)의 단어 번호. 없으면 null. */ export function wordAtPoint(result: OcrResult, point: OcrPoint, pad = 2): number | null { for (const word of result.words) { if (containsPoint(word, point, pad)) return word.index } return null } /** * 글 흐름 선택의 끝점 — 점에서 가장 가까운 줄을 고르고, 그 줄 안에서 가장 가까운 단어를 고른다. * 줄 밖 여백으로 끌어도 선택이 이어지게 하려는 것이다(일반 글 선택과 같은 느낌). */ export function nearestWordIndex(result: OcrResult, point: OcrPoint): number | null { if (result.words.length === 0) return null let bestLine: OcrLine | null = null let bestDistance = Infinity for (const line of result.lines) { const dy = point.y < line.y ? line.y - point.y : point.y > line.y + line.height ? point.y - (line.y + line.height) : 0 const dx = point.x < line.x ? line.x - point.x : point.x > line.x + line.width ? point.x - (line.x + line.width) : 0 // 세로 거리를 훨씬 무겁게 본다 — 같은 높이의 줄이 먼 옆 단(column)이라도 위아래 줄보다 우선이다. const distance = dy * 4 + dx if (distance < bestDistance) { bestDistance = distance bestLine = line } } if (!bestLine) return null let best = bestLine.start let bestDx = Infinity for (let i = bestLine.start; i < bestLine.start + bestLine.count; i += 1) { const word = result.words[i] const dx = point.x < word.x ? word.x - point.x : point.x > word.x + word.width ? point.x - (word.x + word.width) : 0 if (dx < bestDx) { bestDx = dx best = i } } return best } /** 글 흐름 선택 — 시작 단어부터 끝 단어까지 읽는 순서로 전부. */ export function flowSelection(anchor: number, focus: number): number[] { const from = Math.min(anchor, focus) const to = Math.max(anchor, focus) const out: number[] = [] for (let i = from; i <= to; i += 1) out.push(i) return out } /** 단어가 속한 줄 전체. */ export function lineSelection(result: OcrResult, wordIndex: number): number[] { const word = result.words[wordIndex] if (!word) return [] const line = result.lines[word.line] return flowSelection(line.start, line.start + line.count - 1) } export function allWords(result: OcrResult): number[] { return result.words.map((word) => word.index) } // ============================================================ // 선택 → 텍스트 // ============================================================ /** 한자 · 히라가나 · 가타카나 — 띄어 쓰지 않는 글자. (한글은 띄어 쓴다) */ function isUnspacedScript(char: string): boolean { const code = char.codePointAt(0) ?? 0 return ( (code >= 0x3040 && code <= 0x30ff) || // 히라가나 · 가타카나 (code >= 0x3400 && code <= 0x4dbf) || // 한자 확장 A (code >= 0x4e00 && code <= 0x9fff) || // 한자 (code >= 0x3000 && code <= 0x303f) || // CJK 문장부호 (code >= 0xff00 && code <= 0xffef) // 전각 문자 ) } function lastChar(text: string): string { const chars = Array.from(text) return chars[chars.length - 1] ?? '' } function firstChar(text: string): string { return Array.from(text)[0] ?? '' } /** 한 줄 안에서 이웃한 두 단어 사이에 공백을 넣을지. 일본어 · 중국어는 엔진이 글자마다 단어로 준다. */ function joiner(previous: string, next: string): string { return isUnspacedScript(lastChar(previous)) && isUnspacedScript(firstChar(next)) ? '' : ' ' } export interface SelectionTextOptions { /** true 면 줄바꿈 없이 한 줄로 잇는다 */ singleLine?: boolean } /** * 선택한 단어들을 글로 만든다. 줄은 인식된 줄 순서를 따르고, 같은 줄의 단어는 왼쪽부터 잇는다. * 번호가 범위를 벗어나거나 겹쳐도 무시한다. */ export function selectionText( result: OcrResult, selected: readonly number[], options: SelectionTextOptions = {} ): string { const picked = Array.from(new Set(selected)) .filter((index) => Number.isInteger(index) && index >= 0 && index < result.words.length) .sort((a, b) => a - b) const lines: string[] = [] let currentLine = -1 let buffer = '' for (const index of picked) { const word = result.words[index] if (word.line !== currentLine) { if (currentLine !== -1) lines.push(buffer) currentLine = word.line buffer = word.text } else { buffer += joiner(buffer, word.text) + word.text } } if (currentLine !== -1) lines.push(buffer) if (!options.singleLine) return lines.join('\n') let joined = '' for (const line of lines) { joined = joined.length === 0 ? line : joined + joiner(joined, line) + line } return joined } /** 선택한 단어를 모두 감싸는 사각형. 선택이 비면 null. */ export function selectionBounds(result: OcrResult, selected: readonly number[]): OcrRect | null { const rects = selected.map((index) => result.words[index]).filter((word): word is OcrWord => Boolean(word)) return rects.length === 0 ? null : unionRect(rects) } /** * 강조 표시용 사각형 — 같은 줄에서 연달아 선택된 단어는 하나로 잇는다(단어 사이 틈이 비어 보이지 않게). * 높이는 그 줄의 높이로 맞춰 글자마다 들쭉날쭉하지 않게 한다. */ export function selectionHighlightRects(result: OcrResult, selected: readonly number[]): OcrRect[] { const picked = Array.from(new Set(selected)) .filter((index) => Number.isInteger(index) && index >= 0 && index < result.words.length) .sort((a, b) => a - b) const out: OcrRect[] = [] let runStart = -1 let previous = -1 const flush = (): void => { if (runStart === -1) return const first = result.words[runStart] const last = result.words[previous] const line = result.lines[first.line] out.push({ x: first.x, y: line.y, width: last.x + last.width - first.x, height: line.height }) } for (const index of picked) { const word = result.words[index] const continues = previous !== -1 && index === previous + 1 && result.words[previous].line === word.line if (!continues) { flush() runStart = index } previous = index } flush() return out } // ============================================================ // 인식 배율 // ============================================================ /** * OCR 에 넣기 전 확대 배율. 화면 글자(100% 배율에서 9~10pt)는 그대로 넣으면 인식률이 뚝 떨어지고 * 2배로 키우면 크게 좋아진다(2026-11-20 실측). 이미 고배율(HiDPI) 화면이면 덜 키운다. * 엔진의 최대 변 길이를 넘지 않게 줄인다. */ export function chooseOcrScale( width: number, height: number, displayScaleFactor: number, maxDimension: number ): number { const factor = Number.isFinite(displayScaleFactor) && displayScaleFactor > 0 ? displayScaleFactor : 1 const wanted = Math.max(1, 2 / factor) const longest = Math.max(width, height) if (longest <= 0) return 1 const allowed = maxDimension / longest const scale = Math.min(wanted, allowed) return Math.round(scale * 100) / 100 } // ============================================================ // 링크 · 번역 대상 // ============================================================ const URL_PATTERN = /\b((?:https?:\/\/|www\.)[^\s<>"'`]+[^\s<>"'`.,;:!?)\]}])/giu const EMAIL_PATTERN = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu /** 글에서 열 수 있는 주소를 찾는다 (http/https, www. 로 시작하는 주소, 메일 주소). 중복은 뺀다. */ export function detectLinks(text: string): string[] { const out: string[] = [] const add = (value: string): void => { if (!out.includes(value)) out.push(value) } for (const match of text.matchAll(EMAIL_PATTERN)) add(`mailto:${match[0]}`) for (const match of text.matchAll(URL_PATTERN)) { const raw = match[1] add(/^https?:\/\//iu.test(raw) ? raw : `https://${raw}`) } return out } /** 앱 언어 코드 → 번역 프롬프트에 넣을 언어 이름. */ const LOCALE_LANGUAGE_NAMES: Readonly> = { ko: 'Korean', en: 'English', ja: 'Japanese', zh: 'Chinese (Simplified)', 'zh-TW': 'Chinese (Traditional)', es: 'Spanish', fr: 'French', de: 'German', pt: 'Portuguese', ru: 'Russian', th: 'Thai', vi: 'Vietnamese' } function scriptShare(text: string, test: (code: number) => boolean): number { let letters = 0 let hits = 0 for (const char of text) { if (!/\p{L}/u.test(char)) continue letters += 1 if (test(char.codePointAt(0) ?? 0)) hits += 1 } return letters === 0 ? 0 : hits / letters } const isHangul = (code: number): boolean => (code >= 0xac00 && code <= 0xd7a3) || (code >= 0x1100 && code <= 0x11ff) const isKana = (code: number): boolean => code >= 0x3040 && code <= 0x30ff const isHan = (code: number): boolean => (code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3400 && code <= 0x4dbf) const isCyrillic = (code: number): boolean => code >= 0x0400 && code <= 0x04ff const isThai = (code: number): boolean => code >= 0x0e00 && code <= 0x0e7f const isLatin = (code: number): boolean => (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a) || (code >= 0xc0 && code <= 0x24f) /** 글이 이미 사용자의 언어로 보이는지 (문자 체계로만 어림한다). */ function looksLikeLocale(text: string, locale: string): boolean { switch (locale) { case 'ko': return scriptShare(text, isHangul) >= 0.3 case 'ja': return scriptShare(text, isKana) >= 0.15 case 'zh': case 'zh-TW': return scriptShare(text, isHan) >= 0.5 && scriptShare(text, isKana) < 0.05 case 'ru': return scriptShare(text, isCyrillic) >= 0.5 case 'th': return scriptShare(text, isThai) >= 0.5 default: // 라틴 문자 언어끼리는 문자로 구분할 수 없다 — 라틴 글이면 "이미 사용자 언어"로 본다. return scriptShare(text, isLatin) >= 0.7 } } /** * 번역 대상 언어를 고른다 — 기본은 사용자의 앱 언어로 옮긴다. * 글이 이미 그 언어로 보이면 설정의 번역 대상 언어(configuredTarget)로 옮긴다. */ export function pickTranslationTarget(text: string, appLocale: string, configuredTarget: string): string { const own = LOCALE_LANGUAGE_NAMES[appLocale] if (!own) return configuredTarget return looksLikeLocale(text, appLocale) ? configuredTarget : own } // ============================================================ // 검색 가능한 PDF 문서 // ============================================================ function escapeHtml(value: string): string { return value .replace(/&/gu, '&') .replace(//gu, '>') .replace(/"/gu, '"') } export interface SearchablePdfInput { /** 그림의 data URL (image/png) */ imageDataUrl: string /** 그림 크기 (물리 픽셀) — 쪽 크기가 된다 */ width: number height: number /** 그림 좌표계의 단어 (잘라낸 영역이면 그 영역 기준으로 옮긴 좌표) */ words: ReadonlyArray> /** 문서 lang 속성 */ language: string } /** * 그림 한 장 + 글자 층으로 된 한 쪽짜리 HTML — printToPDF 로 넘기면 검색·복사가 되는 PDF 가 된다. * * 글자를 투명하게 칠하지 않고 **그림 아래에** 깐다: 투명 글자는 PDF 백엔드가 그리지 않고 버릴 수 있지만, * 가려진 글자는 내용 스트림에 그대로 남아 보기 프로그램이 찾고 고를 수 있다. * 글자 폭은 SVG textLength 로 단어 상자에 정확히 맞춘다(측정용 스크립트가 필요 없다). */ export function buildSearchablePdfHtml(input: SearchablePdfInput): string { const width = Math.max(1, Math.round(input.width)) const height = Math.max(1, Math.round(input.height)) const texts = input.words .filter((word) => word.text.trim().length > 0 && word.width > 0 && word.height > 0) .map((word) => { const fontSize = Math.max(1, word.height * 0.9) const baseline = word.y + word.height * 0.82 return ( `${escapeHtml(word.text)}` ) }) .join('') return ( `` + `` + `
` + `${texts}` + `` + `
` ) } /** 사각형 안에 중심이 든 단어를 그 사각형 기준 좌표로 옮긴다 (영역만 PDF/그림으로 낼 때). */ export function wordsRelativeTo(result: OcrResult, rect: OcrRect): OcrWord[] { return wordsInRect(result, rect).map((index) => { const word = result.words[index] return { ...word, x: word.x - rect.x, y: word.y - rect.y } }) }