From 74fc19a8e32b373c2cf1849e57ee9cb643169e49 Mon Sep 17 00:00:00 2001 From: butubb Date: Thu, 22 Oct 2026 17:18:25 +0800 Subject: [PATCH] =?UTF-8?q?fix(tags):=20=E8=AF=9D=E9=A2=98=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E8=A2=AB=20desc=20=E6=88=AA=E6=96=AD=E5=AF=BC?= =?UTF-8?q?=E8=87=B4=E6=BC=8F=E8=B4=B4=E6=A0=87=E7=AD=BE=20=E2=80=94?= =?UTF-8?q?=E2=80=94=20=E6=94=B9=E7=94=A8=20text=5Fextra?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户反馈:一条作品明明有 #szgtgg 这个话题,却没贴上「广告」标签。 原因不是规则:**抖音返回的 desc 会在话题列表中途截断**,尾部是 「……版本过低,升级后可展示全部信息」。实测那条作品: desc 尾部:… #噶痔疮 #……版本过低,升级后可展示全部信息 text_extra:痔疮 / 痔疮术后 / 苏州肛肠科 / 噶痔疮 / szgtgg ← 完整 而标签规则只匹配 title(= desc),后面的 #szgtgg 根本不在里面。 改动: * `normalize_aweme` 从 `text_extra` 提取完整话题列表,落成 `#a #b` 的字符串; * `monitor_note` 新增 `hashtags` 列(自动补列),ingest 写入; * 自动打标签改匹配「**标题 + 话题列表**」; * `reapply_tag_rules`(编辑标签时重跑)同样带上 hashtags —— 否则手动重跑也修不回来。 线上已有数据需要等下一轮采集把 hashtags 补上,再跑一次 reapply 才能补齐历史标签。 测试:normalize 从 text_extra 取话题;标题截断但话题在 hashtags 里也能贴上。 --- api/monitor/douyin_api.py | 11 +++++++++++ api/monitor/ingest.py | 10 +++++++++- api/monitor/models.py | 3 +++ api/monitor/tagrules.py | 27 +++++++++++++++++++-------- tests/test_douyin_api.py | 22 ++++++++++++++++++++++ tests/test_monitor_ingest.py | 25 +++++++++++++++++++++++++ 6 files changed, 89 insertions(+), 9 deletions(-) diff --git a/api/monitor/douyin_api.py b/api/monitor/douyin_api.py index bbbcce5..f20f0e3 100644 --- a/api/monitor/douyin_api.py +++ b/api/monitor/douyin_api.py @@ -422,12 +422,23 @@ def normalize_aweme(aweme: Dict[str, Any]) -> Dict[str, Any]: uid = str(author.get("uid") or "") nickname = author.get("nickname") or "" + # 话题列表。**`desc` 会被抖音截断** —— 尾部是「……版本过低,升级后可展示全部信息」, + # 后面的话题根本不在 desc 里。标签规则只匹配标题的话,那些话题永远命中不了 + # (实测:一条作品的 desc 截断在「#噶痔疮 #…」,而完整话题列表里还有 #szgtgg)。 + # `text_extra` 是结构化的,不受截断影响。 + hashtags = " ".join( + f"#{item.get('hashtag_name')}" + for item in (aweme.get("text_extra") or []) + if isinstance(item, dict) and item.get("hashtag_name") + ) + return { "aweme_id": aweme_id, "aweme_type": str(aweme.get("aweme_type") or ""), # store 那边 title 取的是 desc。 "title": aweme.get("desc") or "", "desc": aweme.get("desc") or "", + "hashtags": hashtags, # **秒**。adapters.time_scale 会把它换成毫秒,和 store 写出来的形态一致。 "create_time": _as_int(aweme.get("create_time")), "creator_hash": anonymize_user_id(uid or author.get("sec_uid") or ""), diff --git a/api/monitor/ingest.py b/api/monitor/ingest.py index d92e866..0b52e0f 100644 --- a/api/monitor/ingest.py +++ b/api/monitor/ingest.py @@ -408,6 +408,10 @@ async def _ingest_notes( ) title = (adapter.note_field(record, "title") or "")[:500] + hashtags = (adapter.note_field(record, "hashtags") or "")[:2000] + # 标签规则匹配的是**标题 + 话题列表**。desc 会被抖音截断,后半段话题只在 + # text_extra 里 —— 只看标题会漏掉它们。 + tag_text = f"{title} {hashtags}".strip() cover = adapter.cover(record) fresh_name = adapter.note_field(record, "creator_name") or "" if fresh_name: @@ -416,11 +420,12 @@ async def _ingest_notes( if note is None: # **只在这一支里**收,也就是作品第一次入库时。自动打标签只贴不摘,所以 # 每轮都跑的话,用户手动摘掉的标签下一轮就会长回来。 - first_seen_notes.append((note_id, title)) + first_seen_notes.append((note_id, tag_text)) note = MonitorNote( task_id=run.task_id, note_id=note_id, title=title, + hashtags=hashtags, note_url=adapter.note_field(record, "note_url") or "", cover=cover, creator_hash=adapter.note_field(record, "creator_hash") or "", @@ -449,6 +454,9 @@ async def _ingest_notes( # Only refresh descriptive fields; seen-tracking is updated below. if title: note.title = title + # 话题列表可能上一轮还没采到(desc 截断 / 老数据),补上。 + if hashtags: + note.hashtags = hashtags # 封面地址**带签名、会过期**,所以每轮都用最新的覆盖它。原先只在首次入库 # 时写一次,结果旧作品的封面地址烂在库里 —— 隔天开始全是 403,而且再怎么 # 重跑也修不回来。落盘那份由 covers.cache_pending 负责(网络操作不在本模块)。 diff --git a/api/monitor/models.py b/api/monitor/models.py index c244071..b1d7767 100644 --- a/api/monitor/models.py +++ b/api/monitor/models.py @@ -224,6 +224,9 @@ class MonitorNote(MonitorBase): ) note_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True) title: Mapped[str] = mapped_column(Text, nullable=False, default="") + # 话题列表(`#a #b`)。**不能只靠 title 打标签**:抖音的 desc 会被截断,后半段 + # 话题不在里面;`text_extra` 才是完整的那份。小红书暂不提供,存空串。 + hashtags: Mapped[str] = mapped_column(Text, nullable=False, default="") note_url: Mapped[str] = mapped_column(Text, nullable=False, default="") cover: Mapped[str] = mapped_column(Text, nullable=False, default="") # 创作者匿名哈希。爬虫刻意不落原始 user_id(见 tools/user_hash.py), diff --git a/api/monitor/tagrules.py b/api/monitor/tagrules.py index 6988b1e..22289c6 100644 --- a/api/monitor/tagrules.py +++ b/api/monitor/tagrules.py @@ -45,11 +45,14 @@ def split_keywords(raw: str) -> List[str]: def tags_matching(title: str, tags: Sequence[MonitorTag]) -> List[int]: - """一个标题命中了哪些标签的规则。**纯函数**,所以能单独测。 + """一段文本命中了哪些标签的规则。**纯函数**,所以能单独测。 - 匹配的是**标题里的子串**(不分大小写),不是只匹配 ``#话题#`` —— 话题本来就长在标题 - 里,而像 ``szgtdzb`` 这种代号未必包在井号里。一条标题可以命中**多条**规则,命中几条 - 就贴几个标签。 + 传进来的 ``title`` 实际是**标题 + 话题列表**(见 ``ingest`` 的 ``tag_text``)—— + 抖音的 ``desc`` 会在话题列表中途截断,后半段只能在 ``text_extra`` 里拿到,只看标题 + 会漏贴。 + + 匹配的是**子串**(不分大小写),不是只匹配 ``#话题#`` —— 话题本来就长在标题里,而像 + ``szgtdzb`` 这种代号未必包在井号里。一段文本可以命中**多条**规则,命中几条就贴几个标签。 代价是关键词定得太宽会误伤(把「苏州」设成关键词,几乎每条都会被贴上),设置页里 写了这句提醒。 @@ -132,12 +135,20 @@ async def reapply_tag_rules( """ rows = ( await session.execute( - select(MonitorTask.platform, MonitorNote.note_id, MonitorNote.title).join( - MonitorTask, MonitorTask.id == MonitorNote.task_id - ) + select( + MonitorTask.platform, + MonitorNote.note_id, + MonitorNote.title, + MonitorNote.hashtags, + ).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) + # 匹配的是**标题 + 话题列表**:抖音的 desc 会被截断,后半段话题只在 hashtags 里。 + return await apply_tag_rules( + session, + [(r[0], r[1], f"{r[2] or ''} {r[3] or ''}".strip()) for r in rows], + only_tag_id, + ) def keywords_by_tag(tags: Sequence[MonitorTag]) -> Dict[int, List[str]]: diff --git a/tests/test_douyin_api.py b/tests/test_douyin_api.py index a67be0c..50ad46e 100644 --- a/tests/test_douyin_api.py +++ b/tests/test_douyin_api.py @@ -106,6 +106,28 @@ class TestNormalizeAweme: assert record["liked_count"] == "3" assert record["collected_count"] == "2" + def test_hashtags_come_from_text_extra_not_the_truncated_desc(self): + """`desc` 会在话题列表中途被截断,后半段话题只在 `text_extra` 里。 + + 实测那条:desc 断在「#噶痔疮 #……版本过低,升级后可展示全部信息」,而完整 + 话题列表里还有 #szgtgg —— 只看 desc 的话,后面的标签规则永远命中不了。 + """ + record = douyin_api.normalize_aweme( + { + "aweme_id": "1", + "desc": "经历过痔疮术后才懂…… #痔疮 #痔疮术后 #噶痔疮 " + "#……版本过低,升级后可展示全部信息", + "text_extra": [ + {"hashtag_name": "痔疮", "type": 1}, + {"hashtag_name": "噶痔疮", "type": 1}, + {"hashtag_name": "szgtgg", "type": 1}, + {"type": 0}, + ], + } + ) + + assert record["hashtags"] == "#痔疮 #噶痔疮 #szgtgg" + def test_missing_fields_do_not_crash(self): record = douyin_api.normalize_aweme({"aweme_id": "1"}) diff --git a/tests/test_monitor_ingest.py b/tests/test_monitor_ingest.py index 7d17bd2..8f1d498 100644 --- a/tests/test_monitor_ingest.py +++ b/tests/test_monitor_ingest.py @@ -1189,6 +1189,31 @@ class TestAutoTaggingOnIngest: assert await self._note_tags(db) == [("n1", "大字报")] + @pytest.mark.asyncio + async def test_a_tag_only_present_in_hashtags_is_matched(self, db, tmp_path): + """标题被截断、话题在后半段 —— 只在 hashtags 里,也得贴上。 + + 抖音的 desc 断在「……版本过低,升级后可展示全部信息」,后面的话题不在标题里。 + """ + await self._seed_rule(db, "szgtgg") + task = await _make_task(db) + run = await _make_run(db, task, started_at=1) + _write_run_dir( + tmp_path, + [ + _note( + "n1", + title="经历过痔疮术后才懂 #痔疮 #痔疮术后 #……版本过低,升级后可展示全部信息", + hashtags="#痔疮 #痔疮术后 #szgtgg", + ) + ], + 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")