diff --git a/.agents/notes/implemented/feature/2026-11-04-content-check-ai-traces.md b/.agents/notes/implemented/feature/2026-11-04-content-check-ai-traces.md index 8fbca46b..6c8f896a 100644 --- a/.agents/notes/implemented/feature/2026-11-04-content-check-ai-traces.md +++ b/.agents/notes/implemented/feature/2026-11-04-content-check-ai-traces.md @@ -1,6 +1,6 @@ # Agent Note: 文稿检测 AI 痕迹维度合同 -Status: implemented — #228 一期启发式统计;无持久化、无迁移 +Status: implemented — #228 一期启发式统计;#241 改写建议(检测→改写闭环);无持久化、无迁移(prompt_registry 只加数据行) ## Problem @@ -61,6 +61,38 @@ start/end 是原文 codepoint 偏移、不做 NFKC。两维度命中合并后按 风险命中红/黄系不变,AI 痕迹命中**紫色系**(设计系统 --color-purple), 同区间重叠时风险命中优先。「未发现违禁词,可以发布」只看 sensitive.total。 +### 改写建议(检测→改写闭环,#241) + +对 AI 痕迹命中密集的句子生成「保留原意的口语化改写」。长期合同: + +- **请求体 = 全文,不是句列表**:分句正则与词库命中只在后端一份 + (ai_trace_service);若前端传目标句,TS 必须重复实现分句+命中归因,词库 + 口径双份漂移。「限流」的意图改由后端实现:只有服务端选取的 ≤3 句进入 + LLM prompt,**全文永不进 prompt**(20000 字请求体 ≠ 20000 字 prompt)。 +- **选句规则**(humanize_rewrite_service.select_target_sentences 纯函数): + 逐句 scan_words 统计句内命中(句末标点属掩码分隔符,词命中不可能跨句界, + 逐句重扫与全扫在句内等价——测试锁该等价性);命中数降序(同数按原文顺序) + 取前 3,零命中句不入选。**没有「句数不足 422」**:1~2 句有命中照样改写, + 响应建议数 <3 即可;只有选取结果为空(全文零命中)才 422 显式原因。 +- **响应不信 LLM 回显**:条目必须与服务端选取句逐字对应,original 以服务端 + 为准;hit_words 逐条对照该句真实 scan_words 过滤(LLM 编造词进不了徽标), + LLM 未回显时退回该句真实命中,不空着也不编造。 +- **数字/事实一致性不硬校验**:「3 个方法」→「三个方法」是合法改写,运行时 + 硬校验会误杀。可测口径 = prompt 显式指令(照抄时间/数字/专有名词/结论)+ + mock 测试断言响应管道逐字透传。真实 LLM 服从性无法确定性保证,UI 文案 + 明示「发布前请自行核对事实与数字」。 +- 错误映射照 content_events 先例:LLM 链路异常(熔断/容量/预算/上下文)与 + 不可解析输出 → 502 显式中文文案;零命中 → 422;401 由 router 级 + get_current_user 覆盖。文案红线沿用:改写是「写作建议」,禁止「AI 率/ + 概率/检测模型」表述,也不暗示能改变文稿来源判定。 +- 模块边界:humanize_rewrite_service 有 LLM IO,**不并入** ai_trace_service + (后者合同是纯启发式统计无 IO);prompt 收进 llm/prompts/humanize_rewrite.py + 并注册 prompt_registry(scene=humanize_rewrite,无 schema 变更)。 +- 前端:AI 痕迹面板下加「生成改写建议」按钮(_humanize.tsx,紫色系徽标), + 按钮禁用条件 = phase 非 current 或 aiTraces.hits 为空(scanPhase 合同保证 + current 时 text===scannedText,建议与展示结果同一文稿快照);建议 state 随 + 重扫/清空作废;生成错误独立 inline 展示,不复用检测的 ErrorState 重试语义。 + ### 测试口径 `tests/test_ai_traces.py`:词表零跳过/预算、偏移切片还原(含 emoji)、密度与 @@ -69,7 +101,14 @@ CV 分档边界等值行为、insufficient 边界、401/422、万字基准(均 零回归验证:`tests/test_sensitive_word.py` 未改动、单跑通过;前端 `npm run test:coverage` 通过(_scan-state / _highlight 用例同步扩)。 +改写闭环(#241)加 `tests/test_humanize_rewrite.py`:选句纯函数(优先级/ +补足/上限/零命中/逐句重扫等价)、mock call_llm_json 的成功路径(hit_words +过滤、original=服务端选取句、数字逐字透传、prompt 含不改事实指令且全文不进 +prompt)、LLM 异常→502、零命中→422、401、超长 422;前端 `_humanize.test.tsx` +渲染对照(建议句/紫色徽标/禁用态/独立 inline 错误)。 + ## 后续(v2 再议) -全局总分/评分体系、逐句均匀度高亮(v1 只做词级定位)、改写建议生成、 -词库入库与用户自定义、英文文稿。 +全局总分/评分体系、逐句均匀度高亮(v1 只做词级定位)、改写建议的 diff 高亮 +对齐/一键替换/风格模板/改写回写检测(#241 只做生成与展示)、词库入库与用户 +自定义、英文文稿。 diff --git a/backend/app/api/v1/content_check.py b/backend/app/api/v1/content_check.py index 0e5c527d..692fbb50 100644 --- a/backend/app/api/v1/content_check.py +++ b/backend/app/api/v1/content_check.py @@ -1,25 +1,39 @@ -"""文稿检测入口——发布前违禁词 / 广告法极限词扫描,附 AI 痕迹启发式统计。 +"""文稿检测入口——发布前违禁词 / 广告法极限词扫描,附 AI 痕迹启发式统计与改写建议。 入口层只做三件事:路由、schema 校验、调 service(`sensitive_word_service.scan` -与 `ai_trace_service.analyze` 纯函数)。无 ORM、无 session。认证用 -`Depends(get_current_user)` 防匿名刷大文本(与 skill.py 同模式);限流由 -`/api/v1` 前缀的全局中间件自动覆盖,无需单列规则。 +与 `ai_trace_service.analyze` 纯函数、`humanize_rewrite_service` 的 LLM 编排)。 +无 ORM、无 session。认证用 `Depends(get_current_user)` 防匿名刷大文本(与 +skill.py 同模式);限流由 `/api/v1` 前缀的全局中间件自动覆盖,无需单列规则。 """ from __future__ import annotations -from fastapi import APIRouter, Depends +import logging + +from fastapi import APIRouter, Depends, HTTPException, status from app.api.v1.auth import get_current_user from app.schemas.content_check import ( AiTracesCheckRequest, AiTracesReport, + HumanizeRewriteRequest, + HumanizeRewriteResponse, SensitiveCheckRequest, SensitiveCheckResponse, ) from app.services.ai_trace_service import analyze as analyze_ai_traces +from app.services.humanize_rewrite_service import ( + HumanizeRewriteNoTargetError, + HumanizeRewriteUnavailableError, + generate_humanize_rewrites, +) +from app.services.llm.budget_guard import LlmBudgetExceededError +from app.services.llm.circuit_breaker import CircuitOpenError +from app.services.llm.provider import LlmCapacityUnavailableError, LlmContextWindowExceededError from app.services.sensitive_word_service import scan +logger = logging.getLogger(__name__) + router = APIRouter(prefix="/content-check", tags=["content-check"], dependencies=[Depends(get_current_user)]) @@ -55,3 +69,59 @@ async def check_sensitive(payload: SensitiveCheckRequest) -> SensitiveCheckRespo ) async def check_ai_traces(payload: AiTracesCheckRequest) -> AiTracesReport: return AiTracesReport(**analyze_ai_traces(payload.text)) + + +@router.post( + "/humanize-rewrite", + response_model=HumanizeRewriteResponse, + summary="文稿「去 AI 味」改写建议", + description=( + "对 AI 痕迹命中最密集的句子(≤3 句)生成保留原意的口语化改写建议:" + "服务端分句选句,只有选取句进入模型,全文不进 prompt。响应 original 是" + "服务端选取句,hit_words 已对照词库真实命中过滤。这是写作建议,不是" + "「AI 检测/降 AI 率」工具,不承诺改变文稿来源判定;事实与数字是否保留" + "需作者自行核对。单次最多 20000 字符,超出返回 422;无任何命中句时返回" + " 422 并说明原因。" + ), +) +async def check_humanize_rewrite(payload: HumanizeRewriteRequest) -> HumanizeRewriteResponse: + try: + result = await generate_humanize_rewrites(payload.text) + except HumanizeRewriteNoTargetError as exc: + raise HTTPException( + status_code=422, + detail="没有可改写的句子:文稿未命中 AI 高频词或套话连接词,请先参考 AI 痕迹统计。", + ) from exc + except HumanizeRewriteUnavailableError as exc: + logger.warning("Humanize rewrite unparsable: %s", exc) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail="改写建议生成失败:模型返回结构不可用,请稍后重试", + ) from exc + except ( + CircuitOpenError, + LlmCapacityUnavailableError, + LlmBudgetExceededError, + LlmContextWindowExceededError, + ) as exc: + # LLM 链路失败 → 502 显式文案;不折叠成 200 假成功(AGENTS 2.1,模式同 content_events)。 + details = { + CircuitOpenError: "改写建议生成失败:模型链路熔断中,请稍后重试", + LlmCapacityUnavailableError: "改写建议生成失败:模型服务暂不可用,请稍后重试", + LlmBudgetExceededError: "改写建议生成失败:模型预算已耗尽,请稍后重试", + LlmContextWindowExceededError: "改写建议生成失败:句子长度超出模型上下文,请稍后重试", + } + detail = next( + (text for exc_type, text in details.items() if isinstance(exc, exc_type)), "改写建议生成失败,请稍后重试" + ) + logger.warning("Humanize rewrite LLM failure: %s", type(exc).__name__) + raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=detail) from exc + except Exception as exc: + # 超时、全部候选耗尽等末路异常的兜底:也走 502 中文文案, + # 不落到全局 500 英文裸错(模式同 content_events / mother_topics)。 + logger.warning("Humanize rewrite failed unexpectedly", exc_info=True) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail="改写建议生成失败,请稍后重试", + ) from exc + return HumanizeRewriteResponse(**result) diff --git a/backend/app/schemas/content_check.py b/backend/app/schemas/content_check.py index 5937f278..b6671ac5 100644 --- a/backend/app/schemas/content_check.py +++ b/backend/app/schemas/content_check.py @@ -87,7 +87,7 @@ class AiTraceRhythmStat(BaseModel): class AiTracesReport(BaseModel): - """POST /content-check/ai-traces 响应。 + """POST /content-check/ai-traces 响应. 启发式统计(非模型检测):不输出「AI 率/AI 概率」,不影响风险把关结论, 只给写作建议,前端独立展示。 @@ -100,3 +100,38 @@ class AiTracesReport(BaseModel): rhythm: AiTraceRhythmStat = Field(..., description="句式均匀度统计") hits: list[AiTraceHitResponse] = Field(default_factory=list, description="词命中清单(start 升序、区间不重叠)") advice: str = Field(..., description="综合建议(明示启发式统计口径)") + + +class HumanizeRewriteRequest(BaseModel): + """POST /content-check/humanize-rewrite 请求体(与 sensitive 同长度口径)。 + + 传全文而非句列表:分句与命中口径只在后端一份,服务端自行选取命中最密集 + 的 ≤3 句进模型,全文永不进 prompt。 + """ + + text: str = Field( + ..., + min_length=1, + max_length=20000, + description="待改写文稿原文(1~20000 字符,超限返回 422;服务端只选取命中密集的 ≤3 句进入模型)", + ) + + +class HumanizeRewriteSuggestionResponse(BaseModel): + """单条改写建议:服务端选取的原句 + 保留原意的口语化改写 + 该句真实命中词。""" + + original: str = Field(..., description="服务端选取的原句(以服务端选取为准,不取模型回显)") + rewritten: str = Field(..., description="口语化改写建议(写作参考,需自行核对事实与数字)") + hit_words: list[str] = Field( + default_factory=list, + description="该句真实命中的 AI 痕迹词(已对照词库命中过滤,不含模型编造词)", + ) + + +class HumanizeRewriteResponse(BaseModel): + """POST /content-check/humanize-rewrite 响应(≤3 条,按命中密集程度排序)。""" + + suggestions: list[HumanizeRewriteSuggestionResponse] = Field( + default_factory=list, + description="改写建议清单;命中句不足 3 句时条数相应减少", + ) diff --git a/backend/app/services/humanize_rewrite_service.py b/backend/app/services/humanize_rewrite_service.py new file mode 100644 index 00000000..9a9a1fab --- /dev/null +++ b/backend/app/services/humanize_rewrite_service.py @@ -0,0 +1,158 @@ +"""文稿「去 AI 味」改写建议:对 AI 痕迹命中密集的句子生成保留原意的口语化改写。 + +检测→改写闭环的服务端编排(owning note: 2026-11-04-content-check-ai-traces.md): + +- 选句是纯函数 `select_target_sentences`:复用 ai_trace_service 的分句与词扫描 + 口径(services 引 services 有先例,见 angle_recommend.py)。逐句重扫与全扫在 + 句内等价——句末标点属 ``_SEPARATOR_RE`` 掩码,词命中不可能跨句界。 +- 只有选取出的 ≤3 句进入 LLM prompt,**全文永不进 prompt**(token 由选句上限 + 天然限流,20000 字请求体不等于 20000 字 prompt)。 +- 响应不信任 LLM 回显:条目必须与服务端选取句逐字对应,original 以服务端为 + 准;hit_words 逐条对照该句真实 scan_words 结果过滤,徽标词都来自真实命中。 +- 与 ai_trace_service 的模块合同不同:那个模块是纯启发式统计、无 IO;本模块 + 有 LLM IO,故独立成模块,不并入。 + +口径红线:改写建议是「写作建议」,全链路文案不得出现「AI 率 / AI 概率 / +检测模型」类表述(词库命中判不了文稿来源,改写也只降套话密度)。 +""" + +from __future__ import annotations + +import logging +from typing import Any, TypedDict + +from app.services.ai_trace_service import scan_words, split_sentences +from app.services.llm import call_llm_json +from app.services.llm.prompts.humanize_rewrite import SYSTEM_PROMPT, USER_TEMPLATE +from app.utils.prompt_safety import sanitize_prompt_input + +logger = logging.getLogger(__name__) + +# 选句上限:一次最多改写 3 句。命中数 ≥2 的句子优先,不足再补命中数 =1 的句子。 +MAX_TARGET_SENTENCES = 3 +# 单句进 prompt 前的清洗上限:选句已含命中词、正常远短于此,防极端长句撑爆 token。 +SENTENCE_PROMPT_MAX_CHARS = 1000 +# 低温改写:只许换说法,不许自由发挥;上限收紧到改写 3 句所需(provider 默认 2000)。 +LLM_TEMPERATURE = 0.4 +LLM_MAX_TOKENS = 1200 + + +class HumanizeRewriteSuggestion(TypedDict): + """一条改写建议:服务端选取的原句、改写句与该句真实命中的词。""" + + original: str + rewritten: str + hit_words: list[str] + + +class HumanizeRewriteNoTargetError(ValueError): + """文稿没有任何 buzzword/connective 命中句,无从改写(API 映射 422)。""" + + +class HumanizeRewriteUnavailableError(RuntimeError): + """LLM 输出不可解析,或没有任何能与选取句对应的有效条目(API 映射 502)。""" + + +def _sentence_hit_words(sentence: str) -> list[str]: + """句内真实命中的词,按出现顺序去重(服务端过滤 hit_words 的事实源)。""" + words: list[str] = [] + for hit in scan_words(sentence): + if hit["word"] not in words: + words.append(hit["word"]) + return words + + +def select_target_sentences(text: str, limit: int = MAX_TARGET_SENTENCES) -> list[str]: + """选取 AI 痕迹命中最密集的句子(纯函数,复用 ai_trace_service 口径)。 + + 逐句 ``scan_words`` 统计句内命中数,按命中数降序取前 ``limit`` 句;零命中 + 句不入选。稳定排序保证同命中数按原文顺序——命中 ≥2 的句子天然排在 =1 + 之前,不足 ``limit`` 句时自动用命中数 =1 的句子补足。 + """ + scored: list[tuple[str, int]] = [] + for sentence in split_sentences(text): + count = len(scan_words(sentence)) + if count > 0: + scored.append((sentence, count)) + if not scored: + return [] + scored.sort(key=lambda item: -item[1]) + return [sentence for sentence, _count in scored[:limit]] + + +def _build_messages(sentences: list[str]) -> list[dict[str, str]]: + """选取句逐条 sanitize 后拼入模板;全文不进 prompt。""" + lines = [ + f"{index}. {sanitize_prompt_input(sentence, max_chars=SENTENCE_PROMPT_MAX_CHARS)}" + for index, sentence in enumerate(sentences, start=1) + ] + return [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": USER_TEMPLATE.format(sentences="\n".join(lines))}, + ] + + +def _parse_suggestions(result: Any, selected: list[str]) -> list[HumanizeRewriteSuggestion]: + """校验并整形 LLM 返回;original 以服务端选取句为准,hit_words 只留真实命中。 + + 条目必须与某个选取句逐字对应(不信回显),rewritten 必须非空;全部无效时 + 抛 :class:`HumanizeRewriteUnavailableError`,不返回空建议装成功。 + 输出按服务端选取顺序排列(不按 LLM 返回顺序)。 + """ + if not isinstance(result, dict): + raise HumanizeRewriteUnavailableError("LLM 返回不是 JSON 对象") + raw_suggestions = result.get("suggestions") + if not isinstance(raw_suggestions, list): + raise HumanizeRewriteUnavailableError("LLM 返回缺少 suggestions 列表") + + real_words = {sentence: _sentence_hit_words(sentence) for sentence in selected} + rewritten_by_sentence: dict[str, tuple[str, list[str]]] = {} + for item in raw_suggestions: + if not isinstance(item, dict): + continue + original = item.get("original") + rewritten = item.get("rewritten") + if not isinstance(original, str) or original not in real_words: + continue # 回显与选取句对不上:丢弃,不用 LLM 的句子冒充原句 + if not isinstance(rewritten, str) or not rewritten.strip(): + continue + truth = real_words[original] + echoed = item.get("hit_words") + candidates = [word for word in echoed if isinstance(word, str)] if isinstance(echoed, list) else [] + hit_words = [word for word in candidates if word in truth] + if not hit_words: + # LLM 未回显或全部被过滤:徽标退回该句真实命中,仍不编造 + hit_words = truth + rewritten_by_sentence[original] = (rewritten, hit_words) + + valid = [ + HumanizeRewriteSuggestion( + original=sentence, + rewritten=rewritten_by_sentence[sentence][0], + hit_words=rewritten_by_sentence[sentence][1], + ) + for sentence in selected + if sentence in rewritten_by_sentence + ] + if not valid: + raise HumanizeRewriteUnavailableError("LLM 返回中没有可与选取句对应的有效改写") + return valid + + +async def generate_humanize_rewrites(text: str) -> dict[str, list[HumanizeRewriteSuggestion]]: + """对 AI 痕迹命中最密集的 ≤3 句生成口语化改写建议。 + + 选句为空抛 :class:`HumanizeRewriteNoTargetError`(API 映射 422 显式原因); + LLM 链路异常(熔断/容量/预算/上下文)由 provider 原样抛出,入口层映射 502。 + """ + selected = select_target_sentences(text) + if not selected: + raise HumanizeRewriteNoTargetError("文稿没有命中 AI 高频词或套话连接词的句子,无从生成改写建议") + + result = await call_llm_json( + _build_messages(selected), + temperature=LLM_TEMPERATURE, + max_tokens=LLM_MAX_TOKENS, + scene="humanize_rewrite", + ) + return {"suggestions": _parse_suggestions(result, selected)} diff --git a/backend/app/services/llm/prompts/humanize_rewrite.py b/backend/app/services/llm/prompts/humanize_rewrite.py new file mode 100644 index 00000000..26fc9334 --- /dev/null +++ b/backend/app/services/llm/prompts/humanize_rewrite.py @@ -0,0 +1,29 @@ +""" +Humanize Rewrite LLM prompts — 文稿「去 AI 味」改写建议. + +Used by: + - app.services.humanize_rewrite_service.generate_humanize_rewrites + +口径红线(owning note: 2026-11-04-content-check-ai-traces.md):改写是 +**写作建议**,不是「AI 检测 / 降 AI 率」工具——prompt 与输出不得出现 +「AI 率 / AI 概率 / 检测模型」类表述。 +""" + +SYSTEM_PROMPT = """你是一位资深中文编辑,擅长把模板化的书面腔改成自然的口语,同时不损失任何信息。 + +你的任务是逐句改写给定的句子,规则: +1. 只改写给定的句子,一条建议只对应一个原句;不扩写、不合并、不新增句子之外的信息。 +2. 保留原意与全部事实:时间、数字、专有名词、结论一律照抄,不得改写、增删或概括。 +3. 去掉空泛的黑话与套话连接词(如「赋能」「抓手」「首先/其次/最后」),换成具体的动作、数字或事例;没有对应内容就直接删掉该词,不要编造。 +4. 口语化但克制:像跟朋友解释一件事,不堆语气词、不用网络梗、不夸张。 +5. hit_words 填该原句里你处理掉的黑话/套话词,原样照抄,不要发明新词。 + +输出严格 JSON,不要任何解释或多余文字: +{"suggestions": [{"original": "原句原文照抄", "rewritten": "改写后的句子", "hit_words": ["原句中被处理的黑话/套话词"]}]}""" + +USER_TEMPLATE = """请逐句改写以下句子(按输入顺序,每句一条): + +{sentences} + +只输出 JSON:{{"suggestions": [{{"original": "", "rewritten": "", "hit_words": [""]}}]}} +""" diff --git a/backend/app/services/prompt_registry_service.py b/backend/app/services/prompt_registry_service.py index aea54239..eeea6d3f 100644 --- a/backend/app/services/prompt_registry_service.py +++ b/backend/app/services/prompt_registry_service.py @@ -261,6 +261,20 @@ "module": "app.services.llm.prompts.discovery", "attr": "TOPIC_CLUSTER_USER_TEMPLATE", }, + { + "name": "humanize_rewrite_system", + "scene": "humanize_rewrite", + "description": "文稿「去 AI 味」改写建议系统提示词(写作建议口径,不改事实与数字)", + "module": "app.services.llm.prompts.humanize_rewrite", + "attr": "SYSTEM_PROMPT", + }, + { + "name": "humanize_rewrite_user", + "scene": "humanize_rewrite", + "description": "文稿「去 AI 味」改写建议用户提示词(只拼入选取的 ≤3 句,不拼全文)", + "module": "app.services.llm.prompts.humanize_rewrite", + "attr": "USER_TEMPLATE", + }, ] diff --git a/backend/tests/test_humanize_rewrite.py b/backend/tests/test_humanize_rewrite.py new file mode 100644 index 00000000..991a14a8 --- /dev/null +++ b/backend/tests/test_humanize_rewrite.py @@ -0,0 +1,327 @@ +"""文稿「去 AI 味」改写建议(service 纯函数 + LLM 编排 + POST /content-check/humanize-rewrite)测试。 + +覆盖(对应任务书验收): +1. 选句纯函数:命中数 ≥2 优先、不足 3 句用命中数 =1 的句子补足、同命中数按 + 原文顺序、上限 3 句、零命中返回空; +2. 逐句重扫与全扫等价:句末标点属 _SEPARATOR_RE 掩码,词命中不可能跨句界 + (逐句重扫的词频合计与全扫一致,含同词跨句出现); +3. 成功路径:hit_words ⊆ 该句真实命中(LLM 编造词被过滤)、original 以服务端 + 选取句为准(回显错配条目被丢弃)、rewritten 逐字透传(数字不被管道改动)、 + prompt 含「不改事实与数字」指令且全文不进 prompt; +4. LLM 异常注入 → 502;选句为空 → 422 显式原因;未登录 401;超长 20001 → 422。 + +测试命令:一次性 PG 单跑(conftest 的 autouse fixture 需要 PG),如 +bash backend/scripts/test_full_local.sh(实际执行全量 tests/ 套件)。 +""" + +from __future__ import annotations + +from collections import Counter +from types import SimpleNamespace + +import pytest +import pytest_asyncio +from fastapi import FastAPI +from httpx import ASGITransport, AsyncClient + +from app.api.v1.auth import get_current_user +from app.api.v1.content_check import router as content_check_router +from app.services import humanize_rewrite_service as svc +from app.services.ai_trace_service import scan_words, split_sentences +from app.services.humanize_rewrite_service import ( + HumanizeRewriteNoTargetError, + HumanizeRewriteUnavailableError, + generate_humanize_rewrites, + select_target_sentences, +) +from app.services.llm.budget_guard import LlmBudgetExceededError +from app.services.llm.circuit_breaker import CircuitOpenError +from app.services.llm.provider import LlmCapacityUnavailableError, LlmContextWindowExceededError + +# 密集 AI 套话样文(同 test_ai_traces.DENSE_TEXT,逐句命中数 [1, 3, 3, 8], +# 已对真实词库核实:S4=首先/对齐/其次/沉淀/方法论/最后/复用/打法) +DENSE_TEXT = ( + "在流量红利见顶的今天,品牌必须找到新的增长抓手。" + "我们以用户为中心重构底层逻辑,通过私域运营形成增长闭环。" + "这套组合拳能够有效赋能创作者,显著提升转化效率。" + "首先对齐目标,其次沉淀方法论,最后形成可复用的打法。" +) + +# 口语化样文:零命中(选句为空 → 422 的口径基础) +COLLOQUIAL_TEXT = ( + "今天下楼吃了一碗牛肉面,老板还是给我多加了一勺辣油。" + "爽。" + "吃完顺着河边遛了半小时弯儿,风一吹整个人都清醒了,回家倒头睡了个午觉,猫窝在我脚边也睡着了。" +) + +# 构造样文(命中数已对真实词库核实):A=0(含数字)、B=8、C=2(含数字 +# 3 个月/40%)、D=1、E=2。常量按 split_sentences 的返回口径定义(句末标点被 +# 去掉),拼接时补回句号。 +SENTENCE_A = "这个做法帮我在 3 天里涨了 5000 个粉丝" +SENTENCE_B = "首先对齐目标,其次沉淀方法论,最后形成可复用的打法" +SENTENCE_C = "这套组合拳能够有效赋能创作者,3 个月内转化率提升了 40%" +SENTENCE_D = "我们必须找到新的增长抓手" +SENTENCE_E = "围绕底层逻辑跑出一个增长闭环" + +MIXED_TEXT = "。".join([SENTENCE_A, SENTENCE_B, SENTENCE_C, SENTENCE_D, SENTENCE_E]) + "。" + + +def _real_hit_words(sentence: str) -> list[str]: + return [h["word"] for h in scan_words(sentence)] + + +def _install_llm(monkeypatch, *, llm_result=None, llm_error=None) -> dict: + """替换 service 模块内的 call_llm_json,返回捕获到的调用参数(模式同 test_content_event_angles)。""" + + captured: dict = {} + + async def fake_llm(messages, **kwargs): + captured["messages"] = messages + captured["kwargs"] = kwargs + if llm_error is not None: + raise llm_error + return llm_result + + monkeypatch.setattr(svc, "call_llm_json", fake_llm) + return captured + + +# ── Service:选句纯函数 ───────────────────────────────────────────────── + + +def test_select_prefers_dense_hits_and_keeps_original_order_on_tie(): + """命中数降序:B(8) → C(2) → E(2)(同命中数按原文顺序);A(0)/D(1) 不入前三。""" + assert select_target_sentences(MIXED_TEXT) == [SENTENCE_B, SENTENCE_C, SENTENCE_E] + + +def test_select_caps_at_three_sentences(): + """上限 3 句:密集样文逐句命中 [1, 3, 3, 8],选 S4 → S2 → S3。""" + sentences = split_sentences(DENSE_TEXT) + selected = select_target_sentences(DENSE_TEXT) + assert len(selected) == 3 + assert selected == [sentences[3], sentences[1], sentences[2]] # 8 命中句优先,3 命中句按原文顺序 + + +def test_select_pads_with_single_hit_sentences_when_fewer_dense(): + """不足 3 句时用命中数 =1 的句子补足;句数再少就有多少返回多少。""" + assert select_target_sentences(SENTENCE_B + "。" + SENTENCE_D) == [SENTENCE_B, SENTENCE_D] + assert select_target_sentences(SENTENCE_D) == [SENTENCE_D] + + +def test_select_returns_empty_for_zero_hit_text(): + """零命中句不入选:口语化样文返回空列表(API 据此 422)。""" + assert select_target_sentences(COLLOQUIAL_TEXT) == [] + assert select_target_sentences("") == [] + + +def test_per_sentence_rescan_equals_full_scan(): + """逐句重扫与全扫等价:词命中不可能跨句界(句末标点是掩码分隔符)。 + + 逐句重扫的词频合计与全扫一致;样文刻意让同一词跨句出现(赋能×2、抓手×2), + 等价性不是逐句互不重叠的偶然结果。 + """ + text = "。".join([SENTENCE_C, SENTENCE_D, SENTENCE_E, SENTENCE_D, SENTENCE_C]) + "。" + full_counter = Counter(h["word"] for h in scan_words(text)) + per_sentence_counter: Counter[str] = Counter() + for sentence in split_sentences(text): + per_sentence_counter.update(h["word"] for h in scan_words(sentence)) + assert full_counter == per_sentence_counter + assert full_counter["赋能"] == 2 and full_counter["抓手"] == 2 # 同词跨句,等价性有实质内容 + + +# ── Service:LLM 编排与响应校验 ───────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_generate_success_filters_hit_words_and_preserves_text_verbatim(monkeypatch): + """成功路径:hit_words 只留真实命中、original=服务端选取句、rewritten 逐字透传。""" + captured = _install_llm( + monkeypatch, + llm_result={ + "suggestions": [ + # 编造词「降本增效」不在 B 句真实命中里,必须被过滤掉 + { + "original": SENTENCE_B, + "rewritten": "先定目标,再把能反复用的做法整理出来。", + "hit_words": ["方法论", "降本增效", "打法"], + }, + # hit_words 回显为空:徽标退回该句真实命中,不编造也不空着 + { + "original": SENTENCE_C, + "rewritten": "这套做法真能帮创作者用起来,3 个月内转化率提升了 40%。", + "hit_words": [], + }, + # 回显与选取句对不上:整条丢弃,不用 LLM 的句子冒充原句 + {"original": "完全没出现过的句子。", "rewritten": "随便改写", "hit_words": ["赋能"]}, + ] + }, + ) + + result = await generate_humanize_rewrites(SENTENCE_A + "。" + SENTENCE_B + "。" + SENTENCE_C + "。") + + assert [s["original"] for s in result["suggestions"]] == [SENTENCE_B, SENTENCE_C] + first, second = result["suggestions"] + assert first["hit_words"] == [w for w in ("方法论", "打法") if w in _real_hit_words(SENTENCE_B)] + assert "降本增效" not in first["hit_words"] + assert second["hit_words"] == _real_hit_words(SENTENCE_C) + # 响应管道不改动文本:含数字的改写句逐字保留(「3 个月」「40%」原样到达前端) + assert second["rewritten"] == "这套做法真能帮创作者用起来,3 个月内转化率提升了 40%。" + + # 调用参数:scene 与低温/收紧的 token 上限 + assert captured["kwargs"]["scene"] == "humanize_rewrite" + assert captured["kwargs"]["temperature"] <= 0.4 + assert captured["kwargs"]["max_tokens"] <= 1200 + + +@pytest.mark.asyncio +async def test_generate_prompt_contains_fact_guard_and_never_includes_full_text(monkeypatch): + """prompt 合同:system 含不改事实/数字指令;只有选取句进 prompt,全文与其余句子不进。""" + text = MIXED_TEXT + captured = _install_llm( + monkeypatch, + llm_result={"suggestions": [{"original": SENTENCE_B, "rewritten": "改写。", "hit_words": []}]}, + ) + + await generate_humanize_rewrites(text) + + system_content = captured["messages"][0]["content"] + user_content = captured["messages"][1]["content"] + assert captured["messages"][0]["role"] == "system" + assert "事实" in system_content and "数字" in system_content # 不改事实与数字的显式指令 + assert SENTENCE_B in user_content and SENTENCE_C in user_content # 只有选取句进 prompt + assert SENTENCE_A not in user_content # 零命中句不进 + assert SENTENCE_D not in user_content # 落选的低命中句不进 + assert text not in user_content # 全文永不进 prompt + + +@pytest.mark.asyncio +async def test_generate_without_hits_raises_before_any_llm_call(monkeypatch): + """零命中文稿:先抛 422 业务异常,不烧任何 LLM 调用。""" + captured = _install_llm(monkeypatch, llm_result={"suggestions": []}) + with pytest.raises(HumanizeRewriteNoTargetError): + await generate_humanize_rewrites(COLLOQUIAL_TEXT) + assert "messages" not in captured + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "llm_result", + [ + {"raw_response": "not-json"}, # 不可解析输出(provider 解析失败合同) + {"suggestions": "not-a-list"}, + {"suggestions": [{"original": "不存在的句子", "rewritten": "改写"}]}, # 全部回显错配 + {"suggestions": [{"original": SENTENCE_B, "rewritten": " "}]}, # rewritten 空 + ], +) +async def test_generate_raises_unavailable_when_no_valid_entries(monkeypatch, llm_result): + """没有任何有效条目 → 业务异常(API 映射 502),不返回空建议装成功。""" + _install_llm(monkeypatch, llm_result=llm_result) + with pytest.raises(HumanizeRewriteUnavailableError): + await generate_humanize_rewrites(SENTENCE_B) + + +# ── API:POST /content-check/humanize-rewrite ────────────────────────── + + +@pytest_asyncio.fixture +async def app(): + app = FastAPI() + app.include_router(content_check_router) + return app + + +@pytest_asyncio.fixture +async def anon_client(app): + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://testserver") as client: + yield client + + +@pytest_asyncio.fixture +async def authed_client(app): + app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(id=1, email="writer@example.com") + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://testserver") as client: + yield client + + +@pytest.mark.asyncio +async def test_endpoint_rejects_anonymous(anon_client): + """未认证请求 401(与 sensitive/ai-traces 同口径)。""" + resp = await anon_client.post("/content-check/humanize-rewrite", json={"text": DENSE_TEXT}) + assert resp.status_code == 401 + + +@pytest.mark.asyncio +async def test_endpoint_returns_suggestions_from_server_selected_sentences(monkeypatch, authed_client): + """成功路径:≤3 条建议,original 全部来自服务端选取句,hit_words ⊆ 该句真实命中。""" + selected = select_target_sentences(DENSE_TEXT) + llm_result = { + "suggestions": [ + { + "original": sentence, + "rewritten": f"口语化改写 {i}:保留 3 个方法与 40% 的数字。", + "hit_words": ["编造的词"] + _real_hit_words(sentence)[:1], + } + for i, sentence in enumerate(selected) + ] + } + _install_llm(monkeypatch, llm_result=llm_result) + + resp = await authed_client.post("/content-check/humanize-rewrite", json={"text": DENSE_TEXT}) + + assert resp.status_code == 200 + suggestions = resp.json()["suggestions"] + assert 1 <= len(suggestions) <= 3 + assert [s["original"] for s in suggestions] == selected # 服务端选取顺序 + for suggestion in suggestions: + assert suggestion["hit_words"] # 过滤后仍非空(退回真实命中) + assert set(suggestion["hit_words"]) <= set(_real_hit_words(suggestion["original"])) + assert "3 个方法" in suggestion["rewritten"] and "40%" in suggestion["rewritten"] + + +@pytest.mark.asyncio +async def test_endpoint_no_hit_sentences_returns_422_with_reason(monkeypatch, authed_client): + """零命中文稿 → 422 且 detail 说明原因(不是静默空建议)。""" + _install_llm(monkeypatch, llm_result={"suggestions": []}) + resp = await authed_client.post("/content-check/humanize-rewrite", json={"text": COLLOQUIAL_TEXT}) + assert resp.status_code == 422 + assert "命中" in resp.json()["detail"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "llm_error,expected_detail", + [ + (CircuitOpenError("circuit open"), "熔断"), + (LlmCapacityUnavailableError(routing_group="default", next_available_at=None), "暂不可用"), + (LlmBudgetExceededError("over budget"), "预算"), + (LlmContextWindowExceededError("too long"), "上下文"), + # 末路异常兜底(评审 C-1):超时/候选耗尽不落 500 英文裸错 + (RuntimeError("unexpected"), "改写建议生成失败,请稍后重试"), + ], +) +async def test_endpoint_maps_llm_chain_errors_to_502(monkeypatch, authed_client, llm_error, expected_detail): + """LLM 链路异常 → 502 显式中文文案,不折叠成 200 假成功。""" + _install_llm(monkeypatch, llm_error=llm_error) + resp = await authed_client.post("/content-check/humanize-rewrite", json={"text": DENSE_TEXT}) + assert resp.status_code == 502 + assert expected_detail in resp.json()["detail"] + + +@pytest.mark.asyncio +async def test_endpoint_maps_unparsable_output_to_502(monkeypatch, authed_client): + """不可解析输出 → 502「结构不可用」。""" + _install_llm(monkeypatch, llm_result={"raw_response": "not-json"}) + resp = await authed_client.post("/content-check/humanize-rewrite", json={"text": DENSE_TEXT}) + assert resp.status_code == 502 + assert "结构不可用" in resp.json()["detail"] + + +@pytest.mark.asyncio +async def test_endpoint_rejects_empty_and_overlong_text(authed_client): + """长度口径与 sensitive/ai-traces 一致:空文本、20001 字 → 422。""" + empty = await authed_client.post("/content-check/humanize-rewrite", json={"text": ""}) + assert empty.status_code == 422 + over = await authed_client.post("/content-check/humanize-rewrite", json={"text": "好" * 20001}) + assert over.status_code == 422 diff --git a/frontend/src/app/content-check/_humanize.test.tsx b/frontend/src/app/content-check/_humanize.test.tsx new file mode 100644 index 00000000..9f9984c1 --- /dev/null +++ b/frontend/src/app/content-check/_humanize.test.tsx @@ -0,0 +1,69 @@ +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it } from 'vitest'; +import { HumanizeRewritePanel } from './_humanize'; +import type { HumanizeRewriteSuggestion } from '@/types/content-check'; + +const suggestion = (over: Partial = {}): HumanizeRewriteSuggestion => ({ + original: '首先对齐目标,其次沉淀方法论,最后形成可复用的打法', + rewritten: '先定目标,再把能反复用的做法整理出来,3 个月跑通了 40% 的增长', + hit_words: ['方法论', '打法'], + ...over, +}); + +function renderPanel(over: Partial> = {}) { + const props: React.ComponentProps = { + suggestions: null, + loading: false, + error: null, + canGenerate: true, + onGenerate: () => {}, + ...over, + }; + return renderToStaticMarkup(React.createElement(HumanizeRewritePanel, props)); +} + +describe('HumanizeRewritePanel', () => { + it('renders suggestions with original → rewritten pairs and purple hit-word badges', () => { + const html = renderPanel({ suggestions: [suggestion()] }); + expect(html).toContain('改写建议'); + expect(html).toContain('首先对齐目标,其次沉淀方法论,最后形成可复用的打法'); // 原句 + expect(html).toContain('先定目标,再把能反复用的做法整理出来,3 个月跑通了 40% 的增长'); // 建议句(数字原样) + expect(html).toContain('>方法论'); // 徽标词 + expect(html).toContain('>打法'); + expect(html).toContain('bg-purple-light'); // 徽标沿用 AI 痕迹紫色系 + expect(html).not.toContain('bg-red-'); // 不染风险红系 + }); + + it('renders multiple suggestions as separate items', () => { + const html = renderPanel({ suggestions: [suggestion(), suggestion({ original: '这套组合拳能够有效赋能创作者', rewritten: '这套做法真能帮创作者用起来', hit_words: ['赋能'] })] }); + expect((html.match(/data-humanize-suggestion/g) ?? []).length).toBe(2); + expect(html).toContain('这套组合拳能够有效赋能创作者'); + }); + + it('disables the button when there is nothing to rewrite and explains why', () => { + const html = renderPanel({ canGenerate: false }); + expect(html).toContain('disabled'); // 按钮禁用 + expect(html).toContain('暂无可改写的句子'); + }); + + it('shows loading state and keeps the button disabled while generating', () => { + const html = renderPanel({ loading: true }); + expect(html).toContain('生成中…'); + expect(html).toContain('disabled'); + expect(html).not.toContain('暂无可改写的句子'); // loading 不与零命中提示同屏 + }); + + it('shows the standalone inline error without hijacking the scan retry UI', () => { + const html = renderPanel({ error: '改写建议生成失败:模型服务暂不可用,请稍后重试' }); + expect(html).toContain('role="alert"'); + expect(html).toContain('模型服务暂不可用'); + expect(html).not.toContain('重新检测'); // 不复用检测 ErrorState 的重试语义 + }); + + it('falls back to a hint when the server returns zero usable suggestions', () => { + const html = renderPanel({ suggestions: [] }); + expect(html).toContain('本次未生成可用的改写建议'); + expect(html).not.toContain('data-humanize-suggestion'); + }); +}); diff --git a/frontend/src/app/content-check/_humanize.tsx b/frontend/src/app/content-check/_humanize.tsx new file mode 100644 index 00000000..66d8e919 --- /dev/null +++ b/frontend/src/app/content-check/_humanize.tsx @@ -0,0 +1,102 @@ +'use client'; + +/** + * 「去 AI 味」改写建议面板(从 page.tsx 拆出便于测试,模式同 _highlight)。 + * + * 口径红线(owning note 2026-11-04-content-check-ai-traces.md):改写建议是 + * 「写作建议」,文案保持启发式统计口径,禁止「AI 率 / AI 概率 / 检测模型」 + * 类表述。徽标沿用 AI 痕迹的紫色系语义,与风险红/黄分开。 + */ + +import React from 'react'; +import { ArrowRight, Loader2, PenLine, Sparkles } from 'lucide-react'; +import { Badge, Button, Panel } from '@/components/ui'; +import type { HumanizeRewriteSuggestion } from '@/types/content-check'; + +export function HumanizeRewritePanel({ + suggestions, + loading, + error, + canGenerate, + onGenerate, +}: { + /** 已生成的建议;null 表示尚未生成(首屏不展示建议区)。 */ + suggestions: HumanizeRewriteSuggestion[] | null; + loading: boolean; + /** 独立的生成失败提示(inline 展示,不复用检测的 ErrorState 重试语义)。 */ + error: string | null; + /** 只有检测结果 current 且存在 AI 痕迹命中时才可生成。 */ + canGenerate: boolean; + onGenerate: () => void; +}) { + return ( + +
+ + + 改写建议 + +
+

