feat(monitor): 按关键词自动打标签 —— 命中几个话题就打几个标签
标签上配一串关键词(逗号分隔),作品标题里出现其中任意一个就自动贴上。一条标题可以 命中多条规则,命中几条贴几个。关键词和标签名是两回事:标签叫「大字报」,关键词可能是 `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:
+17
-3
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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}
|
||||
+25
-5
@@ -24,7 +24,7 @@ from typing import Any, Dict, List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Query, Response
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from ..monitor import covers, notify, qrlogin, report, service, upstream
|
||||
from ..monitor import covers, notify, qrlogin, report, service, tagrules, upstream
|
||||
from ..monitor.db import get_session
|
||||
from ..monitor.platforms import PLATFORM_XHS
|
||||
from ..monitor.settings import (
|
||||
@@ -448,20 +448,40 @@ async def list_tags():
|
||||
async def create_tag(payload: TagPayload):
|
||||
async with get_session() as session:
|
||||
try:
|
||||
tag = await service.create_tag(session, payload.name, payload.color)
|
||||
tag = await service.create_tag(
|
||||
session, payload.name, payload.color, payload.keywords
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
return {"id": tag.id, "name": tag.name, "color": tag.color, "note_count": 0}
|
||||
# 新建的规则也立刻对已有作品生效 —— 否则「刚配好关键词,一条都没贴上」。
|
||||
tagged = await tagrules.reapply_tag_rules(session, only_tag_id=tag.id)
|
||||
return {
|
||||
"id": tag.id,
|
||||
"name": tag.name,
|
||||
"color": tag.color,
|
||||
"keywords": tag.keywords,
|
||||
"note_count": tagged,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/tags/{tag_id}")
|
||||
async def update_tag(tag_id: int, payload: TagPayload):
|
||||
async with get_session() as session:
|
||||
try:
|
||||
tag = await service.update_tag(session, tag_id, payload.name, payload.color)
|
||||
tag = await service.update_tag(
|
||||
session, tag_id, payload.name, payload.color, payload.keywords
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
return {"id": tag.id, "name": tag.name, "color": tag.color}
|
||||
# 只重跑**这一条**规则。全都重跑的话,会把用户手动摘掉的别的标签又贴回来。
|
||||
tagged = await tagrules.reapply_tag_rules(session, only_tag_id=tag_id)
|
||||
return {
|
||||
"id": tag.id,
|
||||
"name": tag.name,
|
||||
"color": tag.color,
|
||||
"keywords": tag.keywords,
|
||||
"tagged": tagged,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/tags/{tag_id}")
|
||||
|
||||
@@ -121,10 +121,15 @@ class NoteAliasPayload(BaseModel):
|
||||
|
||||
|
||||
class TagPayload(BaseModel):
|
||||
"""新建/改名一个标签。`color` 是调色板里的名字,不认识的会被回落到默认色。"""
|
||||
"""新建/改名一个标签。`color` 是调色板里的名字,不认识的会被回落到默认色。
|
||||
|
||||
``keywords`` 是自动打标签的规则:逗号分隔,标题里出现其中任意一个就自动贴上这条标签。
|
||||
改成空就等于关掉这条规则(已经贴上去的**不会**被摘掉)。
|
||||
"""
|
||||
|
||||
name: str = Field(min_length=1, max_length=32)
|
||||
color: str = Field(default="", max_length=16)
|
||||
keywords: str = Field(default="", max_length=512)
|
||||
|
||||
|
||||
class NoteTagsPayload(BaseModel):
|
||||
|
||||
@@ -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) == []
|
||||
|
||||
@@ -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,探店"
|
||||
@@ -26,17 +26,24 @@ export function TagSettings() {
|
||||
|
||||
const [draftName, setDraftName] = useState('')
|
||||
const [draftColor, setDraftColor] = useState<string>(TAG_COLOR_CHOICES[0])
|
||||
const [draftKeywords, setDraftKeywords] = useState('')
|
||||
// 正在改名的那一个(标签 id)。
|
||||
const [editingId, setEditingId] = useState<number | null>(null)
|
||||
const [editName, setEditName] = useState('')
|
||||
const [editColor, setEditColor] = useState<string>(TAG_COLOR_CHOICES[0])
|
||||
const [editKeywords, setEditKeywords] = useState('')
|
||||
|
||||
const submit = () => {
|
||||
const name = draftName.trim()
|
||||
if (!name) return
|
||||
createTag.mutate(
|
||||
{ name, color: draftColor },
|
||||
{ onSuccess: () => setDraftName('') },
|
||||
{ name, color: draftColor, keywords: draftKeywords },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setDraftName('')
|
||||
setDraftKeywords('')
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -44,13 +51,14 @@ export function TagSettings() {
|
||||
setEditingId(tag.id)
|
||||
setEditName(tag.name)
|
||||
setEditColor(tag.color)
|
||||
setEditKeywords(tag.keywords)
|
||||
}
|
||||
|
||||
const saveEdit = () => {
|
||||
if (editingId === null) return
|
||||
const name = editName.trim()
|
||||
if (!name) return
|
||||
updateTag.mutate({ id: editingId, name, color: editColor })
|
||||
updateTag.mutate({ id: editingId, name, color: editColor, keywords: editKeywords })
|
||||
setEditingId(null)
|
||||
}
|
||||
|
||||
@@ -71,7 +79,7 @@ export function TagSettings() {
|
||||
|
||||
{tags?.map((tag) =>
|
||||
editingId === tag.id ? (
|
||||
<div key={tag.id} className="flex items-center gap-2">
|
||||
<div key={tag.id} className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={editName}
|
||||
@@ -80,9 +88,20 @@ export function TagSettings() {
|
||||
if (event.key === 'Enter') saveEdit()
|
||||
if (event.key === 'Escape') setEditingId(null)
|
||||
}}
|
||||
className="w-40 rounded border border-cyber-neon-cyan/40 bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none"
|
||||
className="w-32 rounded border border-cyber-neon-cyan/40 bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none"
|
||||
/>
|
||||
<ColorPicker value={editColor} onChange={setEditColor} />
|
||||
<input
|
||||
value={editKeywords}
|
||||
placeholder="关键词,逗号分隔:szgtdzb,探店"
|
||||
title="标题里出现其中任意一个就自动贴上这条标签"
|
||||
onChange={(event) => setEditKeywords(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') saveEdit()
|
||||
if (event.key === 'Escape') setEditingId(null)
|
||||
}}
|
||||
className="w-64 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5" onClick={saveEdit}>
|
||||
<Check className="w-3 h-3 text-cyber-neon-green" />
|
||||
</Button>
|
||||
@@ -103,8 +122,18 @@ export function TagSettings() {
|
||||
>
|
||||
{tag.name}
|
||||
</Badge>
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted">
|
||||
{tag.note_count > 0 ? `用在 ${tag.note_count} 条作品上` : '还没用过'}
|
||||
{/* 规则直接摆出来 —— 「这条标签为什么会自动贴上」得一眼看得出来。 */}
|
||||
{tag.keywords ? (
|
||||
<span className="text-[10px] font-mono text-cyber-text-secondary truncate max-w-[240px]">
|
||||
命中「{tag.keywords}」
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted">
|
||||
没配关键词(只能手动贴)
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] font-mono text-cyber-text-muted flex-shrink-0">
|
||||
{tag.note_count > 0 ? `${tag.note_count} 条作品` : '还没用过'}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button
|
||||
@@ -144,22 +173,40 @@ export function TagSettings() {
|
||||
),
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 pt-2 mt-1 border-t border-cyber-border-subtle">
|
||||
<div className="flex flex-wrap items-center gap-2 pt-2 mt-1 border-t border-cyber-border-subtle">
|
||||
<input
|
||||
value={draftName}
|
||||
placeholder="新标签,比如「重点」"
|
||||
placeholder="新标签,比如「大字报」"
|
||||
onChange={(event) => setDraftName(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') submit()
|
||||
}}
|
||||
className="w-40 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
className="w-32 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<ColorPicker value={draftColor} onChange={setDraftColor} />
|
||||
<input
|
||||
value={draftKeywords}
|
||||
placeholder="关键词,逗号分隔:szgtdzb,探店"
|
||||
title="标题里出现其中任意一个就自动贴上这条标签"
|
||||
onChange={(event) => setDraftKeywords(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') submit()
|
||||
}}
|
||||
className="w-64 rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40"
|
||||
/>
|
||||
<Button size="sm" disabled={!draftName.trim() || createTag.isPending} onClick={submit}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
添加
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[10px] font-mono text-cyber-text-muted leading-relaxed">
|
||||
配了关键词的标签会
|
||||
<span className="text-cyber-text-secondary"> 自动贴上 </span>
|
||||
:作品标题里出现其中任意一个就贴,命中几条规则就贴几个标签。匹配的是标题里的子串、
|
||||
不分大小写,所以关键词别定得太宽(只写「苏州」的话几乎每条都会被贴上)。
|
||||
<span className="text-cyber-text-secondary"> 只贴不摘 </span>
|
||||
—— 你手动摘掉的,下一轮采集不会又长回来。
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
|
||||
@@ -148,15 +148,16 @@ function useTagMutation<TArgs>(
|
||||
|
||||
export function useCreateTag() {
|
||||
return useTagMutation(
|
||||
({ name, color }: { name: string; color: string }) => monitorApi.createTag(name, color),
|
||||
({ name, color, keywords }: { name: string; color: string; keywords: string }) =>
|
||||
monitorApi.createTag(name, color, keywords),
|
||||
'标签已创建',
|
||||
)
|
||||
}
|
||||
|
||||
export function useUpdateTag() {
|
||||
return useTagMutation(
|
||||
({ id, name, color }: { id: number; name: string; color: string }) =>
|
||||
monitorApi.updateTag(id, name, color),
|
||||
({ id, name, color, keywords }: { id: number; name: string; color: string; keywords: string }) =>
|
||||
monitorApi.updateTag(id, name, color, keywords),
|
||||
'标签已保存',
|
||||
)
|
||||
}
|
||||
|
||||
@@ -303,10 +303,10 @@ export const monitorApi = {
|
||||
|
||||
/** 标签词表(设置页维护),带各自被用在多少条作品上。 */
|
||||
listTags: () => api.get<{ tags: MonitorTag[] }>('/monitor/tags'),
|
||||
createTag: (name: string, color = '') =>
|
||||
api.post<MonitorTag>('/monitor/tags', { name, color }),
|
||||
updateTag: (id: number, name: string, color = '') =>
|
||||
api.put<MonitorTag>(`/monitor/tags/${id}`, { name, color }),
|
||||
createTag: (name: string, color = '', keywords = '') =>
|
||||
api.post<MonitorTag>('/monitor/tags', { name, color, keywords }),
|
||||
updateTag: (id: number, name: string, color = '', keywords = '') =>
|
||||
api.put<MonitorTag>(`/monitor/tags/${id}`, { name, color, keywords }),
|
||||
deleteTag: (id: number) => api.delete<{ removed: number }>(`/monitor/tags/${id}`),
|
||||
/** 把一条作品的标签**整体替换**成这一组。空数组 = 全摘掉。 */
|
||||
setNoteTags: (noteId: string, tagIds: number[], platform?: string) =>
|
||||
|
||||
@@ -188,6 +188,13 @@ export interface TagRef {
|
||||
/** 词表里的标签,额外带一个「被用在多少条作品上」—— 删之前要能看清代价。 */
|
||||
export interface MonitorTag extends TagRef {
|
||||
note_count: number
|
||||
/**
|
||||
* 自动打标签的规则:**逗号分隔的关键词**。作品标题里出现其中任意一个,这条标签就
|
||||
* 自动贴上;命中几条规则就贴几个标签。空串 = 这条标签只能手动贴。
|
||||
*
|
||||
* 关键词和标签名是两回事 —— 标签叫「大字报」,关键词可能是 `szgtdzb`。
|
||||
*/
|
||||
keywords: string
|
||||
}
|
||||
|
||||
export interface MetricPoint {
|
||||
|
||||
Reference in New Issue
Block a user