Files
AIAssist/Action.php

473 lines
20 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* AI 助手 · 深度分析 Action
*
* 文章顶部卡片五个 tab 中的「写作分析 / 技能分析 / 成长分析 / 润文」四个 tab,
* 点击时由前端 fetch 请求本端点:服务端取文章全文调 AI,结果写入自定义字段缓存,
* 下次点击直接读缓存(force=1 时忽略缓存重新生成)。
*
* 路由:/aiassist-analyze(activate 时 Helper::addRoute 注册)
* 安全:token 由 API Key 派生(actionToken),与卡片上嵌入的 data-token 比对,
* 防止端点被外部任意调用消耗 AI 额度。
*
* PHP 8.5 兼容:可空参数显式声明、不用弃用变量。
*
* @package AIAssist
* @author 石头厝
* @version 1.0.4
* @link https://www.shitoucuo.com/
*/
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
if (!class_exists('AIAssist_Plugin')) {
require_once dirname(__FILE__) . '/Plugin.php';
}
class AIAssist_Action extends Typecho_Widget implements Widget_Interface_Do
{
/** 提交给 AI 的正文上限(与发布时摘要生成一致) */
private const MAX_TEXT_LENGTH = 8000;
/**
* 「润文」任务陈述(拼在 user 消息最前面,代码内固定,不受设置页配置影响)
*/
private const ORIGINAL_TASK = '【任务】把下面这篇文章逐段重写一遍。这是改写,不是校对:'
. '每一段都必须换一种说法重新组织句子结构,不许整句照抄原文;'
. '把口语化的碎片句子合并成通顺的复句,删掉重复的表述,补上缺失的连接词;'
. '原意、事实、数字、日期、人名地名、观点立场、图片一律不动,一段都不能漏;'
. '图片按原文的写法原样保留:原文写 ![说明](地址) 就照内联式,原文写 ![IMG_xx.jpg][1] '
. '并在文末配了 [1]: 地址 定义块的,就照引用式写、文末那串定义一行都不能少(少一行图就全空),'
. '不许换写法、不许改地址、不许删图;'
. '原文若用 {flex} 与 {/flex} 包住几张图片(表示并排显示),这对标记和组里的图片要原样保留,'
. '不要删标记、不要拆开、不要把图挪到组外;'
. '{map-数字} 是地图卡片短代码,原样留在原来的位置,不要改写、不要移动、不要删除;'
. '保留第一人称和作者的情绪语气,不要改成公文腔、不要加总结升华;'
. '篇幅与原文相当。直接输出改写后的完整正文,不要任何解释或前后缀。';
/**
* 「润文」重做时的加强指令(首轮几乎照抄原文才用)
*/
private const ORIGINAL_RETRY = '【重要】上一次给你的改写结果几乎照抄了原文,只换了个别词,不合格。'
. '现在重做一次,要求更严:逐段重写,每一段都要重新组织句子——可以合并、拆分、调整语序、'
. '替换用词,只要意思不变。不允许出现连续 10 个字与原文完全相同(专有名词、数字、日期除外)。'
. '读起来要像一篇重新写过的文章,而不是原文的轻微修补。'
. '事实、观点、图片、段落数量一律不变,保留第一人称。直接输出完整正文。';
public function execute()
{
}
public function action()
{
if (function_exists('set_time_limit')) {
@set_time_limit(300);
}
@ignore_user_abort(true);
header('Content-Type: application/json; charset=UTF-8');
$cid = isset($_POST['cid']) ? (int) $_POST['cid'] : 0;
$type = isset($_POST['type']) ? trim((string) $_POST['type']) : '';
$force = isset($_POST['force']) && $_POST['force'] === '1';
$token = isset($_POST['token']) ? trim((string) $_POST['token']) : '';
// 基础校验
if (!isset(AIAssist_Plugin::ANALYZE_TYPES[$type])) {
self::fail('未知分析类型');
}
if ($cid <= 0) {
self::fail('文章参数错误');
}
$cfg = AIAssist_Plugin::getConfig();
if (!hash_equals(AIAssist_Plugin::actionToken($cfg), $token)) {
self::fail('页面校验失败,请刷新页面后重试');
}
// force=1 是「重新分析」:忽略缓存重新烧 AI 额度,只允许管理员
//(前台这个按钮本身也只对管理员输出,这里再挡一层防止被直接构造请求)
if ($force && !AIAssist_Plugin::isAdmin()) {
self::fail('仅管理员可重新分析');
}
// 文章必须存在且已发布
$db = Typecho_Db::get();
$row = $db->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;
}
}