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) == []
+183
View File
@@ -0,0 +1,183 @@
# -*- coding: utf-8 -*-
"""自动打标签 —— 标题里出现关键词就贴上,命中几个贴几个。
规则长在标签自己身上(标签叫「大字报」,关键词可能是 `szgtdzb`),因为话题词和给人看的
分类名不是一回事。
"""
import httpx
import pytest
import pytest_asyncio
from api.main import app
from api.monitor import db as monitor_db
from api.monitor.models import MODE_CREATOR, MonitorNote, MonitorTag, MonitorTask
from api.monitor.tagrules import split_keywords, tags_matching
TITLE = "苏州探店 #szgtdzb #苏州旅游 今天真热闹"
@pytest_asyncio.fixture
async def client(tmp_path):
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
await monitor_db.init_db()
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http_client:
yield http_client
await monitor_db.dispose_engine()
async def _seed_notes(titles=("第一条",)) -> None:
async with monitor_db.get_session() as session:
task = MonitorTask(
name="任务", platform="xhs", mode=MODE_CREATOR, enabled=True,
interval_minutes=60, max_notes_count=20, enable_comments=False,
max_comments_count=50, run_timeout_seconds=3600,
notify_enabled=False, created_at=0, updated_at=0,
)
session.add(task)
await session.flush()
for index, title in enumerate(titles):
session.add(
MonitorNote(
task_id=task.id, note_id=f"note-{index}", title=title,
note_url="", cover="", creator_hash="hash-a",
creator_name="博主", source_kind="", published_at=1,
first_seen_run_id=1, first_seen_at=1,
last_seen_run_id=1, last_seen_at=1,
)
)
async def _make_tag(client, name, keywords="", color=""):
response = await client.post(
"/api/monitor/tags", json={"name": name, "color": color, "keywords": keywords}
)
assert response.status_code == 200, response.text
return response.json()["id"]
async def _notes(client, platform="xhs"):
return (await client.get("/api/monitor/notes", params={"platform": platform})).json()["notes"]
def _tags_by_note(notes):
return {
note["note_id"]: sorted(tag["name"] for tag in note["tags"]) for note in notes
}
class TestSplitKeywords:
def test_both_comma_styles_are_accepted(self):
"""中文逗号是最常见的输入法产物 —— 只认英文逗号的话人会以为规则没生效。"""
assert split_keywords("广告, 合作,推广") == ["广告", "合作", "推广"]
def test_blanks_and_duplicates_are_dropped(self):
assert split_keywords("广告,, 广告 , ") == ["广告"]
def test_empty_stays_empty(self):
assert split_keywords("") == []
class TestTagsMatching:
@staticmethod
def _tag(keywords: str, tag_id: int = 1) -> MonitorTag:
return MonitorTag(id=tag_id, name="t", color="", keywords=keywords, sort_order=0, created_at=0)
def test_a_keyword_matches_the_title(self):
assert tags_matching(TITLE, [self._tag("szgtdzb")]) == [1]
def test_matching_ignores_case(self):
"""代号大小写混着写的很常见,用户不该为了这个配两遍。"""
assert tags_matching("今天 #SZGTDZB", [self._tag("szgtdzb")]) == [1]
def test_several_rules_can_hit_at_once(self):
"""**这是这个功能的核心**:一条作品命中几个话题,就贴几个标签。"""
rules = [self._tag("szgtdzb", 1), self._tag("苏州旅游", 2), self._tag("不存在的词", 3)]
assert tags_matching(TITLE, rules) == [1, 2]
def test_a_tag_without_keywords_never_matches(self):
assert tags_matching(TITLE, [self._tag("")]) == []
def test_an_empty_title_matches_nothing(self):
assert tags_matching("", [self._tag("szgtdzb")]) == []
class TestRulesApplyToExistingWorks:
@pytest.mark.asyncio
async def test_creating_a_tag_with_keywords_tags_matching_works(self, client):
"""配好关键词却一条都没贴上,正是这个功能最容易被当成坏掉的样子。"""
await _seed_notes(titles=[TITLE, "无关的一条"])
await _make_tag(client, "大字报", keywords="szgtdzb")
assert _tags_by_note(await _notes(client)) == {
"note-0": ["大字报"],
"note-1": [],
}
@pytest.mark.asyncio
async def test_one_work_can_get_several_tags_at_once(self, client):
await _seed_notes(titles=[TITLE])
await _make_tag(client, "大字报", keywords="szgtdzb")
await _make_tag(client, "旅游号", keywords="苏州旅游")
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报", "旅游号"]
@pytest.mark.asyncio
async def test_editing_keywords_retags_existing_works(self, client):
await _seed_notes(titles=[TITLE])
tag_id = await _make_tag(client, "大字报", keywords="别的词")
assert _tags_by_note(await _notes(client))["note-0"] == []
response = await client.put(
f"/api/monitor/tags/{tag_id}",
json={"name": "大字报", "keywords": "szgtdzb"},
)
assert response.json()["tagged"] == 1
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报"]
@pytest.mark.asyncio
async def test_editing_one_rule_does_not_rerun_the_others(self, client):
"""**只贴不摘的一种具体后果**:改 A 的关键词,不该把用户从 B 上摘掉的标签贴回来。
两条规则都命中这条作品 → 两条都自动贴上 → 用户手动全摘掉 → 只改 A 的关键词。
结果应该只有 A 回来,B 保持被摘掉的状态。
"""
await _seed_notes(titles=[TITLE])
a = await _make_tag(client, "大字报", keywords="szgtdzb")
await _make_tag(client, "旅游号", keywords="苏州旅游")
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报", "旅游号"]
await client.put(
"/api/monitor/notes/note-0/tags",
params={"platform": "xhs"},
json={"tag_ids": []},
)
assert _tags_by_note(await _notes(client))["note-0"] == []
await client.put(f"/api/monitor/tags/{a}", json={"name": "大字报", "keywords": "szgtdzb"})
# 只有 A 回来了 —— B 没被顺手重跑,「旅游号」不该出现。
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报"]
@pytest.mark.asyncio
async def test_turning_keywords_off_does_not_remove_existing_tags(self, client):
"""**只贴不摘** —— 关掉规则不等于把已经贴上的撕下来。"""
await _seed_notes(titles=[TITLE])
tag_id = await _make_tag(client, "大字报", keywords="szgtdzb")
await client.put(f"/api/monitor/tags/{tag_id}", json={"name": "大字报", "keywords": ""})
assert _tags_by_note(await _notes(client))["note-0"] == ["大字报"]
@pytest.mark.asyncio
async def test_keywords_come_back_with_the_tag_list(self, client):
await _make_tag(client, "大字报", keywords="szgtdzb, 探店")
tags = (await client.get("/api/monitor/tags")).json()["tags"]
assert tags[0]["keywords"] == "szgtdzb,探店"