diff --git a/public-api.js b/public-api.js index a863c39..fc7f294 100644 --- a/public-api.js +++ b/public-api.js @@ -225,10 +225,65 @@ async function translateTemplateHtml(ai, products) { } } +// ===== 网站产品介绍:没手动填英文介绍的产品,由 AI 根据参数自动写一段 ===== +// 参数变了会重新生成(缓存按参数内容算);手动填了英文介绍就一直用手动的。 +const TYPE_EN = { '迷你UPS': 'Mini DC UPS', '离线式UPS': 'Offline UPS', '离线式锂电UPS': 'Lithium-ion offline UPS', '在线互动式UPS': 'Line-interactive UPS' }; +const DESC_SKIP = new Set(['model', 'brand', 'category', 'type', 'machineVariant', 'description', 'sale', 'youtube', 'sellingPoints', 'sockets', 'extraSpecs']); +const SOCKET_EN = { SCHUKO: 'Schuko', NEMA: 'NEMA 5-15', UK: 'BS 1363 (UK)', UNIVERSAL: 'universal', IEC: 'IEC C13', AU: 'Type I (AU/CN)' }; +function descFacts(p) { + const f = { model: p.model }; + if (TYPE_EN[p.type]) f.type = TYPE_EN[p.type]; + for (const [k, v] of Object.entries(p)) { + if (DESC_SKIP.has(k) || k.startsWith('_') || ['slug', 'images', 'detailImages', 'templateImages', 'templateHtml', 'specI18n'].includes(k)) continue; + const en = p.specI18n && p.specI18n[k] && p.specI18n[k].en; + if (en) { f[k] = en; continue; } + if (typeof v === 'string' && v.trim() && !hasZh(v)) f[k] = v.trim(); + else if (Array.isArray(v) && k === 'outputPorts') f[k] = v.map((o) => [o.type, o.voltage, o.current].filter(Boolean).join(' ')).filter((x) => !hasZh(x)); + } + if (Array.isArray(p.sockets) && p.sockets.length) f.sockets = p.sockets.map((x) => `${x.count} x ${SOCKET_EN[x.type] || x.type}`).join(' + '); + if (p._points && p._points.length) f.sellingPoints = p._points; + return f; +} +async function generateDescriptions(ai, products) { + const todo = products.filter((p) => !(p.description && String(p.description.en || '').trim())); + if (!todo.length) return; + const cache = loadCache(); + // 参数太少(只有型号、类型)不生成,免得 AI 编内容 + const items = todo.map((p) => { const f = descFacts(p); const facts = JSON.stringify(f); return { p, facts, key: cacheKey('aidesc', facts), n: Object.keys(f).length }; }).filter((x) => x.n >= 4); + const need = items.filter((x) => !cache[x.key]); + let dirty = false; + if (ai && need.length) { + const cfg = ai.loadAiConfig(); + if (cfg.apiKey) { + const system = `You write short product introductions for the B2B website of a Chinese UPS manufacturer that sells to importers and distributors. +For each product spec object, write 2-3 sentences (45-80 words), plain English text, no markdown, no line breaks. +Use ONLY facts present in the specs: never invent certifications, warranty, prices, runtime figures or features that are not given. +Mention the model and product type, its capacity or output, and the 2-3 most useful specs for a buyer (battery, transfer time, waveform, sockets or output ports, display). +Finish with typical applications that fit this kind of product. Confident, factual tone; no superlatives such as "best" or "ultimate". +Input is a JSON array of spec objects. Return ONLY a JSON array of strings, same length and order, no extra text.`; + for (let i = 0; i < need.length; i += 6) { + const chunk = need.slice(i, i + 6); + try { + const content = await ai.callDeepSeekWithRetry(cfg.apiKey, [ + { role: 'system', content: system }, + { role: 'user', content: '[' + chunk.map((x) => x.facts).join(',') + ']' }, + ], { maxTokens: 2500, temperature: 0.4 }); + const { data } = ai.extractJson(content); + if (!Array.isArray(data) || data.length !== chunk.length) throw new Error('wrong shape'); + chunk.forEach((x, j) => { const t = String(data[j] || '').trim(); if (t) { cache[x.key] = t; dirty = true; } }); + } catch (e) { console.warn('[public-api] AI 产品介绍生成失败:', e.message); } + } + } + } + if (dirty) { try { saveCache(cache); } catch (e) {} } + for (const x of items) if (cache[x.key]) x.p.description = { ...(x.p.description || {}), en: cache[x.key] }; +} + // 给一批产品补齐各语言的介绍和卖点。翻译失败不影响构建:那一项网站上显示英文。 async function translateProducts(ai, products) { try { await translateSpecs(ai, products); } catch (e) { console.warn('[public-api] 参数翻译失败:', e.message); } try { await translateTemplateHtml(ai, products); } catch (e) { console.warn('[public-api] HTML 模板翻译失败:', e.message); } + try { await generateDescriptions(ai, products); } catch (e) { console.warn('[public-api] AI 产品介绍失败:', e.message); } if (!ai) { for (const p of products) { if (p._points.length) p.sellingPointsI18n = { en: p._points }; delete p._points; } return products; @@ -450,6 +505,21 @@ module.exports = function mountPublicApi(app, { dataFile, uploadsDir, requireAut res.sendFile(path.resolve(uploadsDir, SITE_ASSETS_DIR, file), (err) => { if (err) res.status(404).end(); }); }); + // 后台产品编辑页"查看 AI 生成的介绍":不管有没有发布都能看;用的是同一份缓存,网站上就是这段 + app.get('/api/site/ai-description/:id', requireAuth, async (req, res) => { + try { + const p = readProducts(dataFile).find((x) => String(x.id) === String(req.params.id)); + if (!p) return res.status(404).json({ error: '产品不存在(新建的产品先保存一次)' }); + const pub = toPublic(p, readTemplates(dataFile)); + pub.description = {}; // 预览时忽略手动介绍,看 AI 会写什么 + await translateSpecs(ai, [pub]); + await generateDescriptions(ai, [pub]); + const text = pub.description && pub.description.en; + if (!text) return res.status(502).json({ error: 'AI 生成失败,请检查 DeepSeek 设置或稍后再试' }); + res.json({ text }); + } catch (e) { res.status(500).json({ error: e.message }); } + }); + // 后台"更新到网站"按钮:触发 Cloudflare Pages 重新构建(需要后台登录) // Cloudflare 在上一次构建还没跑完时会返回 304(不新建构建)。这时不让用户等: // 服务器记下"还有一次待更新",每 20 秒自动重试,直到 Cloudflare 接受新的构建为止。