Update micUploadRoutes.js via upload script - 2026-09-22 11:57:56

This commit is contained in:
mike 2026-09-22 11:58:07 +08:00
parent c3df1f6c49
commit 80a1a72204
1 changed files with 78 additions and 10 deletions

View File

@ -27,19 +27,20 @@
const crypto = require('crypto');
const WebSocket = require('ws');
const { MicBrowserSession } = require('./micBrowserSession');
const { buildAttributeList, sanitizeValue, parsePackageDimensionsCm } = require('./micFieldMapping');
const { buildAttributeList, sanitizeValue, parsePackageDimensionsCm, hasNonAscii } = require('./micFieldMapping');
// 标题/关键词规则来自MIC官方说明(2026-09抓取):
// 标题 https://service.made-in-china.com/help/promotionskill/product/3243.htm
// 关键词 https://service.made-in-china.com/help/promotionskill/product/473.htm
const _TITLE_SYSTEM_PROMPT = `You write English product titles for Made-in-China.com B2B listings, following the platform's official rules:
- 5 to 12 words total.
- Suggested structure: [modifier(s)] + [ONE core noun] + for [application scope] + with [certifications/key feature] + (model/standard/feature). Omit the "for"/"with" parts if there's nothing relevant to fill them with — never leave a literal "for"/"with" with nothing after it.
- 5 to 12 words total (the brand name below, if given, counts toward this).
- If a brand name is provided in the user message, the title MUST start with that exact brand name as the very first word. If no brand is provided, do NOT include any brand name anywhere in the title.
- Suggested structure: [Brand] + [modifier(s)] + [ONE core noun] + for [application scope] + with [certifications/key feature] + (model/standard/feature). Omit the "for"/"with" parts if there's nothing relevant to fill them with — never leave a literal "for"/"with" with nothing after it.
- The whole title must revolve around a SINGLE core noun (the main product category term, e.g. "UPS", "Inverter", "Battery"). Do not stack multiple synonyms for the same thing.
- Do not write an overly bare/generic title with no modifiers — add descriptive modifiers (capacity, technology, application) so it matches varied buyer search phrasing.
- Precision matters more than keyword stuffing.
You must also report which exact word in your title is the core noun (copy it verbatim, single word, as it literally appears in the title — e.g. "UPS", not "UPS unit").
You must also report which exact word in your title is the core noun (copy it verbatim, single word, as it literally appears in the title — e.g. "UPS", not "UPS unit"). The core noun is never the brand name.
Output ONLY a JSON object, nothing else, in this exact shape:
{"title": "...", "coreNoun": "..."}`;
@ -65,9 +66,10 @@ function summarizeSpecsForAi(attrList, max = 8) {
return attrList.slice(0, max).map((a) => `${a.name}: ${a.value}`).join('; ');
}
function localFallbackTitle(categoryName, model) {
function localFallbackTitle(categoryName, model, brand) {
// AI不可用时的兜底——尽量别太离谱,但明确标注这是兜底,提醒人工检查
return { title: `${categoryName || 'Power Equipment'} ${model}`.trim(), coreNoun: categoryName || 'Product' };
const prefix = brand ? `${brand} ` : '';
return { title: `${prefix}${categoryName || 'Power Equipment'} ${model}`.trim(), coreNoun: categoryName || 'Product' };
}
function localFallbackKeywords(coreNoun) {
@ -82,7 +84,7 @@ function localFallbackKeywords(coreNoun) {
// 返回 { title, coreNoun }——中心词直接由生成标题的同一次AI调用给出,不再靠
// 事后从标题字符串里猜(之前那套"for前面最后一个词"的算法碰到标题里"for"
// 前面刚好是别的修饰词时就会猜错,产出一堆带着错误中心词的关键词)。
async function generateTitle(ctx, { categoryName, model, applicationScenarios, specsSummary }, log) {
async function generateTitle(ctx, { categoryName, model, brand, applicationScenarios, specsSummary }, log) {
let apiKey = '';
try {
const cfg = ctx.loadAiConfig();
@ -91,10 +93,11 @@ async function generateTitle(ctx, { categoryName, model, applicationScenarios, s
if (!apiKey) {
log('未配置DeepSeek Key,标题使用简单兜底,建议人工检查/补充', 'WARNING');
return localFallbackTitle(categoryName, model);
return localFallbackTitle(categoryName, model, brand);
}
const userLines = [
brand ? `Brand: ${brand}` : 'Brand: (none — do not include any brand name in the title)',
`Product category: ${categoryName || '(unknown)'}`,
`Model: ${model}`,
applicationScenarios ? `Application scenarios: ${applicationScenarios}` : null,
@ -115,8 +118,13 @@ async function generateTitle(ctx, { categoryName, model, applicationScenarios, s
if (raw.startsWith('json')) raw = raw.slice(4);
}
const parsed = JSON.parse(raw.trim());
const title = String(parsed.title || '').trim();
let title = String(parsed.title || '').trim();
const coreNoun = String(parsed.coreNoun || '').trim();
// 代码层兜底:品牌规则比较死板(只在恰好是SKE时加),不完全依赖AI听话——
// 该加没加上就补上,不该加却加了就去掉。
if (brand) {
if (!title.toLowerCase().startsWith(brand.toLowerCase())) title = `${brand} ${title}`;
}
const wordCount = title.split(/\s+/).filter(Boolean).length;
if (!title || wordCount < 3 || wordCount > 20) throw new Error(`AI标题长度异常(${wordCount}词): ${title}`);
if (!coreNoun || !title.toLowerCase().includes(coreNoun.toLowerCase())) {
@ -178,6 +186,62 @@ async function generateKeywords(ctx, title, coreNoun, model, log) {
}
}
// 净化/量词替换表只能处理已知的固定符号和单词,碰到整句中文描述(比如
// "三进单出(可调单进单出)"这种)没法靠替换表覆盖——这里兜底用AI把attrList里
// 净化后仍然残留非ASCII字符的值整句翻译成英文。一次性把所有需要翻译的值打包
// 成一个请求,而不是每条都单独调用,省时间也省token。
async function translateResidualChineseFields(ctx, attrList, log) {
const indices = [];
const toTranslate = [];
attrList.forEach((item, i) => {
if (hasNonAscii(item.value)) { indices.push(i); toTranslate.push(item.value); }
});
if (toTranslate.length === 0) return attrList;
let apiKey = '';
try {
const cfg = ctx.loadAiConfig();
apiKey = cfg && cfg.apiKey;
} catch (e) { /* 走兜底 */ }
if (!apiKey) {
log(`有 ${toTranslate.length} 个属性值仍含中文,但没配置DeepSeek Key无法自动翻译,需要人工检查后再提交`, 'WARNING');
return attrList;
}
const prompt = `Translate each of these product spec values (from a power equipment / UPS / battery datasheet) `
+ `from Chinese (or mixed Chinese/English) into concise, natural English suitable for a B2B product listing. `
+ `Keep numbers, units, model codes, and any English words unchanged — only translate the Chinese text. `
+ `Return ONLY a JSON array of strings, same length and same order as the input, no explanation.\n\n`
+ `Values: ${JSON.stringify(toTranslate)}`;
try {
const content = await ctx.callDeepSeekWithRetry(apiKey, [{ role: 'user', content: prompt }], { temperature: 0.3, maxTokens: 600 }, 2);
let raw = String(content).trim();
if (raw.startsWith('```')) {
raw = raw.split('```')[1];
if (raw.startsWith('json')) raw = raw.slice(4);
}
const translated = JSON.parse(raw.trim());
if (!Array.isArray(translated) || translated.length !== toTranslate.length) {
throw new Error(`AI返回的翻译数量(${Array.isArray(translated) ? translated.length : '非数组'})跟请求数量(${toTranslate.length})对不上`);
}
const result = attrList.map((item) => ({ ...item }));
indices.forEach((idx, j) => {
const newVal = sanitizeValue(translated[j]); // 翻译结果再跑一遍已知符号净化
log(`AI翻译属性值: "${attrList[idx].value}" -> "${newVal}"`);
if (hasNonAscii(newVal)) {
log(` ⚠️ 翻译后仍含非ASCII字符,需要人工检查这一条: ${result[idx].name}`, 'WARNING');
}
result[idx] = { ...result[idx], value: newVal };
});
return result;
} catch (e) {
log(`AI翻译残留中文属性值失败,保留原文,需要人工检查后再提交: ${e.message}`, 'WARNING');
return attrList;
}
}
// 拆成两个函数是因为路由必须注册在SPA兜底路由(app.get('*', ...))之前,
// 而WebSocket的upgrade监听依赖 app.listen() 返回的 server 实例,只能在那之后
// 才能拿到——这两个时间点在server.js里天然不是同一个地方,所以拆开成两次调用,
@ -360,14 +424,18 @@ function registerMicUploadRoutes(app, ctx) {
});
}
const { model, attrList, warnings } = buildAttributeList(product);
const { model, attrList: rawAttrList, warnings } = buildAttributeList(product);
for (const w of warnings) session.log(w, 'WARNING');
const attrList = await translateResidualChineseFields(ctx, rawAttrList, (m, l) => session.log(m, l));
await session.gotoPublishTemplate(templateUrl);
// 只有品牌恰好是SKE才在标题里加品牌前缀,没有品牌或者品牌不是SKE都不加
const brandForTitle = (product.brand && String(product.brand).trim().toUpperCase() === 'SKE') ? 'SKE' : null;
const { title, coreNoun } = await generateTitle(ctx, {
categoryName: product.type || product.category,
model,
brand: brandForTitle,
applicationScenarios: product.applicationScenarios,
specsSummary: summarizeSpecsForAi(attrList),
}, (m, l) => session.log(m, l));