将上述代码保存为 deepseek_writer.php
准备一个文本文件,每行一个关键词,例如 keywords.txt:
-
请确保PHP已安装curl扩展
-
需要有效的DeepSeek API密钥
-
生成大量内容时请注意API的token消耗
-
中文内容计算准确需要确保PHP已启用mbstring扩展
<?php /** * DeepSeek 长文本生成工具 * 功能:读取每行关键词,生成不少于2000字的内容,不足时自动补足 */ // 配置DeepSeek API define('DEEPSEEK_API_KEY', 'your-api-key-here'); // 替换为你的API密钥 define('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat/completions'); define('MIN_CHARACTERS', 2000); // 最小字符数要求 // 错误报告设置 error_reporting(E_ALL); ini_set('display_errors', 1); /** * 调用DeepSeek API */ function callDeepSeekApi($messages, $maxTokens = 4000, $temperature = 0.7) { $data = [ 'model' => 'deepseek-chat', 'messages' => $messages, 'max_tokens' => $maxTokens, 'temperature' => $temperature ]; $ch = curl_init(DEEPSEEK_API_URL); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Authorization: Bearer ' . DEEPSEEK_API_KEY ], CURLOPT_TIMEOUT => 60 ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($response === false) { throw new Exception('API请求失败'); } $result = json_decode($response, true); if ($httpCode !== 200) { $errorMsg = $result['error']['message'] ?? '未知错误'; throw new Exception("API错误: {$errorMsg} (HTTP {$httpCode})"); } return $result['choices'][0]['message']['content']; } /** * 确保生成文本达到最小字数要求 */ function ensureMinLength($keyword, $initialContent = '') { $result = $initialContent; $attempts = 0; $maxAttempts = 3; // 最大尝试次数 while (mb_strlen($result) < MIN_CHARACTERS && $attempts < $maxAttempts) { $remaining = MIN_CHARACTERS - mb_strlen($result); $prompt = $attempts === 0 ? "请以'{$keyword}'为主题,撰写一篇不少于" . MIN_CHARACTERS . "字的详细文章。要求:\n" . "1. 结构完整,包含引言、主体和结论\n" . "2. 内容详实,有具体案例和数据支持\n" . "3. 语言流畅,逻辑清晰" : "请继续补充关于'{$keyword}'的内容,还需要大约{$remaining}字。\n" . "当前已生成内容开头:\n" . mb_substr($result, 0, 500) . "...\n" . "请保持内容连贯性,补充细节和案例。"; try { $response = callDeepSeekApi([ ['role' => 'system', 'content' => '你是一位专业作家,擅长撰写详细的长篇文章'], ['role' => 'user', 'content' => $prompt] ], $remaining * 2); // 按需分配token $result .= $response; $attempts++; // 避免重复内容 $result = removeDuplicateContent($result); } catch (Exception $e) { error_log("生成失败: " . $e->getMessage()); break; } } return $result; } /** * 移除重复内容 */ function removeDuplicateContent($text) { $paragraphs = explode("\n\n", $text); $uniqueParagraphs = []; foreach ($paragraphs as $para) { $para = trim($para); if (!empty($para) { $isDuplicate = false; $simplifiedPara = preg_replace('/\s+/', '', $para); foreach ($uniqueParagraphs as $uniquePara) { $simplifiedUnique = preg_replace('/\s+/', '', $uniquePara); similar_text($simplifiedPara, $simplifiedUnique, $percent); if ($percent > 80) { // 相似度超过80%视为重复 $isDuplicate = true; break; } } if (!$isDuplicate) { $uniqueParagraphs[] = $para; } } } return implode("\n\n", $uniqueParagraphs); } /** * 处理关键词文件 */ function processKeywords($filename) { if (!file_exists($filename)) { die("文件不存在: {$filename}"); } $keywords = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $outputDir = 'output_' . date('Ymd_His'); if (!mkdir($outputDir)) { die("无法创建输出目录"); } foreach ($keywords as $index => $keyword) { $keyword = trim($keyword); if (empty($keyword)) continue; echo "正在处理关键词: {$keyword}...\n"; try { $content = ensureMinLength($keyword); $charCount = mb_strlen($content); if ($charCount < MIN_CHARACTERS) { echo "警告: 未能为'{$keyword}'生成足够内容 ({$charCount}/" . MIN_CHARACTERS . ")\n"; } else { echo "成功生成: {$charCount} 字符\n"; } // 保存结果 $filename = sprintf("%s/%03d_%s.txt", $outputDir, $index+1, preg_replace('/[^\w]/u', '_', $keyword)); file_put_contents($filename, "关键词: {$keyword}\n\n" . $content); // API限制友好处理 if ($index < count($keywords) - 1) { sleep(2); // 避免频繁调用 } } catch (Exception $e) { error_log("处理关键词'{$keyword}'失败: " . $e->getMessage()); echo "错误: 处理'{$keyword}'时出错 - " . $e->getMessage() . "\n"; } } echo "\n处理完成!结果已保存到目录: {$outputDir}\n"; } // 主程序 if ($argc < 2) { echo "使用方法: php {$argv[0]} 关键词文件.txt\n"; echo "示例: php {$argv[0]} keywords.txt\n"; exit(1); } $keywordFile = $argv[1]; processKeywords($keywordFile);
转载请注明:三五二萌文网 » DeepSeek 长文本生成工具