fetchRow( $db->select('cid', 'title', 'text', 'status', 'type') ->from('table.contents') ->where('cid = ?', $cid) ->limit(1) ); if (empty($row) || $row['type'] !== 'post' || $row['status'] !== 'publish') { self::fail('文章不存在或未发布'); } $field = AIAssist_Plugin::ANALYZE_TYPES[$type]; // 优先读缓存(不重新消耗 AI 调用) if (!$force) { $cached = AIAssist_Plugin::getField($cid, $field); if ($cached !== '') { self::okAnalyze($cached, $type, $cid); } } // API Key 检查 if ($cfg['provider'] === 'deepseek') { $apiKey = $cfg['deepseekApiKey']; $apiUrl = 'https://api.deepseek.com/chat/completions'; $model = $cfg['deepseekChatModel']; } else { $apiKey = $cfg['zhipuApiKey']; $apiUrl = 'https://open.bigmodel.cn/api/paas/v4/chat/completions'; $model = $cfg['zhipuChatModel']; } if (trim($apiKey) === '') { self::fail('尚未配置 ' . ($cfg['provider'] === 'deepseek' ? 'DeepSeek' : '智谱') . ' API Key,请到插件设置页填写'); } // 正文纯文字(长度校验用)与提交版(保留 markdown、图片转 markdown 绝对地址) $plainText = AIAssist_Plugin::extractPlainText((string) $row['text']); if (mb_strlen($plainText, 'UTF-8') < 30) { self::fail('文章正文过短,无法分析'); } $text = AIAssist_Plugin::contentForAi((string) $row['text']); $title = (string) $row['title']; $isOriginal = $type === 'original'; /* 「润文」的硬约束写在 user 消息里,不只靠 system 提示词: 设置页保存时会把当时的默认提示词原样存进配置,用户站点上可能还存着 1.3.10 之前那版「保留原意、篇幅相当」的宽松提示词——AI 拿到那种指令 只会把逗号改成句号就交差(2026-11-23 用户反馈「点了重新分析还是没润色」)。 把「逐段重写」放在 user 里,配置里存的是哪一版都不影响改写力度。 */ $articleBlock = "文章标题:{$title}\n\n文章全文:\n{$text}"; $userContent = $isOriginal ? self::ORIGINAL_TASK . "\n\n" . $articleBlock : $articleBlock; $messages = array( array('role' => 'system', 'content' => self::promptFor($type)), array('role' => 'user', 'content' => $userContent), ); $reply = AIAssist_AiClient::chat( $apiUrl, $apiKey, $model, $messages, $isOriginal ? 8192 : 2200 ); /* 改写力度体检:模型(尤其是免费的小模型)常把「润色」理解成「改标点」, 句子结构一点没动。判据是「原文的连续 8 字片段有多少原样出现在结果里」—— 真正重写过的文章这个比例很低(换语序、换词、合句拆句就断了), 而只改标点的「微调版」能保留一半以上(实测 56%)。 超过 45% 就带更强指令重做一次,避免用户看到「等于没改」。 */ if ($isOriginal && $reply !== null && trim($reply) !== '') { $keep = self::gramRetention($plainText, $reply); $sent = self::copiedSentenceRatio($plainText, $reply); AIAssist_Plugin::logRun("文章 {$cid} 润文首轮:原文片段保留率 " . round($keep * 100) . '%' . "(连续 8 字),整句照抄 {$sent[0]}/{$sent[1]},共 " . mb_strlen($reply, 'UTF-8') . ' 字'); if ($keep > 0.45) { AIAssist_Plugin::logRun("文章 {$cid} 润文改写力度不足(保留率 " . round($keep * 100) . '%),带强指令重做一次'); $retry = AIAssist_AiClient::chat( $apiUrl, $apiKey, $model, array( // 重做时不再用配置里的提示词(可能还是那版宽容的「润色」), // 直接用代码内的强指令,确保这一轮一定按「重写」来 array('role' => 'system', 'content' => self::ORIGINAL_RETRY), array('role' => 'user', 'content' => self::ORIGINAL_TASK . "\n\n" . $articleBlock), ), 8192 ); if ($retry !== null && trim($retry) !== '') { $keep2 = self::gramRetention($plainText, $retry); $sent2 = self::copiedSentenceRatio($plainText, $retry); AIAssist_Plugin::logRun("文章 {$cid} 润文重做:保留率 " . round($keep2 * 100) . '%' . ",整句照抄 {$sent2[0]}/{$sent2[1]},共 " . mb_strlen($retry, 'UTF-8') . ' 字'); // 只有确实改得更多才换掉首轮结果(重做版可能更差) if ($keep2 < $keep) { $reply = $retry; } } } } if ($reply === null || trim($reply) === '') { $reason = AIAssist_AiClient::lastError(); AIAssist_Plugin::logRun("文章 {$cid} 深度分析[{$type}] 调用失败" . ($reason !== '' ? ':' . $reason : '(详见 debug.log)')); // 输出被思考过程吃光(推理型模型)时给个能看懂的提示,别只说「调用失败」 if (strpos($reason, '占满') !== false) { self::fail('AI 把输出预算用在了思考上(推理型模型),已自动放大重试仍不够,请稍后再试,或到插件设置里换一个对话模型'); } self::fail('AI 调用失败(可能高峰限速,请稍后点击「重新分析」再试)'); } // 四个面板都不要标题:AI 若在开头写了大标题,这里去掉(缓存里也存干净版) $reply = AIAssist_Plugin::stripPaneTitle($reply); // 结果写入自定义字段缓存,之后点击直接展示 AIAssist_Plugin::saveField($cid, $field, $reply); AIAssist_Plugin::logRun("文章 {$cid} 深度分析[{$type}] 完成,已缓存"); self::okAnalyze($reply, $type, $cid); } /** * 归一化:去掉全部空白与标点,只留文字(比对改写力度用) */ private static function normText(string $s): string { /* 先把「非正文」的东西整段剔掉,再算改写力度。 图片路径、引用定义里的网址几篇文章都一样,一个字都不会被 AI 改; 留着它们,8 字片段保留率会被 URL 撑到虚高,白白触发一次「改写不足」重做。 (手记类文章几十张图,URL 能占到全文一半以上) */ $s = (string) preg_replace('/!\[[^\]]*\]\([^)]*\)/u', '', $s); // 内联图片 $s = (string) preg_replace('/!\[[^\]]*\]\[[^\]]*\]/u', '', $s); // 引用式图片 $s = (string) preg_replace('/^[ \t]{0,3}\[[^\]\n]+\]:[ \t]*\S+[ \t]*$/mu', '', $s); // 引用定义行 $s = (string) preg_replace('/\{\/?flex[^}\n]*\}/i', '', $s); // 横排标记 $s = (string) preg_replace('/\{map-\d+\}/i', '', $s); // 地图短代码 $s = (string) preg_replace('/[\s\x{3000}]+/u', '', $s); return (string) preg_replace('/[,。!?;:、“”‘’「」()《》〈〉…—\-,.!?;:"\'()\[\]\/\\\\]+/u', '', $s); } /** * 统计原文有多少「整句」被原样搬进了结果(改写力度体检,只用于日志) * * 按句末标点切句,去掉空白和标点后长度 ≥ 8 字的句子,若在结果里能原样找到, * 就算「照抄」。注意断句也算改写,所以这个比例天然偏低,别拿它当唯一判据 *(真正的判据是 gramRetention)。 * * @return array [照抄句数, 参与统计的句子总数] */ private static function copiedSentenceRatio(string $src, string $out): array { $flat = self::normText($out); $parts = preg_split('/[。!?!?\r\n]+/u', $src); if (!is_array($parts)) { return array(0, 0); } $total = 0; $copied = 0; foreach ($parts as $part) { $n = self::normText((string) $part); if (mb_strlen($n, 'UTF-8') < 8) { continue; } $total++; if ($flat !== '' && strpos($flat, $n) !== false) { $copied++; } } return array($copied, $total); } /** * 原文连续 N 字片段在结果里的保留率(0~1,越小说明改写越彻底) * * 只改标点的「微调版」会保留一半以上原文片段;真正重新组织过句子结构的 * 改写会降到两三成以下(实测:同一篇文章的微调版 53%)。 * * @param string $src 原文 * @param string $out 改写结果 * @param int $n 片段长度(字) */ private static function gramRetention(string $src, string $out, int $n = 8): float { $s = self::normText($src); $w = self::normText($out); if ($w === '') { return 1.0; } $chars = preg_split('//u', $s, -1, PREG_SPLIT_NO_EMPTY); $len = is_array($chars) ? count($chars) : 0; if ($len < $n * 2) { return 0.0; // 原文太短,不做判定 } $seen = array(); $total = 0; $hit = 0; for ($i = 0; $i + $n <= $len; $i++) { $gram = implode('', array_slice($chars, $i, $n)); if (isset($seen[$gram])) { continue; } $seen[$gram] = true; $total++; if (strpos($w, $gram) !== false) { $hit++; } } return $total > 0 ? $hit / $total : 0.0; } /** * 各分析类型的 system 提示词 * * 默认值在 AIAssist_Plugin::DEFAULT_PROMPTS,设置页「AI提示词」Tab 可编辑覆盖, * 这里只按类型名取(writing / original / skill / growth)。 */ private static function promptFor(string $type): string { $prompt = AIAssist_Plugin::getPrompt($type); if ($prompt === '') { return '请分析用户提供的博客文章并输出详细报告。'; } return $prompt; } private static function ok(string $content, array $maps = array()): void { $payload = array('ok' => true, 'content' => $content); if ($maps) { // 地图卡片的 HTML({map-数字} 短代码渲染结果),前端按占位符插入 $payload['maps'] = $maps; } echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } /** * 输出润文结果:把 MyTrack 的 {map-数字} 在这里渲染成卡片 HTML * * 为什么不交给前端:地图要读足迹数据库、要高德 key、要一套初始化脚本, * 前端那点 markdown 渲染做不到,只能后端渲染好随 JSON 一起发回去。 * 库里存的仍是原始短代码(换主题/关插件也不会坏),只有返回值是渲染版。 */ private static function okAnalyze(string $content, string $type, int $cid): void { $maps = array(); if ($type === 'original') { list($content, $maps) = AIAssist_Plugin::renderTrackShortcodes( $content, (object) array('cid' => $cid) ); } self::ok($content, $maps); } private static function fail(string $message): void { echo json_encode( array('ok' => false, 'error' => $message), JSON_UNESCAPED_UNICODE ); exit; } /* ================================================================== * 插件设置备份 / 恢复(/aiassist-settings 路由,设置页顶部按钮走这里) * ================================================================== */ /** * 设置页顶部的备份 / 恢复动作入口 * * 只接受 GET 的 do=backup / do=restore,处理完 302 回插件设置页 *(结果写在查询参数里,由设置页顶部的卡片渲染成提示条)。 * 权限:仅管理员;安全:动作令牌校验(防 CSRF / 防盗刷)。 */ public function settings() { if (!class_exists('AIAssist_Settings')) { require_once dirname(__FILE__) . '/Settings.php'; } $isAdmin = false; try { $user = Typecho_Widget::widget('Widget_User'); $isAdmin = $user && $user->pass('administrator', true); } catch (Exception $e) { $isAdmin = false; } catch (Throwable $e) { $isAdmin = false; } if (!$isAdmin) { $this->redirectTo(AIAssist_Plugin::configUrl('_ai=auth')); return; } if (!AIAssist_Plugin::checkSettingsToken(isset($_GET['_']) ? (string) $_GET['_'] : '')) { $this->redirectTo(AIAssist_Plugin::configUrl('_ai=token')); return; } $action = isset($_GET['do']) ? trim((string) $_GET['do']) : ''; if ($action === 'backup') { $result = AIAssist_Settings::backup(); if (!empty($result['ok'])) { $this->redirectTo(AIAssist_Plugin::configUrl( '_ai=backup_ok&n=' . intval($result['count']) . '&t=' . intval($result['created']) . '&f=' . intval(isset($result['total']) ? $result['total'] : 0) . '&k=' . intval(isset($result['keep']) ? $result['keep'] : 0) )); return; } $this->redirectTo(AIAssist_Plugin::configUrl( '_ai=backup_fail&detail=' . rawurlencode((string) $result['message']) )); return; } if ($action === 'restore') { /* 不传 file 就是恢复最新一份;传了走文件名白名单校验(restoreLatest 内部 还会再 basename + isBackupName 校验一次,这里只挡住数组之类的怪值) */ $file = isset($_GET['file']) && is_scalar($_GET['file']) ? trim((string) $_GET['file']) : ''; $result = AIAssist_Settings::restoreLatest($file); if (!empty($result['ok'])) { $this->redirectTo(AIAssist_Plugin::configUrl( '_ai=restore_ok&n=' . intval($result['count']) . '&t=' . intval($result['created']) )); return; } $this->redirectTo(AIAssist_Plugin::configUrl( '_ai=restore_fail&detail=' . rawurlencode((string) $result['message']) )); return; } $this->redirectTo(AIAssist_Plugin::configUrl('_ai=unknown')); } /** * 跳转(优先走 Typecho 的 Response,它会正确记下 302) * * @access private * @param string $url * @return void */ private function redirectTo($url) { try { if (isset($this->response) && is_object($this->response) && method_exists($this->response, 'redirect')) { $this->response->redirect($url); exit; } } catch (Exception $e) { } catch (Throwable $e) { } header('Location: ' . $url, true, 302); exit; } }