feat(monitor): 按关键词自动打标签 —— 命中几个话题就打几个标签
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

标签上配一串关键词(逗号分隔),作品标题里出现其中任意一个就自动贴上。一条标题可以
命中多条规则,命中几条贴几个。关键词和标签名是两回事:标签叫「大字报」,关键词可能是
`szgtdzb`。

三条刻意的设计:

* **只贴不摘。** 手动摘掉的标签不会被下一轮采集又贴回来 —— 这也是为什么它只在「作品
  第一次入库」和「有人改了规则」这两个时机跑,而不是每轮都跑。
* **改哪条规则就只重跑哪条。** 全都重跑的话,改 A 会把用户从 B 上摘掉的标签也贴回来。
  新建/改关键词时立刻对已有作品跑一遍,否则「刚配好关键词,一条都没贴上」会被当成坏了。
* **匹配标题里的子串、不分大小写**,不是只匹配 `#话题#` —— 话题本来就长在标题里,而
  `szgtdzb` 这种代号未必包在井号里。代价是关键词定太宽会误伤,设置页里写了这句提醒。

规则单独放 `tagrules.py`:`ingest` 和路由都要用它,而 `ingest` 不能 import `service`
(service → runner → ingest 会成环)。

测试验过关键那条会拦:把「只在第一次入库时收」改成每轮都收,
`test_a_tag_removed_by_hand_does_not_come_back_next_run` 立刻变红。
This commit is contained in:
2026-10-15 10:33:49 +08:00
parent ad92b5bc33
commit aaf943c662
12 changed files with 558 additions and 30 deletions
+10 -3
View File
@@ -19,7 +19,8 @@
"""Task CRUD and dashboard queries for the monitoring layer."""
import asyncio
from typing import Any, Dict, List, Optional, Sequence
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple
from urllib.parse import parse_qs, urlparse
import httpx
@@ -50,6 +51,7 @@ from .models import (
RUN_PARTIAL,
)
from .runner import execute_task
from .tagrules import split_keywords
# Keep strong references to in-flight manual runs; asyncio only holds weak ones,
# so without this a run can be garbage collected mid-flight.
@@ -543,13 +545,16 @@ async def list_tags(session: AsyncSession) -> List[Dict[str, Any]]:
"id": row.id,
"name": row.name,
"color": row.color or DEFAULT_TAG_COLOR,
"keywords": row.keywords or "",
"note_count": counts.get(row.id, 0),
}
for row in rows
]
async def create_tag(session: AsyncSession, name: str, color: str = "") -> MonitorTag:
async def create_tag(
session: AsyncSession, name: str, color: str = "", keywords: str = ""
) -> MonitorTag:
"""新建标签。重名直接拒绝 —— 两个「重点」在筛选列表里是灾难。"""
name = (name or "").strip()[:32]
if not name:
@@ -564,6 +569,7 @@ async def create_tag(session: AsyncSession, name: str, color: str = "") -> Monit
tag = MonitorTag(
name=name,
color=color if color in TAG_COLORS else DEFAULT_TAG_COLOR,
keywords=",".join(split_keywords(keywords))[:512],
sort_order=(last or 0) + 1,
created_at=get_current_timestamp(),
)
@@ -573,7 +579,7 @@ async def create_tag(session: AsyncSession, name: str, color: str = "") -> Monit
async def update_tag(
session: AsyncSession, tag_id: int, name: str, color: str = ""
session: AsyncSession, tag_id: int, name: str, color: str = "", keywords: str = ""
) -> MonitorTag:
tag = await session.get(MonitorTag, tag_id)
if tag is None:
@@ -591,6 +597,7 @@ async def update_tag(
tag.name = name
tag.color = color if color in TAG_COLORS else DEFAULT_TAG_COLOR
tag.keywords = ",".join(split_keywords(keywords))[:512]
await session.flush()
return tag