@heripo/pdf-parser 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ko.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - [사전 요구사항](#사전-요구사항)
21
21
  - [설치](#설치)
22
22
  - [사용법](#사용법)
23
+ - [OCR 전략 시스템](#ocr-전략-시스템)
23
24
  - [왜 macOS 전용인가?](#왜-macos-전용인가)
24
25
  - [시스템 의존성 상세](#시스템-의존성-상세)
25
26
  - [API 문서](#api-문서)
@@ -28,7 +29,8 @@
28
29
 
29
30
  ## 주요 기능
30
31
 
31
- - **고품질 OCR**: Docling SDK를 활용한 문서 인식
32
+ - **고품질 OCR**: Docling SDK를 활용한 문서 인식 (ocrmac / Apple Vision Framework)
33
+ - **혼합 문자 자동 감지 및 보정**: 한글·한자 혼용 페이지를 자동 감지하여 VLM으로 보정
32
34
  - **Apple Silicon 최적화**: M1/M2/M3/M4/M5 칩에서 GPU 가속 지원
33
35
  - **자동 환경 설정**: Python 가상환경 및 docling-serve 자동 설치
34
36
  - **이미지 추출**: PDF 내 이미지 자동 추출 및 저장
@@ -68,13 +70,21 @@ brew install python@3.11
68
70
  python3.11 --version
69
71
  ```
70
72
 
71
- #### 4. jq (JSON 처리 도구)
73
+ #### 4. poppler (PDF 텍스트 추출)
74
+
75
+ OCR 전략 시스템의 텍스트 레이어 사전 검사(`pdftotext`)에 필요합니다.
76
+
77
+ ```bash
78
+ brew install poppler
79
+ ```
80
+
81
+ #### 5. jq (JSON 처리 도구)
72
82
 
73
83
  ```bash
74
84
  brew install jq
75
85
  ```
76
86
 
77
- #### 5. lsof (포트 관리)
87
+ #### 6. lsof (포트 관리)
78
88
 
79
89
  macOS에 기본적으로 설치되어 있습니다. 확인:
80
90
 
@@ -190,6 +200,51 @@ const outputPath = await pdfParser.parse(
190
200
  await pdfParser.shutdown();
191
201
  ```
192
202
 
203
+ ## OCR 전략 시스템
204
+
205
+ ### 왜 이 전략인가?
206
+
207
+ **ocrmac(Apple Vision Framework)은 매우 우수한 OCR 엔진입니다** — 무료이고, GPU 가속을 지원하며, 고품질 결과를 제공합니다. 수천~수백만 권의 고고학 보고서를 처리할 때 이만한 솔루션이 없습니다.
208
+
209
+ **그러나 ocrmac은 혼합 문자 체계를 처리하지 못합니다.** 한글·한자 혼용 문서(그리고 잠재적으로 다른 혼합 문자 조합)에서 보조 문자가 깨진 텍스트로 변환됩니다. 전체 파이프라인을 비용이 높은 VLM으로 전환하는 대신, **문제가 있는 페이지만 타겟팅**하여 VLM으로 보정합니다.
210
+
211
+ ### 2단계 감지 (`OcrStrategySampler`)
212
+
213
+ 1. **텍스트 레이어 사전 검사** (비용 없음): `pdftotext`로 문서의 텍스트 레이어를 추출하여 한글과 CJK 문자가 모두 존재하는지 확인합니다. 둘 다 존재하면 즉시 혼합 문자 문서로 판별합니다.
214
+ 2. **VLM 샘플링** (필요 시에만): 최대 15페이지를 샘플링(앞뒤 10%는 표지·부록으로 제외)하여 Vision LLM으로 분석합니다. 최초 한글·한자 혼용 감지 시 즉시 종료하여 API 비용을 최소화합니다.
215
+
216
+ ### 페이지별 보정 (`VlmTextCorrector`)
217
+
218
+ 혼합 문자 페이지가 감지되면, 해당 페이지만 VLM에 전송하여 보정합니다:
219
+
220
+ - 각 페이지의 OCR 텍스트 요소와 표 셀을 추출
221
+ - `pdftotext` 참조 텍스트를 품질 기준으로 활용
222
+ - VLM이 치환 기반 보정(find → replace)을 반환
223
+ - 실패한 페이지는 원본 OCR 텍스트를 유지하며 건너뜀
224
+
225
+ ### 전략 옵션
226
+
227
+ ```typescript
228
+ const outputPath = await pdfParser.parse(
229
+ 'input.pdf',
230
+ 'output',
231
+ (result) => console.log(result),
232
+ {
233
+ // OCR 전략 샘플링 활성화 (Vision LLM 모델 제공)
234
+ strategySamplerModel: openai('gpt-5.1'),
235
+
236
+ // VLM 텍스트 보정 모델 (혼합 문자 감지 시 필요)
237
+ vlmProcessorModel: openai('gpt-5.1'),
238
+
239
+ // VLM 페이지 처리 동시성 (기본값: 1)
240
+ vlmConcurrency: 3,
241
+
242
+ // 샘플링을 건너뛰고 특정 OCR 방식 강제
243
+ forcedMethod: 'ocrmac', // 또는 'vlm'
244
+ },
245
+ );
246
+ ```
247
+
193
248
  ## 왜 macOS 전용인가?
194
249
 
195
250
  `@heripo/pdf-parser`는 **의도적으로 macOS에 강하게 의존**합니다. 이 결정의 핵심 이유는 **Docling SDK의 로컬 OCR 성능**입니다.
@@ -226,11 +281,12 @@ await pdfParser.shutdown();
226
281
 
227
282
  `@heripo/pdf-parser`는 다음 시스템 레벨 의존성이 필요합니다:
228
283
 
229
- | 의존성 | 필수 버전 | 설치 방법 | 용도 |
230
- | ------ | ---------- | -------------------------- | -------------------------- |
231
- | Python | 3.9 - 3.12 | `brew install python@3.11` | Docling SDK 실행 환경 |
232
- | jq | Any | `brew install jq` | JSON 처리 (변환 결과 파싱) |
233
- | lsof | Any | macOS 기본 설치됨 | docling-serve 포트 관리 |
284
+ | 의존성 | 필수 버전 | 설치 방법 | 용도 |
285
+ | ------- | ---------- | -------------------------- | ----------------------------------------- |
286
+ | Python | 3.9 - 3.12 | `brew install python@3.11` | Docling SDK 실행 환경 |
287
+ | poppler | Any | `brew install poppler` | OCR 전략용 텍스트 레이어 추출 (pdftotext) |
288
+ | jq | Any | `brew install jq` | JSON 처리 (변환 결과 파싱) |
289
+ | lsof | Any | macOS 기본 설치됨 | docling-serve 포트 관리 |
234
290
 
235
291
  > ⚠️ **Python 3.13+는 지원하지 않습니다.** Docling SDK의 일부 의존성이 Python 3.13과 호환되지 않습니다.
236
292
 
@@ -314,6 +370,18 @@ interface ConversionOptions {
314
370
  }
315
371
  ```
316
372
 
373
+ ### PDFConvertOptions (확장)
374
+
375
+ ```typescript
376
+ interface PDFConvertOptions extends ConversionOptions {
377
+ strategySamplerModel?: LanguageModel; // OCR 전략 샘플링용 Vision LLM
378
+ vlmProcessorModel?: LanguageModel; // 텍스트 보정용 Vision LLM
379
+ vlmConcurrency?: number; // 병렬 페이지 처리 (기본값: 1)
380
+ skipSampling?: boolean; // 전략 샘플링 건너뛰기
381
+ forcedMethod?: 'ocrmac' | 'vlm'; // 특정 OCR 방식 강제
382
+ }
383
+ ```
384
+
317
385
  ## 문제 해결
318
386
 
319
387
  ### Python 버전 오류
package/README.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - [Prerequisites](#prerequisites)
21
21
  - [Installation](#installation)
22
22
  - [Usage](#usage)
23
+ - [OCR Strategy System](#ocr-strategy-system)
23
24
  - [Why macOS Only?](#why-macos-only)
24
25
  - [System Dependencies Details](#system-dependencies-details)
25
26
  - [API Documentation](#api-documentation)
@@ -28,7 +29,8 @@
28
29
 
29
30
  ## Key Features
30
31
 
31
- - **High-Quality OCR**: document recognition using Docling SDK
32
+ - **High-Quality OCR**: Document recognition using Docling SDK (ocrmac / Apple Vision Framework)
33
+ - **Mixed Script Auto-Detection & Correction**: Automatically detects Korean-Hanja mixed pages and corrects them via VLM
32
34
  - **Apple Silicon Optimized**: GPU acceleration on M1/M2/M3/M4/M5 chips
33
35
  - **Automatic Environment Setup**: Automatic Python virtual environment and docling-serve installation
34
36
  - **Image Extraction**: Automatic extraction and saving of images from PDFs
@@ -68,13 +70,21 @@ brew install python@3.11
68
70
  python3.11 --version
69
71
  ```
70
72
 
71
- #### 4. jq (JSON processing tool)
73
+ #### 4. poppler (PDF text extraction)
74
+
75
+ Required for the OCR strategy system's text layer pre-check (`pdftotext`).
76
+
77
+ ```bash
78
+ brew install poppler
79
+ ```
80
+
81
+ #### 5. jq (JSON processing tool)
72
82
 
73
83
  ```bash
74
84
  brew install jq
75
85
  ```
76
86
 
77
- #### 5. lsof (port management)
87
+ #### 6. lsof (port management)
78
88
 
79
89
  Installed by default on macOS. Verify:
80
90
 
@@ -190,6 +200,51 @@ Clean up resources after work is complete:
190
200
  await pdfParser.shutdown();
191
201
  ```
192
202
 
203
+ ## OCR Strategy System
204
+
205
+ ### Why This Strategy?
206
+
207
+ **ocrmac (Apple Vision Framework) is an excellent OCR engine** — it's free, GPU-accelerated, and delivers high-quality results. For processing thousands to millions of archaeological reports, there's no better solution.
208
+
209
+ **However, ocrmac cannot handle mixed character systems.** Documents containing Korean-Hanja combinations (and potentially other mixed scripts) produce garbled text for the non-primary script. Rather than switching the entire pipeline to a costly VLM, the system **targets only the affected pages** for VLM correction, minimizing cost and processing time.
210
+
211
+ ### Two-Stage Detection (`OcrStrategySampler`)
212
+
213
+ 1. **Text Layer Pre-Check** (zero cost): Extracts the document's text layer using `pdftotext` and checks for both Hangul and CJK characters. If both are present, the document is immediately flagged as mixed-script.
214
+ 2. **VLM Sampling** (only when needed): Samples up to 15 pages (trimming 10% from front/back to skip covers and appendices) and analyzes them with a Vision LLM. Uses early exit on first Korean-Hanja mix detection to minimize API costs.
215
+
216
+ ### Per-Page Correction (`VlmTextCorrector`)
217
+
218
+ When mixed-script pages are detected, only those pages are sent to the VLM for correction:
219
+
220
+ - Extracts OCR text elements and table cells from each page
221
+ - Uses `pdftotext` reference text as a quality anchor
222
+ - VLM returns substitution-based corrections (find → replace)
223
+ - Failed page corrections are gracefully skipped, preserving original OCR text
224
+
225
+ ### Strategy Options
226
+
227
+ ```typescript
228
+ const outputPath = await pdfParser.parse(
229
+ 'input.pdf',
230
+ 'output',
231
+ (result) => console.log(result),
232
+ {
233
+ // Enable OCR strategy sampling (provide a Vision LLM model)
234
+ strategySamplerModel: openai('gpt-5.1'),
235
+
236
+ // VLM model for text correction (required when mixed-script is detected)
237
+ vlmProcessorModel: openai('gpt-5.1'),
238
+
239
+ // Concurrency for VLM page processing (default: 1)
240
+ vlmConcurrency: 3,
241
+
242
+ // Skip sampling and force a specific OCR method
243
+ forcedMethod: 'ocrmac', // or 'vlm'
244
+ },
245
+ );
246
+ ```
247
+
193
248
  ## Why macOS Only?
194
249
 
195
250
  `@heripo/pdf-parser` **intentionally relies heavily on macOS**. The key reason for this decision is **Docling SDK's local OCR performance**.
@@ -226,11 +281,12 @@ Archaeological excavation report PDFs have the following characteristics:
226
281
 
227
282
  `@heripo/pdf-parser` requires the following system-level dependencies:
228
283
 
229
- | Dependency | Required Version | Installation | Purpose |
230
- | ---------- | ---------------- | -------------------------- | ------------------------------------------- |
231
- | Python | 3.9 - 3.12 | `brew install python@3.11` | Docling SDK runtime |
232
- | jq | Any | `brew install jq` | JSON processing (conversion result parsing) |
233
- | lsof | Any | Included with macOS | docling-serve port management |
284
+ | Dependency | Required Version | Installation | Purpose |
285
+ | ---------- | ---------------- | -------------------------- | -------------------------------------------------- |
286
+ | Python | 3.9 - 3.12 | `brew install python@3.11` | Docling SDK runtime |
287
+ | poppler | Any | `brew install poppler` | Text layer extraction for OCR strategy (pdftotext) |
288
+ | jq | Any | `brew install jq` | JSON processing (conversion result parsing) |
289
+ | lsof | Any | Included with macOS | docling-serve port management |
234
290
 
235
291
  > ⚠️ **Python 3.13+ is not supported.** Some Docling SDK dependencies are not compatible with Python 3.13.
236
292
 
@@ -314,6 +370,18 @@ interface ConversionOptions {
314
370
  }
315
371
  ```
316
372
 
373
+ ### PDFConvertOptions (Extended)
374
+
375
+ ```typescript
376
+ interface PDFConvertOptions extends ConversionOptions {
377
+ strategySamplerModel?: LanguageModel; // Vision LLM for OCR strategy sampling
378
+ vlmProcessorModel?: LanguageModel; // Vision LLM for text correction
379
+ vlmConcurrency?: number; // Parallel page processing (default: 1)
380
+ skipSampling?: boolean; // Skip strategy sampling
381
+ forcedMethod?: 'ocrmac' | 'vlm'; // Force specific OCR method
382
+ }
383
+ ```
384
+
317
385
  ## Troubleshooting
318
386
 
319
387
  ### Python Version Error