From 255e1e92c0ed316eab924fba22d146c67d2655b6 Mon Sep 17 00:00:00 2001 From: mike Date: Mon, 9 Nov 2026 16:28:21 +0800 Subject: [PATCH] Update server.js via upload script - 2026-11-09 16:28:12 --- server.js | 807 +----------------------------------------------------- 1 file changed, 5 insertions(+), 802 deletions(-) diff --git a/server.js b/server.js index 9dbc864..69cbdc4 100644 --- a/server.js +++ b/server.js @@ -1033,11 +1033,6 @@ app.post('/api/ai/parse-catalog', requireAuth, aiLimiter, (req, res) => { 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-')); @@ -1127,17 +1122,7 @@ app.post('/api/ai/parse-catalog', requireAuth, aiLimiter, (req, res) => { 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, autoLangs: PRECISE_AUTO_LANGS.filter((l) => l !== pd.srcLang) }; - finalProducts.forEach((fp) => { fp.preciseDocId = pd.id; }); - autoTranslatePrecise(pd.id); - } - } - res.json({ products: finalProducts, ocrTextLength: text.length, truncated, preciseDoc, preciseError }); + res.json({ products: finalProducts, ocrTextLength: text.length, truncated }); } catch (e) { const hint = /empty response/i.test(e.message) ? '(重试后仍然失败,可能是一次上传的文件太多导致AI输出内容超长;建议减少单次上传的数量,比如分成2-3批,每批3-5张)' @@ -1150,791 +1135,6 @@ app.post('/api/ai/parse-catalog', requireAuth, aiLimiter, (req, res) => { }); }); -/* ================================ 精准导入 ================================ */ -// AI 导入时勾选"精准导入":除了照常提取产品字段,还把原文件按原版式 1:1 还原成网页("原版彩页"),之后可以一键翻译成其他语言, -// 翻译后版式不变(文字在原位置替换,图片里的文字用同底色的色块盖住再写译文)。 -// -// 三种来源: -// · 有文字层的 PDF(WPS / Word / InDesign 导出的规格书):pdftocairo 把每页转成 SVG,去掉里面的文字只留线条/色块/图片当底图; -// 文字用 pdftohtml 取出(位置、字号、颜色、粗体),基线位置从 SVG 里每个字的坐标取,所以和原文件严丝合缝; -// 图片里的文字(曲线图坐标轴等)用 OCR 找出来,只在翻译版里盖色块替换。 -// · 扫描版 PDF / JPG / PNG:整页图片当底图,文字全部靠 OCR 定位,原文版就是原图,翻译版在图上盖色块写译文。 -// · HTML:原样保存,翻译时只替换文字节点,结构和样式不动。 -// 存储:uploads/_precise//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, '"'); -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(//g, (m, x, y) => { glyphs.push([+x, +y]); return ''; }); - // 描边加粗的文字(标题常见):cairo 先画一组字,紧跟着再画一条带曲线的描边路径,这条也去掉(表格线是直线,不受影响) - svg = svg.replace(/(\s*<\/g>)\s*]*?d="([^"]*)"[^>]*\/>/g, (m, g, d) => ((d.match(/[MLCQZ]/gi) || []).length >= 8 ? g : m)); - // 带透明蒙版的图片:cairo 用"滤镜 + 蒙版"实现,浏览器按低分辨率算滤镜,边缘会出噪点;亮度蒙版本身就是同样效果,去掉滤镜 - svg = svg.replace(/\s*]*?) filter="url\(#filter-color-to-alpha\)"([^>]*)\/>\s*<\/g>/g, ''); - 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(//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(/([\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: //.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(//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(/\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(/ !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], ``); - } catch (e) { console.warn('[精准导入] 合成图片失败:', e.message); } - } - // 不再用到的蒙版和原图删掉,文件小一些 - svg = svg.replace(/[\s\S]*?<\/mask>/g, (m, k) => (svg.includes(`url(#mask-${k})`) ? m : '')); - svg = svg.replace(/]*\/>/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(/(|||<[^>]+>)/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. 标题就译成标题,表格里的参数名就译成参数名,句子译成完整句子;不要加解释、不要加引号; -${lang === 'ru' ? ' 俄语:单位用俄文写法(В、А、А·ч、Вт、мОм、кг、мм、с、мин、ч),小数用逗号(6,0 мОм);参数名用俄语技术资料常见缩写(Номин.、Макс.、Напряж.、Термокомп.);\n' : ''}${lang === 'es' || lang === 'fr' ? ' 小数用逗号(6,0 mΩ),参数名用该语言技术资料常见缩写(Máx.、Temp.、Nom.);\n' : ''}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; - // 只写回这一种语言的译文(后台同时在翻别的语言,不能用旧的整份覆盖掉) - const cur = loadPreciseDoc(doc.id) || doc; - cur.translations = { ...(cur.translations || {}), [lang]: have }; - cur.pending = (cur.pending || []).filter((x) => x !== lang); - savePreciseDoc(cur); - return { total: units.length, translated: units.filter((u) => have[u]).length }; -} - -// 精准导入完成后自动翻译成网站要用的语言(英语 / 俄语 / 西班牙语),后台依次进行,不影响导入本身 -const PRECISE_AUTO_LANGS = ['en', 'ru', 'es']; -function autoTranslatePrecise(id) { - const doc0 = loadPreciseDoc(id); - if (!doc0) return; - const langs = PRECISE_AUTO_LANGS.filter((l) => l !== doc0.srcLang); - doc0.pending = langs; doc0.pendingSince = Date.now(); savePreciseDoc(doc0); - (async () => { - const cfg = loadAiConfig(); - for (const lang of langs) { - try { - const doc = loadPreciseDoc(id); - if (!doc) return; - const r = await translatePreciseDoc(doc, lang, cfg); - console.log(`[精准导入] ${id} 自动翻译 ${lang}: ${r.translated}/${r.total}`); - } catch (e) { - console.warn(`[精准导入] ${id} 自动翻译 ${lang} 失败:`, e.message); - const cur = loadPreciseDoc(id); - if (cur) { cur.pending = (cur.pending || []).filter((x) => x !== lang); cur.failed = { ...(cur.failed || {}), [lang]: e.message }; savePreciseDoc(cur); } - } - } - })(); -} - -// 同一类文字(同一列、同字号、同颜色)——译文统一字号用 -const lineGroup = (l) => `${l.color}_${Math.round(l.size * 4)}_${Math.round(l.x / 3)}`; -// 表头常见的西文时间单位,按目标语言换写法(英文版不变) -const UNIT_WORDS = { - ru: { time: 'Время', min: 'мин', h: 'ч' }, es: { time: 'Tiempo', min: 'min', h: 'h' }, fr: { time: 'Temps', min: 'min', h: 'h' }, - ar: { time: 'الوقت', min: 'دقيقة', h: 'ساعة' }, zh: { time: '时间', min: '分钟', h: '小时' }, -}; -function unitWord(text, lang) { - const u = UNIT_WORDS[lang]; if (!u) return ''; - const t = String(text || '').trim(); - if (/^time$/i.test(t)) return u.time; - const m = t.match(/^(\d+(?:\.\d+)?)\s*(min|mins|minutes?|h|hr|hrs|hours?)$/i); - if (!m) return ''; - return `${lang === 'ru' ? m[1].replace('.', ',') : m[1]} ${/^m/i.test(m[2]) ? u.min : u.h}`; -} - -// 渲染成一个独立的 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(/]*)\blang="[^"]*"/i, ` { - const ext = pg.bg.split('.').pop(); - const bg = `data:${mime[ext]};base64,${fs.readFileSync(path.join(dir, pg.bg)).toString('base64')}`; - const els = [``]; - const runHtml = (l) => l.runs.map((r) => (r.gap ? `` : `${htmlEsc(r.t)}`)).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(`

${htmlEsc(t)}

`); - continue; - } - // 段落没译到:退回逐行显示原文 - for (const id of b ? b.lines : [l.id]) { - const x = pg.lines.find((y) => y.id === id); - if (x) els.push(`${runHtml(x)}`); - } - continue; - } - const t = tr ? T(l.text) : null; - if (t) { - const fam = l.runs.find((r) => r.f)?.f === 't' ? 't' : 'e'; - els.push(`${htmlEsc(t)}`); - } else if (tr && lang !== 'zh' && /[(),:;]/.test(l.text)) { - // 没翻译的数值行(如 27.2Kg(1±3%)):中文全角标点换成西文标点 - const t2 = l.text.replace(/\s*(/g, ' (').replace(/)/g, ')').replace(/,\s*/g, ', ').replace(/:\s*/g, ': ').replace(/;\s*/g, '; '); - els.push(`${htmlEsc(t2)}`); - } else if (tr && unitWord(l.text, lang)) { - // 表头里的 Time / 10min / 1h 这类西文单位,也换成目标语言的写法 - els.push(`${htmlEsc(unitWord(l.text, lang))}`); - } else { - els.push(`${runHtml(l)}`); - } - } - if (tr) { - for (const o of preciseOcrList(pg)) { - const t = T(o.text); - if (!t) continue; - if (o.para) els.push(`${htmlEsc(t)}`); - else els.push(`${htmlEsc(t)}`); - } - } - return `
${els.join('')}
`; - }); - const w0 = doc.pages[0] ? doc.pages[0].w : 595.3, h0 = doc.pages[0] ? doc.pages[0].h : 841.9; - return ` - -${htmlEsc(doc.name)}${tr ? ' · ' + (PRECISE_LANGS[lang] || lang) : ''} - -${pages.join('\n')} - -`; -} - -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, pending: doc.pendingSince && Date.now() - doc.pendingSince < 20 * 60 * 1000 ? doc.pending || [] : [], failed: doc.failed || {}, 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 { - if (doc.failed && doc.failed[lang]) { delete doc.failed[lang]; savePreciseDoc(doc); } - 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接口)兜底: // 前端自己先查缓存,只有命中不了的词才会调这个接口,这里只管翻译,不管缓存的存取。 @@ -2021,7 +1221,10 @@ 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)); +// 多语言原版彩页可能是 HTML:用沙箱方式打开,页面里的脚本拿不到 CRM 的登录状态 +app.use('/uploads', requireAuth, express.static(UPLOADS_DIR, { + setHeaders: (res, filePath) => { if (/\.html?$/i.test(filePath)) res.setHeader('Content-Security-Policy', 'sandbox allow-scripts allow-modals allow-popups'); }, +})); // MIC 产品上传(远程浏览器 + 自动填表),模块文件在 mic-upload/ 目录 const { registerMicUploadRoutes, attachMicUploadWebSocket } = require('./mic-upload/micUploadRoutes');