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-12 23:46:39 +08:00
|
|
|
// Convert any input format (HEIC, AVIF, WebP, TIFF, etc.) to PNG
|
|
|
|
|
// so Tesseract and PaddleOCR can read it reliably.
|
|
|
|
|
const pngBuffer = await sharp(inputBuffer).png().toBuffer();
|
|
|
|
|
await writeFile(inputPath, pngBuffer);
|
|
|
|
|
|
2026-03-25 09:27:12 +08:00
|
|
|
const { stdout } = await runPythonWithProgress("ocr.py", [inputPath, JSON.stringify(options)], {
|
|
|
|
|
onProgress,
|
2026-04-12 18:34:47 +08:00
|
|
|
timeout: 600_000, // 10 min timeout for VLM on CPU
|
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
|
|
|
};
|
|
|
|
|
}
|