2026-03-22 04:31:49 +08:00
|
|
|
import { writeFile } from "node:fs/promises";
|
|
|
|
|
import { join } from "node:path";
|
2026-04-12 23:46:39 +08:00
|
|
|
import sharp from "sharp";
|
2026-04-19 12:13:26 +08:00
|
|
|
import { type ProgressCallback, parseStdoutJson, runPythonWithProgress } from "./bridge.js";
|
2026-03-22 04:31:49 +08:00
|
|
|
|
2026-04-12 18:34:47 +08:00
|
|
|
export type OcrQuality = "fast" | "balanced" | "best";
|
|
|
|
|
|
2026-03-22 04:31:49 +08:00
|
|
|
export interface OcrOptions {
|
2026-04-12 18:34:47 +08:00
|
|
|
quality?: OcrQuality;
|
2026-03-22 04:31:49 +08:00
|
|
|
language?: string;
|
2026-04-12 18:34:47 +08:00
|
|
|
enhance?: boolean;
|
|
|
|
|
/** @deprecated Use quality instead. Kept for backward compat. */
|
|
|
|
|
engine?: "tesseract" | "paddleocr";
|
2026-03-22 04:31:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface OcrResult {
|
|
|
|
|
text: string;
|
2026-04-17 14:15:27 +08:00
|
|
|
engine?: string;
|
2026-03-22 04:31:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function extractText(
|
|
|
|
|
inputBuffer: Buffer,
|
|
|
|
|
outputDir: string,
|
|
|
|
|
options: OcrOptions = {},
|
2026-03-23 01:39:52 +08:00
|
|
|
onProgress?: ProgressCallback,
|
2026-03-22 04:31:49 +08:00
|
|
|
): Promise<OcrResult> {
|
|
|
|
|
const inputPath = join(outputDir, "input_ocr.png");
|
|
|
|
|
|
2026-04-25 07:23:58 +08:00
|
|
|
// Convert to PNG and cap at 2048px to prevent PaddleOCR OOM on large images.
|
|
|
|
|
const MAX_OCR_DIM = 2048;
|
|
|
|
|
const pngBuffer = await sharp(inputBuffer)
|
|
|
|
|
.resize({ width: MAX_OCR_DIM, height: MAX_OCR_DIM, fit: "inside", withoutEnlargement: true })
|
|
|
|
|
.png()
|
|
|
|
|
.toBuffer();
|
2026-04-12 23:46:39 +08:00
|
|
|
await writeFile(inputPath, pngBuffer);
|
|
|
|
|
|
2026-04-25 07:23:58 +08:00
|
|
|
const meta = await sharp(pngBuffer).metadata();
|
2026-04-20 21:46:07 +08:00
|
|
|
const megapixels = ((meta.width ?? 0) * (meta.height ?? 0)) / 1_000_000;
|
|
|
|
|
const timeout = Math.max(600_000, megapixels * 30 * 1000);
|
|
|
|
|
|
2026-03-25 09:27:12 +08:00
|
|
|
const { stdout } = await runPythonWithProgress("ocr.py", [inputPath, JSON.stringify(options)], {
|
|
|
|
|
onProgress,
|
2026-04-20 21:46:07 +08:00
|
|
|
timeout,
|
2026-03-25 09:27:12 +08:00
|
|
|
});
|
2026-03-22 04:31:49 +08:00
|
|
|
|
2026-04-19 12:13:26 +08:00
|
|
|
const result = parseStdoutJson(stdout);
|
2026-03-22 04:31:49 +08:00
|
|
|
if (!result.success) {
|
|
|
|
|
throw new Error(result.error || "OCR failed");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
text: result.text,
|
2026-04-17 14:15:27 +08:00
|
|
|
engine: result.engine,
|
2026-03-22 04:31:49 +08:00
|
|
|
};
|
|
|
|
|
}
|