1991 lines
152 KiB
JavaScript
1991 lines
152 KiB
JavaScript
const express = require('express');
|
||
const session = require('express-session');
|
||
const bcrypt = require('bcryptjs');
|
||
const multer = require('multer');
|
||
const rateLimit = require('express-rate-limit');
|
||
const crypto = require('crypto');
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
const PORT = process.env.PORT || 3210;
|
||
// 127.0.0.1 by default: on a VPS, Nginx fronts this with TLS and is the only
|
||
// thing that should be reachable from outside. On the old local-Windows setup
|
||
// this was 0.0.0.0 for LAN access; set HOST=0.0.0.0 explicitly if you still
|
||
// need that. COOKIE_SECURE should be "true" once you're behind real HTTPS.
|
||
const HOST = process.env.HOST || '127.0.0.1';
|
||
const COOKIE_SECURE = process.env.COOKIE_SECURE === 'true';
|
||
const DATA_FILE = path.join(__dirname, 'data.json');
|
||
const PID_FILE = path.join(__dirname, 'server.pid');
|
||
const FRONTEND_DIST = path.join(__dirname, '..', 'frontend', 'dist');
|
||
const UPLOADS_DIR = path.join(__dirname, 'uploads');
|
||
const AUTH_FILE = path.join(__dirname, 'auth.json');
|
||
const DEFAULT_USERNAME = 'admin';
|
||
const DEFAULT_PASSWORD = 'admin123';
|
||
// AI批量导入解析时,PDF渲染成图片/OCR用的临时文件放在这里,而不是系统的 os.tmpdir()(一般是
|
||
// /tmp)——有些VPS/容器环境会把 /tmp 挂载成只读或者单独的受限分区,直接用系统临时目录在这类
|
||
// 环境下会导致 mkdtempSync 抛出 EROFS 之类的错误,而且这个调用当时没被 try/catch 包住,会
|
||
// 直接让整个Node进程崩溃。用应用自己目录下这个文件夹,保证和 uploads/ 一样一定可读写。
|
||
const OCR_TMP_ROOT = path.join(__dirname, 'tmp-ocr');
|
||
|
||
if (!fs.existsSync(UPLOADS_DIR)) fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||
if (!fs.existsSync(OCR_TMP_ROOT)) fs.mkdirSync(OCR_TMP_ROOT, { recursive: true });
|
||
|
||
/* --------------------------------- auth ---------------------------------- */
|
||
|
||
function loadAuth() {
|
||
if (!fs.existsSync(AUTH_FILE)) {
|
||
const auth = { username: DEFAULT_USERNAME, passwordHash: bcrypt.hashSync(DEFAULT_PASSWORD, 10) };
|
||
fs.writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), 'utf8');
|
||
return auth;
|
||
}
|
||
try {
|
||
return JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
|
||
} catch (e) {
|
||
const auth = { username: DEFAULT_USERNAME, passwordHash: bcrypt.hashSync(DEFAULT_PASSWORD, 10) };
|
||
fs.writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), 'utf8');
|
||
return auth;
|
||
}
|
||
}
|
||
function saveAuth(auth) {
|
||
fs.writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), 'utf8');
|
||
}
|
||
|
||
/* ------------------------------ secret / crypto -------------------------- */
|
||
// Used to encrypt the DeepSeek API key (and anything else sensitive) at
|
||
// rest, so it isn't sitting around the filesystem as plain text.
|
||
|
||
const SECRET_KEY_FILE = path.join(__dirname, '.secret-key');
|
||
function getSecretKey() {
|
||
if (!fs.existsSync(SECRET_KEY_FILE)) {
|
||
const key = crypto.randomBytes(32);
|
||
fs.writeFileSync(SECRET_KEY_FILE, key.toString('base64'), { encoding: 'utf8', mode: 0o600 });
|
||
return key;
|
||
}
|
||
return Buffer.from(fs.readFileSync(SECRET_KEY_FILE, 'utf8').trim(), 'base64');
|
||
}
|
||
const SECRET_KEY = getSecretKey();
|
||
|
||
function encrypt(text) {
|
||
if (!text) return '';
|
||
const iv = crypto.randomBytes(12);
|
||
const cipher = crypto.createCipheriv('aes-256-gcm', SECRET_KEY, iv);
|
||
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
|
||
const tag = cipher.getAuthTag();
|
||
return Buffer.concat([iv, tag, encrypted]).toString('base64');
|
||
}
|
||
function decrypt(b64) {
|
||
if (!b64) return '';
|
||
try {
|
||
const buf = Buffer.from(b64, 'base64');
|
||
const iv = buf.subarray(0, 12);
|
||
const tag = buf.subarray(12, 28);
|
||
const encrypted = buf.subarray(28);
|
||
const decipher = crypto.createDecipheriv('aes-256-gcm', SECRET_KEY, iv);
|
||
decipher.setAuthTag(tag);
|
||
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
|
||
} catch (e) {
|
||
return '';
|
||
}
|
||
}
|
||
|
||
/* --------------------------------- AI config ------------------------------ */
|
||
|
||
const AI_CONFIG_FILE = path.join(__dirname, 'ai-config.json');
|
||
// Lets you point this at a different OpenAI-compatible endpoint if needed
|
||
// (e.g. testing against a mock server); defaults to the real DeepSeek API.
|
||
const DEEPSEEK_API_BASE = process.env.DEEPSEEK_API_BASE || 'https://api.deepseek.com';
|
||
|
||
// 备用服务商:阿里云百炼(通义千问),OpenAI 兼容接口。DeepSeek 繁忙/故障时自动切换过去。
|
||
// 阿里云的 Key 分地域:中国大陆(北京)和国际(新加坡)的 Key 不能混用。
|
||
const ALIYUN_BASES = {
|
||
cn: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||
intl: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
|
||
};
|
||
const ALIYUN_DEFAULT_MODEL = 'qwen-plus';
|
||
|
||
function readAiConfigRaw() {
|
||
try { return JSON.parse(fs.readFileSync(AI_CONFIG_FILE, 'utf8')) || {}; } catch (e) { return {}; }
|
||
}
|
||
function writeAiConfigRaw(raw) {
|
||
fs.writeFileSync(AI_CONFIG_FILE, JSON.stringify(raw, null, 2), 'utf8');
|
||
}
|
||
function loadAiConfig() {
|
||
const raw = readAiConfigRaw();
|
||
return {
|
||
apiKey: raw.apiKeyEnc ? decrypt(raw.apiKeyEnc) : '',
|
||
backup: {
|
||
apiKey: raw.backupKeyEnc ? decrypt(raw.backupKeyEnc) : '',
|
||
model: raw.backupModel || ALIYUN_DEFAULT_MODEL,
|
||
region: raw.backupRegion === 'intl' ? 'intl' : 'cn',
|
||
},
|
||
};
|
||
}
|
||
function saveAiConfig(apiKey) {
|
||
const raw = readAiConfigRaw();
|
||
raw.apiKeyEnc = encrypt(apiKey);
|
||
writeAiConfigRaw(raw);
|
||
}
|
||
function aliyunProvider(backup) {
|
||
return {
|
||
name: '阿里云',
|
||
base: ALIYUN_BASES[backup.region] || ALIYUN_BASES.cn,
|
||
apiKey: backup.apiKey,
|
||
model: backup.model || ALIYUN_DEFAULT_MODEL,
|
||
// 通义千问非思考模式的输出上限一般是 8K~16K,超了会直接报 400,所以先封顶到 16384,
|
||
// 如果还是报 max_tokens 相关的 400,会自动降到 8192 再试一次
|
||
maxTokensCap: 16384,
|
||
extraBody: { enable_thinking: false },
|
||
};
|
||
}
|
||
|
||
async function callDeepSeek(apiKey, messages, opts) {
|
||
return callLLM({
|
||
name: 'DeepSeek', base: DEEPSEEK_API_BASE, apiKey,
|
||
model: (opts && opts.model) || 'deepseek-v4-flash',
|
||
// deepseek-v4-flash 默认开启thinking mode,复杂输入会把整个max_tokens预算都花在推理链上,
|
||
// content留空、finish_reason变成length(就是"AI返回空响应"这个报错的根因)。这里都是纯
|
||
// 结构化提取/翻译任务,不需要推理,显式关掉thinking让token预算全部用来输出实际内容。
|
||
extraBody: { thinking: { type: 'disabled' } },
|
||
}, messages, opts);
|
||
}
|
||
|
||
// 用流式(stream)方式调用:DeepSeek 繁忙时请求会先排队,期间只发 keep-alive 空行、不出内容,
|
||
// 非流式调用根本分不清"在排队"还是"在生成",只能干等到超时。流式就能看到第一个字什么时候出来:
|
||
// firstTokenMs 内一个字都没出 → 判定为繁忙(e.slow),上层直接切换到备用服务商。
|
||
async function callLLM(provider, messages, opts) {
|
||
const { temperature = 0.7, timeoutMs = 120000, firstTokenMs = 60000 } = opts || {};
|
||
let maxTokens = (opts && opts.maxTokens) || 600;
|
||
if (provider.maxTokensCap) maxTokens = Math.min(maxTokens, provider.maxTokensCap);
|
||
const model = provider.model;
|
||
const label = provider.name;
|
||
const controller = new AbortController();
|
||
let abortReason = '';
|
||
const timer = setTimeout(() => { abortReason = 'total'; controller.abort(); }, timeoutMs);
|
||
let firstTimer = setTimeout(() => { abortReason = 'first'; controller.abort(); }, Math.min(firstTokenMs, timeoutMs));
|
||
const clearTimers = () => { clearTimeout(timer); if (firstTimer) clearTimeout(firstTimer); firstTimer = null; };
|
||
const startedAt = Date.now();
|
||
const abortError = () => {
|
||
if (abortReason === 'first') {
|
||
const e = new Error(`${label} ${Math.round(firstTokenMs / 1000)} 秒内没有开始输出(服务器繁忙在排队)`);
|
||
e.slow = true;
|
||
return e;
|
||
}
|
||
return new Error(`${label} 超过 ${Math.round(timeoutMs / 1000)} 秒没有返回结果,请重试`);
|
||
};
|
||
|
||
let content = '', finish = null, usage = null;
|
||
try {
|
||
const resp = await fetch(`${provider.base}/chat/completions`, {
|
||
signal: controller.signal,
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${provider.apiKey}` },
|
||
body: JSON.stringify({
|
||
model, messages, temperature, max_tokens: maxTokens,
|
||
stream: true, stream_options: { include_usage: true },
|
||
...(provider.extraBody || {}),
|
||
}),
|
||
});
|
||
if (!resp.ok) {
|
||
const errText = await resp.text().catch(() => '');
|
||
const err = new Error(`${label} API error ${resp.status}: ${errText.slice(0, 200)}`);
|
||
err.status = resp.status;
|
||
throw err;
|
||
}
|
||
const decoder = new TextDecoder();
|
||
let buf = '';
|
||
for await (const chunk of resp.body) {
|
||
buf += decoder.decode(chunk, { stream: true });
|
||
let nl;
|
||
while ((nl = buf.indexOf('\n')) >= 0) {
|
||
const line = buf.slice(0, nl).trim();
|
||
buf = buf.slice(nl + 1);
|
||
if (!line.startsWith('data:')) continue; // 空行、": keep-alive" 注释
|
||
const payload = line.slice(5).trim();
|
||
if (payload === '[DONE]') continue;
|
||
let j;
|
||
try { j = JSON.parse(payload); } catch (e) { continue; }
|
||
if (j.error) {
|
||
const err = new Error(`${label} API error: ${JSON.stringify(j.error).slice(0, 200)}`);
|
||
err.status = 503;
|
||
throw err;
|
||
}
|
||
if (j.usage) usage = j.usage;
|
||
const ch = j.choices && j.choices[0];
|
||
if (!ch) continue;
|
||
const piece = ch.delta && (ch.delta.content || ch.delta.reasoning_content);
|
||
if (piece && firstTimer) { clearTimeout(firstTimer); firstTimer = null; }
|
||
if (ch.delta && ch.delta.content) content += ch.delta.content;
|
||
if (ch.finish_reason) finish = ch.finish_reason;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
clearTimers();
|
||
if (e.name === 'AbortError' || controller.signal.aborted) throw abortError();
|
||
throw e;
|
||
}
|
||
clearTimers();
|
||
// 记录耗时和 token 用量,以后再遇到"很慢"可以直接在日志里看到原因
|
||
console.log(`[${label}] ${model} ${Math.round((Date.now() - startedAt) / 1000)}s, finish=${finish}, usage=${JSON.stringify(usage || {})}`);
|
||
if (!content) {
|
||
const reason = finish ? `(finish_reason: ${finish})` : '';
|
||
throw new Error(`${label} API returned an empty response${reason}`);
|
||
}
|
||
return content;
|
||
}
|
||
|
||
// 可以重试的错误:
|
||
// - 空响应(偶发,重试一次往往就好)
|
||
// - 服务器繁忙/临时故障:429 限流、500/502/503/504(DeepSeek 高峰期常见 "Service is too busy")
|
||
// - 网络瞬断(fetch failed / ECONNRESET)
|
||
// 其他错误(key不对、额度用完 401/402、超时)重试没用,直接抛出。
|
||
const LLM_BUSY_STATUS = new Set([429, 500, 502, 503, 504]);
|
||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
const isBusyError = (e) => LLM_BUSY_STATUS.has(e.status) || /fetch failed|ECONNRESET|ETIMEDOUT|socket hang up/i.test(e.message);
|
||
|
||
// 对单个服务商做"繁忙重试 + 空响应重试"
|
||
async function callWithRetries(provider, messages, opts, backoffs, emptyRetries) {
|
||
let busyTries = 0, emptyTries = 0, shrunk = false;
|
||
for (;;) {
|
||
try {
|
||
return await callLLM(provider, messages, opts);
|
||
} catch (e) {
|
||
if (e.slow) { e.busyExhausted = true; e.busyTries = busyTries; throw e; } // 排队太久:不再死等,交给上层切换
|
||
if (isBusyError(e)) {
|
||
if (busyTries >= backoffs.length) { e.busyExhausted = true; e.busyTries = busyTries; throw e; }
|
||
const wait = backoffs[busyTries++];
|
||
console.warn(`[${provider.name}] ${e.status || 'network'} 繁忙,${wait / 1000}s 后第 ${busyTries} 次重试`);
|
||
await sleep(wait);
|
||
continue;
|
||
}
|
||
// 阿里云:max_tokens 超过模型上限会报 400,降到 8192 再试一次
|
||
if (e.status === 400 && !shrunk && provider.maxTokensCap && /max_tokens|max_output|maximum/i.test(e.message)) {
|
||
shrunk = true;
|
||
provider = { ...provider, maxTokensCap: 8192 };
|
||
continue;
|
||
}
|
||
if (/empty response/i.test(e.message) && emptyTries < emptyRetries) { emptyTries++; continue; }
|
||
throw e;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 主力 DeepSeek,失败(繁忙/网络问题)时自动切到备用的阿里云。
|
||
// 名字保留 callDeepSeekWithRetry,所有调用方(目录导入、词汇翻译、网站翻译)都不用改。
|
||
// 熔断:DeepSeek 刚判定过繁忙,接下来 10 分钟内的请求直接走阿里云,不再每次先白等 DeepSeek
|
||
const DEEPSEEK_COOLDOWN_MS = 10 * 60 * 1000;
|
||
let deepseekBusyUntil = 0;
|
||
async function callDeepSeekWithRetry(apiKey, messages, opts, retries = 1) {
|
||
const { backup } = loadAiConfig();
|
||
const hasBackup = !!backup.apiKey;
|
||
if (!apiKey && hasBackup) return callWithRetries(aliyunProvider(backup), messages, opts, [3000, 8000], retries);
|
||
if (hasBackup && Date.now() < deepseekBusyUntil) {
|
||
console.log(`[AI] DeepSeek 最近繁忙,直接使用阿里云 ${backup.model}(${Math.round((deepseekBusyUntil - Date.now()) / 60000)} 分钟后再试 DeepSeek)`);
|
||
return callWithRetries(aliyunProvider(backup), messages, opts, [3000, 8000], retries);
|
||
}
|
||
// DeepSeek 正常时几秒内就会开始输出;有备用时只给它 20 秒,没备用时才耐心等 60 秒
|
||
const primaryOpts = { firstTokenMs: hasBackup ? 20000 : 60000, ...(opts || {}) };
|
||
const primary = { name: 'DeepSeek', base: DEEPSEEK_API_BASE, apiKey, model: (opts && opts.model) || 'deepseek-v4-flash', extraBody: { thinking: { type: 'disabled' } } };
|
||
try {
|
||
// 有备用时只重试一次就切换,不让用户干等;没备用时多重试几次
|
||
return await callWithRetries(primary, messages, primaryOpts, hasBackup ? [3000] : [3000, 8000, 15000], retries);
|
||
} catch (e) {
|
||
if (!(e.busyExhausted || (hasBackup && /empty response/i.test(e.message)))) throw e;
|
||
if (e.busyExhausted) deepseekBusyUntil = Date.now() + DEEPSEEK_COOLDOWN_MS;
|
||
if (!hasBackup) {
|
||
const fe = new Error(e.slow ? `${e.message}。请过几分钟再试;也可以在"设置"里配置备用的阿里云。` : `DeepSeek 服务器繁忙(${e.status || '网络错误'}),已自动重试 ${e.busyTries} 次仍失败。这是 DeepSeek 那边高峰期过载,请过几分钟再试;也可以在"设置"里配置备用的阿里云。`);
|
||
fe.status = e.status;
|
||
throw fe;
|
||
}
|
||
console.warn(`[AI] DeepSeek 不可用(${e.message.slice(0, 80)}),切换到阿里云 ${backup.model}`);
|
||
try {
|
||
return await callWithRetries(aliyunProvider(backup), messages, opts, [3000, 8000], retries);
|
||
} catch (e2) {
|
||
throw new Error(`DeepSeek 繁忙,备用的阿里云也失败了:${e2.message.slice(0, 200)}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 从DeepSeek返回的内容里提取JSON——模型有时会用```json代码块包一层,或者前后带几句解释文字,
|
||
// 这里做宽松解析:优先找代码块,找不到就找第一个 { 或 [ 开始的内容。
|
||
// 返回 { data, truncated }:如果完整JSON解析失败(常见原因是撞到了max_tokens,数组还没写完
|
||
// 就被截断了),会尝试抢救出前面已经完整生成的那些顶层对象,丢弃最后一个写了一半的,这样至少
|
||
// 能拿到部分结果,而不是整批因为最后一个字符缺失就全部作废。
|
||
function extractJson(content) {
|
||
const fenced = content.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
||
const raw = fenced ? fenced[1] : content;
|
||
const start = raw.search(/[\[{]/);
|
||
if (start === -1) throw new Error('AI返回内容里没有找到JSON');
|
||
const trimmed = raw.slice(start);
|
||
|
||
try {
|
||
return { data: JSON.parse(trimmed), truncated: false };
|
||
} catch (e) {
|
||
const salvaged = salvageTruncatedJsonArray(trimmed);
|
||
if (salvaged !== null) return { data: salvaged, truncated: true };
|
||
throw new Error(`AI返回的内容不是完整的JSON,解析失败:${e.message}`);
|
||
}
|
||
}
|
||
|
||
// 只处理"最外层是数组"的截断抢救:逐字符扫描(跳过字符串内部的引号/转义),每次遇到顶层元素
|
||
// 完整闭合(深度归零)就记一下位置,最后从抢救到的最后一个完整位置那里把数组截断重新拼上 ]。
|
||
function salvageTruncatedJsonArray(text) {
|
||
const t = text.trim();
|
||
if (!t.startsWith('[')) return null;
|
||
let depth = 0;
|
||
let lastCompleteEnd = -1;
|
||
let inString = false;
|
||
let escapeNext = false;
|
||
for (let i = 1; i < t.length; i++) {
|
||
const ch = t[i];
|
||
if (inString) {
|
||
if (escapeNext) escapeNext = false;
|
||
else if (ch === '\\') escapeNext = true;
|
||
else if (ch === '"') inString = false;
|
||
continue;
|
||
}
|
||
if (ch === '"') { inString = true; continue; }
|
||
if (ch === '{' || ch === '[') depth++;
|
||
else if (ch === '}' || ch === ']') {
|
||
depth--;
|
||
if (depth === 0 && ch === '}') lastCompleteEnd = i; // 顶层数组里某个对象完整闭合了
|
||
}
|
||
}
|
||
if (lastCompleteEnd === -1) return null;
|
||
try {
|
||
return JSON.parse(t.slice(0, lastCompleteEnd + 1) + ']');
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/* ------------------------------ data file ------------------------------ */
|
||
|
||
function readData() {
|
||
try {
|
||
return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
|
||
} catch (e) {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
// 自动备份:每次写入前,如果距离上次备份超过 1 小时,把当前 data.json 复制一份到 server/data-backups/,保留最近 168 份(约一周)
|
||
const BACKUP_DIR = path.join(__dirname, 'data-backups');
|
||
let lastBackupAt = 0;
|
||
function backupData(force) {
|
||
try {
|
||
if (!fs.existsSync(DATA_FILE)) return;
|
||
if (!force && Date.now() - lastBackupAt < 3600 * 1000) return;
|
||
fs.mkdirSync(BACKUP_DIR, { recursive: true });
|
||
const ts = new Date().toISOString().replace(/[:T]/g, '-').slice(0, 19);
|
||
fs.copyFileSync(DATA_FILE, path.join(BACKUP_DIR, `data-${ts}.json`));
|
||
lastBackupAt = Date.now();
|
||
const files = fs.readdirSync(BACKUP_DIR).filter(f => /^data-.*\.json$/.test(f)).sort();
|
||
for (const f of files.slice(0, Math.max(0, files.length - 168))) fs.unlinkSync(path.join(BACKUP_DIR, f));
|
||
} catch (e) { console.warn('[backup] 备份失败:', e.message); }
|
||
}
|
||
|
||
function writeData(data) {
|
||
backupData(false);
|
||
// write to a temp file then rename, avoids corrupting data.json if the
|
||
// process is killed mid-write
|
||
const tmp = DATA_FILE + '.tmp';
|
||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
|
||
fs.renameSync(tmp, DATA_FILE);
|
||
}
|
||
|
||
// only allow simple ids (our customer ids are like "c_169..._ab12c"),
|
||
// this keeps the upload path from ever escaping the uploads/ folder
|
||
function safeId(id) {
|
||
return /^[A-Za-z0-9_-]+$/.test(id) ? id : null;
|
||
}
|
||
|
||
/* --------------------------------- app ---------------------------------- */
|
||
|
||
const app = express();
|
||
|
||
// behind Nginx, Express needs this to read X-Forwarded-* correctly —
|
||
// otherwise req.ip is always Nginx's own address (breaks rate limiting)
|
||
// and the "secure" cookie flag can't tell the request was HTTPS.
|
||
app.set('trust proxy', 1);
|
||
|
||
app.use(express.json({ limit: '30mb' })); // 模板里的 HTML 片段可能嵌了图片,整份模板数据会比较大;Nginx 的 client_max_body_size 也要 ≥ 这个值
|
||
app.use(session({
|
||
secret: crypto.randomBytes(32).toString('hex'),
|
||
resave: false,
|
||
saveUninitialized: false,
|
||
cookie: {
|
||
httpOnly: true,
|
||
sameSite: 'lax',
|
||
secure: COOKIE_SECURE,
|
||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||
},
|
||
}));
|
||
|
||
function requireAuth(req, res, next) {
|
||
if (req.session && req.session.authed) return next();
|
||
res.status(401).json({ error: 'not authenticated' });
|
||
}
|
||
|
||
const loginLimiter = rateLimit({
|
||
windowMs: 15 * 60 * 1000,
|
||
max: 5,
|
||
standardHeaders: true,
|
||
legacyHeaders: false,
|
||
message: { error: 'too many login attempts, please try again in a few minutes' },
|
||
});
|
||
|
||
/* -------------------------------- auth api ------------------------------- */
|
||
|
||
app.post('/api/auth/login', loginLimiter, (req, res) => {
|
||
const body = req.body || {};
|
||
const username = body.username || '';
|
||
const password = body.password || '';
|
||
const auth = loadAuth();
|
||
if (username === auth.username && bcrypt.compareSync(password, auth.passwordHash)) {
|
||
req.session.authed = true;
|
||
req.session.username = username;
|
||
return res.json({ ok: true, username });
|
||
}
|
||
res.status(401).json({ error: 'invalid credentials' });
|
||
});
|
||
|
||
app.post('/api/auth/logout', (req, res) => {
|
||
if (req.session) {
|
||
req.session.destroy(() => res.json({ ok: true }));
|
||
} else {
|
||
res.json({ ok: true });
|
||
}
|
||
});
|
||
|
||
app.get('/api/auth/check', (req, res) => {
|
||
const authed = !!(req.session && req.session.authed);
|
||
res.json({ authed, username: authed ? req.session.username : null });
|
||
});
|
||
|
||
app.post('/api/auth/change-password', requireAuth, (req, res) => {
|
||
const body = req.body || {};
|
||
const currentPassword = body.currentPassword || '';
|
||
const newPassword = body.newPassword || '';
|
||
const auth = loadAuth();
|
||
if (!bcrypt.compareSync(currentPassword, auth.passwordHash)) {
|
||
return res.status(400).json({ error: 'current password is incorrect' });
|
||
}
|
||
if (newPassword.length < 4) {
|
||
return res.status(400).json({ error: 'new password is too short' });
|
||
}
|
||
auth.passwordHash = bcrypt.hashSync(newPassword, 10);
|
||
saveAuth(auth);
|
||
res.json({ ok: true });
|
||
});
|
||
|
||
/* ------------------------------ 模板:单个保存 ------------------------------ */
|
||
// 网站详情模板(crm:webDetailTemplates)一个一个保存:只发改动的那个模板,不再每次上传全部模板
|
||
// (全部模板加起来可能很大,以前整份上传时容易被 Nginx 的大小限制拦下,后面的修改就都存不上)
|
||
const TPL_KEY = 'crm:webDetailTemplates';
|
||
// 网站相关的数据(产品、模板、箱规、网站图片、近期动态)改动后通知 public-api:停手 3 分钟后自动同步并更新网站(public-api 挂载后才有)
|
||
let onTemplatesChanged = () => {};
|
||
const SITE_DATA_KEYS = new Set(['crm:products', 'crm:webPackSpecs', 'crm:webAssets', 'crm:webNews']);
|
||
const parseList = (v) => { try { const x = typeof v === 'string' ? JSON.parse(v) : v; return Array.isArray(x) ? x : []; } catch (e) { return []; } };
|
||
function saveTplList(data, list) {
|
||
data[TPL_KEY] = JSON.stringify(list);
|
||
const v = data.__versions || (data.__versions = {});
|
||
v[TPL_KEY] = (v[TPL_KEY] || 0) + 1;
|
||
}
|
||
app.put('/api/templates/:id', requireAuth, (req, res) => {
|
||
const id = safeId(req.params.id);
|
||
const t = req.body && req.body.value;
|
||
if (!id || !t || typeof t !== 'object' || t.id !== id) return res.status(400).json({ error: 'invalid template' });
|
||
const data = readData();
|
||
const list = parseList(data[TPL_KEY]);
|
||
const i = list.findIndex((x) => x && x.id === id);
|
||
if (i >= 0) list[i] = t;
|
||
else {
|
||
// 新模板按页面上的位置插入(复制模板时排在原模板后面)
|
||
const at = Number.isInteger(req.body.index) ? Math.min(Math.max(0, req.body.index), list.length) : list.length;
|
||
list.splice(at, 0, t);
|
||
}
|
||
saveTplList(data, list);
|
||
writeData(data);
|
||
onTemplatesChanged();
|
||
res.json({ ok: true });
|
||
});
|
||
app.delete('/api/templates/:id', requireAuth, (req, res) => {
|
||
const id = safeId(req.params.id);
|
||
if (!id) return res.status(400).json({ error: 'invalid id' });
|
||
const data = readData();
|
||
const list = parseList(data[TPL_KEY]);
|
||
const next = list.filter((x) => !(x && x.id === id));
|
||
if (next.length !== list.length) { saveTplList(data, next); writeData(data); onTemplatesChanged(); }
|
||
res.json({ ok: true });
|
||
});
|
||
|
||
/* ------------------------------ storage api ------------------------------ */
|
||
|
||
app.get('/api/storage/:key', requireAuth, (req, res) => {
|
||
const data = readData();
|
||
const key = req.params.key;
|
||
const version = (data.__versions && data.__versions[key]) || 0;
|
||
if (!(key in data)) return res.status(404).json({ error: 'not found', version });
|
||
res.json({ value: data[key], version });
|
||
});
|
||
|
||
// 防误清空:列表类数据(客户、产品等)一次从 ≥3 条变成 0 条,或者少掉八成以上,拒绝保存(多半是页面没读到数据就自动保存了)。
|
||
// 真要一次删很多,请求头带 x-allow-shrink: 1。
|
||
const listLen = (v) => { try { const x = typeof v === 'string' ? JSON.parse(v) : v; return Array.isArray(x) ? x.length : -1; } catch (e) { return -1; } };
|
||
// 版本号:每个键保存一次加 1。页面保存时带上它读到的版本(baseVersion),
|
||
// 对不上说明这份数据已经被别的页面 / 设备改过,拒绝覆盖(409 conflict),页面提示刷新。
|
||
app.put('/api/storage/:key', requireAuth, (req, res) => {
|
||
const data = readData();
|
||
const key = req.params.key;
|
||
if (key === '__versions') return res.status(400).json({ error: 'reserved key' });
|
||
const versions = data.__versions || (data.__versions = {});
|
||
const current = versions[key] || 0;
|
||
if (req.body.baseVersion !== undefined && req.body.baseVersion !== null && Number(req.body.baseVersion) !== current) {
|
||
console.warn(`[storage] 版本冲突 ${key}:页面版本 ${req.body.baseVersion},服务器版本 ${current}`);
|
||
return res.status(409).json({ error: 'conflict', conflict: true, version: current });
|
||
}
|
||
const before = listLen(data[req.params.key]);
|
||
const after = listLen(req.body.value);
|
||
if (before >= 3 && after >= 0 && (after === 0 || after < before * 0.2) && req.get('x-allow-shrink') !== '1') {
|
||
console.warn(`[storage] 拒绝保存 ${req.params.key}:${before} 条 → ${after} 条(疑似误清空)`);
|
||
backupData(true);
|
||
return res.status(409).json({ error: `refused: ${req.params.key} would shrink from ${before} to ${after}` });
|
||
}
|
||
data[key] = req.body.value;
|
||
versions[key] = current + 1;
|
||
writeData(data);
|
||
if (SITE_DATA_KEYS.has(key)) onTemplatesChanged();
|
||
res.json({ ok: true, version: versions[key] });
|
||
});
|
||
|
||
/* --------------------------------- ai api --------------------------------- */
|
||
|
||
app.get('/api/ai-config', requireAuth, (req, res) => {
|
||
const cfg = loadAiConfig();
|
||
res.json({ hasKey: !!cfg.apiKey, backup: { hasKey: !!cfg.backup.apiKey, model: cfg.backup.model, region: cfg.backup.region } });
|
||
});
|
||
|
||
app.put('/api/ai-config', requireAuth, (req, res) => {
|
||
const apiKey = ((req.body && req.body.apiKey) || '').trim();
|
||
if (!apiKey) return res.status(400).json({ error: 'apiKey is required' });
|
||
saveAiConfig(apiKey);
|
||
res.json({ ok: true });
|
||
});
|
||
|
||
app.delete('/api/ai-config', requireAuth, (req, res) => {
|
||
const raw = readAiConfigRaw();
|
||
delete raw.apiKeyEnc; // 只清 DeepSeek 的 Key,备用阿里云的配置保留
|
||
writeAiConfigRaw(raw);
|
||
res.json({ ok: true });
|
||
});
|
||
|
||
// 备用服务商(阿里云百炼):Key 可留空表示只改模型/地域
|
||
app.put('/api/ai-config/backup', requireAuth, (req, res) => {
|
||
const b = req.body || {};
|
||
const raw = readAiConfigRaw();
|
||
const key = String(b.apiKey || '').trim();
|
||
if (key) raw.backupKeyEnc = encrypt(key);
|
||
if (!raw.backupKeyEnc) return res.status(400).json({ error: 'apiKey is required' });
|
||
const model = String(b.model || '').trim();
|
||
if (model && !/^[\w.\-]{1,64}$/.test(model)) return res.status(400).json({ error: 'invalid model' });
|
||
raw.backupModel = model || ALIYUN_DEFAULT_MODEL;
|
||
raw.backupRegion = b.region === 'intl' ? 'intl' : 'cn';
|
||
writeAiConfigRaw(raw);
|
||
res.json({ ok: true });
|
||
});
|
||
app.delete('/api/ai-config/backup', requireAuth, (req, res) => {
|
||
const raw = readAiConfigRaw();
|
||
delete raw.backupKeyEnc; delete raw.backupModel; delete raw.backupRegion;
|
||
writeAiConfigRaw(raw);
|
||
res.json({ ok: true });
|
||
});
|
||
app.post('/api/ai-config/backup/test', requireAuth, async (req, res) => {
|
||
const { backup } = loadAiConfig();
|
||
if (!backup.apiKey) return res.status(400).json({ error: 'no backup key configured' });
|
||
try {
|
||
const content = await callLLM(aliyunProvider(backup), [{ role: 'user', content: 'Reply with exactly: OK' }], { maxTokens: 20, timeoutMs: 30000 });
|
||
res.json({ ok: true, reply: content.trim() });
|
||
} catch (e) {
|
||
res.status(400).json({ error: e.message });
|
||
}
|
||
});
|
||
|
||
app.post('/api/ai-config/test', requireAuth, async (req, res) => {
|
||
const cfg = loadAiConfig();
|
||
if (!cfg.apiKey) return res.status(400).json({ error: 'no API key configured' });
|
||
try {
|
||
const content = await callDeepSeek(cfg.apiKey, [{ role: 'user', content: 'Reply with exactly: OK' }]);
|
||
res.json({ ok: true, reply: content.trim() });
|
||
} catch (e) {
|
||
res.status(400).json({ error: e.message });
|
||
}
|
||
});
|
||
|
||
const aiLimiter = rateLimit({
|
||
windowMs: 10 * 60 * 1000,
|
||
max: 30,
|
||
standardHeaders: true,
|
||
legacyHeaders: false,
|
||
message: { error: 'too many AI requests, please slow down' },
|
||
});
|
||
|
||
/* --------------------------- ai catalog import --------------------------- */
|
||
// 上传一份/多份PDF或图片形式的产品目录(可能包含多个型号),做OCR文字识别后交给
|
||
// DeepSeek解析成结构化的产品字段数组,前端拿到后先给用户一个预览/确认页面,
|
||
// 用户确认后再批量建档。
|
||
//
|
||
// 实测发现很多正式排版的产品目录PDF(比如设计软件导出的宣传册)整页都是图片/矢量
|
||
// 图形,没有可提取的文字层,所以这里统一走"渲染成图片 + OCR"这条路,而不是直接
|
||
// 提取PDF文字——这样PDF和图片两种输入方式可以复用同一套OCR逻辑。
|
||
//
|
||
// 依赖:
|
||
// 1. npm包 tesseract.js(纯JS+WASM,不需要装系统级OCR程序,但第一次识别时会从
|
||
// jsdelivr CDN下载语言包,VPS需要能访问外网)
|
||
// 2. 系统程序 poppler-utils,只有上传PDF时才需要,用来把PDF每页渲染成图片:
|
||
// apt install -y poppler-utils
|
||
|
||
const { execFile } = require('child_process');
|
||
const Tesseract = require('tesseract.js');
|
||
|
||
const uploadMemory = multer({
|
||
storage: multer.memoryStorage(),
|
||
limits: { files: 30 }, // 不限制单文件大小;最多30个文件(AI批量解析成本考虑,数量上限保留)
|
||
});
|
||
|
||
// 把一份PDF的每一页渲染成PNG图片(用poppler-utils的pdftoppm),返回图片路径数组
|
||
function renderPdfToImages(pdfBuffer, tmpDir) {
|
||
return new Promise((resolve, reject) => {
|
||
const pdfPath = path.join(tmpDir, 'source.pdf');
|
||
fs.writeFileSync(pdfPath, pdfBuffer);
|
||
const outPrefix = path.join(tmpDir, 'page');
|
||
execFile('pdftoppm', ['-png', '-r', '200', pdfPath, outPrefix], (err) => {
|
||
if (err) {
|
||
return reject(new Error(
|
||
`PDF转图片失败,请确认服务器已安装 poppler-utils(SSH执行:apt install -y poppler-utils):${err.message}`
|
||
));
|
||
}
|
||
const files = fs.readdirSync(tmpDir)
|
||
.filter((f) => f.startsWith('page') && f.endsWith('.png'))
|
||
.sort()
|
||
.map((f) => path.join(tmpDir, f));
|
||
resolve(files);
|
||
});
|
||
});
|
||
}
|
||
|
||
// PDF 自带文字层(WPS / Word 导出的规格书都有):直接取文字比 OCR 准得多(数字、小数点、Ω、℃、± 不会认错,也不会漏行)。
|
||
// 扫描件没有文字层、或者字体映射坏了取出来是乱码,就返回空字符串,调用方回退到 OCR。
|
||
function pdfTextLayer(pdfBuffer, tmpDir) {
|
||
return new Promise((resolve) => {
|
||
const pdfPath = path.join(tmpDir, 'text-source.pdf');
|
||
try { fs.writeFileSync(pdfPath, pdfBuffer); } catch (e) { return resolve(''); }
|
||
execFile('pdftotext', ['-layout', '-enc', 'UTF-8', pdfPath, '-'], { maxBuffer: 20 * 1024 * 1024, timeout: 60000 }, (err, out) => {
|
||
if (err) return resolve('');
|
||
const t = String(out || '').replace(/\f/g, '\n\n--- 下一页 ---\n\n').replace(/[ \t]+$/gm, '').replace(/\n{4,}/g, '\n\n\n').trim();
|
||
const vis = t.replace(/\s/g, '');
|
||
if (vis.length < 80) return resolve('');
|
||
const bad = (vis.match(/[\uFFFD\uE000-\uF8FF]/g) || []).length;
|
||
const good = (vis.match(/[\u4e00-\u9fffA-Za-z0-9]/g) || []).length;
|
||
resolve(bad / vis.length > 0.03 || good / vis.length < 0.5 ? '' : t);
|
||
});
|
||
});
|
||
}
|
||
|
||
// 导入后的漏行检查(只在"一个 PDF 文字层 → 一个产品"时做):把文字层里"参数名 数值"这种行逐行拿出来,
|
||
// 数值在 AI 输出里找不到的,原样补进 extraSpecs(参数名照抄原文)。AI 偶尔会漏掉几行(比如浮充电压、参考内阻),这里兜底。
|
||
const normSpec = (x) => String(x || '').toLowerCase().replace(/\s+/g, '').replace(/(/g, '(').replace(/)/g, ')').replace(/[~〜]/g, '~').replace(/:/g, ':').replace(/,/g, ',');
|
||
function specLinesFromLayout(layout) {
|
||
const rows = [];
|
||
for (const line of String(layout || '').split('\n')) {
|
||
const cells = line.trim().split(/\s{2,}/);
|
||
if (cells.length < 2) continue;
|
||
const label = cells[0].trim(), value = cells[1].trim();
|
||
if (!/^[\u4e00-\u9fff][\u4e00-\u9fffA-Za-z()()*\/·\s]{1,24}$/.test(label) || /\d/.test(label)) continue;
|
||
if (!/\d/.test(value)) continue;
|
||
rows.push({ label: label.replace(/\s+/g, ''), value });
|
||
}
|
||
return rows;
|
||
}
|
||
function fillMissingSpecRows(product, layout) {
|
||
const vals = [];
|
||
const walk = (v) => { if (v == null) return; if (typeof v === 'string' || typeof v === 'number') vals.push(String(v)); else if (Array.isArray(v)) v.forEach(walk); else if (typeof v === 'object') Object.values(v).forEach(walk); };
|
||
walk(product);
|
||
const dump = normSpec(vals.join(' | '));
|
||
const has = (v) => {
|
||
if (dump.includes(normSpec(v))) return true;
|
||
const n = (String(v).match(/\d+(?:\.\d+)?/) || [])[0];
|
||
if (!n) return true;
|
||
return new RegExp('(^|[^\\d.])' + n.replace('.', '\\.') + '(?![\\d.])').test(dump);
|
||
};
|
||
const added = [];
|
||
for (const r of specLinesFromLayout(layout)) {
|
||
if (has(r.value)) continue;
|
||
if ((product.extraSpecs || []).some((x) => normSpec(x.label) === normSpec(r.label))) continue;
|
||
product.extraSpecs = [...(Array.isArray(product.extraSpecs) ? product.extraSpecs : []), { label: r.label, value: r.value, afterLabel: '' }];
|
||
added.push(`${r.label}=${r.value}`);
|
||
}
|
||
return added;
|
||
}
|
||
|
||
// 复用同一个OCR worker,避免每次请求都重新初始化/重新下载语言包
|
||
let ocrWorkerPromise = null;
|
||
function getOcrWorker() {
|
||
if (!ocrWorkerPromise) {
|
||
ocrWorkerPromise = Tesseract.createWorker('eng+chi_sim').catch((e) => {
|
||
ocrWorkerPromise = null; // 初始化失败下次重试,不要把失败结果缓存住
|
||
throw e;
|
||
});
|
||
}
|
||
return ocrWorkerPromise;
|
||
}
|
||
|
||
async function ocrImages(imagePaths) {
|
||
const worker = await getOcrWorker();
|
||
const parts = [];
|
||
for (const p of imagePaths) {
|
||
const { data } = await worker.recognize(p);
|
||
if (data && data.text) parts.push(data.text.trim());
|
||
}
|
||
return parts.join('\n\n--- 下一页 ---\n\n').trim();
|
||
}
|
||
|
||
const CATALOG_PARSE_SYSTEM_PROMPT = `你是一个电力设备(UPS/逆变器/储能电池等)产品资料的结构化提取助手。
|
||
用户会给你一份产品目录/规格书经OCR识别出的文字内容(可能包含多个不同型号的产品,每个产品通常有自己的Specifications表格;
|
||
OCR识别可能有少量错字或格式错乱,请结合上下文合理判断)。
|
||
你的任务:识别文本里有几个不同型号的产品,为每一个产品提取字段,严格按下面的JSON schema输出一个数组,每个元素是一个产品对象:
|
||
|
||
【特别注意"系列名"和"具体型号"的区别】很多规格表会在标题里写"XX系列智能在线式UPS"这种大标题(这是整个系列的统称,
|
||
不是某个产品的型号),真正的具体型号一定在表格里"型号"那一行/列里能找到(比如ATP-10K/CRT、ATP-20K/CRT这种)。
|
||
绝对不能把标题里的系列泛称当成name字段的值去输出一条"合并"的记录——表格里"型号"那一行有几个不同的型号名称,
|
||
就必须输出几条独立的产品记录,哪怕它们之间只有额定功率/尺寸/净重这几个数字不一样、其他参数全部相同,也不能因为
|
||
"看起来很像"就合并成一条、更不能因为拿不准就用系列名代替。如果OCR识别出来的文字比较模糊、型号名称对不齐对应的
|
||
数值,宁可把能确定的字段填全、拿不准的字段留空,也不要瞎猜合并。
|
||
|
||
【特别注意"型号(L)"这种带括号的写法】规格表的型号列里如果出现类似"MS1000(L)"这种写法,代表这里其实是两个型号,
|
||
要拆成两条独立的产品记录输出,不能只输出一条:
|
||
- 不带L后缀的(如MS1000)是标准机型:machineVariant填"标准机型"
|
||
- 带L后缀的(如MS1000L)是长延时机型:machineVariant填"长延时机型"
|
||
这两条记录的输入/输出/保护/警告/接口/环境这些参数完全共用同一份数据,只有 batterySpec(电池型号和数量)、
|
||
chargeCurrent(充电电流)、dimensions(尺寸)、netWeight(净重)这几项不同——严格按表格里"Standard Model/标准机型"
|
||
和"Long-run Model/长延机型"这两个子分类去分别取值,标准机型用Standard Model那部分数据,长延时机型用Long-run Model那部分数据。
|
||
如果某个型号在"Standard Model"部分对应列是NA或空、只有"Long-run Model"部分有数据,说明这个型号本身就是长延机型
|
||
(哪怕名字里没有明显的"(L)"标记也一样),直接当长延时机型处理,不要再凭空拆出一个去掉后缀的"标准版";反过来如果只有
|
||
"Standard Model"部分有数据、"Long-run Model"部分是NA或空,说明这个型号只有标准机型,也不要凭空造一个带L的长延版本。
|
||
|
||
【特别注意多型号规格对比表】有些规格表把好几个型号(比如1200/1600/2200/3000)放在同一张表里,
|
||
每一行参数对应多个型号列,但不是每个参数都是"一型号一个值"——有些参数(比如输入电压、频率范围)
|
||
全系列共用同一个值,直接抄给每个型号;但有些参数(比如尺寸、净重、电池型号和数量)会因为型号不同
|
||
分成几组不同的值(比如1200/1600/2200共用一组尺寸,3000单独一组),这种情况必须先看清楚该行数值
|
||
和哪几个型号对齐,再把正确的那组数值填到对应型号的记录里,不能所有型号都填同一个值、也不能填错组。
|
||
|
||
【特别注意不要丢弃"认不出属于哪个字段"的参数】上面这个JSON schema列出的都是已知产品类型常见的具名字段,但不同品牌、不同版本的规格表经常会出现一些没有被收录进这个schema的参数
|
||
(比如"浮充电压"这种字段)。只要原文规格表里出现了某一行参数、但左侧标签在下面schema里找不到任何一个匹配的具名字段(也不属于机型拆分/两段式结构那些已经处理过的特殊情况),
|
||
绝对不能因为"没地方放"就把这行数据丢弃——把这一行的参数填进 extraSpecs 数组里,格式为 {"label":"浮充电压","value":"13.7VDC/节","afterLabel":"充电时间"},
|
||
其中 label 必须是**中文**(跟上面所有具名字段的标签一样,不管原文表格里这行的标签本来是中文、英文还是其他语言,都要翻译/转换成简体中文行业规范书面用词,
|
||
不要逐字直译成生硬的中文,要符合电力设备行业书面表述习惯),value 保持和原文完全一致、不要翻译(数值、单位、型号这些内容原样抄,翻译反而容易出错或丢失准确性)。
|
||
表格里有几行匹配不上具名字段,就填几条。其中 afterLabel 是这条参数在原文表格里紧挨着的上一行对应的**已知具名字段的中文标签**(比如这条"浮充电压"在原文里排在"充电时间"上面,
|
||
就填"充电时间";如果紧挨着的上一行同样是个不认识的参数,就沿着原文往上找,直到找到一个能对应上schema里具名字段的中文标签为止;实在找不到(比如这条参数在原文表格最开头)就填空字符串,
|
||
这种情况显示时会自动排在最后)。注意:如果某一行明明能对应上面某个具名字段(比如"20尺柜"对应container20ft),必须优先填那个具名字段,
|
||
不要重复放进extraSpecs;只有真的找不到对应具名字段的参数才放进extraSpecs。
|
||
|
||
【特别注意保留原文的参数名称和限定词】原文是中文的,extraSpecs 的 label 一字不改照抄原文左侧的参数名(去掉空格即可),
|
||
不要缩写、不要换成近义词:比如"参考内阻"不能写成"内阻","月自放电率"不能写成"自放电率","最大持续放电电流"不能写成"最大放电电流",
|
||
"壳体材料"不能写成"外壳材质","尺寸(长*宽*高*总高)"不能写成"尺寸"。数值连同括号里的条件、公差一起照抄(比如"7.3Kg(1±3%)"、"13mΩ(25°,满荷电)"、"2%(20℃)")。
|
||
如果某一行填进了具名字段,而具名字段的中文名比原文少了限定词(月、持续、参考、峰值、总高等),把限定信息写进数值里,
|
||
比如原文"月自放电率 2%(20℃)"填 selfDischargeRate 时写"2%/月(20℃)"。
|
||
原文规格参数表里的每一行都必须出现在输出里(具名字段或 extraSpecs 二选一),输出前逐行对照原文检查一遍,不能漏行。
|
||
|
||
【特别注意装箱数量容易被漏填】规格表如果出现"20尺柜/40尺柜/40高柜"这几行(通常在表格最下方,标注每种柜型能装多少台,如"1000PCS(无栈板)"),
|
||
必须提取到 container20ft / container40ft / container40hq 这三个字段里,不能因为在整个schema里排得靠后就跳过——
|
||
提取完所有字段后,回头检查一遍原文里是否出现过"尺柜"或"PCS"这类字样,如果出现了但container20ft/container40ft/container40hq
|
||
还是空的,说明漏填了,要补上。
|
||
|
||
【特别注意"UPS配套锂电池系统"这类产品的两段式结构】这类产品(储能电池大类下)的规格表通常明确分成两个区域,
|
||
一个是"模块/Module"(单个电池模块本身的参数),一个是"锂电池系统柜/电池系统柜"(整个机柜/整套系统的参数),
|
||
跟模块化UPS"功率模块 + UPS机柜"是同样的两段式逻辑。这两个区域各自包含好几项参数,请务必把两个区域的每一项
|
||
都完整提取,绝对不能只提取其中一个区域、漏掉另一个区域——常见的漏提取情况是:只填了型号/循环寿命/通信接口/
|
||
保护功能这种"看起来一目了然"的字段,却漏掉了电芯类型、放电倍率、充电倍率、模块最大能量、模块输出功率、
|
||
模块尺寸、模块重量这些"模块"区域的参数,或者漏掉了电池最大能量、运行温度、相对湿度、颜色、系统柜尺寸、
|
||
系统柜重量、海拔、自放电率这些"锂电池系统柜"区域的参数。提取完之后自己检查一遍:below schema里所有标注了
|
||
"储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用)"的字段,只要OCR文字里出现了对应的数值,就必须填上,不能遗漏。
|
||
|
||
【不是所有储能电池产品都有这种两段式结构】如果规格表本身就是单层的(比如整机就是一个电池包/电池柜,没有再往下拆分成"模块"和"系统柜"两级,
|
||
常见于机架式电池、单体电池包这类产品),不要硬套两段式——直接把整机的容量、电压、尺寸、重量等参数填进moduleCapacity/moduleVoltage/
|
||
moduleDimensions/moduleWeight这组字段里就行,cabinetXxx那组(cabinetMaxEnergy/cabinetRatedVoltage/cabinetDimensions/cabinetWeight)
|
||
留空,不用为了凑两级结构而重复填一遍或瞎编。
|
||
|
||
【特别注意表头里"一个型号分成几个子列"的写法】有些规格表的型号行里,一个型号用 colspan 横跨好几列,下一行再把它分成几个子列
|
||
(比如按电池数量分成"2 batt. / 4 batt. / 6 batt.",或按电池容量、配置分成几列),每个子列下面的电池数量、电池容量、重量等数值不同。
|
||
这种情况一个型号只输出一条产品记录(name 就是型号本身,比如"C1K-Pro",不要加子列标签,也不要拆成几条):
|
||
- 这个型号所有子列共用的参数(功率、输入输出、尺寸等跨子列合并的单元格)照常填写;
|
||
- 各子列数值不同的参数,按从左到右的子列顺序用"/"合并成一个值,并在后面括号注明子列含义,比如电池数量填"2/4/6节"、
|
||
电池容量填"1792/3584/5376Wh(2/4/6节)"、净重填"28/38.5/49(2/4/6节)";只有一个子列的型号直接填那个值(比如 C3K-Pro 只有 6 节,就填"6节"、"5376Wh"、"52")。
|
||
数清楚每个型号下面有几个子列,按顺序对齐每一行的数值,不要错位,也不要把别的型号的子列数值合并进来。
|
||
|
||
{
|
||
"name": "型号,比如 POE-532E",
|
||
"brand": "品牌中文名,从厂家名称/logo文字判断;看不出就填空字符串",
|
||
"category": "产品大类中文名,从这些里选最接近的:UPS不间断电源 / 光伏逆变器 / 储能电池;不确定就填 UPS不间断电源",
|
||
"type": "细分品类中文名。如果是这种带USB/DC/POE多路直流输出口的小型UPS,填 迷你UPS;如果是没有LCD/LED显示、简单的家用小型UPS(型号通常带Offline/后备式字样),填 离线式UPS;如果是这种离线式/后备式UPS但电池是锂电池(Lithium-ion、LiFePO4、锂电、磷酸铁锂),填 离线式锂电UPS;如果标注了Line-Interactive/互动式,填 在线互动式UPS;如果是True double-conversion/真双变换在线式且明确标注了机架安装、2U/3U/4U这种机架单位、rack-mount字样,填 机架式UPS;如果是同样的机架式在线UPS,但电池是锂电池(Lithium-ion、LiFePO4、锂电、磷酸铁锂),填 机架式锂电UPS;如果同样是True double-conversion/真双变换在线式,但看起来是塔式/立式外观(没有明确的机架安装标注),填 在线式高频UPS;这两个类型区分不确定的话,优先填 在线式高频UPS,用户在确认预览阶段还可以手动改;如果是在线式UPS且锂电池内置在UPS机身里、电池节数可选(比如\"All-in-One\"、\"Lithium battery built in\"、\"Scalable battery count\"、同一型号有2/4/6节电池几种配置),填 一体式锂电UPS;如果产品大类是储能电池,且是挂墙安装的锂电池(Wall-mounted / Powerwall),填 壁挂式锂电池;如果是落地放置、带轮子或立式的家用锂电池包(Floor-mounted / Floor-standing / 带滚轮),填 落地式锂电池;如果是高压(额定电压一两百伏以上,比如 204.8V、409.6V)的机柜式磷酸铁锂电池(Cabinet LiFePO4 Battery、按 U 数标机柜尺寸、给 UPS 或高压逆变器用),填 磷酸铁锂储能柜;如果是 12.8V / 25.6V / 51.2V 的磷酸铁锂电池、用来直接替换铅酸电池(Lead-Acid Replacement / Drop-in,型号像 12V7AH、24V100AH),填 锂电替换铅酸电池,并且 name 前面加 LFP- 前缀(比如 12V7AH 写成 LFP-12V7AH,原型号已经有 LFP 前缀的不要重复加;LFP 是磷酸铁锂的意思,只有这一类锂电池加,铅酸电池和其他任何产品都绝对不能加 LFP- 前缀);如果是 12V(或 6V、2V)阀控式铅酸蓄电池(VRLA、AGM、GEL 胶体、Lead Acid、阀控式密封铅酸蓄电池、固定型免维护蓄电池,型号像 SK100-12、SK250-12v、6-GFM-100),填 铅酸电池(用户已经预选了细分品类、且名字里带 铅酸 / 蓄电池 / VRLA / AGM / 胶体 / 阀控 的,比如"AGM阀控密封式免维护铅酸蓄电池",type 照用户预选的写,但下面这些铅酸电池规则同样全部适用),并且:moduleVoltage 填额定电压数字(如 12),moduleCapacity 填规格表的额定容量 Ah 数字(如 250,不要用 20HR 实测的 261.8 这种),moduleDimensions 填 长*宽*高*总高 的数字(如 520*269*220*224,不带单位),moduleWeight 填重量数字并保留原文括号里的公差(如 7.3(1±3%),不带 Kg),cycleLife 有循环寿命就填;铅酸电池除了这四项和 cycleLife 以外,规格参数表里的其他每一行(参考内阻、运行温度范围、温度对容量的影响、浮充电压、循环使用充电电压、温度补偿系数、最大充电电流、最大持续放电电流、月自放电率、端子、壳体材料等)一律放进 extraSpecs,label 照抄原文参数名、按原文顺序排列、afterLabel 填空字符串,不要填进 selfDischargeRate / maxDischargeCurrent / maxChargingCurrent / shellMaterial / operatingTemp 这些具名字段;放电表按 extraSpecs 字段说明里的【铅酸电池】要求填;如果是电池和逆变器做在一起的家用储能一体机(All-in-One ESS、Battery + inverter integrated),挂墙安装的(Wall-Mounted)填 壁挂式储能一体机,落地放置的(Floor-Standing)填 落地式储能一体机,工商业户外储能柜(C&I Outdoor ESS Cabinet,电池 + PCS 一体、IP54、交流功率几十到上百 kW):风冷(Air-Cooled)填 风冷工商业储能柜,液冷(Liquid-Cooled)填 液冷工商业储能柜,交流功率填 ratedPower(单位 kW),电池容量填 moduleMaxEnergy,光伏 DC-DC 和 STS 的参数放 extraSpecs(不支持的写 /);逆变器主机加一层层电池模块堆叠的(Stacked All-in-One ESS):高压电池(一两百伏以上)填 高压堆叠式储能一体机,低压电池(51.2V)填 低压堆叠式储能一体机,name 照规格表里的型号写(比如 2.5kWh + 3kW),逆变器功率填 ratedPower(单位 kW)、电池能量填 moduleMaxEnergy;如果产品大类是储能电池,且规格表明确分成"模块"和"电池系统柜/电池柜"两级、给UPS配套用的中大功率锂电池系统,填 UPS配套锂电池系统;如果产品大类是储能电池,且规格表里同时出现了电池参数(容量/电压/循环寿命等)和逆变器/充电器参数(太阳能充电器MPPT、交流充电、峰值功率、负载电压等),是电池和逆变器/充电控制器做在一起的家用一体机,填 家庭储能系统;如果产品大类是光伏逆变器,且明确标注了Hybrid/On-Off-Grid/混网/既能并网又能离网这种既能接市电又能脱网独立供电的能力(通常还带电池输入参数),填 太阳能混网逆变器;储能电池大类下其他常见值:铅酸电池、磷酸铁锂电池;光伏逆变器大类下其他常见值:并网/离网逆变器;UPS不间断电源大类下其他常见值:高频塔式UPS、工频UPS、模块化UPS(立式机柜,插功率模块)、机架式模块化UPS(19英寸机架安装的模块化UPS,标注了2U/3U/4U/6U这种机架单位或rack-mount,插功率模块);不确定就留空字符串",
|
||
"machineVariant": "标准机型 或 长延时机型:按前面【型号(L)拆分规则】判断,标准机型(内置电池)填\"标准机型\",长延时机型(外接电池,通常型号带L后缀)填\"长延时机型\";不属于这种拆分场景的常规产品,按容量(Capacity)判断——容量超过10KVA的默认填\"长延时机型\"(10KVA以上的UPS机型基本都是外接电池、不含内置电池了);容量在10KVA以内、或者看不出容量,才默认填\"标准机型\"",
|
||
"powerOrCapacity": "功率/容量;如果是迷你UPS,这里填输出功率(如 17W);如果是UPS不间断电源大类下的其他细分品类(离线式UPS/离线式锂电UPS/在线互动式UPS/机架式UPS/在线式高频UPS/工频UPS/高频塔式UPS/模块化UPS,以及以后系统里新增的其他细分品类),这里填Capacity/容量,\n 格式统一成\"kVA数值/kW数值\"(如 250KVA/200KW):原文如果已经配套给出了kVA和kW两个数值(比如\"60KVA/48KW\"或者两行分别写VA和W),直接按原文两个数值拼成这个格式;\n 如果原文只给了kVA(比如\"Rated Capacity: 250KVA\"),要去规格表里找Output Power Factor/负载功率因数/输出功率因数这一项(哪怕它属于别的字段比如outputPowerFactor对应的那一行),\n 用 kVA数值 × 功率因数 算出kW数值(比如250KVA×0.8=200KW),四舍五入到整数,拼成\"250KVA/200KW\"这样的组合字符串;如果原文既没给kW、也找不到功率因数算不出来,就只填kVA部分(如\"250KVA\");\n 其他情况不确定就填空字符串",
|
||
"voltage": "如果是迷你UPS,这里填输入电压,如 100~240Vac/50-60Hz;如果是离线式UPS/离线式锂电UPS/在线互动式UPS/机架式UPS,这个字段不用填(用下面的inputVoltage/outputVoltage代替);其他情况填常规电压参数,不确定填空字符串",
|
||
"ratedPower": "", "ratedPowerUnit": "VA", "powerFactor": "",
|
||
"outputPortCount": "迷你UPS专属:这个型号有几路输出口,数字字符串,如 4,不适用就填空字符串",
|
||
"outputPortTypes": "迷你UPS专属:输出口类型数组,只能用这些token:USB、DC、DC1、DC2、DC3、POE、Type-C、DC interface、POE interface;不适用就填空数组",
|
||
"outputPorts": "迷你UPS专属:数组,每项 {\\"type\\":\\"USB\\",\\"voltage\\":\\"5Vdc\\",\\"current\\":\\"3.0A\\"},和outputPortTypes一一对应;不适用就填空数组",
|
||
"inputVoltage": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Input Voltage/输入电压(或Nominal Voltage/标称电压),如 110V/120Vac or 220V/230Vac;不适用就填空字符串",
|
||
"inputVoltageRange": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Voltage range/输入电压范围,如 162-268Vac/170-280Vac;不适用就填空字符串",
|
||
"inputFrequency": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Frequency/输入频率(范围),如 50/60Hz(Auto sensing)或 40Hz~70Hz;不适用就填空字符串",
|
||
"outputVoltage": "UPS不间断电源大类通用(除了迷你UPS,含以后系统里新增的其他细分品类)/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):Output Voltage/输出电压,如 110V/120Vac or 220V/230Vac;不适用就填空字符串",
|
||
"outputVoltageRange": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):输出电压范围(或Voltage Regulation/电压调整率),如 ±10% 或 ±1%;不适用就填空字符串",
|
||
"transferTime": "离线式UPS/离线式锂电UPS/在线互动式UPS专属:Transfer time/转换时间,如 Typical 2-8ms, 13ms max;机架式UPS/在线式高频UPS/工频UPS/高频塔式UPS/模块化UPS这里填Inverter to Bypass那个转换时间(AC to Battery那个用下面的transferTimeAcToBattery);不适用就填空字符串",
|
||
"waveform": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Wave form/波形,如 Simulated Sine Wave 或 pure sine wave;不适用就填空字符串",
|
||
"batteryVoltage": "离线式UPS/离线式锂电UPS/在线互动式UPS/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):Battery Voltage/电池电压,如 12V 或 24V;不适用就填空字符串",
|
||
"chargeCurrent": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Charge current/充电电流,如 1A;如果涉及【型号(L)拆分规则】,要按标准机型/长延时机型分别取Standard Model或Long-run Model那部分的数据;不适用就填空字符串",
|
||
"frequencyRangeBatteryMode": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Frequency range(battery mode)/频率范围(电池模式),如 50/60Hz±1Hz;不适用就填空字符串",
|
||
"chargeTime": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Charge time/充电时间(或Typical Recharge Time),如 8 hours recover to 90% capacity;不适用就填空字符串",
|
||
"lcdDisplay": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):LCD display/LCD显示(或LCD Panel)能展示哪些信息,把原文整段抄下来,如 UPS status, Load level, Battery level, Input/Output voltage, Discharge timer, and Fault conditions;不适用就填空字符串",
|
||
"ledDisplay": "离线式UPS/离线式锂电UPS/在线互动式UPS专属:LED display/LED显示,把各个模式对应的灯光颜色都列出来(一行一条,用\\n分隔),如 AC mode: Green lighting\\nBattery mode: Yellow lighting\\nFault: Red lighting;如果原文是中文且几个模式和颜色紧挨着写在一起、没有明显换行分隔(比如\"市电模式 绿灯常亮 电池模式 黄灯常亮 故障 红灯常亮\"),要把每个模式和它后面紧跟着的颜色状态配对拆开,同样按一行一条的格式输出,如 市电模式:绿灯常亮\\n电池模式:黄灯常亮\\n故障:红灯常亮;不适用就填空字符串",
|
||
"fullProtection": "离线式UPS/离线式锂电UPS/在线互动式UPS专属:Full Protection/全面保护,如 Discharge, Short circuit and overload protection;不适用就填空字符串",
|
||
"alarmInfo": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Alarm/警告提示,把电池模式/低电量/过载/故障这几种蜂鸣提示规律都列出来(一行一条,用\\n分隔),如 Battery mode: Sounding every 10 seconds\\nLow battery: Sounding every second\\nOverload: Sounding every 0.5 seconds\\nFault: Continuously sounding;不适用就填空字符串",
|
||
"interfacePort": "UPS不间断电源大类通用(除了迷你UPS,不管是离线式、在线互动式、机架式、在线式高频、工频、高频塔式、模块化UPS,还是以后系统里新增的其他细分品类,都适用):Interface/控制管理接口说明,如 USB/RS232 port(optional), Support windows xp/vista, windows 7/8/11 and MAC,或 Smart RS-232/USB, Supports Windows 2000/2003/XP/Vista/2008, Windows 7/8, Linux, Unix, and MAC;不适用就填空字符串",
|
||
"humidity": "UPS不间断电源大类通用(除了迷你UPS,含以后系统里新增的其他细分品类)/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):Humidity/湿度(或相对湿度),如 0-90% RH@0-40°C(Non-condensing) 或 5%~95%(无凝露);不适用就填空字符串",
|
||
"noiseLevel": "UPS不间断电源大类通用(除了迷你UPS,含以后系统里新增的其他细分品类)/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):Noise Level/噪音,如 Less than 40dB(1m spacing);不适用就填空字符串",
|
||
"phase": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Phase/相数,如 1-phase input/1-phase output 或 3-phase input/1-phase output;不适用就填空字符串",
|
||
"inputPowerFactor": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):输入侧Power Factor/功率因数,如 ≥0.99@100% load;不适用就填空字符串",
|
||
"transferTimeAcToBattery": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Transfer Time - AC Mode to Battery Mode/转换时间(市电到电池),如 0ms;不适用就填空字符串",
|
||
"currentCrestRatio": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Current Crest Ratio/峰值电流比,如 3:1;不适用就填空字符串",
|
||
"harmonicDistortion": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Harmonic Distortion/谐波失真,如 ≤3% THD (Linear Load), ≤5% THD (Non-linear Load);不适用就填空字符串",
|
||
"efficiencyAcMode": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Efficiency - AC Mode/效率(市电模式),如 88%;不适用就填空字符串",
|
||
"efficiencyBatteryMode": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Efficiency - Battery Mode/效率(电池模式),如 83%;不适用就填空字符串",
|
||
"chargingVoltage": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Charging Voltage/充电电压,如 27.4VDC±1%;如果涉及【型号(L)拆分规则】,要按标准机型/长延时机型分别取Standard Model或Long-run Model那部分的数据;不适用就填空字符串",
|
||
"optionalSnmp": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(机架式、在线式高频、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Optional SNMP/可选SNMP,如 Power management from SNMP manager and web browser;不适用就填空字符串",
|
||
"outputPowerFactor": "在线式高频UPS/机架式UPS/工频UPS/高频塔式UPS/模块化UPS/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):Output Power Factor/输出功率因数,如 0.9 或 1;不适用就填空字符串",
|
||
"upsModuleCapacity": "模块化UPS/机架式模块化UPS专属:单个功率模块的容量(Power module / 功率模块 / Module capacity),格式统一成\"kVA数值/kW数值\",如 50kVA/50kW;只给了一个数就照写(如 50kVA);不适用就填空字符串",
|
||
"upsModuleCount": "模块化UPS/机架式模块化UPS专属:机柜最多能装几个功率模块(Max. modules / 模块数量 / 槽位数),只填数字,如 6;如果原文只写了机柜总容量和单模块容量,用 总容量÷单模块容量 算出来;不适用就填空字符串",
|
||
"upsModuleDimensions": "模块化UPS/机架式模块化UPS专属:功率模块尺寸(mm),如 440*700*130(机柜尺寸填在dimensions里);不适用就填空字符串",
|
||
"upsModuleWeight": "模块化UPS/机架式模块化UPS专属:功率模块重量(kg),只填数字,如 32(机柜重量填在netWeight里);不适用就填空字符串",
|
||
"parallelUnits": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(在线式高频、机架式、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Number of Parallel Units/可并联台数,如 Not supported,或具体可并联数量;不适用就填空字符串",
|
||
"overload": "UPS不间断电源大类通用,但不包括迷你UPS、离线式UPS、离线式锂电UPS、在线互动式UPS这四类小型/家用UPS(在线式高频、机架式、工频、高频塔式、模块化UPS,以及以后系统里新增的其他大功率UPS细分品类都适用):Overload/过载保护,如 105%-125% 6-25s; >150% 200ms;不适用就填空字符串",
|
||
"moduleType": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块类型,如 长延时型;不适用就填空字符串",
|
||
"moduleCapacity": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块额定容量(Ah),如 100;不适用就填空字符串",
|
||
"cellType": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):电芯类型,如 磷酸铁锂电池(LFP);不适用就填空字符串",
|
||
"moduleVoltage": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块额定电压(V),如 51.2;不适用就填空字符串",
|
||
"dischargeRate": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):放电倍率(C),如 2;不适用就填空字符串",
|
||
"chargeRate": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):充电倍率(C),如 1;不适用就填空字符串",
|
||
"moduleMaxEnergy": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块最大能量(kWh),如 5.12;不适用就填空字符串",
|
||
"moduleOutputPower": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块输出功率(kW),如 10.24;不适用就填空字符串",
|
||
"moduleDimensions": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块尺寸(mm),如 440*440*131;不适用就填空字符串",
|
||
"moduleWeight": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):模块重量(kg),如 43±2;不适用就填空字符串",
|
||
"cabinetMaxEnergy": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):电池系统柜最大能量(kWh),如 40.96;不适用就填空字符串",
|
||
"cabinetRatedVoltage": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):额定输出电压(V),如 409.6/±204.8/460.8/512/±256/563.2/614.4/±307.2;不适用就填空字符串",
|
||
"cycleLife": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):循环寿命,如 5000次@50%DOD;不适用就填空字符串",
|
||
"commInterface": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):通信接口,如 LAN/CAN/RS485/干接点;不适用就填空字符串",
|
||
"protectionFunctions": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):保护功能,如 过充、过放、过温、过流、短路等;不适用就填空字符串",
|
||
"operatingTemp": "UPS不间断电源大类通用(除了迷你UPS,含以后系统里新增的其他细分品类)/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):运行温度(或工作温度/工作温度范围),如 0~40℃(推荐20~25℃运行);不适用就填空字符串",
|
||
"color": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):颜色,如 RAL9004;不适用就填空字符串",
|
||
"cabinetDimensions": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):电池系统柜尺寸(mm),如 600×850×2000;不适用就填空字符串",
|
||
"cabinetWeight": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):电池系统柜重量(kg),如 544±10(8模组配置);不适用就填空字符串",
|
||
"altitude": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):海拔(m),如 ≤4000(>2000降额使用);不适用就填空字符串",
|
||
"selfDischargeRate": "储能电池大类通用(不管是铅酸电池、磷酸铁锂电池、UPS配套锂电池系统,还是以后系统里新增的其他细分品类,都适用):自放电率,如 <5%(环境温度0~30℃/30天);不适用就填空字符串",
|
||
"cellConfiguration": "储能电池大类通用:电芯串并联组合,如 16S1P;不适用就填空字符串",
|
||
"chargingEfficiency": "储能电池大类通用:充电效率,如 ≥97%;不适用就填空字符串",
|
||
"dischargingEfficiency": "储能电池大类通用:放电效率,如 ≥98%;不适用就填空字符串",
|
||
"recommendedChargingVoltage": "储能电池大类通用:推荐充电电压,如 57.6V(注意跟maxChargingVoltage/最大充电电压是两个不同的值,原文分别列出就分别填,不要混用);不适用就填空字符串",
|
||
"maxChargingCurrent": "储能电池大类通用:最大充电电流,单位是安培(A),如 200A(跟chargeRate/充电倍率是两种不同的表述方式,原文如果直接给了安培数值就填这个字段,不要换算成倍率);不适用就填空字符串",
|
||
"recommendedDischargeCurrent": "储能电池大类通用:推荐放电电流,单位是安培(A),如 100A;不适用就填空字符串",
|
||
"maxDischargeCurrent": "储能电池大类通用:最大放电电流,单位是安培(A),如 200A(跟dischargeRate/放电倍率是两种不同的表述方式,原文如果直接给了安培数值就填这个字段,不要换算成倍率);不适用就填空字符串",
|
||
"dischargeCutoffVoltage": "储能电池大类通用:放电截止电压,如 43.2V;不适用就填空字符串",
|
||
"packageDimensions": "储能电池大类通用:包装尺寸/外箱尺寸(mm),如 1025×545×320(注意跟moduleDimensions/模块尺寸是两个不同的值——一个是产品本体尺寸,一个是带包装箱的尺寸,原文分别列出就分别填);不适用就填空字符串",
|
||
"grossWeight": "储能电池大类通用:毛重(kg),如 95±2(注意跟moduleWeight/模块重量(净重)是两个不同的值,原文分别列出就分别填);不适用就填空字符串",
|
||
"shellMaterial": "储能电池大类通用:外壳材质,如 Metal;不适用就填空字符串",
|
||
"optionalFunctions": "储能电池大类通用:可选功能,把原文列出的可选项都抄下来,用、分隔,如 防盗、LCD显示;不适用就填空字符串",
|
||
"chargingTempRange": "储能电池大类通用:充电温度范围,如 0°C~45°C(注意跟operatingTemp/运行温度是两个不同的值——运行温度通常范围更宽,充电温度范围更窄,原文分别列出就分别填);不适用就填空字符串",
|
||
"batterySpec": "电池数量和容量/电池型号和数量,如 2200mAh*4 或 12V4.5AH*1;一体式锂电UPS填\"电池节数,总容量\",几种配置用/合并,如 2/4/6节,1792/3584/5376Wh;机架式UPS这里可以把Battery Type和Numbers合并成一句话,如 12V/9AH x2;机架式锂电UPS这里填锂电池组的电压和容量,如 51.2V 50Ah(原文分开写的电压和容量合并成这个格式);如果这个型号涉及【型号(L)拆分规则】,要按这条记录是标准机型还是长延时机型,分别取Standard Model或Long-run Model那部分的数据,不确定填空字符串",
|
||
"dimensions": "尺寸(mm),如 175*105*30;如果涉及【型号(L)拆分规则】,同样要按标准机型/长延时机型分别取对应子分类的数据,不确定填空字符串",
|
||
"netWeight": "净重(kg),如 0.4;如果涉及【型号(L)拆分规则】,同样要按标准机型/长延时机型分别取对应子分类的数据,不确定填空字符串",
|
||
"batteryType": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):电池类型,如 Lithium or lead acid battery;不适用就填空字符串",
|
||
"maxChargingVoltage": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大充电电压,如 ≤60 (Configurable);不适用就填空字符串",
|
||
"maxChargeDischargeCurrent": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大充放电电流,如 190A;不适用就填空字符串",
|
||
"maxDcInputPower": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大直流输入功率,如 16000W;不适用就填空字符串",
|
||
"maxDcInputVoltage": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大直流输入电压,如 1000V;不适用就填空字符串",
|
||
"mpptVoltageRange": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):MPPT工作电压范围,如 200~800V;不适用就填空字符串",
|
||
"startingVoltage": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):启动电压,如 150V;不适用就填空字符串",
|
||
"maxInputCurrent": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大输入电流,如 18/18A;不适用就填空字符串",
|
||
"mpptNumber": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):MPPT路数,如 2;不适用就填空字符串",
|
||
"onGridMaxApparentPower": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):并网最大输出视在功率,如 8800W;不适用就填空字符串",
|
||
"ratedOutputFrequency": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):额定输出频率,如 50/60Hz;不适用就填空字符串",
|
||
"onGridMaxOutputCurrent": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):并网最大输出电流,如 13.3A;不适用就填空字符串",
|
||
"offGridRatedApparentPower": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):离网额定输出视在功率,如 8000W;不适用就填空字符串",
|
||
"offGridMaxApparentPower": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):离网最大输出视在功率,如 >200%,15sec;不适用就填空字符串",
|
||
"offGridMaxOutputCurrent": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):离网最大输出电流,如 13.3A;不适用就填空字符串",
|
||
"efficiencyMppt": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大效率(MPPT),如 98%;不适用就填空字符串",
|
||
"efficiencyMax": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):最大效率,如 94.5%;不适用就填空字符串",
|
||
"efficiencyEurope": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):欧洲效率,如 97.5%;不适用就填空字符串",
|
||
"storageTemp": "UPS不间断电源大类通用(除了迷你UPS,含以后系统里新增的其他细分品类)/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):存储温度,如 -30~65°C(不含电池);不适用就填空字符串",
|
||
"cooling": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):散热方式,如 Intelligent forced air cooling;不适用就填空字符串",
|
||
"protectionClass": "UPS不间断电源大类通用(除了迷你UPS,含以后系统里新增的其他细分品类)/储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):防护等级(或IP等级),如 IP66 或 IP20;不适用就填空字符串",
|
||
"topology": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):拓扑结构,如 HF isolation(Battery side);不适用就填空字符串",
|
||
"safetyStandard": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):安规/EMC标准,把原文列出来的标准编号都抄下来,如 NB/T32004-2018, IEC62109, IEC61000;不适用就填空字符串",
|
||
"gridStandard": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):并网标准,如 IEC61727, EN50549-1, VDE-4105;不适用就填空字符串",
|
||
"otherStandard": "储能电池大类通用/光伏逆变器大类通用(不管是太阳能混网逆变器、并网/离网逆变器、家庭储能系统,还是以后系统里新增的其他细分品类,都适用):其他标准,如 IEC61683, IEC62116, EN50530;不适用就填空字符串",
|
||
"applicationScenarios": "应用场景:原文里如果有\"应用/Applications\"这类板块,用图标+文字标注了这个产品适合哪些应用场景(如电脑、投影仪、打印机、摄像机、收银机),把图标下面配的文字标签提取出来,用\"、\"分隔拼成一句话,如 电脑、投影仪、打印机、摄像机、收银机;只提取文字标签,不用管图标本身;原文没有这个板块就填空字符串",
|
||
"container20ft": "装箱数量:20尺柜能装多少台(无栈板),如 1000PCS;不适用/未提供就填空字符串",
|
||
"container40ft": "装箱数量:40尺柜能装多少台(无栈板),如 2080PCS;不适用/未提供就填空字符串",
|
||
"container40hq": "装箱数量:40高柜能装多少台(无栈板),如 2340PCS;不适用/未提供就填空字符串",
|
||
"extraSpecs": "数组,装那些在上面所有具名字段里都找不到匹配、但原文规格表里确实出现的参数行,每项格式 {\\"label\\":\\"参数名,必须翻译成中文,不管原文是什么语言\\",\\"value\\":\\"原文右侧数值,保持原样不翻译\\",\\"afterLabel\\":\\"这条参数在原文里紧挨着的上一个已知具名字段的中文标签,找不到就填空字符串\\"};没有这种情况就填空数组[],不要为了凑数编造内容。【铅酸电池】type 是 铅酸电池(或用户预选的细分品类名里带 铅酸 / 蓄电池 / VRLA / AGM / 胶体 / 阀控)时,extraSpecs 必须包含这些行(原文有才填,label 用原文的叫法,比如原文写"参考内阻"就写"参考内阻"):{\"label\":\"容量率\",\"value\":\"10HR 或 20HR\"}(看额定容量后面标的是 10HR 还是 20HR,比如标签上 250Ah/10HR,或技术参数表里额定容量对应的小时率;标题里写 20HR 就是 20HR)、{\"label\":\"电池系列\",\"value\":\"AGM备用型 / 深循环 / 胶体GEL / 高倍率HR / 前置端子 之一\"}(原文写胶体/GEL 填 胶体GEL;写深循环/Deep Cycle 填 深循环;写高倍率/High Rate/HR 且主要给 UPS 用 填 高倍率HR;端子在正面、给通信机柜用的 填 前置端子;其他固定型/备用/免维护 填 AGM备用型)、设计寿命(如 8年(浮充))、端子(如 M8 或 Φ20*M8)、浮充电压、循环使用充电电压、最大充电电流、内阻(这几行最容易漏,输出前对照原文确认);放电表的每一行(每个终止电压一行)各写成一条:恒功率表 label 写 \"恒功率放电(W) 终止电压10.50V\"(表头是每单格电压、每单格瓦数的,比如 F.V/Time 1.75V/Cell、CP Unit:W,就照写 \"恒功率放电(W) 终止电压1.75V/Cell\",数值照抄不要换算),value 写 \"10min=4087; 15min=3740; 30min=2380; 1h=1459; 2h=839; 3h=644; 4h=517; 5h=441; 8h=296; 10h=271; 20h=148\"(时间和数值一一对应,照原表抄,不要漏列);恒流表 label 写 \"恒流放电(A) 终止电压10.50V\",value 格式相同",
|
||
"sellingPoints": "如果原文里除了技术规格表之外,还有一些营销性质的卖点/主要特点描述(通常是几条带图标或项目符号的短句,比如\"Up-to-36A maximum input current\"、\"IP66 design\"这种面向客户宣传的亮点,不是纯技术参数表格里的数值),把这些提取出来,每条一行,用\\n分隔;如果原文只有技术规格表、没有这种营销卖点描述,就填空字符串,不要自己瞎编凑数。原文卖点是中文的,逐字照抄原文句子(只去掉多余空格和换行),不要改写、不要换词(比如\"排气结构\"不能写成\"板栅结构\")、不要删减并列的特点、更不要加原文没有的说法(比如原文没写\"使用寿命长\"就不能加)",
|
||
"notes": "其他有用但上面字段装不下的信息,一两句话,没有就填空字符串"
|
||
}
|
||
|
||
【输出精简】上面的 schema 只是字段说明:每条产品记录里,值为空字符串或空数组的字段一律省略不写,只输出原文里真正有值的字段(name 必须输出)。
|
||
这样输出更短、更快,也不会因为输出太长被截断。
|
||
|
||
只返回一个JSON数组,不要有任何解释文字、不要用markdown代码块包裹、不要省略任何一个识别到的型号。`;
|
||
|
||
// 后台任务:AI 导入可能要一两分钟(DeepSeek 排队、生成长输出),浏览器一直挂着一个请求很容易被
|
||
// 中间的代理/CDN 掐断(前端只看到 "Failed to fetch",后台其实还在跑)。改成:上传后立刻返回 jobId,
|
||
// 前端每隔几秒来查一次结果。任务结果保留 30 分钟。
|
||
const aiJobs = new Map();
|
||
function createAiJob() {
|
||
const id = crypto.randomBytes(9).toString('hex');
|
||
const job = { status: 'running', startedAt: Date.now(), code: 0, data: null };
|
||
aiJobs.set(id, job);
|
||
for (const [k, j] of aiJobs) if (Date.now() - j.startedAt > 30 * 60 * 1000) aiJobs.delete(k);
|
||
// 伪装成 express 的 res,原来的处理逻辑一行不用改
|
||
const fakeRes = {
|
||
status(code) { job.code = code; return fakeRes; },
|
||
json(obj) {
|
||
if (!job.code) job.code = 200;
|
||
job.status = job.code < 400 ? 'done' : 'error';
|
||
job.data = obj;
|
||
if (job.status === 'error') console.warn(`[AI任务 ${id}] 失败 ${job.code}: ${(obj && obj.error) || ''}`);
|
||
else console.log(`[AI任务 ${id}] 完成,用时 ${Math.round((Date.now() - job.startedAt) / 1000)}s`);
|
||
return fakeRes;
|
||
},
|
||
};
|
||
return { id, fakeRes };
|
||
}
|
||
app.get('/api/ai/jobs/:id', requireAuth, (req, res) => {
|
||
const job = aiJobs.get(String(req.params.id));
|
||
if (!job) return res.status(404).json({ error: '任务不存在或已过期,请重新导入' });
|
||
res.json({ status: job.status, code: job.code, data: job.data, elapsed: Math.round((Date.now() - job.startedAt) / 1000) });
|
||
});
|
||
|
||
// HTML 规格书转给 AI 前先压缩:
|
||
// 以前的 HTML 打开就是一张参数表,现在很多是"前面产品介绍 + 卖点 + 型号概览,后面参数表",还常常内嵌 base64 图片。
|
||
// 原样发给 AI 时,几十 KB 的图片编码占满了截断长度(24000 字),参数表反而被截掉,AI 对着乱码一直生成、很久不出结果。
|
||
// 这里:去掉 <head>/样式/脚本/注释/SVG/图片和所有 data: 编码;表格只保留 table/tr/th/td 标签和 rowspan/colspan(分组关系靠它们);
|
||
// 其他标签变成换行/项目符号的纯文字;介绍和规格表分别加标题,AI 一眼知道哪部分是卖点、哪部分是参数。
|
||
function compactHtmlForAi(raw) {
|
||
let s = String(raw || '');
|
||
const title = (s.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '';
|
||
s = s.replace(/<head[\s\S]*?<\/head>/gi, ' ')
|
||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||
.replace(/<![^>]*>/g, ' ')
|
||
.replace(/<(style|script|noscript|svg|canvas|iframe|template)\b[\s\S]*?<\/\1>/gi, ' ')
|
||
.replace(/<(img|picture|source|video|audio|object|embed|link|meta|input)\b[^>]*>/gi, ' ')
|
||
.replace(/data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+/gi, ' ');
|
||
const TABLE_TAG = /^(table|thead|tbody|tfoot|tr|th|td|caption)$/i;
|
||
const BLOCK_TAG = /^(p|div|section|article|header|footer|main|aside|h[1-6]|ul|ol|dl|dt|dd|br|hr|figure|figcaption|blockquote|nav)$/i;
|
||
s = s.replace(/<(\/?)([a-z][a-z0-9]*)\b([^>]*)>/gi, (m, close, tag, attrs) => {
|
||
if (TABLE_TAG.test(tag)) {
|
||
if (close) return `</${tag.toLowerCase()}>`;
|
||
const keep = (attrs.match(/\b(rowspan|colspan)\s*=\s*["']?\d+["']?/gi) || []).map((a) => a.replace(/\s+/g, '').replace(/["']/g, '')).join(' ');
|
||
return `<${tag.toLowerCase()}${keep ? ' ' + keep : ''}>`;
|
||
}
|
||
if (/^li$/i.test(tag)) return close ? '\n' : '\n• ';
|
||
if (BLOCK_TAG.test(tag)) return '\n';
|
||
return ' ';
|
||
});
|
||
const ENT = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", times: '×', plusmn: '±', deg: '°', ge: '≥', le: '≤', middot: '·', ndash: '–', mdash: '—', micro: 'µ', sup2: '²', sup3: '³', ohm: 'Ω' };
|
||
s = s.replace(/&(#x[0-9a-f]+|#\d+|[a-z0-9]+);/gi, (m, e) => {
|
||
if (e[0] === '#') { const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10); return Number.isFinite(n) ? String.fromCodePoint(n) : m; }
|
||
return ENT[e.toLowerCase()] !== undefined ? ENT[e.toLowerCase()] : m;
|
||
});
|
||
// 单元格里的换行 / 多余空白合并;表格标签之间不留空白
|
||
s = s.replace(/[ \t\f\v ]+/g, ' ').replace(/ *\n[\s]*/g, '\n').replace(/>\s+</g, '><').replace(/<(t[dh][^>]*)>\s+/g, '<$1>').replace(/\s+<\/(t[dh])>/g, '</$1>');
|
||
// 拆成"介绍文字"和"规格表"两部分(表格可能有几张)
|
||
const tables = s.match(/<table[\s\S]*?<\/table>/gi) || [];
|
||
const intro = tables.reduce((acc, t) => acc.replace(t, '\n'), s).replace(/\n{2,}/g, '\n').trim();
|
||
const parts = [];
|
||
if (title.trim()) parts.push(`【页面标题】${title.replace(/\s+/g, ' ').trim()}`);
|
||
if (intro) parts.push(`【产品介绍(卖点、型号概览,放进 sellingPoints;具体参数以下面的规格表为准)】\n${intro}`);
|
||
if (tables.length) parts.push(`【规格表(HTML 表格,rowspan/colspan 表示合并单元格)】\n${tables.join('\n')}`);
|
||
return parts.join('\n\n').trim();
|
||
}
|
||
|
||
app.post('/api/ai/parse-catalog', requireAuth, aiLimiter, (req, res) => {
|
||
uploadMemory.array('files', 30)(req, res, async (err) => {
|
||
if (err) return res.status(400).json({ error: err.message });
|
||
if (!req.files || !req.files.length) return res.status(400).json({ error: 'no file received' });
|
||
if (req.query.async === '1') {
|
||
const job = createAiJob();
|
||
res.status(202).json({ jobId: job.id });
|
||
res = job.fakeRes;
|
||
}
|
||
const cfg = loadAiConfig();
|
||
if (!cfg.apiKey && !cfg.backup.apiKey) return res.status(400).json({ error: 'AI API key not configured(设置里填 DeepSeek 或阿里云的 Key)' });
|
||
|
||
// 用户可以提前告诉我们这批文件大概是什么大类/品牌/细分品类,这样AI不用自己瞎猜这几个字段,
|
||
// 只需要专心提取每个型号的具体规格参数;提供了的话,最后会直接用这几个值覆盖AI的猜测结果。
|
||
const hintCategory = (req.body && req.body.hintCategory || '').trim();
|
||
const hintBrand = (req.body && req.body.hintBrand || '').trim();
|
||
const hintType = (req.body && req.body.hintType || '').trim();
|
||
// 勾了"精准导入":同时把原文件按原版式还原成"原版彩页"(和下面的字段提取并行进行),导入的产品都关联这份彩页
|
||
const precisePromise = req.body && req.body.precise === '1'
|
||
? buildPreciseDoc(req.files, (m) => console.log('[AI导入]', m)).catch((e) => { console.warn('[精准导入] 失败:', e.message); return { error: e.message }; })
|
||
: null;
|
||
|
||
let tmpDir;
|
||
try {
|
||
tmpDir = fs.mkdtempSync(path.join(OCR_TMP_ROOT, 'catalog-ocr-'));
|
||
const imagePaths = [];
|
||
const htmlTextParts = []; // HTML文件不用OCR,直接读文字内容(保留表格标签结构,AI能看懂rowspan这种分组关系)
|
||
const pdfTextParts = []; // 有文字层的PDF不用OCR,直接取文字(见 pdfTextLayer)
|
||
for (const file of req.files) {
|
||
const isPdf = (file.mimetype || '').includes('pdf') || file.originalname.toLowerCase().endsWith('.pdf');
|
||
const isImage = (file.mimetype || '').startsWith('image/');
|
||
const isHtml = (file.mimetype || '').includes('html') || /\.html?$/i.test(file.originalname);
|
||
if (isPdf) {
|
||
const pdfSubDir = fs.mkdtempSync(path.join(tmpDir, 'pdf-'));
|
||
const layer = await pdfTextLayer(file.buffer, pdfSubDir);
|
||
if (layer) {
|
||
console.log('[AI导入] 使用PDF文字层:', file.originalname, layer.length, '字');
|
||
pdfTextParts.push(`【PDF文字层:${file.originalname}(规格书自带的文字,数字准确;按版面排列,同一行左边是参数名、右边是数值,右侧可能夹着旁边一栏的文字,注意区分)】\n${layer}`);
|
||
} else {
|
||
const pages = await renderPdfToImages(file.buffer, pdfSubDir);
|
||
imagePaths.push(...pages);
|
||
}
|
||
} else if (isImage) {
|
||
const ext = path.extname(file.originalname) || '.png';
|
||
const imgPath = path.join(tmpDir, `img_${imagePaths.length}${ext}`);
|
||
fs.writeFileSync(imgPath, file.buffer);
|
||
imagePaths.push(imgPath);
|
||
} else if (isHtml) {
|
||
const cleaned = compactHtmlForAi(file.buffer.toString('utf8'));
|
||
if (cleaned) htmlTextParts.push(cleaned);
|
||
} else {
|
||
return res.status(400).json({ error: `不支持的文件类型:${file.originalname}(只支持PDF、图片或HTML)` });
|
||
}
|
||
}
|
||
|
||
const ocrText = imagePaths.length ? await ocrImages(imagePaths) : '';
|
||
const text = [ocrText, ...pdfTextParts, ...htmlTextParts].filter(Boolean).join('\n\n--- 下一份文件 ---\n\n');
|
||
console.log('[AI导入] OCR/HTML文本长度:', text.length, '| 含"应用":', text.includes('应用'), '| 含"尺柜":', text.includes('尺柜'));
|
||
if (!text) return res.status(400).json({ error: '没有识别/读取到任何文字内容,请确认文件清晰、内容完整' });
|
||
|
||
// 识别出来的文本太长就截断,避免超出模型输出预算;产品目录类文档核心信息通常靠前
|
||
const MAX_CHARS = 24000;
|
||
const clippedText = text.length > MAX_CHARS ? text.slice(0, MAX_CHARS) : text;
|
||
|
||
const hintLines = [];
|
||
if (hintCategory) hintLines.push(`产品大类:${hintCategory}`);
|
||
if (hintBrand) hintLines.push(`品牌:${hintBrand}`);
|
||
if (hintType) hintLines.push(`细分品类:${hintType}`);
|
||
const userContent = hintLines.length
|
||
? `【用户已确认以下信息,直接使用,不用自己判断】\n${hintLines.join('\n')}\n\n【以下是文档内容,可能是OCR识别结果、也可能是直接提取的HTML源码——HTML里的表格标签结构(比如rowspan)请重点利用,能帮助你判断字段的分组归属】\n${clippedText}`
|
||
: clippedText;
|
||
|
||
const content = await callDeepSeekWithRetry(cfg.apiKey, [
|
||
{ role: 'system', content: CATALOG_PARSE_SYSTEM_PROMPT },
|
||
{ role: 'user', content: userContent },
|
||
], {
|
||
// 按文档长度给输出预算:短文档(比如一页HTML规格表)不需要64000这么大的上限,
|
||
// 上限太大时一旦模型输出失控,会一直生成十几分钟才结束
|
||
maxTokens: Math.min(64000, Math.max(12000, Math.round(clippedText.length * 1.5))),
|
||
temperature: 0.2,
|
||
timeoutMs: 300000, // 5分钟
|
||
});
|
||
const { data: products, truncated } = extractJson(content);
|
||
if (!Array.isArray(products)) throw new Error('AI没有返回预期的数组格式,请重试');
|
||
// 双保险:即使AI没完全听话,这里直接强制覆盖,保证和用户预选的一致
|
||
const finalProducts = products.map((p) => ({
|
||
...p,
|
||
category: hintCategory || p.category,
|
||
brand: hintBrand || p.brand,
|
||
type: hintType || p.type,
|
||
}));
|
||
// LFP- 前缀只给"锂电替换铅酸电池"(LFP = 磷酸铁锂)。其他产品(尤其铅酸电池)如果被 AI 加上了、而原文里没有这个前缀,去掉
|
||
const srcNorm = text.toUpperCase().replace(/\s+/g, '');
|
||
finalProducts.forEach((fp) => {
|
||
const nm = String(fp.name || '').trim();
|
||
const m = nm.match(/^LFP[-_\s]*(.+)$/i);
|
||
if (!m || fp.type === '锂电替换铅酸电池') return;
|
||
if (srcNorm.includes(nm.toUpperCase().replace(/\s+/g, ''))) return; // 原文型号本来就带 LFP,保留
|
||
console.log('[AI导入] 去掉误加的 LFP 前缀:', nm, '→', m[1]);
|
||
fp.name = m[1];
|
||
});
|
||
// 一个PDF文字层 → 一个产品:逐行核对,AI漏掉的参数行补进 extraSpecs
|
||
if (finalProducts.length === 1 && pdfTextParts.length === 1 && !imagePaths.length && !htmlTextParts.length) {
|
||
const added = fillMissingSpecRows(finalProducts[0], pdfTextParts[0]);
|
||
if (added.length) console.log('[AI导入] 漏行补回:', finalProducts[0].name, added.join(' / '));
|
||
}
|
||
finalProducts.forEach(fp => {
|
||
if (Array.isArray(fp.extraSpecs) && fp.extraSpecs.length) {
|
||
console.log('[AI导入] extraSpecs for', fp.name, ':', JSON.stringify(fp.extraSpecs));
|
||
}
|
||
});
|
||
let preciseDoc = null, preciseError = '';
|
||
if (precisePromise) {
|
||
const pd = await precisePromise;
|
||
if (pd && pd.error) preciseError = pd.error;
|
||
else if (pd) { preciseDoc = { id: pd.id, pages: pd.pages.length || 1, source: pd.source, srcLang: pd.srcLang }; finalProducts.forEach((fp) => { fp.preciseDocId = pd.id; }); }
|
||
}
|
||
res.json({ products: finalProducts, ocrTextLength: text.length, truncated, preciseDoc, preciseError });
|
||
} catch (e) {
|
||
const hint = /empty response/i.test(e.message)
|
||
? '(重试后仍然失败,可能是一次上传的文件太多导致AI输出内容超长;建议减少单次上传的数量,比如分成2-3批,每批3-5张)'
|
||
: '';
|
||
console.warn('[AI导入] 失败:', e.message);
|
||
res.status(502).json({ error: `${e.message}${hint}` });
|
||
} finally {
|
||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (e) {}
|
||
}
|
||
});
|
||
});
|
||
|
||
/* ================================ 精准导入 ================================ */
|
||
// AI 导入时勾选"精准导入":除了照常提取产品字段,还把原文件按原版式 1:1 还原成网页("原版彩页"),之后可以一键翻译成其他语言,
|
||
// 翻译后版式不变(文字在原位置替换,图片里的文字用同底色的色块盖住再写译文)。
|
||
//
|
||
// 三种来源:
|
||
// · 有文字层的 PDF(WPS / Word / InDesign 导出的规格书):pdftocairo 把每页转成 SVG,去掉里面的文字只留线条/色块/图片当底图;
|
||
// 文字用 pdftohtml 取出(位置、字号、颜色、粗体),基线位置从 SVG 里每个字的坐标取,所以和原文件严丝合缝;
|
||
// 图片里的文字(曲线图坐标轴等)用 OCR 找出来,只在翻译版里盖色块替换。
|
||
// · 扫描版 PDF / JPG / PNG:整页图片当底图,文字全部靠 OCR 定位,原文版就是原图,翻译版在图上盖色块写译文。
|
||
// · HTML:原样保存,翻译时只替换文字节点,结构和样式不动。
|
||
// 存储:uploads/_precise/<id>/doc.json + 每页底图(p1.svg / p1.jpg …),产品上记 preciseDocId。
|
||
// 依赖:poppler-utils(pdftocairo / pdftohtml / pdftoppm / pdfinfo,和 AI 导入用的是同一个包)+ tesseract.js(已有)。
|
||
|
||
const PRECISE_DIR = path.join(UPLOADS_DIR, '_precise');
|
||
const PRECISE_LANGS = { zh: '简体中文', en: 'English', fr: 'French', ru: 'Russian', es: 'Spanish', ar: 'Arabic' };
|
||
const preciseRun = (cmd, args, opts = {}) => new Promise((resolve, reject) => {
|
||
execFile(cmd, args, { maxBuffer: 300 * 1024 * 1024, timeout: 240000, ...opts }, (err, out) => (err ? reject(err) : resolve(out)));
|
||
});
|
||
const htmlEsc = (s) => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||
const xmlDecode = (s) => String(s || '').replace(/<[^>]+>/g, '').replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (m, e) => {
|
||
if (e[0] === '#') { const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10); return Number.isFinite(n) ? String.fromCodePoint(n) : m; }
|
||
return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }[e.toLowerCase()];
|
||
});
|
||
const CJK_RE = /[㐀-鿿豈-]/;
|
||
// 文字长度:汉字算 1,其他字符算 0.5(判断一行是不是"写满了的正文")
|
||
const textLen = (t) => [...String(t || '')].reduce((n, ch) => n + (CJK_RE.test(ch) ? 1 : 0.5), 0);
|
||
const hasWords = (t, srcLang) => (srcLang === 'zh' ? CJK_RE.test(t) : /[A-Za-zÀ-ɏЀ-ӿ]{2,}/.test(t));
|
||
// 字体 → 三类:t = 西文衬线(Times),s = 中文宋体类,y = 无衬线(雅黑 / 黑体 / Arial …)
|
||
function preciseFam(family) {
|
||
const f = String(family || '');
|
||
if (/song|simsun|ming|fangsong|kai|stsong|宋|仿宋|楷/i.test(f)) return 's';
|
||
if (/times|roman|georgia|garamond|serif|minion|cambria|book/i.test(f) && !/sans/i.test(f)) return 't';
|
||
return 'y';
|
||
}
|
||
// 图片尺寸(只读文件头,不需要图像库)
|
||
function imageSize(buf) {
|
||
if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20), ext: 'png' };
|
||
if (buf[0] === 0xff && buf[1] === 0xd8) {
|
||
let i = 2;
|
||
while (i < buf.length - 9) {
|
||
if (buf[i] !== 0xff) { i++; continue; }
|
||
const m = buf[i + 1], len = buf.readUInt16BE(i + 2);
|
||
if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { w: buf.readUInt16BE(i + 7), h: buf.readUInt16BE(i + 5), ext: 'jpg' };
|
||
i += 2 + len;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// OCR:返回 [{text, x0, y0, x1, y1}](像素),兼容 tesseract.js v4(data.lines)和 v5(data.blocks)
|
||
async function preciseOcrLines(imgPath) {
|
||
const worker = await getOcrWorker();
|
||
let r;
|
||
try { r = await worker.recognize(imgPath, {}, { text: true, blocks: true }); } catch (e) { r = await worker.recognize(imgPath); }
|
||
const data = (r && r.data) || {};
|
||
let lines = Array.isArray(data.lines) ? data.lines : [];
|
||
if (!lines.length && Array.isArray(data.blocks)) lines = data.blocks.flatMap((b) => (b.paragraphs || []).flatMap((p) => p.lines || []));
|
||
const out = [];
|
||
for (const l of lines) {
|
||
const words = (l.words || []).filter((w) => w.text && w.text.trim() && (w.confidence == null || w.confidence > 35));
|
||
const text = (words.length ? words.map((w) => w.text).join(' ') : l.text || '').replace(/\s+/g, ' ').trim()
|
||
.replace(new RegExp(`(${CJK_RE.source})\\s+(?=${CJK_RE.source})`, 'g'), '$1');
|
||
const b = l.bbox || {};
|
||
if (text && b.x1 > b.x0) out.push({ text, x0: b.x0, y0: b.y0, x1: b.x1, y1: b.y1, words: words.map((w) => ({ text: w.text, ...w.bbox })) });
|
||
}
|
||
return out;
|
||
}
|
||
// OCR 行 → 页面上的条目(pt)。竖排的单字(坐标轴"充电电压"一个字一行)合成一个竖排条目,翻译版旋转 90° 显示
|
||
function ocrItems(lines, scale, srcLang, avoid, idBase, pageW) {
|
||
const items = [];
|
||
// 所有文字(包括数字、文字层的字)都算障碍物,用来限制译文往右延伸
|
||
const obstacles = [...avoid, ...lines.map((l) => ({ x: l.x0 * scale, y: l.y0 * scale, w: (l.x1 - l.x0) * scale, h: (l.y1 - l.y0) * scale }))];
|
||
const singles = [];
|
||
for (const l of lines) {
|
||
const box = { x: l.x0 * scale, y: l.y0 * scale, w: (l.x1 - l.x0) * scale, h: (l.y1 - l.y0) * scale };
|
||
if (!hasWords(l.text, srcLang)) continue;
|
||
const area = box.w * box.h;
|
||
// 和文字层已有的文字重叠就不要(OCR 常把一整行"参数名 + 数值"识别成一行,所以按文字层每个字块被盖住的比例判断)
|
||
const covered = avoid.some((a) => {
|
||
const ix = Math.max(0, Math.min(a.x + a.w, box.x + box.w) - Math.max(a.x, box.x));
|
||
const iy = Math.max(0, Math.min(a.y + a.h, box.y + box.h) - Math.max(a.y, box.y));
|
||
return ix * iy > area * 0.3 || ix * iy > a.w * a.h * 0.4;
|
||
});
|
||
if (covered) continue;
|
||
const plain = l.text.replace(/\s+/g, '');
|
||
if (srcLang === 'zh' && plain.length === 1) { singles.push({ ...box, text: plain }); continue; }
|
||
items.push({ ...box, text: l.text });
|
||
}
|
||
// 竖排:x 中心对齐、上下相邻的单字
|
||
singles.sort((a, b) => a.x - b.x || a.y - b.y);
|
||
const used = new Set();
|
||
for (let i = 0; i < singles.length; i++) {
|
||
if (used.has(i)) continue;
|
||
const grp = [singles[i]]; used.add(i);
|
||
for (let j = 0; j < singles.length; j++) {
|
||
if (used.has(j)) continue;
|
||
const last = grp[grp.length - 1], c = singles[j];
|
||
const cx = (s) => s.x + s.w / 2;
|
||
if (Math.abs(cx(c) - cx(last)) < Math.max(last.w, c.w) * 0.6 && c.y > last.y && c.y - (last.y + last.h) < last.h * 1.6) { grp.push(c); used.add(j); }
|
||
}
|
||
grp.sort((a, b) => a.y - b.y);
|
||
if (grp.length < 2) continue;
|
||
const x0 = Math.min(...grp.map((g) => g.x)), y0 = grp[0].y, x1 = Math.max(...grp.map((g) => g.x + g.w)), y1 = grp[grp.length - 1].y + grp[grp.length - 1].h;
|
||
items.push({ x: x0, y: y0, w: x1 - x0, h: y1 - y0, text: grp.map((g) => g.text).join(''), vertical: true });
|
||
}
|
||
// 段落:左对齐、行高相近、行距正常、上一行写得比较满的几行 OCR 文字合成一段(整段翻译,译文在这一块里自动换行)
|
||
const horiz = items.filter((it) => !it.vertical).sort((a, b) => a.y - b.y || a.x - b.x);
|
||
const merged = new Set();
|
||
const blocks = [];
|
||
for (const it of horiz) {
|
||
if (merged.has(it)) continue;
|
||
const blk = [it];
|
||
for (;;) {
|
||
const last = blk[blk.length - 1];
|
||
const nxt = horiz.find((c) => !merged.has(c) && !blk.includes(c) && Math.abs(c.x - blk[0].x) < last.h * 0.8 && Math.abs(c.h - last.h) < last.h * 0.35
|
||
&& c.y > last.y + last.h * 0.5 && c.y - (last.y + last.h) < last.h * 1.2);
|
||
const fullW = Math.max(...blk.map((b) => b.w));
|
||
if (!nxt || textLen(last.text) < 18 || last.w < Math.max(fullW, nxt.w) * 0.72 || /[。.!!??::]$/.test(last.text)) break;
|
||
blk.push(nxt);
|
||
}
|
||
if (blk.length > 1) {
|
||
blk.forEach((b) => merged.add(b));
|
||
const x0 = Math.min(...blk.map((b) => b.x)), y0 = blk[0].y, x1 = Math.max(...blk.map((b) => b.x + b.w)), y1 = blk[blk.length - 1].y + blk[blk.length - 1].h;
|
||
const zh = blk.every((b) => CJK_RE.test(b.text));
|
||
blocks.push({ x: x0, y: y0, w: x1 - x0, h: y1 - y0, text: blk.map((b) => b.text).join(zh ? '' : ' '), para: true, lh: (y1 - y0) / blk.length, fs: Math.min(...blk.map((b) => b.h)) * 0.72 });
|
||
}
|
||
}
|
||
const all = [...items.filter((it) => !merged.has(it)), ...blocks];
|
||
// 单行译文往右最多能延伸到哪里(右边下一个文字 / 数字为止)
|
||
for (const it of all) {
|
||
if (it.vertical || it.para) continue;
|
||
const right = obstacles.filter((o) => o.x > it.x + it.w - 1 && o.y < it.y + it.h * 0.8 && o.y + o.h > it.y + it.h * 0.2).map((o) => o.x);
|
||
it.maxW = +((right.length ? Math.min(...right) - 3 : pageW - 12) - it.x).toFixed(2);
|
||
}
|
||
return all.map((it, k) => ({ id: `${idBase}o${k}`, kind: 'ocr', ...it, x: +it.x.toFixed(2), y: +it.y.toFixed(2), w: +it.w.toFixed(2), h: +it.h.toFixed(2) }));
|
||
}
|
||
|
||
// 有文字层的 PDF 的一页:底图 SVG(去掉文字)+ 文字行 + 段落 + 图片里的文字
|
||
async function precisePdfVectorPage(pdfPath, pageNo, pageXml, fontXml, workDir, outDir) {
|
||
const svgPath = path.join(workDir, `p${pageNo}.svg`);
|
||
await preciseRun('pdftocairo', ['-svg', '-f', String(pageNo), '-l', String(pageNo), pdfPath, svgPath]);
|
||
let svg = fs.readFileSync(svgPath, 'utf8');
|
||
const glyphs = [];
|
||
svg = svg.replace(/<use xlink:href="#glyph-[^"]*" x="([\d.\-]+)" y="([\d.\-]+)"\s*\/>/g, (m, x, y) => { glyphs.push([+x, +y]); return ''; });
|
||
// 描边加粗的文字(标题常见):cairo 先画一组字,紧跟着再画一条带曲线的描边路径,这条也去掉(表格线是直线,不受影响)
|
||
svg = svg.replace(/(<g fill="[^"]*" fill-opacity="[^"]*">\s*<\/g>)\s*<path fill="none"[^>]*?d="([^"]*)"[^>]*\/>/g, (m, g, d) => ((d.match(/[MLCQZ]/gi) || []).length >= 8 ? g : m));
|
||
// 带透明蒙版的图片:cairo 用"滤镜 + 蒙版"实现,浏览器按低分辨率算滤镜,边缘会出噪点;亮度蒙版本身就是同样效果,去掉滤镜
|
||
svg = svg.replace(/<g filter="url\(#filter-remove-color\)">\s*<use ([^>]*?) filter="url\(#filter-color-to-alpha\)"([^>]*)\/>\s*<\/g>/g, '<use $1$2/>');
|
||
svg = await preciseFixMaskedImages(svg, pdfPath, pageNo, workDir);
|
||
fs.writeFileSync(path.join(outDir, `p${pageNo}.svg`), svg);
|
||
const vb = (svg.match(/viewBox="0 0 ([\d.]+) ([\d.]+)"/) || []).slice(1).map(Number);
|
||
|
||
// pdftohtml 的坐标按 zoom 放大过(实际放大倍数以页宽为准),换回 pt;字体表在整个文件里只声明一次,所以从整份 XML 里取
|
||
const xw = +(pageXml.match(/width="([\d.]+)"/) || [])[1] || 0;
|
||
const Z = vb[0] && xw ? xw / vb[0] : 1;
|
||
const fonts = {};
|
||
for (const m of fontXml.matchAll(/<fontspec id="(\d+)" size="([\d.\-]+)" family="([^"]*)" color="([^"]*)"\s*\/>/g)) fonts[m[1]] = { size: +m[2] / Z, family: m[3], color: m[4] };
|
||
const pw = vb[0] || xw / Z || 595.3;
|
||
const ph = vb[1] || +(pageXml.match(/height="([\d.]+)"/) || [])[1] / Z || 841.9;
|
||
const runs = [];
|
||
for (const m of pageXml.matchAll(/<text top="([\d.\-]+)" left="([\d.\-]+)" width="([\d.\-]+)" height="([\d.\-]+)" font="(\d+)">([\s\S]*?)<\/text>/g)) {
|
||
const t = xmlDecode(m[6]);
|
||
if (!t.trim()) continue;
|
||
const f = fonts[m[5]] || { size: 9, family: '', color: '#000000' };
|
||
const top = +m[1] / Z, left = +m[2] / Z, w = +m[3] / Z, h = +m[4] / Z;
|
||
const g = glyphs.find(([gx, gy]) => Math.abs(gx - left) < 1.6 && gy >= top - 1 && gy <= top + h + 2);
|
||
runs.push({ t, x: left, w, top, h, base: g ? g[1] : top + h * 0.82, size: f.size, color: f.color, fam: preciseFam(f.family), b: /<b>/.test(m[6]) || /bold|black|heavy/i.test(f.family) });
|
||
}
|
||
// 同一基线、挨着的几段合成一行(不同字体的几段也在一行里,按同一条基线对齐)
|
||
runs.sort((a, b) => a.base - b.base);
|
||
let row = -1, prevBase = -99;
|
||
for (const r of runs) { if (r.base - prevBase > 0.9) row++; r.row = row; prevBase = r.base; }
|
||
runs.sort((a, b) => a.row - b.row || a.x - b.x);
|
||
const lines = [];
|
||
for (const r of runs) {
|
||
const L = lines[lines.length - 1];
|
||
const gap = L ? r.x - (L.x + L.w) : 0;
|
||
// 字号不同但颜色相同、挨得很近的也连起来(标题常见"规格参数 (环境25℃)"大小两种字号),整行一起翻译
|
||
if (L && L.row === r.row && (Math.abs(L.size - r.size) < 0.6 || L.color === r.color) && gap > -1 && gap < Math.max(L.size, r.size) * (L.color === r.color && Math.max(L.size, r.size) >= 10 ? 1.3 : 0.8)) {
|
||
if (gap > 0.8) L.runs.push({ gap: +gap.toFixed(2) });
|
||
L.runs.push({ t: r.t, f: r.fam, b: r.b, ...(Math.abs(L.size - r.size) >= 0.6 ? { s: +r.size.toFixed(2) } : {}) });
|
||
L.w = r.x + r.w - L.x; L.top = Math.min(L.top, r.top); L.text += (gap > r.size * 0.25 && !CJK_RE.test(r.t[0]) ? ' ' : '') + r.t;
|
||
} else {
|
||
lines.push({ row: r.row, x: r.x, w: r.w, top: r.top, base: r.base, size: r.size, color: r.color, runs: [{ t: r.t, f: r.fam, b: r.b }], text: r.t });
|
||
}
|
||
}
|
||
lines.forEach((l, i) => { l.id = `p${pageNo}l${i}`; l.text = l.text.trim(); });
|
||
// 段落:同字号同颜色、左对齐、行距正常、上一行写满了(长度接近整段宽度)才算同一段——表格里一格一格的短文字不会被合并
|
||
const byTop = [...lines].sort((a, b) => a.base - b.base || a.x - b.x);
|
||
const blocks = [];
|
||
const inBlock = new Map();
|
||
for (const l of byTop) {
|
||
if (inBlock.has(l.id)) continue;
|
||
const blk = [l];
|
||
for (;;) {
|
||
const last = blk[blk.length - 1];
|
||
const nxt = byTop.find((c) => !inBlock.has(c.id) && !blk.includes(c) && Math.abs(c.x - blk[0].x) < 4 && Math.abs(c.size - last.size) < 0.3 && c.color === last.color
|
||
&& c.base - last.base > last.size * 0.9 && c.base - last.base < last.size * 2.4);
|
||
const fullW = Math.max(...blk.map((b) => b.w));
|
||
if (!nxt || textLen(last.text) < 18 || last.w < Math.max(fullW, nxt.w) * 0.72 || /[。.!!??::]$/.test(last.text)) break;
|
||
blk.push(nxt);
|
||
}
|
||
// 第一行可能被拆成几段(中间有一段字体缺失的空白):上一行同字号同颜色的几段,从段落左边开始、几乎写满整行,也算进来
|
||
if (blk.length > 1) {
|
||
const l0 = blk[0], fullW = Math.max(...blk.map((b) => b.w));
|
||
const prev = byTop.filter((c) => !inBlock.has(c.id) && !blk.includes(c) && c.size === l0.size && c.color === l0.color && l0.base - c.base > l0.size * 0.9 && l0.base - c.base < l0.size * 2.4);
|
||
const rowBase = prev.length ? Math.max(...prev.map((c) => c.base)) : 0;
|
||
const row = prev.filter((c) => Math.abs(c.base - rowBase) < 0.9).sort((a, b) => a.x - b.x);
|
||
if (row.length > 1 && Math.abs(row[0].x - l0.x) < 4 && row[row.length - 1].x + row[row.length - 1].w - row[0].x > fullW * 0.72) blk.unshift(...row);
|
||
}
|
||
if (blk.length > 1) {
|
||
const id = `p${pageNo}b${blocks.length}`;
|
||
blk.forEach((b) => inBlock.set(b.id, id));
|
||
const lh = (blk[blk.length - 1].base - blk[0].base) / (blk.length - 1);
|
||
const zh = blk.every((b) => CJK_RE.test(b.text));
|
||
blocks.push({ id, x: +blk[0].x.toFixed(2), top: +Math.min(...blk.map((b) => b.top)).toFixed(2), w: +Math.max(...blk.map((b) => b.w)).toFixed(2), size: blk[0].size, lh: +lh.toFixed(2), color: blk[0].color,
|
||
fam: blk[0].runs.find((r) => r.f)?.f || 'y', lines: blk.map((b) => b.id), text: blk.map((b) => b.text).join(zh ? '' : ' ') });
|
||
}
|
||
}
|
||
// 每行 / 每段翻译后最多能占多宽、多高(到右边下一个文字、到下面下一行文字为止)
|
||
for (const l of lines) {
|
||
if (inBlock.has(l.id)) l.block = inBlock.get(l.id);
|
||
const right = lines.filter((o) => o !== l && Math.abs(o.base - l.base) < l.size * 0.6 && o.x > l.x + l.w - 0.5).map((o) => o.x);
|
||
l.maxW = +((right.length ? Math.min(...right) - 4 : pw - 18) - l.x).toFixed(2);
|
||
}
|
||
for (const b of blocks) {
|
||
const bottom = b.top + b.lh * b.lines.length;
|
||
const below = lines.filter((o) => !b.lines.includes(o.id) && o.top > bottom - b.lh * 0.5 && o.x < b.x + b.w && o.x + o.w > b.x).map((o) => o.top);
|
||
b.maxH = +((below.length ? Math.min(...below) - 2 : ph - 20) - b.top).toFixed(2);
|
||
}
|
||
const textBoxes = lines.map((l) => ({ x: l.x - 1, y: l.top - 1, w: l.w + 2, h: l.base - l.top + l.size * 0.3 + 2 }));
|
||
return {
|
||
w: +pw.toFixed(2), h: +ph.toFixed(2), bg: `p${pageNo}.svg`,
|
||
lines: lines.map(({ row, ...l }) => ({ ...l, x: +l.x.toFixed(2), w: +l.w.toFixed(2), top: +l.top.toFixed(2), base: +l.base.toFixed(2) })),
|
||
blocks, textBoxes,
|
||
};
|
||
}
|
||
|
||
async function buildPreciseDoc(files, onLog = () => {}) {
|
||
const id = 'pd_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
|
||
const outDir = path.join(PRECISE_DIR, id);
|
||
fs.mkdirSync(outDir, { recursive: true });
|
||
const workDir = fs.mkdtempSync(path.join(OCR_TMP_ROOT, 'precise-'));
|
||
const fname = (f) => Buffer.from(f.originalname, 'latin1').toString('utf8');
|
||
const doc = { id, name: files.map(fname).join(', '), createdAt: new Date().toISOString(), source: '', srcLang: 'zh', pages: [], html: null, translations: {} };
|
||
try {
|
||
let allText = '';
|
||
for (const file of files) {
|
||
const lower = file.originalname.toLowerCase();
|
||
const isPdf = (file.mimetype || '').includes('pdf') || lower.endsWith('.pdf');
|
||
const isHtml = (file.mimetype || '').includes('html') || /\.html?$/.test(lower);
|
||
if (isHtml) {
|
||
if (files.length > 1) throw new Error('HTML 精准导入一次只能选一个文件');
|
||
doc.source = 'html';
|
||
fs.writeFileSync(path.join(outDir, 'source.html'), file.buffer);
|
||
allText += file.buffer.toString('utf8').replace(/<(script|style)[\s\S]*?<\/\1>/gi, ' ').replace(/<[^>]+>/g, ' ');
|
||
continue;
|
||
}
|
||
if (isPdf) {
|
||
const pdfPath = path.join(workDir, `f${doc.pages.length}.pdf`);
|
||
fs.writeFileSync(pdfPath, file.buffer);
|
||
const layer = await pdfTextLayer(file.buffer, workDir);
|
||
if (layer) {
|
||
doc.source = doc.source || 'pdf';
|
||
allText += layer;
|
||
const xmlBase = path.join(workDir, `x${doc.pages.length}`);
|
||
await preciseRun('pdftohtml', ['-xml', '-i', '-nodrm', '-q', '-zoom', '10', pdfPath, xmlBase]);
|
||
const xml = fs.readFileSync(xmlBase + '.xml', 'utf8');
|
||
const pagesXml = [...xml.matchAll(/<page [\s\S]*?<\/page>/g)].map((m) => m[0]).slice(0, 30);
|
||
for (let i = 0; i < pagesXml.length; i++) {
|
||
const no = doc.pages.length + 1;
|
||
onLog(`精准导入:${file.originalname} 第 ${i + 1} 页`);
|
||
const pg = await precisePdfVectorPage(pdfPath, i + 1, pagesXml[i], xml, workDir, outDir);
|
||
if (no !== i + 1) { fs.renameSync(path.join(outDir, `p${i + 1}.svg`), path.join(outDir, `p${no}.svg`)); pg.bg = `p${no}.svg`; }
|
||
pg.lines.forEach((l) => { l.id = l.id.replace(/^p\d+/, `p${no}`); if (l.block) l.block = l.block.replace(/^p\d+/, `p${no}`); });
|
||
pg.blocks.forEach((b) => { b.id = b.id.replace(/^p\d+/, `p${no}`); b.lines = b.lines.map((x) => x.replace(/^p\d+/, `p${no}`)); });
|
||
pg.vector = true;
|
||
// 图片里的文字:整页 150dpi 渲染后 OCR,避开文字层已经有的位置
|
||
const ras = path.join(workDir, `r${no}`);
|
||
await preciseRun('pdftoppm', ['-png', '-r', '150', '-f', String(i + 1), '-l', String(i + 1), '-singlefile', pdfPath, ras]);
|
||
pg.ocrPx = ras + '.png';
|
||
doc.pages.push(pg);
|
||
}
|
||
} else {
|
||
doc.source = doc.source || 'image';
|
||
const ras = path.join(workDir, `s${doc.pages.length}`);
|
||
await preciseRun('pdftoppm', ['-jpeg', '-jpegopt', 'quality=88', '-r', '150', pdfPath, ras]);
|
||
const imgs = fs.readdirSync(workDir).filter((f) => f.startsWith(path.basename(ras)) && f.endsWith('.jpg')).sort().slice(0, 30);
|
||
for (const f of imgs) {
|
||
const no = doc.pages.length + 1;
|
||
fs.copyFileSync(path.join(workDir, f), path.join(outDir, `p${no}.jpg`));
|
||
const sz = imageSize(fs.readFileSync(path.join(workDir, f)));
|
||
doc.pages.push({ w: 595.3, h: +(595.3 * sz.h / sz.w).toFixed(2), bg: `p${no}.jpg`, px: sz, ocrPx: path.join(workDir, f), lines: [], blocks: [], textBoxes: [] });
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
const sz = imageSize(file.buffer);
|
||
if (!sz) throw new Error(`精准导入只支持 PDF、JPG、PNG 和 HTML:${file.originalname}`);
|
||
doc.source = doc.source || 'image';
|
||
const no = doc.pages.length + 1;
|
||
const bg = `p${no}.${sz.ext}`;
|
||
fs.writeFileSync(path.join(outDir, bg), file.buffer);
|
||
doc.pages.push({ w: 595.3, h: +(595.3 * sz.h / sz.w).toFixed(2), bg, px: sz, ocrPx: path.join(outDir, bg), lines: [], blocks: [], textBoxes: [] });
|
||
}
|
||
// 原文语言:中文字多就是中文
|
||
const cjk = (allText.match(new RegExp(CJK_RE.source, 'g')) || []).length;
|
||
doc.srcLang = cjk > 20 || (!allText && true) ? 'zh' : 'en';
|
||
// OCR(图片里的文字 / 扫描件、图片的全部文字)
|
||
for (let i = 0; i < doc.pages.length; i++) {
|
||
const pg = doc.pages[i];
|
||
if (!pg.ocrPx) continue;
|
||
onLog(`精准导入:OCR 第 ${i + 1} 页`);
|
||
try {
|
||
const lines = await preciseOcrLines(pg.ocrPx);
|
||
const scale = pg.vector ? 72 / 150 : pg.w / pg.px.w;
|
||
pg.ocr = ocrItems(lines, scale, doc.srcLang, pg.textBoxes || [], `p${i + 1}`, pg.w);
|
||
if (!pg.vector && doc.srcLang === 'zh' && !cjk) {
|
||
// 图片来源:语言按 OCR 结果判断
|
||
const t = lines.map((l) => l.text).join('');
|
||
if ((t.match(new RegExp(CJK_RE.source, 'g')) || []).length < 10) doc.srcLang = 'en';
|
||
}
|
||
} catch (e) { pg.ocr = []; console.warn('[精准导入] OCR 失败:', e.message); }
|
||
delete pg.ocrPx; delete pg.textBoxes;
|
||
}
|
||
if (!doc.source) throw new Error('没有可以精准导入的文件');
|
||
fs.writeFileSync(path.join(outDir, 'doc.json'), JSON.stringify(doc));
|
||
return doc;
|
||
} catch (e) {
|
||
try { fs.rmSync(outDir, { recursive: true, force: true }); } catch (x) {}
|
||
throw e;
|
||
} finally {
|
||
try { fs.rmSync(workDir, { recursive: true, force: true }); } catch (x) {}
|
||
}
|
||
}
|
||
|
||
// 最小 PNG 编解码(只用 zlib):精准导入合成"图片 + 透明蒙版"用
|
||
const zlibP = require('zlib');
|
||
const CRC_T = (() => { const t = new Int32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c; } return t; })();
|
||
const crc32 = (buf) => { let c = -1; for (let i = 0; i < buf.length; i++) c = CRC_T[(c ^ buf[i]) & 0xff] ^ (c >>> 8); return (c ^ -1) >>> 0; };
|
||
function pngDecode(buf) {
|
||
if (buf.readUInt32BE(0) !== 0x89504e47) return null;
|
||
let i = 8, w, h, depth, ctype, inter, plte = null; const idat = [];
|
||
while (i < buf.length) {
|
||
const len = buf.readUInt32BE(i), type = buf.toString('latin1', i + 4, i + 8), d = buf.subarray(i + 8, i + 8 + len);
|
||
if (type === 'IHDR') { w = d.readUInt32BE(0); h = d.readUInt32BE(4); depth = d[8]; ctype = d[9]; inter = d[12]; }
|
||
else if (type === 'PLTE') plte = d; else if (type === 'IDAT') idat.push(d); else if (type === 'IEND') break;
|
||
i += 12 + len;
|
||
}
|
||
if (inter) return null;
|
||
const ch = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[ctype];
|
||
const raw = zlibP.inflateSync(Buffer.concat(idat));
|
||
const bpr = Math.ceil((w * ch * depth) / 8), bpp = Math.max(1, (ch * depth) >> 3);
|
||
const out = Buffer.alloc(bpr * h); let prev = Buffer.alloc(bpr);
|
||
for (let y = 0; y < h; y++) {
|
||
const f = raw[y * (bpr + 1)], line = raw.subarray(y * (bpr + 1) + 1, (y + 1) * (bpr + 1)), cur = out.subarray(y * bpr, (y + 1) * bpr);
|
||
for (let x = 0; x < bpr; x++) {
|
||
const a = x >= bpp ? cur[x - bpp] : 0, b = prev[x], c = x >= bpp ? prev[x - bpp] : 0;
|
||
let v = line[x];
|
||
if (f === 1) v += a; else if (f === 2) v += b; else if (f === 3) v += (a + b) >> 1;
|
||
else if (f === 4) { const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }
|
||
cur[x] = v & 0xff;
|
||
}
|
||
prev = cur;
|
||
}
|
||
// 统一转成 RGBA 8 位
|
||
const px = Buffer.alloc(w * h * 4);
|
||
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
||
const o = (y * w + x) * 4, row = out.subarray(y * bpr);
|
||
let r, g, b, a = 255;
|
||
if (depth === 8) {
|
||
const s = x * ch;
|
||
if (ctype === 0) r = g = b = row[s]; else if (ctype === 4) { r = g = b = row[s]; a = row[s + 1]; }
|
||
else if (ctype === 2) { r = row[s]; g = row[s + 1]; b = row[s + 2]; } else if (ctype === 6) { r = row[s]; g = row[s + 1]; b = row[s + 2]; a = row[s + 3]; }
|
||
else { const k = row[s] * 3; r = plte[k]; g = plte[k + 1]; b = plte[k + 2]; }
|
||
} else if (depth === 1 && (ctype === 0 || ctype === 3)) {
|
||
const bit = (row[x >> 3] >> (7 - (x & 7))) & 1;
|
||
if (ctype === 0) r = g = b = bit * 255; else { r = plte[bit * 3]; g = plte[bit * 3 + 1]; b = plte[bit * 3 + 2]; }
|
||
} else if (depth === 16) {
|
||
const s = x * ch * 2;
|
||
if (ctype === 0 || ctype === 4) { r = g = b = row[s]; if (ctype === 4) a = row[s + 2]; } else { r = row[s]; g = row[s + 2]; b = row[s + 4]; if (ctype === 6) a = row[s + 6]; }
|
||
} else return null;
|
||
px[o] = r; px[o + 1] = g; px[o + 2] = b; px[o + 3] = a;
|
||
}
|
||
return { w, h, px };
|
||
}
|
||
function pngEncode(w, h, px) {
|
||
const raw = Buffer.alloc((w * 4 + 1) * h);
|
||
for (let y = 0; y < h; y++) px.copy(raw, y * (w * 4 + 1) + 1, y * w * 4, (y + 1) * w * 4);
|
||
const chunk = (type, data) => { const l = Buffer.alloc(4); l.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type, 'latin1'), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc32(td)); return Buffer.concat([l, td, c]); };
|
||
const ih = Buffer.alloc(13); ih.writeUInt32BE(w, 0); ih.writeUInt32BE(h, 4); ih[8] = 8; ih[9] = 6;
|
||
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ih), chunk('IDAT', zlibP.deflateSync(raw, { level: 6 })), chunk('IEND', Buffer.alloc(0))]);
|
||
}
|
||
// 图片 + 蒙版合成 RGBA,太大的按整数倍缩小(显示尺寸的 3 倍够打印)
|
||
function compositeRgba(img, mask, maxW) {
|
||
let { w, h } = img; const px = Buffer.from(img.px);
|
||
if (mask) for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
||
const mx = Math.min(mask.w - 1, Math.floor((x * mask.w) / w)), my = Math.min(mask.h - 1, Math.floor((y * mask.h) / h));
|
||
px[(y * w + x) * 4 + 3] = mask.px[(my * mask.w + mx) * 4];
|
||
}
|
||
const k = maxW && w > maxW ? Math.floor(w / maxW) : 1;
|
||
if (k <= 1) return { w, h, px };
|
||
const nw = Math.floor(w / k), nh = Math.floor(h / k), o = Buffer.alloc(nw * nh * 4);
|
||
for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) {
|
||
let r = 0, g = 0, b = 0, a = 0;
|
||
for (let j = 0; j < k; j++) for (let i = 0; i < k; i++) { const s = ((y * k + j) * w + x * k + i) * 4, al = px[s + 3]; r += px[s] * al; g += px[s + 1] * al; b += px[s + 2] * al; a += al; }
|
||
const d = (y * nw + x) * 4; o[d] = a ? r / a : 255; o[d + 1] = a ? g / a : 255; o[d + 2] = a ? b / a : 255; o[d + 3] = a / (k * k);
|
||
}
|
||
return { w: nw, h: nh, px: o };
|
||
}
|
||
|
||
// 带透明蒙版的图片换成预先合成好的 PNG:cairo 的蒙版写法在浏览器里边缘有噪点(原 PDF 的蒙版带 Matte,浏览器不认)
|
||
async function preciseFixMaskedImages(svg, pdfPath, pageNo, workDir) {
|
||
const usages = [...svg.matchAll(/<g mask="url\(#mask-(\d+)\)">\s*<use xlink:href="#source-(\d+)" transform="([^"]*)"\s*\/>\s*<\/g>/g)];
|
||
if (!usages.length) return svg;
|
||
const list = String(await preciseRun('pdfimages', ['-list', '-f', String(pageNo), '-l', String(pageNo), pdfPath])).split('\n').slice(2).map((l) => l.trim().split(/\s+/)).filter((r) => r.length > 5);
|
||
const prefix = path.join(workDir, `im${pageNo}`);
|
||
await preciseRun('pdfimages', ['-png', '-f', String(pageNo), '-l', String(pageNo), pdfPath, prefix]);
|
||
const pairs = [];
|
||
list.forEach((r, i) => { if (r[2] === 'image' && list[i + 1] && list[i + 1][2] === 'smask') pairs.push({ w: +r[3], h: +r[4], img: i, mask: i + 1, used: false }); });
|
||
const dims = {};
|
||
for (const m of svg.matchAll(/<image id="source-(\d+)" x="0" y="0" width="(\d+)" height="(\d+)"/g)) dims[m[1]] = [+m[2], +m[3]];
|
||
for (const u of usages) {
|
||
const d = dims[u[2]]; if (!d) continue;
|
||
const pr = pairs.find((q) => !q.used && q.w === d[0] && q.h === d[1]); if (!pr) continue;
|
||
pr.used = true;
|
||
try {
|
||
const img = pngDecode(fs.readFileSync(`${prefix}-${String(pr.img).padStart(3, '0')}.png`));
|
||
const mask = pngDecode(fs.readFileSync(`${prefix}-${String(pr.mask).padStart(3, '0')}.png`));
|
||
if (!img || !mask) continue;
|
||
const mt = (u[3].match(/matrix\(([^)]*)\)/) || [])[1];
|
||
const sx = mt ? Math.hypot(...mt.split(',').slice(0, 2).map(Number)) : 1;
|
||
const c = compositeRgba(img, mask, Math.ceil(d[0] * sx * 3.2));
|
||
const href = 'data:image/png;base64,' + pngEncode(c.w, c.h, c.px).toString('base64');
|
||
svg = svg.replace(u[0], `<image width="${d[0]}" height="${d[1]}" preserveAspectRatio="none" transform="${u[3]}" xlink:href="${href}"/>`);
|
||
} catch (e) { console.warn('[精准导入] 合成图片失败:', e.message); }
|
||
}
|
||
// 不再用到的蒙版和原图删掉,文件小一些
|
||
svg = svg.replace(/<mask id="mask-(\d+)">[\s\S]*?<\/mask>/g, (m, k) => (svg.includes(`url(#mask-${k})`) ? m : ''));
|
||
svg = svg.replace(/<image id="source-(\d+)"[^>]*\/>/g, (m, k) => (svg.includes(`#source-${k}"`) ? m : ''));
|
||
return svg;
|
||
}
|
||
|
||
const preciseIdOk = (id) => /^pd_[a-z0-9]+$/.test(String(id || ''));
|
||
function loadPreciseDoc(id) {
|
||
if (!preciseIdOk(id)) return null;
|
||
try { return JSON.parse(fs.readFileSync(path.join(PRECISE_DIR, id, 'doc.json'), 'utf8')); } catch (e) { return null; }
|
||
}
|
||
function savePreciseDoc(doc) { fs.writeFileSync(path.join(PRECISE_DIR, doc.id, 'doc.json'), JSON.stringify(doc)); }
|
||
|
||
// HTML 来源:把文字节点切出来(script / style 里的不算)
|
||
function htmlSegments(html) {
|
||
const parts = String(html).split(/(<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<!--[\s\S]*?-->|<[^>]+>)/i);
|
||
return parts.map((p, i) => ({ p, text: i % 2 === 0 ? xmlDecode(p).replace(/\s+/g, ' ').trim() : '' }));
|
||
}
|
||
// 需要翻译的全部文字(去重)
|
||
// 每条文字在原位置能放下多少个西文字符(给 AI 翻译时作长度上限,译文太长版面会挤)
|
||
// 图片文字(OCR)里和文字层重叠的条目不用(旧版本生成的彩页里可能还存着,这里显示和翻译时再过滤一次)
|
||
function preciseOcrList(pg) {
|
||
const boxes = (pg.lines || []).map((l) => ({ x: l.x, y: l.top, w: l.w, h: l.base - l.top + l.size * 0.3 }));
|
||
return (pg.ocr || []).filter((o) => !boxes.some((a) => {
|
||
const ix = Math.max(0, Math.min(a.x + a.w, o.x + o.w) - Math.max(a.x, o.x));
|
||
const iy = Math.max(0, Math.min(a.y + a.h, o.y + o.h) - Math.max(a.y, o.y));
|
||
return ix * iy > o.w * o.h * 0.3 || ix * iy > a.w * a.h * 0.4;
|
||
}));
|
||
}
|
||
function preciseUnitBudgets(doc) {
|
||
const map = new Map();
|
||
const add = (t, max) => {
|
||
const s = String(t || '').trim();
|
||
if (!s || !hasWords(s, doc.srcLang)) return;
|
||
const m = max > 0 ? Math.max(4, Math.floor(max)) : 0;
|
||
if (!map.has(s)) map.set(s, m); else if (m && (!map.get(s) || m < map.get(s))) map.set(s, m);
|
||
};
|
||
const cw = 0.52; // 西文字符平均宽度约为字号的 0.52 倍
|
||
if (doc.source === 'html') {
|
||
const html = fs.readFileSync(path.join(PRECISE_DIR, doc.id, 'source.html'), 'utf8');
|
||
htmlSegments(html).forEach((s) => add(s.text, 0));
|
||
}
|
||
for (const pg of doc.pages) {
|
||
(pg.blocks || []).forEach((b) => add(b.text, ((b.w * b.maxH) / (b.size * cw * b.lh)) * 0.92));
|
||
(pg.lines || []).filter((l) => !l.block).forEach((l) => add(l.text, l.maxW / (l.size * cw)));
|
||
preciseOcrList(pg).forEach((o) => add(o.text, o.para ? (o.w * o.h) / (o.fs * cw * o.lh) * 0.9 : o.vertical ? o.h / (Math.min(o.w, 12) * 0.74 * cw) : (o.maxW || o.w) / (o.h * 0.74 * cw)));
|
||
}
|
||
return map;
|
||
}
|
||
function preciseUnits(doc) { return [...preciseUnitBudgets(doc).keys()]; }
|
||
|
||
async function translatePreciseDoc(doc, lang, cfg, force) {
|
||
const budgets = preciseUnitBudgets(doc);
|
||
const units = [...budgets.keys()];
|
||
const have = force ? {} : doc.translations[lang] || {};
|
||
const todo = units.filter((u) => !have[u]);
|
||
const cjkTarget = lang === 'zh';
|
||
const sys = `你是专业的电力设备(UPS / 逆变器 / 储能 / 蓄电池)产品资料翻译。把用户给的 JSON 数组里每一条${PRECISE_LANGS[doc.srcLang] || '中文'}文字翻译成${PRECISE_LANGS[lang]},用于在原版彩页的原位置替换原文,所以:
|
||
1. 输入每一项是 {"t": 原文, "max": 最多字符数}。译文要放回原文的位置,空间有限:译文长度不能超过 max 个字符(max 为 0 表示不限)。
|
||
用这个行业规范、简洁的书面表达;放不下时用行业通用缩写、去掉不影响意思的词(如 Temperature→Temp.、Maximum→Max.、Approximately→Approx.、Compensation Coefficient→Temp. Comp.、Characteristics→Char.),宁可短也不要超长;
|
||
2. 数字、单位符号(V、A、Ah、W、kg、mm、℃、%、mΩ)、型号、品牌名保持原样;一条里只有一部分是外文的,只翻译需要翻译的部分;
|
||
3. 标题就译成标题,表格里的参数名就译成参数名,句子译成完整句子;不要加解释、不要加引号;
|
||
4. 严格返回一个 JSON 字符串数组(只有译文,不要 t / max 字段),和输入一一对应、条数相同、顺序相同,不要 markdown 代码块。`;
|
||
for (let i = 0; i < todo.length; i += 50) {
|
||
const chunk = todo.slice(i, i + 50);
|
||
const input = chunk.map((u) => ({ t: u, max: budgets.get(u) ? (cjkTarget ? Math.max(2, Math.floor(budgets.get(u) / 2)) : budgets.get(u)) : 0 }));
|
||
const content = await callDeepSeekWithRetry(cfg.apiKey, [{ role: 'system', content: sys }, { role: 'user', content: JSON.stringify(input) }], { maxTokens: 6000, temperature: 0.2, timeoutMs: 180000 });
|
||
const { data } = extractJson(content);
|
||
if (!Array.isArray(data)) throw new Error('AI 没有按格式返回翻译,请重试');
|
||
chunk.forEach((u, k) => { if (typeof data[k] === 'string' && data[k].trim()) have[u] = data[k].trim(); });
|
||
}
|
||
doc.translations[lang] = have;
|
||
savePreciseDoc(doc);
|
||
return { total: units.length, translated: units.filter((u) => have[u]).length };
|
||
}
|
||
|
||
// 渲染成一个独立的 HTML 文件(底图内嵌),CRM 里预览、下载、打印另存 PDF 都用它
|
||
function renderPreciseHtml(doc, lang) {
|
||
const tr = lang && lang !== doc.srcLang ? doc.translations[lang] || null : null;
|
||
const T = (t) => (tr && tr[String(t || '').trim()]) || null;
|
||
const rtl = lang === 'ar';
|
||
const dir = path.join(PRECISE_DIR, doc.id);
|
||
if (doc.source === 'html') {
|
||
const html = fs.readFileSync(path.join(dir, 'source.html'), 'utf8');
|
||
if (!tr) return html;
|
||
return htmlSegments(html).map((s, i) => {
|
||
if (i % 2 || !s.text) return s.p;
|
||
const t = T(s.text);
|
||
if (!t) return s.p;
|
||
const lead = (s.p.match(/^\s*/) || [''])[0], tail = (s.p.match(/\s*$/) || [''])[0];
|
||
return lead + htmlEsc(t) + tail;
|
||
}).join('').replace(/<html([^>]*)\blang="[^"]*"/i, `<html$1lang="${lang}"`);
|
||
}
|
||
const mime = { svg: 'image/svg+xml', jpg: 'image/jpeg', png: 'image/png' };
|
||
const pages = doc.pages.map((pg) => {
|
||
const ext = pg.bg.split('.').pop();
|
||
const bg = `data:${mime[ext]};base64,${fs.readFileSync(path.join(dir, pg.bg)).toString('base64')}`;
|
||
const els = [`<img class="bg" src="${bg}" alt="">`];
|
||
const runHtml = (l) => l.runs.map((r) => (r.gap ? `<u class="gap" style="width:${r.gap}pt"></u>` : `<u class="${r.f}${r.b ? ' b' : ''}"${r.s ? ` style="font-size:${r.s}pt"` : ''}>${htmlEsc(r.t)}</u>`)).join('');
|
||
const doneBlocks = new Set();
|
||
for (const l of pg.lines || []) {
|
||
if (tr && l.block) {
|
||
if (doneBlocks.has(l.block)) continue;
|
||
doneBlocks.add(l.block);
|
||
const b = pg.blocks.find((x) => x.id === l.block);
|
||
const t = b && T(b.text);
|
||
if (t) {
|
||
els.push(`<p class="tb ${b.fam === 't' ? 't' : 'e'}" data-h="${b.maxH}" style="left:${b.x}pt;top:${b.top}pt;width:${b.w}pt;font-size:${b.size}pt;line-height:${b.lh}pt;color:${b.color}">${htmlEsc(t)}</p>`);
|
||
continue;
|
||
}
|
||
// 段落没译到:退回逐行显示原文
|
||
for (const id of b ? b.lines : [l.id]) {
|
||
const x = pg.lines.find((y) => y.id === id);
|
||
if (x) els.push(`<span class="ln" data-b="${x.base}" data-w="${x.w}" style="left:${x.x}pt;top:${x.top}pt;font-size:${x.size}pt;color:${x.color}">${runHtml(x)}</span>`);
|
||
}
|
||
continue;
|
||
}
|
||
const t = tr ? T(l.text) : null;
|
||
if (t) {
|
||
const fam = l.runs.find((r) => r.f)?.f === 't' ? 't' : 'e';
|
||
els.push(`<span class="ln tr ${fam}" data-b="${l.base}" data-max="${l.maxW}" style="left:${l.x}pt;top:${l.top}pt;font-size:${l.size}pt;color:${l.color}">${htmlEsc(t)}</span>`);
|
||
} else {
|
||
els.push(`<span class="ln" data-b="${l.base}" data-w="${l.w}" style="left:${l.x}pt;top:${l.top}pt;font-size:${l.size}pt;color:${l.color}">${runHtml(l)}</span>`);
|
||
}
|
||
}
|
||
if (tr) {
|
||
for (const o of preciseOcrList(pg)) {
|
||
const t = T(o.text);
|
||
if (!t) continue;
|
||
if (o.para) els.push(`<b class="ov op" style="left:${o.x}pt;top:${o.y}pt;width:${o.w}pt;height:${o.h}pt"><em style="font-size:${o.fs.toFixed(2)}pt;line-height:${(o.lh * 0.92).toFixed(2)}pt">${htmlEsc(t)}</em></b>`);
|
||
else els.push(`<b class="ov${o.vertical ? ' vt' : ''}" data-max="${o.maxW || o.w}" style="left:${o.x}pt;top:${o.y}pt;width:${o.w}pt;height:${o.h}pt"><em style="font-size:${((o.vertical ? Math.min(o.w, 12) : o.h) * 0.74).toFixed(2)}pt">${htmlEsc(t)}</em></b>`);
|
||
}
|
||
}
|
||
return `<section class="page" style="width:${pg.w}pt;height:${pg.h}pt">${els.join('')}</section>`;
|
||
});
|
||
const w0 = doc.pages[0] ? doc.pages[0].w : 595.3, h0 = doc.pages[0] ? doc.pages[0].h : 841.9;
|
||
return `<!DOCTYPE html>
|
||
<html lang="${lang || doc.srcLang}"${rtl ? ' dir="ltr"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>${htmlEsc(doc.name)}${tr ? ' · ' + (PRECISE_LANGS[lang] || lang) : ''}</title>
|
||
<style>
|
||
@page { size: ${w0}pt ${h0}pt; margin: 0; }
|
||
html { background: #8a8a8a; } body { margin: 0; padding: 24px 0; display: grid; gap: 24px; justify-content: center; }
|
||
.page { position: relative; background: #fff; overflow: hidden; box-shadow: 0 4px 18px rgba(0,0,0,.35); }
|
||
.page > * { position: absolute; margin: 0; }
|
||
.bg { left: 0; top: 0; width: 100%; height: 100%; }
|
||
.ln { white-space: pre; line-height: 1; transform-origin: 0 0; display: block; }
|
||
.ln u { text-decoration: none; } .ln u.gap { display: inline-block; }
|
||
.y, .tb.e, .e { font-family: "Microsoft YaHei", "微软雅黑", "PingFang SC", "Noto Sans SC", "Source Han Sans SC", sans-serif; }
|
||
.s { font-family: SimSun, "宋体", "Songti SC", "Noto Serif SC", "Source Han Serif SC", serif; }
|
||
.t { font-family: "Times New Roman", Times, "Liberation Serif", serif; }
|
||
${lang && lang !== 'zh' ? '.e, .tb.e, .ov em { font-family: Arial, "Helvetica Neue", Helvetica, "Liberation Sans", "Noto Sans", sans-serif; }' : ''}
|
||
.b { font-weight: 700; }
|
||
.tb { text-align: ${rtl ? 'right' : 'justify'}; ${rtl ? 'direction: rtl;' : ''} }
|
||
.ov { display: flex; align-items: center; justify-content: flex-start; background: #fff; overflow: visible; font-weight: 400; }
|
||
.ov em { font-style: normal; white-space: nowrap; line-height: 1; ${rtl ? 'direction: rtl;' : ''} }
|
||
.ov.vt { justify-content: center; } .ov.vt em { transform: rotate(-90deg); }
|
||
.ov.op { align-items: flex-start; } .ov.op em { white-space: normal; text-align: ${rtl ? 'right' : 'justify'}; width: 100%; }
|
||
@media print { html { background: none; } body { padding: 0; gap: 0; display: block; } .page { box-shadow: none; break-after: page; } }
|
||
@media screen and (max-width: 860px) { body { zoom: calc(100vw / 860px); } }
|
||
</style></head><body>
|
||
${pages.join('\n')}
|
||
<script>
|
||
(function () {
|
||
var PT = 96 / 72;
|
||
function fit() {
|
||
// 每行按原文件里的基线定位(不同字体的字高不一样,用基线才对得齐)
|
||
document.querySelectorAll('.ln').forEach(function (s) {
|
||
var mk = document.createElement('i'); mk.style.cssText = 'display:inline-block;width:0;height:0;vertical-align:baseline';
|
||
s.appendChild(mk); var off = mk.offsetTop; s.removeChild(mk);
|
||
s.style.top = (parseFloat(s.dataset.b) * PT - off) + 'px';
|
||
var r = s.scrollWidth; if (!r) return;
|
||
if (s.dataset.w) { var w = parseFloat(s.dataset.w) * PT; if (Math.abs(r - w) > 0.5) s.style.transform = 'scaleX(' + (w / r) + ')'; }
|
||
else if (s.dataset.max) {
|
||
// 译文比原位置宽:差得不多就横向压一点,差得多就整体缩小字号(字形不变形),再按新字号重新对基线
|
||
var m = parseFloat(s.dataset.max) * PT;
|
||
if (r > m) {
|
||
var q = m / r;
|
||
if (q >= 0.86) s.style.transform = 'scaleX(' + q + ')';
|
||
else {
|
||
s.style.fontSize = (parseFloat(s.style.fontSize) * q * 1.02) + 'pt';
|
||
s.appendChild(mk); off = mk.offsetTop; s.removeChild(mk);
|
||
s.style.top = (parseFloat(s.dataset.b) * PT - off) + 'px';
|
||
if (s.scrollWidth > m) s.style.transform = 'scaleX(' + (m / s.scrollWidth) + ')';
|
||
}
|
||
}
|
||
}
|
||
});
|
||
// 译文段落超出原来的高度:逐步缩小字号
|
||
document.querySelectorAll('.tb').forEach(function (p) {
|
||
var maxH = parseFloat(p.dataset.h) * PT, fs = parseFloat(p.style.fontSize), lh = parseFloat(p.style.lineHeight), k = 1;
|
||
while (p.scrollHeight > maxH && k > 0.7) { k -= 0.04; p.style.fontSize = (fs * k) + 'pt'; p.style.lineHeight = (lh * k) + 'pt'; }
|
||
});
|
||
// 图片上的译文:色块颜色取原图这块周围的底色,文字颜色取块内和底色差别最大的颜色;文字太长就缩小
|
||
document.querySelectorAll('.page').forEach(function (pg) {
|
||
var ovs = pg.querySelectorAll('.ov'); if (!ovs.length) return;
|
||
var img = pg.querySelector('.bg'), cv = document.createElement('canvas');
|
||
cv.width = Math.round(pg.clientWidth * 2); cv.height = Math.round(pg.clientHeight * 2);
|
||
var ctx = cv.getContext('2d', { willReadFrequently: true });
|
||
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, cv.width, cv.height);
|
||
try { ctx.drawImage(img, 0, 0, cv.width, cv.height); } catch (e) { return; }
|
||
var sx = cv.width / pg.clientWidth;
|
||
ovs.forEach(function (o) {
|
||
var x = o.offsetLeft * sx, y = o.offsetTop * sx, w = o.offsetWidth * sx, h = o.offsetHeight * sx, ring = [], inner = [], d;
|
||
try {
|
||
d = ctx.getImageData(Math.max(0, x - 3), Math.max(0, y - 3), Math.min(cv.width - x, w + 6), Math.min(cv.height - y, h + 6));
|
||
} catch (e) { return; }
|
||
for (var j = 0; j < d.height; j++) for (var i = 0; i < d.width; i++) {
|
||
var k = (j * d.width + i) * 4, px = [d.data[k], d.data[k + 1], d.data[k + 2]];
|
||
if (i < 3 || j < 3 || i >= d.width - 3 || j >= d.height - 3) ring.push(px); else inner.push(px);
|
||
}
|
||
function med(a, c) { var v = a.map(function (p) { return p[c]; }).sort(function (m, n) { return m - n; }); return v[v.length >> 1] || 255; }
|
||
var bgc = [med(ring, 0), med(ring, 1), med(ring, 2)], best = null, bd = 0;
|
||
inner.forEach(function (p) { var dd = Math.abs(p[0] - bgc[0]) + Math.abs(p[1] - bgc[1]) + Math.abs(p[2] - bgc[2]); if (dd > bd) { bd = dd; best = p; } });
|
||
o.style.background = 'rgb(' + bgc.join(',') + ')';
|
||
var em = o.firstChild;
|
||
if (best && bd > 120) em.style.color = 'rgb(' + best.join(',') + ')';
|
||
else em.style.color = (bgc[0] + bgc[1] + bgc[2]) / 3 > 140 ? '#222' : '#fff';
|
||
var fs = parseFloat(em.style.fontSize);
|
||
if (o.classList.contains('op')) {
|
||
// 段落:缩小字号直到放得下
|
||
var k2 = 1, lh0 = parseFloat(em.style.lineHeight);
|
||
while (em.scrollHeight > o.clientHeight + 1 && k2 > 0.55) { k2 -= 0.05; em.style.fontSize = (fs * k2) + 'pt'; em.style.lineHeight = (lh0 * k2) + 'pt'; }
|
||
} else if (o.classList.contains('vt')) {
|
||
var lv = o.offsetHeight * 1.1, ev = em.scrollWidth; if (ev > lv) em.style.fontSize = Math.max(fs * lv / ev, 3) + 'pt';
|
||
} else {
|
||
// 单行:先往右加宽色块(不超过右边下一个文字),还放不下再缩小字号
|
||
var ew = em.scrollWidth + 3, maxw = parseFloat(o.dataset.max) * 96 / 72;
|
||
if (ew > o.offsetWidth) o.style.width = Math.min(ew, Math.max(maxw, o.offsetWidth)) + 'px';
|
||
ew = em.scrollWidth + 2;
|
||
if (ew > o.offsetWidth) em.style.fontSize = Math.max(fs * o.offsetWidth / ew, 3) + 'pt';
|
||
}
|
||
});
|
||
});
|
||
}
|
||
if (document.fonts && document.fonts.ready) document.fonts.ready.then(function () { window.requestAnimationFrame(fit); }); else window.addEventListener('load', fit);
|
||
window.addEventListener('load', function () { setTimeout(fit, 50); });
|
||
// 从"打印 / 另存为PDF"按钮打开:排好版后自动弹出打印窗口
|
||
if (/[?&]print=1/.test(location.search)) window.addEventListener('load', function () { setTimeout(function () { window.print(); }, 700); });
|
||
})();
|
||
</script>
|
||
</body></html>`;
|
||
}
|
||
|
||
app.get('/api/precise/:id', requireAuth, (req, res) => {
|
||
const doc = loadPreciseDoc(req.params.id);
|
||
if (!doc) return res.status(404).json({ error: '找不到这份原版彩页' });
|
||
const units = preciseUnits(doc);
|
||
const langs = {};
|
||
for (const [k, v] of Object.entries(doc.translations || {})) langs[k] = units.filter((u) => v[u]).length;
|
||
res.json({ id: doc.id, name: doc.name, source: doc.source, srcLang: doc.srcLang, pages: doc.pages.length || 1, units: units.length, langs, createdAt: doc.createdAt });
|
||
});
|
||
app.get('/api/precise/:id/html', requireAuth, (req, res) => {
|
||
const doc = loadPreciseDoc(req.params.id);
|
||
if (!doc) return res.status(404).send('not found');
|
||
const lang = PRECISE_LANGS[req.query.lang] ? req.query.lang : doc.srcLang;
|
||
const html = renderPreciseHtml(doc, lang);
|
||
// 原文件里的 HTML 可能带脚本:用沙箱方式打开,脚本拿不到 CRM 的登录状态
|
||
res.set('Content-Security-Policy', 'sandbox allow-scripts allow-modals allow-popups');
|
||
res.set('Content-Type', 'text/html; charset=utf-8');
|
||
if (req.query.download) {
|
||
const base = (String(req.query.name || doc.name || 'brochure').replace(/\.[a-z0-9]+$/i, '').replace(/[\\/:*?"<>|,]+/g, '_').slice(0, 80)) || 'brochure';
|
||
res.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(`${base}_${lang}.html`)}`);
|
||
}
|
||
res.send(html);
|
||
});
|
||
app.post('/api/precise/:id/translate', requireAuth, aiLimiter, async (req, res) => {
|
||
const doc = loadPreciseDoc(req.params.id);
|
||
if (!doc) return res.status(404).json({ error: '找不到这份原版彩页' });
|
||
const lang = (req.body || {}).lang;
|
||
if (!PRECISE_LANGS[lang] || lang === doc.srcLang) return res.status(400).json({ error: 'invalid language' });
|
||
const cfg = loadAiConfig();
|
||
if (!cfg.apiKey && !cfg.backup.apiKey) return res.status(400).json({ error: 'AI API key not configured(设置里填 DeepSeek 或阿里云的 Key)' });
|
||
try {
|
||
const r = await translatePreciseDoc(doc, lang, cfg, !!(req.body || {}).force);
|
||
res.json({ ok: true, ...r });
|
||
} catch (e) {
|
||
res.status(502).json({ error: e.message });
|
||
}
|
||
});
|
||
|
||
/* ------------------------------- ai translate ------------------------------ */
|
||
// 给前端的翻译词条缓存(存在 crm:translationGlossary 里,走通用storage接口)兜底:
|
||
// 前端自己先查缓存,只有命中不了的词才会调这个接口,这里只管翻译,不管缓存的存取。
|
||
|
||
const LANG_NAMES = { en: 'English', fr: 'French', ru: 'Russian', es: 'Spanish', ar: 'Arabic' };
|
||
|
||
app.post('/api/ai/translate-terms', requireAuth, aiLimiter, async (req, res) => {
|
||
const body = req.body || {};
|
||
const terms = Array.isArray(body.terms) ? body.terms.filter(t => typeof t === 'string' && t.trim()) : [];
|
||
const targetLang = body.targetLang;
|
||
if (!terms.length || !LANG_NAMES[targetLang]) return res.status(400).json({ error: 'invalid request' });
|
||
|
||
const cfg = loadAiConfig();
|
||
if (!cfg.apiKey && !cfg.backup.apiKey) return res.status(400).json({ error: 'AI API key not configured(设置里填 DeepSeek 或阿里云的 Key)' });
|
||
|
||
const systemPrompt = `你是专业的电力设备(UPS/逆变器/储能电池)技术资料翻译。把用户给出的技术/业务词汇逐条翻译成${LANG_NAMES[targetLang]}。
|
||
这些词条不一定是中文——有些是从英文(或其他语言)原始资料里原样提取的参数标签/数值,本身可能已经就是${LANG_NAMES[targetLang]}或者是国际通用的表述(比如型号、单位符号、专有名词)。
|
||
如果某个词条已经是${LANG_NAMES[targetLang]}、或者是不需要翻译的国际通用内容,直接原样返回这个词条本身,绝对不要把已经正确的内容翻译成别的语言(尤其不要把已经是英文/其他语言的词条"翻译"成中文)。
|
||
需要翻译的词条要符合这个行业规范书面用词(不要逐字直译),单位符号(如Vdc、A、kg、mm)保持原样不翻译。
|
||
严格按JSON对象格式返回:key是原始词条,value是翻译结果(或原样返回的词条本身),不要有多余文字、不要用markdown代码块包裹,每个词都必须有对应的返回值。`;
|
||
const userPrompt = JSON.stringify(terms);
|
||
|
||
try {
|
||
const content = await callDeepSeekWithRetry(cfg.apiKey, [
|
||
{ role: 'system', content: systemPrompt },
|
||
{ role: 'user', content: userPrompt },
|
||
], { maxTokens: 2000, temperature: 0.3 });
|
||
const { data: translations } = extractJson(content);
|
||
res.json({ translations });
|
||
} catch (e) {
|
||
res.status(502).json({ error: e.message });
|
||
}
|
||
});
|
||
|
||
/* ------------------------- communication attachments ------------------------- */
|
||
|
||
const upload = multer({
|
||
storage: multer.diskStorage({
|
||
destination: (req, file, cb) => {
|
||
const cid = safeId(req.params.customerId);
|
||
if (!cid) return cb(new Error('invalid customer id'));
|
||
const dir = path.join(UPLOADS_DIR, cid);
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
cb(null, dir);
|
||
},
|
||
filename: (req, file, cb) => {
|
||
const ts = Date.now();
|
||
const rand = Math.random().toString(36).slice(2, 8);
|
||
const ext = path.extname(file.originalname).slice(0, 10);
|
||
cb(null, `${ts}_${rand}${ext}`);
|
||
},
|
||
}),
|
||
// 不设fileSize上限——大文件(原版彩页PDF、高清产品图等)不受multer这层限制。
|
||
// 注意:Nginx反向代理默认client_max_body_size是1MB,比这里更早拦截超大请求,
|
||
// 如果还是传不了大文件,去Nginx该站点的server块里加一行 client_max_body_size 0;(不限制)
|
||
// 或设成足够大的值(比如 200m),改完 nginx -t 测试再 systemctl reload nginx。
|
||
});
|
||
|
||
app.post('/api/uploads/:customerId', requireAuth, (req, res) => {
|
||
if (!safeId(req.params.customerId)) return res.status(400).json({ error: 'invalid customer id' });
|
||
upload.single('file')(req, res, (err) => {
|
||
if (err) return res.status(400).json({ error: err.message });
|
||
if (!req.file) return res.status(400).json({ error: 'no file received' });
|
||
// multer/busboy 默认按 latin1 解析 multipart 里的文件名字段(这是老版HTTP规范的行为),
|
||
// 但浏览器实际发送的中文文件名是 UTF-8 字节,所以这里要把它从 latin1 转回 UTF-8,
|
||
// 不然中文文件名会变成乱码存进 data.json。
|
||
const originalName = Buffer.from(req.file.originalname, 'latin1').toString('utf8');
|
||
res.json({ fileName: req.file.filename, originalName, size: req.file.size });
|
||
});
|
||
});
|
||
|
||
app.delete('/api/uploads/:customerId/:fileName', requireAuth, (req, res) => {
|
||
const cid = safeId(req.params.customerId);
|
||
const fname = req.params.fileName;
|
||
const isSafeFile = fname && !fname.includes('..') && !fname.includes('/') && !fname.includes('\\');
|
||
if (!cid || !isSafeFile) return res.status(400).json({ error: 'invalid request' });
|
||
fs.unlink(path.join(UPLOADS_DIR, cid, fname), () => {
|
||
// a missing file is also treated as success, so clicking delete twice never errors
|
||
res.json({ ok: true });
|
||
});
|
||
});
|
||
|
||
const mountPublicApi = require('./public-api');
|
||
const publicApi = mountPublicApi(app, { dataFile: DATA_FILE, uploadsDir: UPLOADS_DIR, requireAuth, writeData, ai: { loadAiConfig, callDeepSeekWithRetry, extractJson } });
|
||
if (publicApi && publicApi.scheduleTemplateSync) onTemplatesChanged = publicApi.scheduleTemplateSync;
|
||
|
||
app.use('/uploads', requireAuth, express.static(UPLOADS_DIR));
|
||
|
||
// MIC 产品上传(远程浏览器 + 自动填表),模块文件在 mic-upload/ 目录
|
||
const { registerMicUploadRoutes, attachMicUploadWebSocket } = require('./mic-upload/micUploadRoutes');
|
||
const micSessions = registerMicUploadRoutes(app, {
|
||
requireAuth, readData, writeData, callDeepSeekWithRetry, loadAiConfig, encrypt, decrypt,
|
||
});
|
||
|
||
app.use(express.static(FRONTEND_DIST));
|
||
app.get('*', (req, res) => {
|
||
res.sendFile(path.join(FRONTEND_DIST, 'index.html'));
|
||
});
|
||
|
||
/* ------------------------------- bootstrap ------------------------------ */
|
||
|
||
loadAuth(); // make sure auth.json exists with default credentials on first run
|
||
|
||
fs.writeFileSync(PID_FILE, String(process.pid), 'utf8');
|
||
process.on('exit', () => {
|
||
try { fs.unlinkSync(PID_FILE); } catch (e) {}
|
||
});
|
||
process.on('SIGINT', () => process.exit(0));
|
||
process.on('SIGTERM', () => process.exit(0));
|
||
|
||
const server = app.listen(PORT, HOST, () => {
|
||
console.log(`[customer-crm] running at http://${HOST}:${PORT}`);
|
||
});
|
||
|
||
attachMicUploadWebSocket(server, micSessions);
|
||
|
||
|
||
server.on('error', (e) => {
|
||
if (e.code === 'EADDRINUSE') {
|
||
console.log('[customer-crm] another instance is already running on this port, exiting.');
|
||
try { fs.unlinkSync(PID_FILE); } catch (err) {}
|
||
process.exit(0);
|
||
}
|
||
throw e;
|
||
});
|