Files
flypic/backend/utils/ocr.js
T
jinghui 50c53a5e21 feat: 设置页(本地/线上OCR可配+一键测试) + 右上角开源地址/版本/通知 + CardAuth 授权接入(v1.2.0)
- 后端: utils/settings.js(settings.json持久化)、utils/ocr.js(本地tesseract+线上视觉模型,失败回退本地)、
  routes/settings.js(GET/PUT/test-ocr,密钥掩码)、utils/hub.js(开机查+6h版本比对+30min心跳+60s公告,失败开放,
  机器码仅存服务端)、routes/hub.js(免登录 /api/hub)、server.js 启动拉起 hub
- 前端: SettingsModal(左菜单右参数,线上OCR默认 ai.88531.cn/v1 + mimo-v2.6-flash)、useHub 60s轮询、
  Header 右上角 开源地址/通知铃铛(红点+公告+在线人数)/设置/版本徽标 v1.2.0、搜索框提示改「支持 OCR 图内文字」
- CardAuth: HUB_API_KEY 经 compose 插值 + .env(不入库), 项目「FlyPic 素材库」project_id=15
- 修复: 前端端点 /api 重复拼接、设置响应结构对齐、测试识别结果解析、版本徽标 v 前缀
2026-11-16 21:57:03 +08:00

154 lines
4.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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<string>} 识别出的文字(清理后的纯文本)
*/
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<string>} 识别出的文字
*/
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 };