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
+93 -1
View File
@@ -30,7 +30,7 @@ from typing import Any, Dict, List, Optional
import pytest
import pytest_asyncio
from sqlalchemy import select
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import StaticPool
@@ -58,7 +58,9 @@ from api.monitor.models import (
MonitorEvent,
MonitorNote,
MonitorNoteMetric,
MonitorNoteTag,
MonitorRun,
MonitorTag,
MonitorTarget,
MonitorTask,
RUN_FAILED,
@@ -1146,3 +1148,93 @@ class TestABrokenTargetIsNotBlamedOnTheCookie:
assert await _events(db, EVENT_AUTH_FAILURE)
assert await _events(db, EVENT_NO_DATA) == []
class TestAutoTaggingOnIngest:
"""新作品按关键词规则自动打标签 —— 而且**只在第一次入库时**跑。
每轮都跑的话,自动打标签「只贴不摘」这件事就变得毫无意义:用户手动摘掉的标签,
下一轮采集又会长回来。
"""
@staticmethod
async def _seed_rule(db, keywords: str) -> int:
tag = MonitorTag(
name="大字报", color="cyan", keywords=keywords, sort_order=1, created_at=0
)
db.add(tag)
await db.flush()
return tag.id
@staticmethod
async def _note_tags(db) -> list:
rows = (
await db.execute(
select(MonitorNote.note_id, MonitorTag.name)
.join(MonitorNoteTag, MonitorNoteTag.note_id == MonitorNote.note_id)
.join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id)
.order_by(MonitorNote.note_id)
)
).all()
return [(row[0], row[1]) for row in rows]
@pytest.mark.asyncio
async def test_a_new_work_matching_a_keyword_gets_the_tag(self, db, tmp_path):
await self._seed_rule(db, "szgtdzb")
task = await _make_task(db)
run = await _make_run(db, task, started_at=1)
_write_run_dir(tmp_path, [_note("n1", title="苏州探店 #szgtdzb")], comments=[])
await ingest_run(db, run, task, tmp_path)
assert await self._note_tags(db) == [("n1", "大字报")]
@pytest.mark.asyncio
async def test_a_work_that_does_not_match_is_left_alone(self, db, tmp_path):
await self._seed_rule(db, "szgtdzb")
task = await _make_task(db)
run = await _make_run(db, task, started_at=1)
_write_run_dir(tmp_path, [_note("n1", title="随便一条")], comments=[])
await ingest_run(db, run, task, tmp_path)
assert await self._note_tags(db) == []
@pytest.mark.asyncio
async def test_one_work_can_pick_up_several_tags(self, db, tmp_path):
"""命中几个话题就打几个标签。"""
await self._seed_rule(db, "szgtdzb")
db.add(MonitorTag(name="旅游号", color="cyan", keywords="苏州旅游", sort_order=2, created_at=0))
await db.flush()
task = await _make_task(db)
run = await _make_run(db, task, started_at=1)
_write_run_dir(
tmp_path, [_note("n1", title="探店 #szgtdzb #苏州旅游")], comments=[]
)
await ingest_run(db, run, task, tmp_path)
assert await self._note_tags(db) == [("n1", "大字报"), ("n1", "旅游号")]
@pytest.mark.asyncio
async def test_a_tag_removed_by_hand_does_not_come_back_next_run(self, db, tmp_path):
"""**这条是这个设计的全部理由。**"""
await self._seed_rule(db, "szgtdzb")
task = await _make_task(db)
first = await _make_run(db, task, started_at=1)
_write_run_dir(tmp_path, [_note("n1", title="苏州探店 #szgtdzb")], comments=[])
await ingest_run(db, first, task, tmp_path)
assert await self._note_tags(db) == [("n1", "大字报")]
# 用户手动摘掉
await db.execute(
delete(MonitorNoteTag).where(MonitorNoteTag.note_id == "n1")
)
await db.commit()
# 下一轮又把同一条作品采回来了
second = await _make_run(db, task, started_at=2000)
_write_run_dir(tmp_path, [_note("n1", title="苏州探店 #szgtdzb")], comments=[])
await ingest_run(db, second, task, tmp_path)
assert await self._note_tags(db) == []