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
+17 -3
View File
@@ -38,14 +38,14 @@ import json
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence
from typing import Any, Dict, List, Optional, Sequence, Tuple
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from tools.time_util import get_current_timestamp
from . import adapters
from . import adapters, tagrules
from .platforms import PLATFORM_XHS
from .models import (
EVENT_AUTH_FAILURE,
@@ -372,6 +372,7 @@ async def _ingest_notes(
records: List[Dict[str, Any]],
is_baseline: bool,
adapter: adapters.PlatformAdapter,
platform: str,
) -> int:
"""Upsert notes, write metric snapshots, and emit new-note/delta events.
@@ -388,6 +389,8 @@ async def _ingest_notes(
# 一个博主只有落在采集窗口里的那几条会被重刷,掉出窗口的那些会一直留着旧名字。
# 所以收完这一轮之后,再拿它把该博主在本任务下的作品统一改一遍(见循环之后)。
fresh_names: Dict[str, str] = {}
# 这一轮**第一次见到**的作品((note_id, title)),出了循环之后按规则自动打标签。
first_seen_notes: List[Tuple[str, str]] = []
for record in records:
note_id = adapter.note_field(record, "note_id")
@@ -411,6 +414,9 @@ async def _ingest_notes(
fresh_names[adapter.note_field(record, "creator_hash") or ""] = fresh_name
if note is None:
# **只在这一支里**收,也就是作品第一次入库时。自动打标签只贴不摘,所以
# 每轮都跑的话,用户手动摘掉的标签下一轮就会长回来。
first_seen_notes.append((note_id, title))
note = MonitorNote(
task_id=run.task_id,
note_id=note_id,
@@ -462,6 +468,12 @@ async def _ingest_notes(
await _snapshot_metrics(session, run, note_id, record, now, is_baseline)
# 这一轮第一次见到的作品,按标签上的关键词规则自动贴上。
# **只对新作品跑**:自动打标签只贴不摘,每轮都跑的话用户手动摘掉的标签会长回来。
await tagrules.apply_tag_rules_for_task(
session, run.task_id, platform, first_seen_notes
)
# 把这一轮的昵称铺到该博主的**全部**作品上,不只这一轮采到的那几条。
# 不做的话,博主改名之后库里会一半是新名字、一半是旧名字:界面按作品名分组时取的是
# 其中任意一个(max),导出和 SQL 更是直接看到旧名字。带上 `!= name` 是为了让没变化
@@ -866,7 +878,9 @@ async def ingest_run(
comments_fetched=len(comments),
is_baseline=is_baseline,
)
result.new_notes = await _ingest_notes(session, run, contents, is_baseline, adapter)
result.new_notes = await _ingest_notes(
session, run, contents, is_baseline, adapter, task.platform
)
if task.enable_comments:
result.new_comments = await _ingest_comments(
session, run, comments, is_baseline, previous_started_at, adapter
+7
View File
@@ -423,6 +423,13 @@ class MonitorTag(MonitorBase):
# 一个**调色板里的名字**(cyan/pink/green/…),不是颜色值。Tailwind 的类名是静态
# 提取的,拼不出 `text-${color}` 那种动态类,所以这里存的是查表用的键。
color: Mapped[str] = mapped_column(String(16), nullable=False, default="")
# 自动打标签的关键词,**逗号分隔**(中英文逗号都收)。作品标题里出现其中任意一个,
# 这条标签就自动贴上 —— 命中几个贴几个。
#
# 关键词和标签名是**两回事**:标签叫「大字报」,关键词可能是 `szgtdzb`。
# 所以存成一个字符串而不是另开一张表:它就是这个标签自带的一小串匹配式,
# 没有独立的生命周期,也不需要在别处被引用。
keywords: Mapped[str] = mapped_column(String(512), nullable=False, default="")
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
created_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
+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
+145
View File
@@ -0,0 +1,145 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2025 [email protected]
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/monitor/tagrules.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
# 1. 不得用于任何商业用途。
# 2. 使用时应遵守对应平台的使用条款和robots.txt规则。
# 3. 不得进行大规模爬取或对平台造成运营干扰。
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
# 5. 不得用于任何非法或不当的用途。
#
# 详细许可条款请参阅项目根目录下的LICENSE文件。
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
"""自动打标签的规则 —— 「标题里出现这几个词,就贴上这条标签」。
**单独一个模块**,不是因为它大,是因为调用方分属两头:`ingest` 在作品第一次入库时要跑,
路由在有人改规则时要跑。而 `ingest` **不能** import `service`(service → runner → ingest
会成环),所以共用部分只能落在没有依赖的这一层。
"""
import re
from typing import Dict, List, Optional, Sequence, Tuple
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from tools.time_util import get_current_timestamp
from .models import MonitorNote, MonitorNoteTag, MonitorTag, MonitorTask
def split_keywords(raw: str) -> List[str]:
"""把「逗号分隔的关键词」切成干净的列表。中英文逗号都收,去空、去重、保序。"""
seen: List[str] = []
for part in re.split(r"[,,]", raw or ""):
word = part.strip()
if word and word not in seen:
seen.append(word)
return seen
def tags_matching(title: str, tags: Sequence[MonitorTag]) -> List[int]:
"""一个标题命中了哪些标签的规则。**纯函数**,所以能单独测。
匹配的是**标题里的子串**(不分大小写),不是只匹配 ``#话题#`` —— 话题本来就长在标题
里,而像 ``szgtdzb`` 这种代号未必包在井号里。一条标题可以命中**多条**规则,命中几条
就贴几个标签。
代价是关键词定得太宽会误伤(把「苏州」设成关键词,几乎每条都会被贴上),设置页里
写了这句提醒。
"""
haystack = (title or "").casefold()
if not haystack:
return []
return [
tag.id
for tag in tags
if any(word.casefold() in haystack for word in split_keywords(tag.keywords))
]
async def apply_tag_rules(
session: AsyncSession,
notes: Sequence[Tuple[str, str, str]],
only_tag_id: Optional[int] = None,
) -> int:
"""按规则给这些作品贴标签,返回新贴了几条。
``notes`` 是 ``(platform, note_id, title)`` 三元组 —— 平台得跟着走,因为
``monitor_note_tag`` 按 ``(platform, note_id)`` 存键,而标签词表本身**不**分平台。
``only_tag_id`` 只重跑一条规则。改某个标签的关键词时用这个:那一下只该重新识别这
一个标签,不该顺手把**别的**规则也重跑一遍 —— 那会把用户手动摘掉的其他标签又贴回来。
**只贴不摘。**
"""
query = select(MonitorTag)
if only_tag_id is not None:
query = query.where(MonitorTag.id == only_tag_id)
rules = [tag for tag in (await session.scalars(query)).all() if split_keywords(tag.keywords)]
if not rules or not notes:
return 0
note_ids = [note_id for _, note_id, _ in notes]
already = set(
(
await session.execute(
select(MonitorNoteTag.note_id, MonitorNoteTag.tag_id).where(
MonitorNoteTag.note_id.in_(note_ids)
)
)
).all()
)
now = get_current_timestamp()
added = 0
for platform, note_id, title in notes:
for tag_id in tags_matching(title, rules):
if (note_id, tag_id) in already:
continue
already.add((note_id, tag_id))
session.add(
MonitorNoteTag(
platform=platform, note_id=note_id, tag_id=tag_id, created_at=now
)
)
added += 1
return added
async def apply_tag_rules_for_task(
session: AsyncSession, task_id: int, platform: str, notes: Sequence[Tuple[str, str]]
) -> int:
"""作品**第一次入库**时调用:``notes`` 是 ``(note_id, title)``。"""
return await apply_tag_rules(
session, [(platform, note_id, title) for note_id, title in notes]
)
async def reapply_tag_rules(
session: AsyncSession, only_tag_id: Optional[int] = None
) -> int:
"""拿**库里已有的全部作品**重跑一遍规则。
改规则时要跑这一次,否则新加的关键词对已经采到的作品永远不生效 —— 而「我刚配好
关键词,结果一条都没贴上」正是这个功能最容易被当成坏掉了的样子。
"""
rows = (
await session.execute(
select(MonitorTask.platform, MonitorNote.note_id, MonitorNote.title).join(
MonitorTask, MonitorTask.id == MonitorNote.task_id
)
)
).all()
return await apply_tag_rules(session, [(r[0], r[1], r[2]) for r in rows], only_tag_id)
def keywords_by_tag(tags: Sequence[MonitorTag]) -> Dict[int, List[str]]:
"""给界面/调试用:标签 id -> 关键词列表。"""
return {tag.id: split_keywords(tag.keywords) for tag in tags if tag.keywords}