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 前缀
This commit is contained in:
1 parent
ffb47a0f81
commit
50c53a5e21
18 files changed
+961
-15
No files matched your search
@@ -1,5 +1,17 @@
|
||||
# 更新日志
|
||||
|
||||
## 2026-11-16 → v1.2.0
|
||||
|
||||
本版本在 v1.1.0 基础上补齐「设置 + 授权系统」能力:OCR 可切换线上/本地、右上角开源地址与版本号与通知公告、接入 CardAuth 授权系统做版本推送与在线统计。
|
||||
|
||||
- ✨ 新功能:**OCR 图内文字搜索(增强)** — 搜索框提示标明支持 OCR 图内文字,关键词同时匹配文件名与图片内文字
|
||||
- ✨ 新功能:**设置页** — 右上角 ⚙ 打开「左菜单 + 右参数」弹窗,OCR 识别方式可选 **本地 tesseract / 线上视觉模型**(接口地址 + 模型 + API Key),支持一键测试识别(返回耗时与识别文字),配置存 `settings.json` 保存即生效
|
||||
- ✨ 新功能:**线上 OCR 默认值** — 接口地址默认 `https://ai.88531.cn/v1`、模型默认 `mimo-v2.6-flash`(后端默认配置 + 设置页表单默认显示,可改)
|
||||
- ✨ 新功能:**右上角图标组** — 开源地址(一键打开 Gitea)、版本号徽标、通知铃铛(未读红点 + 公告下拉 + 在线人数)
|
||||
- ✨ 新功能:**CardAuth 授权系统接入** — 服务端 hub 定时执行:开机即查 + 6h 版本比对(发现新版本提示「去更新」)、30min 心跳(管理后台统计在线人数)、60s 公告拉取(删除即同步消失)
|
||||
- 🔨 可靠性:授权中心**失败开放** —— 不可达只降级显示,不阻塞任何功能;机器码只存服务端,不下发浏览器;`HUB_DISABLED=1` 或 `settings.json` 的 `telemetry:false` 可整体关闭上报
|
||||
- 🐛 修复:OCR 线上接口失败自动回退本地识别,扫描主流程不中断
|
||||
|
||||
## 2026-08-05 → v1.1.0
|
||||
|
||||
本次版本为 FlyPic 的 **Docker 独立部署版**,脱离飞牛应用商店(原开发者已于 2026-03-27 归档停更),可在任何 Linux + Docker 环境运行,并新增 OCR 图片文字搜索。
|
||||
|
||||
@@ -20,13 +20,34 @@
|
||||
- 文字存入索引库 `ocr_text` 列(带索引),**搜索时文件名和图片内文字同时匹配**
|
||||
- OCR 失败不影响扫描主流程;镜像内已预装 tesseract 及中英文语言包
|
||||
|
||||
### 3. Bug 修复
|
||||
### 3. 设置页(新增)
|
||||
|
||||
- 右上角 ⚙ **设置** 打开「左菜单 + 右参数」弹窗:
|
||||
- **OCR 识别**:识别方式二选一(本地 tesseract / 线上视觉模型),线上默认已填 `https://ai.88531.cn/v1` + 模型 `mimo-v2.6-flash`(可改),再填 `API Key`,支持**一键测试识别**(返回耗时与识别文字),留空密钥 = 保持原值
|
||||
- **关于**:当前版本号、开源地址
|
||||
- 配置持久化在 `config/settings.json`,保存后**立即生效**,无需重启
|
||||
|
||||
### 4. 右上角:开源地址 / 版本号 / 通知(新增)
|
||||
|
||||
- 🔗 **开源地址**:一键打开 `gitea.88531.cn/jinghui/flypic`
|
||||
- 🔔 **通知公告**:铃铛带未读红点,下拉展示授权系统推送的公告与在线人数
|
||||
- **版本号徽标**:显示当前运行版本(`v1.2.0`)
|
||||
- 搜索框提示已标明支持 **OCR 图内文字搜索**
|
||||
|
||||
### 5. 授权系统接入(CardAuth,新增)
|
||||
|
||||
- **最新版本推送**:服务端定时比对授权中心,发现新版本时铃铛面板出现「发现新 vX,去更新」
|
||||
- **公告推送**:管理后台发布公告 → 铃铛 60 秒内同步展示(删除公告即同步消失)
|
||||
- **在线人数统计**:服务端 30 分钟一次心跳上报,管理后台可看本项目在线数
|
||||
- **失败开放**:授权中心不可达时只降级显示,**不阻塞任何功能**;机器码只存服务端,不下发浏览器
|
||||
|
||||
### 6. Bug 修复
|
||||
|
||||
- 修复添加素材库报 `Internal server error`(`LibraryService.js` 使用 `logger` 但未 require)
|
||||
- 修复中文路径素材库提示 `Path does not exist`
|
||||
- `.gitignore` 排除 `config/`(含 JWT 密钥与管理员密码哈希,禁止入库)
|
||||
|
||||
### 4. 交互保持原样
|
||||
### 7. 交互保持原样
|
||||
|
||||
- 图片区保持原交互:**单击选中、Ctrl/Shift 多选、双击放大预览**(未改动)
|
||||
|
||||
@@ -54,6 +75,10 @@ services:
|
||||
- PORT=15002
|
||||
- FRONTEND_DIST=/app/backend/public
|
||||
- NODE_ENV=production
|
||||
# 授权系统(可选,留空/删除即关闭,不影响使用)
|
||||
- HUB_URL=https://auth.88531.cn/api
|
||||
- HUB_PROJECT_ID=15
|
||||
- HUB_API_KEY=ak_xxx # 自己项目的密钥,写进 .env(已 gitignore)
|
||||
```
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "flypic-backend",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"description": "FlyPic backend server",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -25,4 +25,4 @@
|
||||
"cross-env": "^7.0.3",
|
||||
"nodemon": "^3.0.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ const { createApp } = require('./src/app');
|
||||
|
||||
// 导入现有的依赖(保持兼容)
|
||||
const config = require('./utils/config');
|
||||
const hub = require('./utils/hub');
|
||||
const dbPool = require('./database/dbPool');
|
||||
const scanner = require('./utils/scanner');
|
||||
const scanManager = require('./utils/scanManager');
|
||||
@@ -118,6 +119,9 @@ server.listen(PORT, () => {
|
||||
if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`);
|
||||
console.log('');
|
||||
|
||||
// 授权系统 hub:版本检查 / 心跳(在线人数) / 公告(失败开放,不影响使用)
|
||||
try { hub.start(); } catch (e) { console.error('[Hub] 启动失败:', e.message); }
|
||||
|
||||
try {
|
||||
const currentConfig = config.loadConfig();
|
||||
|
||||
|
||||
@@ -83,6 +83,8 @@ function createApp(dependencies) {
|
||||
const scanRouter = require('./routes/scan');
|
||||
const fileRouter = require('./routes/file');
|
||||
const uploadRouter = require('./routes/upload');
|
||||
const settingsRouter = require('./routes/settings');
|
||||
const hubRouter = require('./routes/hub');
|
||||
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/library', libraryRouter);
|
||||
@@ -90,6 +92,8 @@ function createApp(dependencies) {
|
||||
app.use('/api/scan', scanRouter);
|
||||
app.use('/api/file', fileRouter);
|
||||
app.use('/api/upload', uploadRouter);
|
||||
app.use('/api/settings', settingsRouter);
|
||||
app.use('/api/hub', hubRouter);
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (req, res) => {
|
||||
|
||||
@@ -61,7 +61,8 @@ function createAuthMiddleware(getPasswordHash, getJwtSecret) {
|
||||
'/api/auth/status',
|
||||
'/api/auth/login',
|
||||
'/api/auth/setup',
|
||||
'/api/health'
|
||||
'/api/health',
|
||||
'/api/hub' // 版本检查/公告(无敏感数据)
|
||||
];
|
||||
|
||||
// 前缀匹配的公开路径(缩略图 & 原图资源)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* hub 路由:前端轮询的同源接口(免登录、不含任何 key/机器码)
|
||||
* GET /api/hub -> { version, latest, update_available, changelog, download_url, announcements, popup, hub_ok }
|
||||
*/
|
||||
const express = require('express');
|
||||
const hub = require('../../utils/hub');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.json({ success: true, data: hub.getStatus() });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* 应用设置路由
|
||||
* GET /api/settings 读取(apiKey 掩码返回)
|
||||
* PUT /api/settings 保存
|
||||
* POST /api/settings/test-ocr 测试 OCR(本地或线上,返回识别文本与耗时)
|
||||
*/
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { getSettings, saveSettings, maskKey } = require('../../utils/settings');
|
||||
const { ocrWithConfig } = require('../../utils/ocr');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
const s = getSettings();
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
provider: s.ocr.provider,
|
||||
online: {
|
||||
url: s.ocr.online.url,
|
||||
model: s.ocr.online.model,
|
||||
apiKeyMasked: maskKey(s.ocr.online.apiKey),
|
||||
configured: !!(s.ocr.online.url && s.ocr.online.apiKey)
|
||||
},
|
||||
telemetry: s.telemetry
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
router.put('/', (req, res) => {
|
||||
try {
|
||||
const saved = saveSettings(req.body || {});
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
provider: saved.ocr.provider,
|
||||
online: {
|
||||
url: saved.ocr.online.url,
|
||||
model: saved.ocr.online.model,
|
||||
apiKeyMasked: maskKey(saved.ocr.online.apiKey),
|
||||
configured: !!(saved.ocr.online.url && saved.ocr.online.apiKey)
|
||||
},
|
||||
telemetry: saved.telemetry
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
res.status(500).json({ success: false, message: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
/** 测试 OCR:用一张内置样图(sharp 生成带文字 PNG)跑识别 */
|
||||
router.post('/test-ocr', async (req, res) => {
|
||||
try {
|
||||
const body = req.body || {};
|
||||
const saved = getSettings();
|
||||
// 未传 apiKey 时回读已保存密钥(测试无需重新输入)
|
||||
const onlineCfg = {
|
||||
url: body.url || saved.ocr.online.url,
|
||||
model: body.model || saved.ocr.online.model,
|
||||
apiKey: body.apiKey || saved.ocr.online.apiKey
|
||||
};
|
||||
const cfg = body.provider === 'online'
|
||||
? { provider: 'online', online: onlineCfg }
|
||||
: { provider: 'local' };
|
||||
|
||||
if (cfg.provider === 'online' && (!cfg.online.url || !cfg.online.apiKey)) {
|
||||
return res.status(400).json({ success: false, message: '线上 OCR 需要填写接口地址和 API Key' });
|
||||
}
|
||||
|
||||
// 生成测试图:白底黑字 "FlyPic OCR Test 2026"(英文避免容器缺 CJK 字体出现豆腐块)
|
||||
const sharp = require('sharp');
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="480" height="120">
|
||||
<rect width="480" height="120" fill="white"/>
|
||||
<text x="30" y="75" font-size="40" font-family="sans-serif" fill="black">FlyPic OCR Test 2026</text>
|
||||
</svg>`;
|
||||
const tmp = path.join(require('os').tmpdir(), `flypic_ocr_test_${Date.now()}.png`);
|
||||
await sharp(Buffer.from(svg)).png().toFile(tmp);
|
||||
|
||||
const start = Date.now();
|
||||
try {
|
||||
const text = await ocrWithConfig(tmp, cfg);
|
||||
const ms = Date.now() - start;
|
||||
const ok = text && text.length > 0;
|
||||
res.json({
|
||||
success: ok,
|
||||
data: { text: text || '', ms, provider: cfg.provider },
|
||||
message: ok ? undefined : '识别成功但未提取到文字'
|
||||
});
|
||||
} finally {
|
||||
fs.unlink(tmp, () => {});
|
||||
}
|
||||
} catch (e) {
|
||||
res.status(500).json({ success: false, message: `OCR 测试失败: ${e.message}` });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* CardAuth 服务端 hub:安装统计(心跳) / 版本检查 / 公告推送
|
||||
*
|
||||
* 形态:key 只存在服务端环境变量,前端只轮询同源 /api/hub。
|
||||
* 节奏:开机即查 + 6h 更新检查;30min 心跳;60s 公告。
|
||||
* 原则:失败开放(授权中心不可达只降级显示,不阻塞任何功能)。
|
||||
* 环境变量:HUB_URL / HUB_PROJECT_ID / HUB_API_KEY / SITE_VERSION / HUB_DISABLED
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const crypto = require('crypto');
|
||||
const { getConfigDir } = require('./config');
|
||||
const { getSettings } = require('./settings');
|
||||
|
||||
const HUB_URL = (process.env.HUB_URL || 'https://auth.88531.cn/api').replace(/\/+$/, '');
|
||||
const HUB_PROJECT_ID = process.env.HUB_PROJECT_ID || '';
|
||||
const HUB_API_KEY = process.env.HUB_API_KEY || '';
|
||||
const SITE_VERSION = process.env.SITE_VERSION || '1.2.0';
|
||||
const TIMEOUT_MS = 8000;
|
||||
|
||||
const state = {
|
||||
version: SITE_VERSION,
|
||||
latest: SITE_VERSION,
|
||||
update_available: false,
|
||||
changelog: null,
|
||||
download_url: null,
|
||||
announcements: [],
|
||||
popup: [],
|
||||
hub_ok: false,
|
||||
updatedAt: null
|
||||
};
|
||||
|
||||
let machineId = null;
|
||||
let started = false;
|
||||
|
||||
function machineIdPath() {
|
||||
return path.join(getConfigDir(), 'hub_machine.json');
|
||||
}
|
||||
|
||||
/** 10-16 位纯数字,首次生成后持久化(重建容器不丢) */
|
||||
function getMachineId() {
|
||||
if (machineId) return machineId;
|
||||
try {
|
||||
const p = machineIdPath();
|
||||
if (fs.existsSync(p)) {
|
||||
const saved = JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||
if (saved && /^\d{10,16}$/.test(saved.machine_id || '')) {
|
||||
machineId = saved.machine_id;
|
||||
return machineId;
|
||||
}
|
||||
}
|
||||
// 用宿主稳定标识派生(非随机),保证重启不变
|
||||
let seed = '';
|
||||
try { seed = fs.readFileSync('/etc/machine-id', 'utf8').trim(); } catch (e) { /* ignore */ }
|
||||
if (!seed) { try { seed = fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim(); } catch (e) { /* ignore */ } }
|
||||
if (!seed) seed = os.hostname();
|
||||
const hash = crypto.createHash('sha256').update(`flypic:${seed}`).digest('hex');
|
||||
machineId = String(BigInt('0x' + hash.slice(0, 15)) % 10000000000000000n).padStart(10, '0').slice(0, 16);
|
||||
fs.writeFileSync(p, JSON.stringify({ machine_id: machineId }, null, 2));
|
||||
return machineId;
|
||||
} catch (e) {
|
||||
console.error('[Hub] machine_id 生成失败:', e.message);
|
||||
machineId = '100000000001';
|
||||
return machineId;
|
||||
}
|
||||
}
|
||||
|
||||
function headers(extra = {}) {
|
||||
const h = { 'Content-Type': 'application/json', ...extra };
|
||||
if (HUB_API_KEY) h['X-Api-Key'] = HUB_API_KEY;
|
||||
if (HUB_PROJECT_ID) h['X-Project-Id'] = String(HUB_PROJECT_ID);
|
||||
return h;
|
||||
}
|
||||
|
||||
async function fetchJSON(url, options = {}) {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, { ...options, signal: ctrl.signal });
|
||||
return await res.json(); // CardAuth HTTP 恒 200,成败看 body code
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** 安装登记 + 更新检查 */
|
||||
async function checkUpdate() {
|
||||
if (!HUB_API_KEY || !HUB_PROJECT_ID) throw new Error('HUB_API_KEY/HUB_PROJECT_ID 未配置');
|
||||
const body = {
|
||||
machine_id: getMachineId(),
|
||||
client_version: SITE_VERSION,
|
||||
device_info: JSON.stringify({ os: `${os.type()} ${os.arch()}`, host: 'web' })
|
||||
};
|
||||
const data = await fetchJSON(`${HUB_URL}/public/installations/check-update`, {
|
||||
method: 'POST',
|
||||
headers: headers(),
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (data.code !== 200) throw new Error(data.message || 'check-update 失败');
|
||||
const d = data.data || {};
|
||||
state.latest = d.latest_version || SITE_VERSION;
|
||||
state.update_available = !!d.update_available;
|
||||
state.changelog = d.changelog || null;
|
||||
state.download_url = d.download_url || null;
|
||||
state.hub_ok = true;
|
||||
}
|
||||
|
||||
/** 心跳(统计在线人数) */
|
||||
async function heartbeat() {
|
||||
if (!HUB_API_KEY || !HUB_PROJECT_ID) throw new Error('HUB_API_KEY/HUB_PROJECT_ID 未配置');
|
||||
const body = {
|
||||
machine_id: getMachineId(),
|
||||
client_version: SITE_VERSION,
|
||||
device_info: JSON.stringify({ os: `${os.type()} ${os.arch()}`, host: 'web' })
|
||||
};
|
||||
const data = await fetchJSON(`${HUB_URL}/public/installations/heartbeat`, {
|
||||
method: 'POST',
|
||||
headers: headers(),
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (data.code !== 200) throw new Error(data.message || 'heartbeat 失败');
|
||||
}
|
||||
|
||||
/** 公告(免 key,但要 project_id + target 过滤) */
|
||||
async function fetchAnnouncements() {
|
||||
const pid = HUB_PROJECT_ID || '0';
|
||||
const data = await fetchJSON(
|
||||
`${HUB_URL}/public/announcements?target=client&project_id=${pid}&limit=20`,
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
if (data.code !== 200) throw new Error(data.message || 'announcements 失败');
|
||||
const d = data.data || {};
|
||||
// 返回空列表必须覆盖为空(管理后台删掉公告后不能继续挂着旧的)
|
||||
state.announcements = Array.isArray(d.list) ? d.list : [];
|
||||
state.popup = Array.isArray(d.popup) ? d.popup : [];
|
||||
}
|
||||
|
||||
async function safeRun(fn, label) {
|
||||
try {
|
||||
await fn();
|
||||
} catch (e) {
|
||||
console.error(`[Hub] ${label} 失败(不影响使用):`, e.message);
|
||||
if (label === '公告') { /* 请求抛错时保留上一次成功结果 */ }
|
||||
else state.hub_ok = state.hub_ok && label !== '更新检查';
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (started) return;
|
||||
if (process.env.HUB_DISABLED === '1') { console.log('[Hub] HUB_DISABLED=1,已关闭'); return; }
|
||||
if (!getSettings().telemetry) { console.log('[Hub] settings telemetry=false,已关闭'); return; }
|
||||
started = true;
|
||||
|
||||
// 开机即查
|
||||
(async () => {
|
||||
await safeRun(checkUpdate, '更新检查');
|
||||
await safeRun(heartbeat, '心跳');
|
||||
await safeRun(fetchAnnouncements, '公告');
|
||||
state.updatedAt = Date.now();
|
||||
console.log(`[Hub] 启动: 版本=${SITE_VERSION} 最新=${state.latest} 公告=${state.announcements.length}条 hub_ok=${state.hub_ok}`);
|
||||
})();
|
||||
|
||||
setInterval(async () => { await safeRun(checkUpdate, '更新检查'); state.updatedAt = Date.now(); }, 6 * 60 * 60 * 1000);
|
||||
setInterval(async () => { await safeRun(heartbeat, '心跳'); }, 30 * 60 * 1000);
|
||||
setInterval(async () => { await safeRun(fetchAnnouncements, '公告'); state.updatedAt = Date.now(); }, 60 * 1000);
|
||||
}
|
||||
|
||||
function getStatus() {
|
||||
// 不下发 machine_id / install_id 等内部标识
|
||||
return { ...state, updatedAt: state.updatedAt };
|
||||
}
|
||||
|
||||
module.exports = { start, getStatus };
|
||||
+99
-7
@@ -2,6 +2,11 @@
|
||||
* 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');
|
||||
@@ -9,25 +14,34 @@ 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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 对单张图片进行 OCR 文字识别
|
||||
* 本地 tesseract 识别
|
||||
* @param {string} imagePath - 图片绝对路径
|
||||
* @returns {Promise<string>} 识别出的文字(清理后的纯文本)
|
||||
*/
|
||||
async function extractText(imagePath) {
|
||||
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,
|
||||
@@ -36,7 +50,7 @@ async function extractText(imagePath) {
|
||||
'--psm', '3', // 自动页面分割
|
||||
'--oem', '3' // 默认 OCR 引擎
|
||||
], { timeout: 15000 }); // 15秒超时
|
||||
|
||||
|
||||
// 读取结果
|
||||
const resultPath = tmpFile.replace('.txt', '.txt');
|
||||
if (fs.existsSync(resultPath)) {
|
||||
@@ -51,11 +65,89 @@ async function extractText(imagePath) {
|
||||
try { fs.unlinkSync(tmpFile); } catch(e) {}
|
||||
try { fs.unlinkSync(tmpFile.replace('.txt', '.txt')); } catch(e) {}
|
||||
}
|
||||
|
||||
|
||||
return '';
|
||||
} catch (error) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { extractText };
|
||||
/**
|
||||
* 线上 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 };
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 应用设置(settings.json,与 config.json 同目录)
|
||||
* 目前包含 OCR 识别方式配置:
|
||||
* ocr.provider: 'local' | 'online'
|
||||
* ocr.online: { url, apiKey, model } 线上 OCR(OpenAI 兼容 /v1/chat/completions)
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { getConfigDir } = require('./config');
|
||||
|
||||
const DEFAULTS = {
|
||||
ocr: {
|
||||
provider: 'local', // local = 本地 tesseract;online = 线上 OCR 接口
|
||||
online: {
|
||||
url: 'https://ai.88531.cn/v1', // OpenAI 兼容接口(含 /v1),默认 ai.88531.cn
|
||||
apiKey: '',
|
||||
model: 'mimo-v2.6-flash' // 默认视觉模型
|
||||
}
|
||||
},
|
||||
telemetry: true // CardAuth 心跳/版本/公告上报开关
|
||||
};
|
||||
|
||||
function settingsPath() {
|
||||
return path.join(getConfigDir(), 'settings.json');
|
||||
}
|
||||
|
||||
function getSettings() {
|
||||
try {
|
||||
const p = settingsPath();
|
||||
if (!fs.existsSync(p)) return JSON.parse(JSON.stringify(DEFAULTS));
|
||||
const data = JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||
// 深合并默认值,防旧文件缺字段
|
||||
return {
|
||||
ocr: {
|
||||
provider: (data.ocr && data.ocr.provider) === 'online' ? 'online' : 'local',
|
||||
online: {
|
||||
url: (data.ocr && data.ocr.online && data.ocr.online.url) || DEFAULTS.ocr.online.url,
|
||||
apiKey: (data.ocr && data.ocr.online && data.ocr.online.apiKey) || '',
|
||||
model: (data.ocr && data.ocr.online && data.ocr.online.model) || DEFAULTS.ocr.online.model
|
||||
}
|
||||
},
|
||||
telemetry: data.telemetry !== false
|
||||
};
|
||||
} catch (e) {
|
||||
console.error('[Settings] 读取失败,使用默认:', e.message);
|
||||
return JSON.parse(JSON.stringify(DEFAULTS));
|
||||
}
|
||||
}
|
||||
|
||||
function saveSettings(settings) {
|
||||
const p = settingsPath();
|
||||
const merged = getSettings();
|
||||
if (settings.ocr) {
|
||||
merged.ocr.provider = settings.ocr.provider === 'online' ? 'online' : 'local';
|
||||
if (settings.ocr.online) {
|
||||
// apiKey 传空/掩码 = 保持原值
|
||||
const incomingKey = settings.ocr.online.apiKey;
|
||||
if (typeof incomingKey === 'string' && incomingKey.trim() && !incomingKey.includes('***')) {
|
||||
merged.ocr.online.apiKey = incomingKey.trim();
|
||||
}
|
||||
if (typeof settings.ocr.online.url === 'string') merged.ocr.online.url = settings.ocr.online.url.trim();
|
||||
if (typeof settings.ocr.online.model === 'string') merged.ocr.online.model = settings.ocr.online.model.trim();
|
||||
}
|
||||
}
|
||||
if (typeof settings.telemetry === 'boolean') merged.telemetry = settings.telemetry;
|
||||
fs.writeFileSync(p, JSON.stringify(merged, null, 2));
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** 掩码展示用:sk-abcdef123456 -> sk-a***56 */
|
||||
function maskKey(key) {
|
||||
if (!key) return '';
|
||||
if (key.length <= 8) return '***';
|
||||
return `${key.slice(0, 4)}***${key.slice(-4)}`;
|
||||
}
|
||||
|
||||
module.exports = { getSettings, saveSettings, maskKey, settingsPath };
|
||||
@@ -17,6 +17,10 @@ services:
|
||||
- PORT=15002
|
||||
- FRONTEND_DIST=/app/backend/public
|
||||
- NODE_ENV=production
|
||||
# 授权系统(CardAuth):版本推送 / 公告 / 在线人数统计 —— 失败开放,不可达不影响使用
|
||||
- HUB_URL=https://auth.88531.cn/api
|
||||
- HUB_PROJECT_ID=15
|
||||
- HUB_API_KEY=${HUB_API_KEY:-}
|
||||
# 如需挂载多个素材库,取消注释并修改路径:
|
||||
# volumes:
|
||||
# - /vol1/1000/图片库:/data/library1:ro
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* hub API:版本检查 / 公告 / 在线人数(后端代理授权系统,前端轮询)
|
||||
* 注意:client 的 API_BASE 已含 /api,这里只写 /hub 段
|
||||
*/
|
||||
import { api } from '../client';
|
||||
|
||||
export function getHub() {
|
||||
return api.get('/hub');
|
||||
}
|
||||
|
||||
export const hubAPI = { getHub };
|
||||
export default hubAPI;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* 设置 API(OCR 等)
|
||||
* 注意:client 的 API_BASE 已含 /api,这里只写 /settings 段
|
||||
*/
|
||||
import { api } from '../client';
|
||||
|
||||
export function getSettings() {
|
||||
return api.get('/settings');
|
||||
}
|
||||
|
||||
export function updateSettings(data) {
|
||||
return api.put('/settings', data);
|
||||
}
|
||||
|
||||
export function testOcr(data) {
|
||||
return api.post('/settings/test-ocr', data);
|
||||
}
|
||||
|
||||
export const settingsAPI = { getSettings, updateSettings, testOcr };
|
||||
export default settingsAPI;
|
||||
@@ -6,11 +6,14 @@ import * as library from './endpoints/library';
|
||||
import * as image from './endpoints/image';
|
||||
import * as scan from './endpoints/scan';
|
||||
import { fileAPI } from './file';
|
||||
import { settingsAPI } from './endpoints/settings';
|
||||
import { hubAPI } from './endpoints/hub';
|
||||
|
||||
export const libraryAPI = library;
|
||||
export const imageAPI = image;
|
||||
export const scanAPI = scan;
|
||||
export { fileAPI };
|
||||
export { settingsAPI, hubAPI };
|
||||
|
||||
export { api, APIError } from './client';
|
||||
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, Star } from 'lucide-react';
|
||||
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, Star, Bell, Github, Settings, ExternalLink } from 'lucide-react';
|
||||
import { useLibraryStore } from '../stores/useLibraryStore';
|
||||
import { useImageStore } from '../stores/useImageStore';
|
||||
import { useUIStore } from '../stores/useUIStore';
|
||||
import { useScanStore } from '../stores/useScanStore';
|
||||
import { useTheme } from '../hooks/useTheme';
|
||||
import { useHub } from '../hooks/useHub';
|
||||
import { libraryAPI, scanAPI, watchAPI } from '../api';
|
||||
import SettingsModal from './SettingsModal';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const logger = createLogger('Header');
|
||||
|
||||
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
|
||||
|
||||
function Header() {
|
||||
const { currentLibraryId } = useLibraryStore();
|
||||
const { searchKeywords, originalImages, selectedFolder, setSearchKeywords, filters, setFilters, resetFilters } = useImageStore();
|
||||
@@ -21,7 +25,14 @@ function Header() {
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const [showMobileSettings, setShowMobileSettings] = useState(false);
|
||||
const [localSearchValue, setLocalSearchValue] = useState(searchKeywords);
|
||||
const [showNotices, setShowNotices] = useState(false);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const searchDebounceRef = useRef(null);
|
||||
|
||||
// 授权系统 hub:版本 / 公告 / 在线人数
|
||||
const hub = useHub();
|
||||
const announcements = hub.announcements || [];
|
||||
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.2.0';
|
||||
|
||||
// 从全局 store 获取筛选状态
|
||||
const selectedFormats = filters.formats || [];
|
||||
@@ -294,6 +305,88 @@ function Header() {
|
||||
);
|
||||
const availableRatings = filterOptions.ratings;
|
||||
|
||||
// 右上角图标组:开源地址 / 通知 / 设置 / 版本号
|
||||
const rightIcons = (
|
||||
<>
|
||||
<a
|
||||
href={REPO_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title="开源地址"
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
<Github className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
</a>
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowNotices((v) => !v)}
|
||||
title="通知公告"
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors relative"
|
||||
>
|
||||
<Bell className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
{announcements.length > 0 && (
|
||||
<span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-red-500"></span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{showNotices && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setShowNotices(false)}></div>
|
||||
<div className="absolute right-0 mt-2 w-80 max-h-96 overflow-y-auto z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-2xl p-3">
|
||||
<div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 pb-2 mb-2 border-b border-gray-100 dark:border-gray-700">
|
||||
<span>通知公告</span>
|
||||
<span className="flex items-center gap-1">
|
||||
{hub.online != null && <span className="text-green-600 dark:text-green-400">在线 {hub.online}</span>}
|
||||
<span>{appVersion}</span>
|
||||
</span>
|
||||
</div>
|
||||
{announcements.length === 0 ? (
|
||||
<div className="text-sm text-gray-400 dark:text-gray-500 py-4 text-center">暂无公告</div>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{announcements.map((a, i) => (
|
||||
<div key={a.id || i} className="p-2.5 rounded-lg bg-gray-50 dark:bg-gray-900/60">
|
||||
{a.title && (
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-white mb-1">{a.title}</div>
|
||||
)}
|
||||
<div className="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap leading-relaxed">{a.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{hub.update_available && (
|
||||
<a
|
||||
href={hub.download_url || REPO_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="mt-2 flex items-center justify-center gap-1 text-xs text-blue-600 dark:text-blue-400 hover:underline py-1.5"
|
||||
>
|
||||
发现新版本 {hub.latest},去更新
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setShowSettings(true)}
|
||||
title="设置"
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
<Settings className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
</button>
|
||||
|
||||
<span className="hidden sm:inline-block px-2 py-0.5 text-xs text-gray-500 dark:text-gray-400 border border-gray-200 dark:border-gray-700 rounded-full select-none">
|
||||
{appVersion}
|
||||
</span>
|
||||
|
||||
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} />
|
||||
</>
|
||||
);
|
||||
|
||||
// 移动端布局
|
||||
if (isMobile) {
|
||||
// 文件夹视图不显示搜索和筛选
|
||||
@@ -331,6 +424,8 @@ function Header() {
|
||||
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{rightIcons}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -342,7 +437,7 @@ function Header() {
|
||||
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索图片..."
|
||||
placeholder="搜索图片...(支持 OCR 图内文字)"
|
||||
value={searchKeywords}
|
||||
onChange={(e) => handleSearchChange(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
|
||||
@@ -512,7 +607,7 @@ function Header() {
|
||||
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索图片... (多个关键词用空格分隔,即时搜索)"
|
||||
placeholder="搜索图片...(支持 OCR 图内文字,多个关键词用空格分隔)"
|
||||
value={localSearchValue}
|
||||
onChange={(e) => handleSearchChange(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
@@ -578,6 +673,9 @@ function Header() {
|
||||
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="w-px h-6 bg-gray-200 dark:bg-gray-700 ml-1"></div>
|
||||
{rightIcons}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink } from 'lucide-react';
|
||||
import { settingsAPI } from '../api';
|
||||
|
||||
const APP_VERSION = 'v1.2.0';
|
||||
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
|
||||
|
||||
/**
|
||||
* 设置弹窗:左侧菜单 + 右侧参数
|
||||
* - OCR 识别:本地 tesseract / 线上接口切换、线上参数、测试
|
||||
* - 关于:版本号 / 开源地址
|
||||
*/
|
||||
export default function SettingsModal({ open, onClose, versionLabel }) {
|
||||
const [active, setActive] = useState('ocr');
|
||||
const [cfg, setCfg] = useState(null); // { provider, online:{url,model,apiKeyMasked} }
|
||||
const [apiKeyInput, setApiKeyInput] = useState(''); // 新密钥(留空=保持原密钥)
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [msg, setMsg] = useState(null); // { type, text }
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setMsg(null);
|
||||
setApiKeyInput('');
|
||||
settingsAPI.getSettings()
|
||||
.then((d) => setCfg({
|
||||
provider: d?.provider || 'local',
|
||||
online: {
|
||||
url: d?.online?.url || 'https://ai.88531.cn/v1',
|
||||
model: d?.online?.model || 'mimo-v2.6-flash',
|
||||
apiKeyMasked: d?.online?.apiKeyMasked || ''
|
||||
},
|
||||
telemetry: d?.telemetry !== false
|
||||
}))
|
||||
.catch((e) => setMsg({ type: 'error', text: '读取设置失败: ' + (e.data?.message || e.message) }));
|
||||
}, [open]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const patch = (p) => setCfg((c) => ({ ...c, ...p, online: { ...c.online, ...(p.online || {}) } }));
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
const payload = {
|
||||
ocr: {
|
||||
provider: cfg.provider,
|
||||
online: {
|
||||
url: cfg.online.url,
|
||||
model: cfg.online.model,
|
||||
apiKey: apiKeyInput // 空字符串 = 保留原密钥
|
||||
}
|
||||
}
|
||||
};
|
||||
const data = await settingsAPI.updateSettings(payload);
|
||||
setCfg((c) => ({ ...(c || {}), ...data, online: { ...(c?.online || {}), ...(data?.online || {}) } }));
|
||||
setApiKeyInput('');
|
||||
setMsg({ type: 'ok', text: '已保存,新配置立即生效' });
|
||||
} catch (e) {
|
||||
setMsg({ type: 'error', text: '保存失败: ' + (e.data?.message || e.message) });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async () => {
|
||||
setTesting(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
// 若用户改了线上参数但没保存,测试时带上输入框内容
|
||||
const apiKey = apiKeyInput || undefined;
|
||||
const d = await settingsAPI.testOcr({
|
||||
provider: cfg.provider,
|
||||
url: cfg.online.url,
|
||||
model: cfg.online.model,
|
||||
...(cfg.provider === 'online' && apiKey ? { apiKey } : {})
|
||||
});
|
||||
if (d && typeof d.ms === 'number') {
|
||||
setMsg({ type: 'ok', text: `识别成功(${d.ms}ms):${(d.text || '').slice(0, 80) || '(空)'}` });
|
||||
} else {
|
||||
setMsg({ type: 'error', text: (d && d.message) || '识别失败' });
|
||||
}
|
||||
} catch (e) {
|
||||
setMsg({ type: 'error', text: '测试失败: ' + (e.data?.message || e.message) });
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const menus = [
|
||||
{ key: 'ocr', label: 'OCR 识别', icon: ScanText },
|
||||
{ key: 'about', label: '关于', icon: Info }
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
||||
<div
|
||||
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] overflow-hidden flex"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* 左侧菜单 */}
|
||||
<div className="w-44 flex-shrink-0 border-r border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 p-3 flex flex-col">
|
||||
<div className="text-sm font-semibold text-gray-900 dark:text-white px-2 py-2">设置</div>
|
||||
{menus.map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
onClick={() => { setActive(m.key); setMsg(null); }}
|
||||
className={`flex items-center gap-2 px-3 py-2.5 rounded-lg text-sm transition-colors ${
|
||||
active === m.key
|
||||
? 'bg-blue-50 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300 font-medium'
|
||||
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<m.icon className="w-4 h-4" />
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 右侧参数 */}
|
||||
<div className="flex-1 p-6 overflow-y-auto">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{active === 'ocr' ? 'OCR 识别设置' : '关于'}
|
||||
</h2>
|
||||
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||
<X className="w-5 h-5 text-gray-500" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{msg && (
|
||||
<div className={`mb-4 px-3 py-2 rounded-lg text-sm ${
|
||||
msg.type === 'ok' ? 'bg-green-50 text-green-700 dark:bg-green-500/15 dark:text-green-300'
|
||||
: 'bg-red-50 text-red-700 dark:bg-red-500/15 dark:text-red-300'
|
||||
}`}>{msg.text}</div>
|
||||
)}
|
||||
|
||||
{active === 'ocr' && cfg && (
|
||||
<div className="space-y-5">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
OCR 用于「图内文字搜索」:识别图片中的文字并建立索引,扫描素材库时自动执行。
|
||||
</p>
|
||||
|
||||
{/* 识别方式 */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">识别方式</label>
|
||||
<div className="space-y-2">
|
||||
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
||||
<input
|
||||
type="radio"
|
||||
className="mt-0.5"
|
||||
checked={cfg.provider === 'local'}
|
||||
onChange={() => patch({ provider: 'local' })}
|
||||
/>
|
||||
<span>
|
||||
<span className="block text-sm font-medium text-gray-900 dark:text-white">本地 OCR(tesseract)</span>
|
||||
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">免费离线,中英文识别,随容器内置,无需任何配置</span>
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
||||
<input
|
||||
type="radio"
|
||||
className="mt-0.5"
|
||||
checked={cfg.provider === 'online'}
|
||||
onChange={() => patch({ provider: 'online' })}
|
||||
/>
|
||||
<span>
|
||||
<span className="block text-sm font-medium text-gray-900 dark:text-white">线上 OCR(视觉大模型)</span>
|
||||
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">识别率更高,需 OpenAI 兼容接口(/v1/chat/completions)</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 线上参数 */}
|
||||
{cfg.provider === 'online' && (
|
||||
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
|
||||
<input
|
||||
type="text"
|
||||
value={cfg.online.url}
|
||||
onChange={(e) => patch({ online: { url: e.target.value } })}
|
||||
placeholder="https://ai.88531.cn/v1(默认)"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">模型名称</label>
|
||||
<input
|
||||
type="text"
|
||||
value={cfg.online.model}
|
||||
onChange={(e) => patch({ online: { model: e.target.value } })}
|
||||
placeholder="mimo-v2.6-flash(默认)"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
|
||||
<input
|
||||
type="password"
|
||||
value={apiKeyInput}
|
||||
onChange={(e) => setApiKeyInput(e.target.value)}
|
||||
placeholder={cfg.online.apiKeyMasked ? `已配置(${cfg.online.apiKeyMasked}),留空保持不变` : 'sk-...'}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
{saving ? '保存中...' : '保存'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleTest}
|
||||
disabled={testing}
|
||||
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
|
||||
>
|
||||
<FlaskConical className="w-4 h-4" />
|
||||
{testing ? '测试中...' : '测试识别'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{active === 'about' && (
|
||||
<div className="space-y-4 text-sm">
|
||||
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
|
||||
<span className="text-gray-500 dark:text-gray-400">当前版本</span>
|
||||
<span className="font-medium text-gray-900 dark:text-white">{versionLabel || APP_VERSION}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
|
||||
<span className="text-gray-500 dark:text-gray-400">项目名称</span>
|
||||
<span className="font-medium text-gray-900 dark:text-white">FlyPic 素材库</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2">
|
||||
<span className="text-gray-500 dark:text-gray-400">开源地址</span>
|
||||
<a
|
||||
href={REPO_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 text-blue-600 dark:text-blue-400 hover:underline"
|
||||
>
|
||||
<Github className="w-4 h-4" />
|
||||
gitea.88531.cn/jinghui/flypic
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-500 pt-2">
|
||||
FlyPic 基于 ZangXincz/FlyPic 二次开发,修复多项问题并新增 OCR 图内文字搜索、线上 OCR、授权系统接入等能力。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { hubAPI } from '../api/endpoints/hub';
|
||||
|
||||
/**
|
||||
* 轮询 hub:新版本 + 公告 + 在线人数
|
||||
* 失败开放:接口不可用时状态保持默认,不影响页面使用
|
||||
*/
|
||||
export function useHub(pollMs = 60000) {
|
||||
const [status, setStatus] = useState({
|
||||
version: '',
|
||||
latest: '',
|
||||
update_available: false,
|
||||
changelog: '',
|
||||
download_url: '',
|
||||
announcements: [],
|
||||
popup: [],
|
||||
online: null,
|
||||
hub_ok: false
|
||||
});
|
||||
const timerRef = useRef(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const data = await hubAPI.getHub();
|
||||
if (data && typeof data === 'object') {
|
||||
setStatus((prev) => ({ ...prev, ...data }));
|
||||
}
|
||||
} catch {
|
||||
// 失败开放
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
timerRef.current = setInterval(refresh, pollMs);
|
||||
return () => clearInterval(timerRef.current);
|
||||
}, [refresh, pollMs]);
|
||||
|
||||
return { ...status, refresh };
|
||||
}
|
||||
|
||||
export default useHub;
|
||||
Reference in new issue
Block a user