/** * OCR 文字识别模块 * 直接调用系统 tesseract 命令行,无需 npm 依赖 * Docker 镜像已预装 tesseract-ocr + chi_sim + eng */ const { execFile } = require('child_process'); const { promisify } = require('util'); const path = require('path'); const fs = require('fs'); const logger = require('../src/utils/logger'); const execFileAsync = promisify(execFile); // Tesseract 路径 const TESSERACT_BIN = process.env.TESSERACT_BIN || 'tesseract'; /** * 对单张图片进行 OCR 文字识别 * @param {string} imagePath - 图片绝对路径 * @returns {Promise} 识别出的文字(清理后的纯文本) */ async function extractText(imagePath) { try { // 检查文件是否存在 if (!fs.existsSync(imagePath)) return ''; // 使用临时文件输出(tesseract 不支持直接输出到 stdout 处理图片) const tmpFile = `/tmp/ocr_${Date.now()}_${Math.random().toString(36).slice(2)}.txt`; try { await execFileAsync(TESSERACT_BIN, [ imagePath, tmpFile.replace('.txt', ''), // tesseract 自动加 .txt 后缀 '-l', 'chi_sim+eng', // 中英文 '--psm', '3', // 自动页面分割 '--oem', '3' // 默认 OCR 引擎 ], { timeout: 15000 }); // 15秒超时 // 读取结果 const resultPath = tmpFile.replace('.txt', '.txt'); if (fs.existsSync(resultPath)) { const text = fs.readFileSync(resultPath, 'utf-8'); fs.unlinkSync(resultPath); return text.replace(/\s+/g, ' ').trim(); } } catch (e) { // OCR 失败静默处理 } finally { // 清理临时文件 try { fs.unlinkSync(tmpFile); } catch(e) {} try { fs.unlinkSync(tmpFile.replace('.txt', '.txt')); } catch(e) {} } return ''; } catch (error) { return ''; } } module.exports = { extractText };