/** * OCR 文字识别模块 * 直接调用系统 tesseract 命令行,无需 npm 依赖 * Docker 镜像已预装 tesseract-ocr + chi_sim + eng * * 支持两种模式(settings.json 里 ocr.provider 切换): * local — 本机 tesseract,零配置 * online — 线上 OCR(OpenAI 兼容 /v1/chat/completions 视觉模型) * 线上失败自动回退本地,不影响扫描主流程。 */ const { execFile } = require('child_process'); const { promisify } = require('util'); const path = require('path'); const fs = require('fs'); const logger = require('../src/utils/logger'); const { getSettings } = require('./settings'); const execFileAsync = promisify(execFile); // Tesseract 路径 const TESSERACT_BIN = process.env.TESSERACT_BIN || 'tesseract'; /** 归一化线上接口地址 -> 完整 chat/completions URL */ function normalizeOnlineUrl(url) { let u = String(url).trim().replace(/\/+$/, ''); if (/\/chat\/completions$/.test(u)) return u; if (/\/v1$/.test(u)) return u + '/chat/completions'; return u + '/v1/chat/completions'; } /** * 本地 tesseract 识别 * @param {string} imagePath - 图片绝对路径 * @returns {Promise} 识别出的文字(清理后的纯文本) */ async function ocrLocal(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 ''; } } /** * 线上 OCR(OpenAI 兼容视觉模型) * online: { url, apiKey, model } */ async function ocrOnline(imagePath, online) { const url = normalizeOnlineUrl(online.url); const ext = (path.extname(imagePath) || '.png').toLowerCase(); const mime = ['.jpg', '.jpeg'].includes(ext) ? 'jpeg' : ext === '.webp' ? 'webp' : ext === '.gif' ? 'gif' : 'png'; const b64 = fs.readFileSync(imagePath).toString('base64'); const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 60000); try { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${online.apiKey}` }, body: JSON.stringify({ model: online.model || 'gpt-4o-mini', max_tokens: 2000, messages: [{ role: 'user', content: [ { type: 'text', text: '请提取图片中的所有文字,只输出识别到的文字内容,不要任何解释。' }, { type: 'image_url', image_url: { url: `data:image/${mime};base64,${b64}` } } ] }] }), signal: ctrl.signal }); const data = await res.json(); if (!res.ok || data.error) { throw new Error((data.error && data.error.message) || `HTTP ${res.status}`); } const text = data.choices && data.choices[0] && data.choices[0].message ? data.choices[0].message.content : ''; return String(text).trim(); } finally { clearTimeout(timer); } } /** * 按显式配置跑 OCR(设置页「测试」按钮用) * cfg: { provider: 'local'|'online', online: { url, apiKey, model } } */ async function ocrWithConfig(imagePath, cfg) { if (cfg && cfg.provider === 'online' && cfg.online && cfg.online.url && cfg.online.apiKey) { return ocrOnline(imagePath, cfg.online); } return ocrLocal(imagePath); } /** * 扫描器入口:读 settings.json 决定走哪条路 * @param {string} imagePath - 图片绝对路径 * @returns {Promise} 识别出的文字 */ async function extractText(imagePath) { try { const s = getSettings(); if (s.ocr && s.ocr.provider === 'online' && s.ocr.online && s.ocr.online.url && s.ocr.online.apiKey) { try { return await ocrOnline(imagePath, s.ocr.online); } catch (e) { logger.warn(`[OCR] 线上识别失败,回退本地: ${e.message}`); } } return await ocrLocal(imagePath); } catch (error) { return ''; } } module.exports = { extractText, ocrWithConfig, ocrLocal, ocrOnline, normalizeOnlineUrl };