feat(desktop): screen text capture (OCR) overlay with selectable text

A rebindable screen-ocr action (default Ctrl+Alt+O) freezes the monitor under the cursor and
covers it with a focusable overlay. Text is selected by flow drag, rectangle drag, double/triple
click, Shift+click or Ctrl+A, then copied, saved as PNG or searchable PDF, translated,
summarized, read aloud, opened as a link or searched.

- Selection, text assembly and the PDF document are pure functions in @d3ro/core/screen-ocr,
  shared by the main process and the overlay.
- Recognition uses Windows.Media.Ocr through powershell.exe -EncodedCommand with 2x upscaling;
  the capture reaches disk only as a temp PNG that is removed right after recognition.
- Capture uses GDI BitBlt for the target monitor (39 ms) because desktopCapturer captured all
  three monitors and took 2.9 s when DXGI duplication timed out.
- The accelerator is reserved only where the feature is available, so macOS does not swallow
  the key for a feature it cannot run (fails closed with a message).

Map: CAP-17 [~], GAP-OCR-01 (live hotkey journey not yet driven in the running app),
GAP-OCR-02 (macOS engine, mixed-language accuracy).
This commit is contained in:
Yun Chan 2026-11-20 15:16:37 +09:00
parent 6791e29f27
commit 03cd8bf890
41 changed files with 4561 additions and 17 deletions

View file