+ 对 AI 痕迹命中最密集的句子生成保留原意的口语化改写(最多 3 句),仅供改稿参考, + 发布前请自行核对事实与数字。 +

+ + {!canGenerate && !loading && !suggestions && !error && ( +

+ 当前文稿没有命中 AI 高频词或套话连接词,暂无可改写的句子。 +

+ )} + {error && ( +

+ {error} +

+ )} + {suggestions !== null && suggestions.length === 0 && !error && ( +

本次未生成可用的改写建议,可稍后再试。

+ )} + {suggestions && suggestions.length > 0 && ( +
    + {suggestions.map((suggestion, index) => ( + + ))} +
+ )} +
+ ); +} + +/** 一条建议:命中词徽标(紫色系,词来自服务端真实命中)+ 原句 → 改写句对照。 */ +function SuggestionItem({ suggestion }: { suggestion: HumanizeRewriteSuggestion }) { + return ( +
  • + {suggestion.hit_words.length > 0 && ( +
    + {suggestion.hit_words.map((word) => ( + + {word} + + ))} +
    + )} +

    + {suggestion.original} +

    +

    + + {suggestion.rewritten} +

    +
  • + ); +} diff --git a/frontend/src/app/content-check/page.tsx b/frontend/src/app/content-check/page.tsx index 88387337..02657f02 100644 --- a/frontend/src/app/content-check/page.tsx +++ b/frontend/src/app/content-check/page.tsx @@ -6,6 +6,7 @@ import { contentCheckApi } from '@/lib/api'; import { Badge, Button, Panel, cx } from '@/components/ui'; import { ErrorState } from '@/components/StateView'; import { HighlightText, type HighlightHit } from './_highlight'; +import { HumanizeRewritePanel } from './_humanize'; import { scanPhase } from './_scan-state'; import { AI_TRACE_LEVEL_META, @@ -14,6 +15,7 @@ import { SENSITIVE_SEVERITY_LABELS, type AiTraceLevel, type AiTracesReport, + type HumanizeRewriteResponse, type SensitiveCategory, type SensitiveCheckResponse, type SensitiveSeverity, @@ -49,6 +51,10 @@ export default function ContentCheckPage() { /** 结果对应的文稿快照:编辑后 phase 变 stale,旧结论与旧偏移不再展示 */ const [scannedText, setScannedText] = useState(null); const [error, setError] = useState(null); + /** 「去 AI 味」改写建议:随检测快照走,重扫/清空即失效;错误独立于检测错误展示 */ + const [rewrites, setRewrites] = useState(null); + const [rewriting, setRewriting] = useState(false); + const [rewriteError, setRewriteError] = useState(null); const phase = scanPhase(scannedText, text, results); const current = phase.kind === 'current' ? phase.result : null; @@ -76,6 +82,8 @@ export default function ContentCheckPage() { async function handleScan() { setScanning(true); setError(null); + setRewrites(null); // 重扫即换文稿快照,旧建议随之作废 + setRewriteError(null); try { const [sensitive, aiTraces] = await Promise.all([ contentCheckApi.checkSensitive(text), @@ -92,11 +100,28 @@ export default function ContentCheckPage() { } } + /** 生成改写建议:只对 current 快照发起(scanPhase 合同保证 scannedText===text),全文上送、服务端选句。 */ + async function handleGenerateRewrites() { + if (scannedText === null) return; + setRewriting(true); + setRewriteError(null); + try { + setRewrites(await contentCheckApi.checkHumanizeRewrite(scannedText)); + } catch (err) { + setRewrites(null); + setRewriteError(err instanceof Error ? err.message : '改写建议生成失败,请稍后重试'); + } finally { + setRewriting(false); + } + } + function handleClear() { setText(''); setResults(null); setScannedText(null); setError(null); + setRewrites(null); + setRewriteError(null); } const sensitiveTotal = current?.sensitive.total ?? 0; @@ -108,8 +133,8 @@ export default function ContentCheckPage() {

    文稿检测

    发布前粘贴文稿,检测广告法极限词、高危违禁词与平台限流词;另附 AI 痕迹启发式统计 - (AI 高频词、套话连接词、句式节奏),仅供改稿参考。命中原文高亮显示,悬停查看建议; - 文稿只在本次检测中使用,不落库、不留存。 + (AI 高频词、套话连接词、句式节奏),并可对命中密集的句子生成口语化改写建议, + 仅供改稿参考。命中原文高亮显示,悬停查看建议;文稿只在本次检测中使用,不落库、不留存。

    @@ -200,6 +225,13 @@ export default function ContentCheckPage() { })} + 0} + onGenerate={() => void handleGenerateRewrites()} + /> ) : phase.kind === 'stale' ? ( diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 646ce9c5..cd6cf4d7 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -36,7 +36,7 @@ import type { NotificationListResponse, } from '@/types'; import type { FavoriteCreatePayload, FavoriteTargetState } from '@/lib/favorites'; -import type { AiTracesReport, SensitiveCheckResponse } from '@/types/content-check'; +import type { AiTracesReport, HumanizeRewriteResponse, SensitiveCheckResponse } from '@/types/content-check'; import type { RSSHubInstance, StatsOverview, @@ -297,6 +297,14 @@ export const contentCheckApi = { body: JSON.stringify({ text }), }); }, + + /** 「去 AI 味」改写建议(需登录):传全文,服务端只选取命中最密集的 ≤3 句进模型。 */ + checkHumanizeRewrite(text: string): Promise { + return request('/content-check/humanize-rewrite', { + method: 'POST', + body: JSON.stringify({ text }), + }); + }, }; // ─── Notifications API ─── diff --git a/frontend/src/types/content-check.ts b/frontend/src/types/content-check.ts index 944825e5..c04cf97a 100644 --- a/frontend/src/types/content-check.ts +++ b/frontend/src/types/content-check.ts @@ -96,3 +96,16 @@ export const AI_TRACE_WORD_DIMENSION_LABELS: Record