1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
| const axios = require('axios'); const fs = require('fs'); const path = require('path'); const { promisify } = require('util'); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const stat = promisify(fs.stat);
const apiKey = process.env.KIMI_API_KEY || hexo.config.kimi_api_key;
const DEFAULT_CONFIG = { apiKey: '', model: 'moonshot-v1-8k', temperature: 0.7, max_tokens: 200, maxLength: 100, minRatio: 0.1, maxRatio: 0.3, minLength: 20, language: 'zh', updateWindow: 5 * 60 * 1000, forceUpdate: false, maxRetries: 3, retryDelay: 1000, concurrency: 3, validateApi: true, validateInterval: 3600000, };
let apiStatus = { lastValidated: 0, isValid: false, error: null };
const processedFiles = new Set(); const processingFiles = new Set();
function getApiKey(config) { if (process.env.KIMI_API_KEY) { return process.env.KIMI_API_KEY; } if (config.apiKey) { return config.apiKey; } return null; }
async function validateApiKey(config) { try { const apiKey = getApiKey(config); if (!apiKey) { throw new Error('未设置 API 密钥,请在环境变量 KIMI_API_KEY 或配置文件中设置'); }
const response = await axios.post('https://api.moonshot.cn/v1/chat/completions', { model: config.model, messages: [ { role: "user", content: "test" } ], max_tokens: 5 }, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, timeout: 5000 });
if (response.status !== 200) { throw new Error(`API 返回错误状态码: ${response.status}`); }
apiStatus = { lastValidated: Date.now(), isValid: true, error: null };
return true; } catch (error) { apiStatus = { lastValidated: Date.now(), isValid: false, error: error.message };
throw error; } }
async function checkApiStatus(config) { if (!config.validateApi) { return true; }
const now = Date.now(); if (now - apiStatus.lastValidated < config.validateInterval && apiStatus.isValid) { return true; }
try { await validateApiKey(config); return true; } catch (error) { console.error('API 验证失败:', error.message); return false; } }
function getConfig(hexo) { return Object.assign({}, DEFAULT_CONFIG, hexo.config.auto_description); }
function calculateSummaryLength(contentLength, config) { let minLength = Math.max(config.minLength, Math.floor(contentLength * config.minRatio)); let maxLength = Math.floor(contentLength * config.maxRatio); if (maxLength > 100) { maxLength = 100; minLength = Math.min(minLength, 90); } maxLength = Math.max(maxLength, minLength + 10); maxLength = Math.min(maxLength, 100); return { minLength, maxLength }; }
async function generateDescription(content, config) { const apiValid = await checkApiStatus(config); if (!apiValid) { throw new Error('API 验证失败,无法生成摘要'); }
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); const TOLERANCE = 10; const rateLimiter = { lastRequestTime: 0, cooldownSeconds: 1, consecutiveErrors: 0, maxConsecutiveErrors: 3, async waitForCooldown() { const now = Date.now(); const timeSinceLastRequest = (now - this.lastRequestTime) / 1000; const waitTime = this.cooldownSeconds * (1 + this.consecutiveErrors); if (timeSinceLastRequest < waitTime) { const actualWaitTime = (waitTime - timeSinceLastRequest) * 1000; console.log(`等待 ${actualWaitTime/1000} 秒后重试...`); await new Promise(resolve => setTimeout(resolve, actualWaitTime)); } this.lastRequestTime = Date.now(); }, handleSuccess() { this.consecutiveErrors = 0; this.cooldownSeconds = 1; }, handleError() { this.consecutiveErrors++; this.cooldownSeconds *= 2; if (this.consecutiveErrors >= this.maxConsecutiveErrors) { throw new Error('连续请求失败次数过多,停止处理'); } } };
function getSystemPrompt(isRecursive, lengthConfig) { if (isRecursive) { return config.language === 'zh' ? `你是一个专业的文章精简专家。请按照以下要求精简摘要: 1. 输出长度控制在100字以内 2. 保留核心信息和关键内容 3. 删除不必要的修饰词 4. 使用简练的表达 5. 保持语言通顺自然` : `You are a professional summary condenser. Please follow these requirements: 6. Keep output within 100 characters 7. Preserve core information and key content 8. Remove unnecessary modifiers 9. Use concise expressions 10. Maintain natural flow`; } else { return config.language === 'zh' ? `你是一个专业的文章摘要生成器。请为以下文章生成一个中文摘要,要求: 11. 字数在${lengthConfig.minLength}-${lengthConfig.maxLength}字之间 12. 完整概括文章主要内容 13. 突出文章的关键信息 14. 保持逻辑连贯 15. 语言简洁清晰` : `You are a professional article summarizer. Please generate an English summary that: 16. Contains ${lengthConfig.minLength}-${lengthConfig.maxLength} words 17. Comprehensively covers main points 18. Highlights key information 19. Maintains logical flow 20. Uses concise language`; } }
async function generateSummary(text, isRecursive = false, retryCount = 0) { const contentLength = text.trim().replace(/\s+/g, '').length; const lengthConfig = isRecursive ? { minLength: 20, maxLength: 100 } : calculateSummaryLength(contentLength, config);
try { await rateLimiter.waitForCooldown();
const response = await axios.post('https://api.moonshot.cn/v1/chat/completions', { model: config.model || 'moonshot-v1-8k', messages: [ { role: "system", content: getSystemPrompt(isRecursive, lengthConfig) }, { role: "user", content: text } ], temperature: isRecursive ? 0.2 : (config.temperature || 0.7), max_tokens: lengthConfig.maxLength * 2 }, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, timeout: 30000 });
const summary = response.data.choices[0].message.content.trim(); const summaryLength = config.language === 'zh' ? summary.length : summary.split(/\s+/).length;
if (!isRecursive && summaryLength > (100 + TOLERANCE)) { console.log(`生成的摘要(${summaryLength}字)超出容差范围,等待3秒后进行精简...`); await delay(3000); return await generateSummary(summary, true); } if (isRecursive && summaryLength > (1000 + TOLERANCE)) { if (retryCount < 2) { console.log(`精简后的摘要(${summaryLength}字)仍超出容差范围,等待2秒后重试第${retryCount + 1}次...`); await delay(2000); return await generateSummary(text, true, retryCount + 1); } else { if (summaryLength > (100 + TOLERANCE * 2)) { console.log(`精简后的摘要显著超出限制,进行截断...`); return summary.slice(0, 100 + TOLERANCE); } return summary; } }
return summary; } catch (error) { if (error.response?.status === 429) { const waitTime = Math.min(2000 * Math.pow(2, retryCount), 16000); console.log(`遇到限流,等待${waitTime/1000}秒后重试...`); await delay(waitTime); if (retryCount < 3) { return await generateSummary(text, isRecursive, retryCount + 1); } } throw error; } }
return await generateSummary(content); }
async function shouldUpdateFile(filePath, config) { try { if (config.forceUpdate) { return true; }
const stats = await stat(filePath); const lastModified = stats.mtime; const now = new Date(); const timeDiff = now - lastModified; return timeDiff < config.updateWindow; } catch (error) { console.error('检查文件状态时出错:', error); return false; } }
async function processSinglePost(filePath, config, progress) { if (processingFiles.has(filePath)) { console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 文件正在处理中,跳过`); return; } if (processedFiles.has(filePath)) { console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 文件已处理,跳过`); return; }
try { processingFiles.add(filePath);
if (!await shouldUpdateFile(filePath, config)) { console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 文件未更新,跳过处理`); return; }
const content = await readFile(filePath, 'utf8'); const frontMatterMatch = content.match(/^---\n([\s\S]*?)\n---/); if (!frontMatterMatch) { console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 未找到 front-matter,跳过处理`); return; }
const frontMatter = frontMatterMatch[1]; const postContent = content.slice(frontMatterMatch[0].length).trim();
console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 正在生成摘要...`); const description = await generateDescription(postContent, config); if (!description) { console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 生成摘要失败`); return; }
let frontMatterLines = frontMatter.split('\n'); let descriptionFound = false; let newFrontMatterLines = frontMatterLines.map(line => { if (line.startsWith('description:')) { descriptionFound = true; return `description: ${description}`; } return line; });
if (!descriptionFound) { newFrontMatterLines.push(`description: ${description}`); }
const newFrontMatter = newFrontMatterLines.join('\n'); const newContent = '---\n' + newFrontMatter + '\n---\n' + postContent;
await writeFile(filePath, newContent, 'utf8'); console.log(`[${progress.current}/${progress.total}] ${path.basename(filePath)}: 成功更新文章摘要`);
processedFiles.add(filePath); } finally { processingFiles.delete(filePath); } }
async function processPostsConcurrently(posts, config) { const apiValid = await checkApiStatus(config); if (!apiValid) { console.error('API 验证失败,无法处理文章'); return; }
const total = posts.length; let current = 0; const progress = { current, total };
const queue = []; for (const post of posts) { current++; progress.current = current; if (queue.length >= config.concurrency) { await Promise.race(queue); } const task = processSinglePost(post, config, progress) .then(() => { const index = queue.indexOf(task); if (index !== -1) { queue.splice(index, 1); } }); queue.push(task); } await Promise.all(queue); }
let processedPosts = new Set();
hexo.extend.filter.register('before_post_render', async function(data) { if (data.layout === 'post' && !processedPosts.has(data.full_source)) { processedPosts.add(data.full_source); const config = getConfig(this); if (!config.forceUpdate && !await shouldUpdateFile(data.full_source, config)) { return data; } const posts = [data.full_source]; await processPostsConcurrently(posts, config); } return data; });
hexo.extend.filter.register('after_generate', function() { processedFiles.clear(); processingFiles.clear(); });
hexo.extend.console.register('generate-descriptions', 'Generate descriptions for all posts', { options: [ { name: '--force', desc: 'Force update all posts' }, { name: '--concurrency', desc: 'Number of concurrent processes' }, { name: '--validate', desc: 'Validate API key only' }, { name: '--show-key', desc: 'Show API key source' } ] }, async function(args) { const config = getConfig(this); if (args.force) { config.forceUpdate = true; } if (args.concurrency) { config.concurrency = parseInt(args.concurrency, 10); }
if (args['show-key']) { const apiKey = getApiKey(config); if (!apiKey) { console.log('未设置 API 密钥'); } else if (process.env.KIMI_API_KEY) { console.log('使用环境变量中的 API 密钥'); } else { console.log('使用配置文件中的 API 密钥'); } return; }
if (args.validate) { try { await validateApiKey(config); console.log('API 验证成功'); } catch (error) { console.error('API 验证失败:', error.message); } return; }
const posts = this.model('Post').toArray().map(post => post.full_source); if (posts.length === 0) { console.log('没有找到需要处理的文章'); return; }
console.log(`开始处理 ${posts.length} 篇文章...`); await processPostsConcurrently(posts, config); console.log('所有文章处理完成'); });
|