@ -0,0 +1,279 @@
import { describe, expect, it } from 'vitest'
import {
allWords,
buildSearchablePdfHtml,
chooseOcrScale,
clampRect,
detectLinks,
flowSelection,
lineSelection,
nearestWordIndex,
parseOcrEngineOutput,
pickTranslationTarget,
rectFromPoints,
selectionBounds,
selectionHighlightRects,
selectionText,
wordAtPoint,
wordsInRect,
wordsRelativeTo,
type OcrResult
} from '../src/screen-ocr'
/** 한 줄에 단어를 폭 40, 간격 10 으로 늘어놓는다. */
function line(y: number, texts: string[], startX = 10): { words: Array<Record<string, unknown>> } {
return { words: texts.map((t, i) => ({ t, x: startX + i * 50, y, w: 40, h: 20 })) }
}
function sample(): OcrResult {
const result = parseOcrEngineOutput({
lang: 'ko',
lines: [line(10, ['화면', 'OCR', '기능']), line(50, ['둘째', '줄']), line(90, ['Third', 'line', 'here'])]
})
if (!result) throw new Error('sample did not parse')
return result
}
describe('parseOcrEngineOutput', () => {
it('엔진출력해석_정상입력_읽는순서로단어번호와줄범위를매긴다', () => {
const result = sample()
expect(result.language).toBe('ko')
expect(result.words.map((w) => w.text)).toEqual(['화면', 'OCR', '기능', '둘째', '줄', 'Third', 'line', 'here'])
expect(result.words.map((w) => w.index)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
expect(result.lines.map((l) => [l.start, l.count])).toEqual([
[0, 3],
[3, 2],
[5, 3]
])
expect(result.lines[0]).toMatchObject({ x: 10, y: 10, width: 140, height: 20 })
})
it('엔진출력해석_모양이틀린최상위_null을돌려줘빈결과로꾸미지않는다', () => {
expect(parseOcrEngineOutput(null)).toBeNull()
expect(parseOcrEngineOutput({ lang: 'ko' })).toBeNull()
expect(parseOcrEngineOutput({ lines: 'nope' })).toBeNull()
})
it('엔진출력해석_망가진단어와빈줄_버리고나머지번호는이어진다', () => {
const result = parseOcrEngineOutput({
lang: 'en',
lines: [
{ words: [{ t: '', x: 0, y: 0, w: 10, h: 10 }, { t: 'ok', x: 'NaN', y: 0, w: 10, h: 10 }] },
{ words: [{ t: 'zero', x: 0, y: 0, w: 0, h: 10 }, { t: 'kept', x: 5, y: 5, w: 10, h: 10 }] },
'garbage'
]
})
expect(result?.words.map((w) => [w.text, w.index, w.line])).toEqual([['kept', 0, 0]])
expect(result?.lines).toHaveLength(1)
})
})
describe('사각형 선택', () => {
it('사각형선택_중심이든단어만_살짝스친옆줄은고르지않는다', () => {
const result = sample()
// 첫 줄 전체를 덮고 둘째 줄(y 50~70) 윗부분 4px 만 스친다.
expect(wordsInRect(result, { x: 0, y: 0, width: 200, height: 54 })).toEqual([0, 1, 2])
})
it('사각형선택_절반넘게걸친단어만_절반이안되면고르지않는다', () => {
const result = sample()
// 첫 단어(x 10~50)의 왼쪽 45% 만 덮으면 고르지 않는다. 높이 20 중 12 만 덮어도 폭을 다 덮으면(60%) 고른다.
expect(wordsInRect(result, { x: 0, y: 0, width: 28, height: 40 })).toEqual([])
expect(wordsInRect(result, { x: 0, y: 12, width: 60, height: 12 })).toEqual([0])
})
it('rectFromPoints_거꾸로끌어도_양수크기사각형이된다', () => {
expect(rectFromPoints({ x: 100, y: 80 }, { x: 20, y: 30 })).toEqual({ x: 20, y: 30, width: 80, height: 50 })
})
it('clampRect_그림밖으로나간영역_안쪽으로자르고완전히밖이면null', () => {
expect(clampRect({ x: -10, y: -5, width: 50.4, height: 30 }, { width: 100, height: 20 })).toEqual({
x: 0,
y: 0,
width: 41,
height: 20
})
expect(clampRect({ x: 200, y: 0, width: 50, height: 10 }, { width: 100, height: 100 })).toBeNull()
expect(clampRect({ x: 10, y: 10, width: 0, height: 0 }, { width: 100, height: 100 })).toBeNull()
})
})
describe('글 흐름 선택', () => {
it('wordAtPoint_단어위와빈곳_단어번호또는null', () => {
const result = sample()
expect(wordAtPoint(result, { x: 70, y: 20 })).toBe(1)
expect(wordAtPoint(result, { x: 300, y: 300 })).toBeNull()
})
it('nearestWordIndex_줄사이여백과줄오른쪽바깥_가까운줄의가까운단어를고른다', () => {
const result = sample()
// 둘째 줄(y 50~70) 오른쪽 바깥 → 둘째 줄의 마지막 단어
expect(nearestWordIndex(result, { x: 400, y: 60 })).toBe(4)
// 셋째 줄 아래 여백 → 셋째 줄에서 가로로 가장 가까운 단어
expect(nearestWordIndex(result, { x: 65, y: 400 })).toBe(6)
})
it('nearestWordIndex_단어가없는결과_null', () => {
const empty = parseOcrEngineOutput({ lang: 'ko', lines: [] })
expect(empty && nearestWordIndex(empty, { x: 0, y: 0 })).toBeNull()
})
it('flowSelection_뒤에서앞으로끌어도_사이단어를전부고른다', () => {
expect(flowSelection(6, 2)).toEqual([2, 3, 4, 5, 6])
expect(flowSelection(3, 3)).toEqual([3])
})
it('lineSelection과allWords_줄전체와전체단어', () => {
const result = sample()
expect(lineSelection(result, 4)).toEqual([3, 4])
expect(lineSelection(result, 99)).toEqual([])
expect(allWords(result)).toHaveLength(8)
})
})
describe('선택 → 텍스트', () => {
it('selectionText_여러줄선택_줄바꿈을유지하고단어는공백으로잇는다', () => {
const result = sample()
expect(selectionText(result, [1, 2, 3, 4, 5])).toBe('OCR 기능\n둘째 줄\nThird')
})
it('selectionText_한줄옵션_줄바꿈없이잇는다', () => {
const result = sample()
expect(selectionText(result, [2, 3, 4], { singleLine: true })).toBe('기능 둘째 줄')
})
it('selectionText_순서가뒤섞이고겹치고범위밖인번호_정리해서읽는순서로낸다', () => {
const result = sample()
expect(selectionText(result, [4, 0, 0, 99, -1, 3])).toBe('화면\n둘째 줄')
})
it('selectionText_일본어중국어처럼글자마다단어인줄_공백없이잇는다', () => {
const result = parseOcrEngineOutput({
lang: 'ja',
lines: [line(0, ['日', '本', '語', 'OCR', 'テ', 'ス', 'ト']), line(40, ['次', 'の', '行'])]
})
if (!result) throw new Error('no result')
expect(selectionText(result, allWords(result))).toBe('日本語 OCR テスト\n次の行')
expect(selectionText(result, allWords(result), { singleLine: true })).toBe('日本語 OCR テスト次の行')
})
it('selectionText_아무것도안고름_빈문자열', () => {
expect(selectionText(sample(), [])).toBe('')
})
})
describe('강조 사각형과 경계', () => {
it('selectionHighlightRects_같은줄에서이어진단어_하나로잇고끊긴곳은나눈다', () => {
const result = sample()
const rects = selectionHighlightRects(result, [0, 1, 3, 5, 7])
expect(rects).toEqual([
{ x: 10, y: 10, width: 90, height: 20 },
{ x: 10, y: 50, width: 40, height: 20 },
{ x: 10, y: 90, width: 40, height: 20 },
{ x: 110, y: 90, width: 40, height: 20 }
])
})
it('selectionBounds_고른단어를모두감싼다_없으면null', () => {
const result = sample()
expect(selectionBounds(result, [1, 4])).toEqual({ x: 60, y: 10, width: 40, height: 60 })
expect(selectionBounds(result, [])).toBeNull()
})
it('wordsRelativeTo_잘라낸영역기준좌표로옮긴다', () => {
const result = sample()
const moved = wordsRelativeTo(result, { x: 50, y: 40, width: 200, height: 40 })
expect(moved.map((w) => [w.text, w.x, w.y])).toEqual([['줄', 10, 10]])
})
})
describe('chooseOcrScale', () => {
it('인식배율_100퍼센트화면_2배로키운다', () => {
expect(chooseOcrScale(1920, 1080, 1, 10000)).toBe(2)
})
it('인식배율_고배율화면_이미큰글자는덜키운다', () => {
expect(chooseOcrScale(2880, 1800, 1.5, 10000)).toBe(1.33)
expect(chooseOcrScale(3840, 2160, 2, 10000)).toBe(1)
})
it('인식배율_엔진최대변길이를넘지않는다', () => {
const scale = chooseOcrScale(7680, 2160, 1, 10000)
expect(scale).toBe(1.3)
expect(7680 * scale).toBeLessThanOrEqual(10000)
})
it('인식배율_배율값이이상하면_1배율화면으로본다', () => {
expect(chooseOcrScale(1000, 1000, Number.NaN, 10000)).toBe(2)
expect(chooseOcrScale(0, 0, 1, 10000)).toBe(1)
})
})
describe('detectLinks', () => {
it('링크찾기_주소와메일_열수있는URL로돌려준다', () => {
expect(detectLinks('보기: https://example.com/path?q=1, 그리고 www.d3ro.io. 문의 help@example.com')).toEqual([
'mailto:help@example.com',
'https://example.com/path?q=1',
'https://www.d3ro.io'
])
})
it('링크찾기_주소가없는글_빈목록', () => {
expect(detectLinks('그냥 문장입니다 3.14 e.g.')).toEqual([])
})
it('링크찾기_같은주소가여러번_한번만', () => {
expect(detectLinks('https://a.io https://a.io')).toEqual(['https://a.io'])
})
})
describe('pickTranslationTarget', () => {
it('번역대상_외국어글_사용자의앱언어로옮긴다', () => {
expect(pickTranslationTarget('The quick brown fox', 'ko', 'English')).toBe('Korean')
expect(pickTranslationTarget('안녕하세요 반갑습니다', 'en', 'Japanese')).toBe('English')
})
it('번역대상_이미사용자언어인글_설정의번역대상언어로옮긴다', () => {
expect(pickTranslationTarget('안녕하세요 반갑습니다', 'ko', 'English')).toBe('English')
expect(pickTranslationTarget('Hello there, friend', 'en', 'Japanese')).toBe('Japanese')
expect(pickTranslationTarget('こんにちは、世界', 'ja', 'English')).toBe('English')
})
it('번역대상_모르는앱언어_설정값을그대로쓴다', () => {
expect(pickTranslationTarget('hello', 'xx', 'German')).toBe('German')
})
})
describe('buildSearchablePdfHtml', () => {
const html = buildSearchablePdfHtml({
imageDataUrl: 'data:image/png;base64,AAAA',
width: 800,
height: 600,
language: 'ko',
words: [
{ text: '화면 <b>&"', x: 10, y: 20, width: 100, height: 20 },
{ text: ' ', x: 0, y: 0, width: 10, height: 10 },
{ text: 'zero', x: 0, y: 0, width: 0, height: 10 }
]
})
it('PDF문서_쪽크기가그림크기와같다', () => {
expect(html).toContain('@page{size:800px 600px;margin:0}')
expect(html).toContain('viewBox="0 0 800 600"')
})
it('PDF문서_글자층이그림아래에깔린다', () => {
expect(html.indexOf('<svg')).toBeLessThan(html.indexOf('<img'))
expect(html).toContain('.page svg{z-index:0}.page img{z-index:1}')
})
it('PDF문서_단어상자폭에맞춘글자를넣고특수문자는이스케이프한다', () => {
expect(html).toContain('textLength="100.0"')
expect(html).toContain('화면 &lt;b&gt;&amp;&quot;')
expect(html).not.toContain('<b>')
})
it('PDF문서_빈글자와크기없는단어_글자층에넣지않는다', () => {
expect(html.match(/<text /gu)).toHaveLength(1)
})
})

View file

@ -101,6 +101,16 @@ export enum ErrorCode {
// === Phase 10: Screen Context (750-759) ===
ContextCaptureFailed = 750,
ContextSelectedTextFailed = 751,
/** 화면 OCR: 화면 캡처 실패 */
ScreenOcrCaptureFailed = 755,
/** 화면 OCR: 글자 인식 실패 (엔진 실행·출력 해석) */
ScreenOcrRecognitionFailed = 756,
/** 화면 OCR: 이 플랫폼·환경에서 쓸 수 있는 인식 엔진이 없다 */
ScreenOcrUnavailable = 757,
/** 화면 OCR: PDF·그림 내보내기 실패 */
ScreenOcrExportFailed = 758,
/** 화면 OCR: 끝난 캡처에 대한 요청이거나 요청 값이 잘못됐다 */
ScreenOcrInvalidRequest = 759,
// === Phase 10: LLM Chain (760-769) ===
ChainNotFound = 760,

View file

@ -457,6 +457,22 @@ export const IPC_CHANNELS = {
KEY_EVENT: 'command:keyEvent',
},
// ── Popup Internal Channels (화면 OCR 오버레이) ──
POPUP_SCREEN_OCR: {
/** main → overlay: 새 캡처 (그림 · 크기 · 문구) */
SESSION: 'screenOcr:session',
/** main → overlay: 인식 결과 또는 인식 실패 */
RECOGNIZED: 'screenOcr:recognized',
/** main → overlay: 요청(REQUEST)에 대한 응답 */
RESPONSE: 'screenOcr:response',
/** overlay → main: 동작 요청 (복사 · PDF · 그림 · 번역 · 요약 · 읽기 · 링크 · 언어 변경) */
REQUEST: 'screenOcr:request',
/** overlay → main: 그림을 다 그렸다 — 이제 창을 보여도 깜빡이지 않는다 */
READY: 'screenOcr:ready',
/** overlay → main: 닫기 */
DISMISS: 'screenOcr:dismiss',
},
// ── Popup Internal Channels (Caption) ──
POPUP_CAPTION: {
HIDE: 'caption:hide',

View file

@ -679,6 +679,7 @@ export type KeyBindingActionId =
| 'caption'
| 'history-popup'
| 'command-popup'
| 'screen-ocr'
| 'suggestion-accept'
| 'suggestion-accept-word'
| 'suggestion-next'
@ -780,6 +781,16 @@ export const KEYBINDING_ACTIONS: readonly KeyBindingActionSpec[] = Object.freeze
doublePress: false,
defaultBindings: [kb(0x43 /* C */, { ctrl: true, shift: true })]
},
{
id: 'screen-ocr',
group: 'window',
labelKey: 'keybinding.action.screenOcr',
descriptionKey: 'keybinding.action.screenOcr.desc',
holdMode: false,
doublePress: false,
// 화면을 캡처해 글자를 고르는 오버레이를 연다. Ctrl+Shift+O 는 브라우저 북마크 관리자와 겹쳐 피했다.
defaultBindings: [kb(0x4f /* O */, { ctrl: true, alt: true })]
},
{
id: 'suggestion-accept',
group: 'input',

View file

@ -0,0 +1,516 @@
// 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<string, unknown> {
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<Record<string, string>> = {
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, '&amp;')
.replace(/</gu, '&lt;')
.replace(/>/gu, '&gt;')
.replace(/"/gu, '&quot;')
}
export interface SearchablePdfInput {
/** 그림의 data URL (image/png) */
imageDataUrl: string
/** 그림 크기 (물리 픽셀) — 쪽 크기가 된다 */
width: number
height: number
/** 그림 좌표계의 단어 (잘라낸 영역이면 그 영역 기준으로 옮긴 좌표) */
words: ReadonlyArray<Pick<OcrWord, 'text' | 'x' | 'y' | 'width' | 'height'>>
/** 문서 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 (
`<text x="${word.x.toFixed(1)}" y="${baseline.toFixed(1)}" font-size="${fontSize.toFixed(1)}" ` +
`textLength="${word.width.toFixed(1)}" lengthAdjust="spacingAndGlyphs">${escapeHtml(word.text)}</text>`
)
})
.join('')
return (
`<!DOCTYPE html><html lang="${escapeHtml(input.language || 'en')}"><head><meta charset="utf-8">` +
`<style>@page{size:${width}px ${height}px;margin:0}` +
`html,body{margin:0;padding:0;background:white}` +
`.page{position:relative;width:${width}px;height:${height}px;overflow:hidden}` +
`.page svg,.page img{position:absolute;left:0;top:0;width:${width}px;height:${height}px;display:block}` +
`.page svg{z-index:0}.page img{z-index:1}` +
`text{font-family:'Malgun Gothic','Segoe UI','Noto Sans CJK KR',sans-serif;fill:black}</style></head>` +
`<body><div class="page">` +
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}">${texts}</svg>` +
`<img alt="" src="${escapeHtml(input.imageDataUrl)}">` +
`</div></body></html>`
)
}
/** 사각형 안에 중심이 든 단어를 그 사각형 기준 좌표로 옮긴다 (영역만 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 }
})
}

View file

@ -443,6 +443,8 @@ export interface AppConfig {
handsFreeEnabled: boolean
/** 스크린 컨텍스트 캡처 활성화 (Phase 10.2) */
screenContextEnabled: boolean
/** 화면 OCR 인식 언어 태그 (예: 'ko', 'en-US'). 'auto' 면 Windows 사용자 언어를 따른다. */
screenOcrLanguage: string
/** Phase 15.5: HuggingFace 토큰 (화자 구분용) */
hfToken: string
/** Phase 15.5: 화자 구분 활성화 */