feat(matrix): 「第一条视频」改成主页最新一条,即使不在监控目标里
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

之前取的是本任务已有作品里**最早**的那条 —— 既不是主页上看到的第一条,
也只看得到被监控的那批链接。现在采集时对每个博主额外问一次作品列表
(倒序,只要第一条),把它的发布时间落进账号快照;矩阵优先用它,没问到
时退回库里最新的一条作品。

- 作品模式:每个博主每轮一次请求,同轮内去重;连接超时重试一次。
- 博主模式:本来就在拉作品列表,直接用其中的最新时间。
- 新列 monitor_creator_stat.latest_published_at(毫秒,可空)。
This commit is contained in:
2026-11-02 10:31:45 +08:00
parent c06848ae98
commit 34a962f75a
7 changed files with 180 additions and 26 deletions
+66 -1
View File
@@ -32,6 +32,8 @@
import asyncio import asyncio
import json import json
from datetime import datetime from datetime import datetime
import httpx
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence from typing import Any, Dict, Iterable, List, Optional, Sequence
@@ -207,9 +209,36 @@ async def _collect_batch(
videos = [] videos = []
# 作品详情里带着作者的粉丝/总获赞。作品模式**不会**单独问博主资料 —— # 作品详情里带着作者的粉丝/总获赞。作品模式**不会**单独问博主资料 ——
# 不从这里收一份,这类任务(超级编导导入的都在这里)的博主粉丝数永远是空的。 # 不从这里收一份,这类任务(超级编导导入的都在这里)的博主粉丝数永远是空的。
#
# 顺带问一次这个博主**主页上最新的视频**:它可能根本不在监控目标里(自然发的、
# 别的活动发的),但「他最近还发不发」只能从主页看。同一轮里一个博主只问一次。
latest_by_creator: Dict[str, Optional[int]] = {}
for video in videos: for video in videos:
profile = _profile_from_author(video) profile = _profile_from_author(video)
if profile is not None: creator_id = str(video.get("creator_id") or "")
latest: Optional[int] = None
if creator_id:
if creator_id not in latest_by_creator:
latest_by_creator[creator_id] = await _latest_video_at(
creator_id, cookie, identity
)
latest = latest_by_creator[creator_id]
if profile is None:
if latest is None:
continue
# 账号指标一个都没拿到,但知道了最新视频时间 —— 也值得落一条快照,
# 否则矩阵上这个号的「最新视频」永远是空的。
profile = {
"creator_hash": str(video.get("creator_hash") or ""),
"creator_id": creator_id,
"nickname": str(video.get("nickname") or ""),
"fans": None,
"total_favorited": None,
"works": None,
"following": None,
}
profile["latest_published_at"] = latest
profiles.append(profile) profiles.append(profile)
else: else:
videos = await _creator_works( videos = await _creator_works(
@@ -286,6 +315,37 @@ def _profile_from_author(video: Dict[str, Any]) -> Optional[Dict[str, Any]]:
} }
async def _latest_video_at(
sec_user_id: str, cookie: str, identity: Any = None
) -> Optional[int]:
"""博主主页第一条(最新)视频的发布时间(毫秒);拿不到返回 None。
作品列表按发布时间倒序,只要最新那条,所以一次请求就够,不翻页。连接超时重试一次
(容器到抖音的 TCP 连接偶尔会卡);其它错误直接放弃 —— 这是附加信息,不值得为一轮
采集增加更多失败面。
"""
if not sec_user_id:
return None
try:
videos = await douyin_api.author_videos(
sec_user_id, count=1, cookie=cookie, identity=identity
)
except httpx.TransportError:
await asyncio.sleep(1.0)
try:
videos = await douyin_api.author_videos(
sec_user_id, count=1, cookie=cookie, identity=identity
)
except Exception: # noqa: BLE001 - 附加信息,失败就留空
return None
except Exception: # noqa: BLE001
return None
stamps = [adapters.DY.to_ms(video.get("create_time")) for video in videos]
stamps = [stamp for stamp in stamps if stamp]
return max(stamps) if stamps else None
async def _creator_profile( async def _creator_profile(
sec_user_id: str, sec_user_id: str,
videos: Sequence[Dict[str, Any]], videos: Sequence[Dict[str, Any]],
@@ -311,6 +371,11 @@ async def _creator_profile(
if videos: if videos:
profile["creator_hash"] = videos[0].get("creator_hash") or profile["creator_hash"] profile["creator_hash"] = videos[0].get("creator_hash") or profile["creator_hash"]
# 作品列表是倒序的,最早取到的这 N 条里最新的那条就是主页第一条。
stamps = [adapters.DY.to_ms(video.get("create_time")) for video in videos]
stamps = [stamp for stamp in stamps if stamp]
if stamps:
profile["latest_published_at"] = max(stamps)
if not profile.get("creator_hash"): if not profile.get("creator_hash"):
# 哈希都算不出来的快照没人能查到,落下去只是垃圾。 # 哈希都算不出来的快照没人能查到,落下去只是垃圾。
errors.append(f"博主 {sec_user_id} 的资料里没有可用的身份标识,跳过账号指标") errors.append(f"博主 {sec_user_id} 的资料里没有可用的身份标识,跳过账号指标")
+1
View File
@@ -718,6 +718,7 @@ async def _ingest_creator_stats(
total_favorited=parse_count(record.get("total_favorited")), total_favorited=parse_count(record.get("total_favorited")),
works_count=parse_count(record.get("works")), works_count=parse_count(record.get("works")),
following=parse_count(record.get("following")), following=parse_count(record.get("following")),
latest_published_at=record.get("latest_published_at"),
captured_at=now, captured_at=now,
) )
) )
+4
View File
@@ -411,6 +411,10 @@ class MonitorCreatorStat(MonitorBase):
total_favorited: Mapped[Optional[int]] = mapped_column(BigInteger) total_favorited: Mapped[Optional[int]] = mapped_column(BigInteger)
works_count: Mapped[Optional[int]] = mapped_column(BigInteger) works_count: Mapped[Optional[int]] = mapped_column(BigInteger)
following: Mapped[Optional[int]] = mapped_column(BigInteger) following: Mapped[Optional[int]] = mapped_column(BigInteger)
# 这个博主**主页上最新一条视频**的发布时间(毫秒)。作品列表是按时间倒序的,
# 「第一条」就是最新那条 —— 它可能根本不在监控的目标里(自然发的、别的活动发的),
# 但能回答「他最近还发不发」。拿不到(接口挡了/超时)就留 None。
latest_published_at: Mapped[Optional[int]] = mapped_column(BigInteger)
captured_at: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True) captured_at: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
+31 -8
View File
@@ -1580,7 +1580,7 @@ async def daily_tag_matrix(
{"dates": ["2026-10-21", ...], # 新到旧 {"dates": ["2026-10-21", ...], # 新到旧
"creators": [{"hash": ..., "name": ..., "fans": 1200, "creators": [{"hash": ..., "name": ..., "fans": 1200,
"total_favorited": 83000, "total_favorited": 83000,
"first_published_at": 1780000000000}], # 按昵称排序 "latest_published_at": 1780000000000}], # 按昵称排序
"cells": {"2026-10-21": {"<hash>": { "cells": {"2026-10-21": {"<hash>": {
"count": 2, "tags": ["大字报", "养号"], "count": 2, "tags": ["大字报", "养号"],
"likes": 120, "comments": 8, "collected": 30, "shares": 4, "likes": 120, "comments": 8, "collected": 30, "shares": 4,
@@ -1704,6 +1704,7 @@ async def daily_tag_matrix(
MonitorCreatorStat.captured_at, MonitorCreatorStat.captured_at,
MonitorCreatorStat.fans, MonitorCreatorStat.fans,
MonitorCreatorStat.total_favorited, MonitorCreatorStat.total_favorited,
MonitorCreatorStat.latest_published_at,
).where( ).where(
MonitorCreatorStat.task_id.in_(task_ids), MonitorCreatorStat.task_id.in_(task_ids),
MonitorCreatorStat.creator_hash != "", MonitorCreatorStat.creator_hash != "",
@@ -1716,6 +1717,8 @@ async def daily_tag_matrix(
latest_fans: Dict[str, tuple] = {} latest_fans: Dict[str, tuple] = {}
# 主页上的「获赞总数」,和粉丝数一样取最近一次读到的值。 # 主页上的「获赞总数」,和粉丝数一样取最近一次读到的值。
latest_likes: Dict[str, tuple] = {} latest_likes: Dict[str, tuple] = {}
# 主页第一条(最新)视频的发布时间。采集时问过主页,这条可能不在监控目标里。
latest_video: Dict[str, tuple] = {}
for stat in stat_rows: for stat in stat_rows:
if stat.fans is not None: if stat.fans is not None:
current_fans = latest_fans.get(stat.creator_hash) current_fans = latest_fans.get(stat.creator_hash)
@@ -1728,6 +1731,13 @@ async def daily_tag_matrix(
stat.total_favorited, stat.total_favorited,
stat.captured_at, stat.captured_at,
) )
if stat.latest_published_at is not None:
current_video = latest_video.get(stat.creator_hash)
if current_video is None or stat.captured_at > current_video[1]:
latest_video[stat.creator_hash] = (
stat.latest_published_at,
stat.captured_at,
)
# **空昵称不算名字。** 资料接口偶尔会回一个空对象(昵称、sec_uid、粉丝、 # **空昵称不算名字。** 资料接口偶尔会回一个空对象(昵称、sec_uid、粉丝、
# 作品数全空),如果把这一轮当最新快照,就会用一个空字符串把之前的好名字 # 作品数全空),如果把这一轮当最新快照,就会用一个空字符串把之前的好名字
# 盖掉,界面上变成「未知(hash)」。实测线上有两个号就是这么丢的名字。 # 盖掉,界面上变成「未知(hash)」。实测线上有两个号就是这么丢的名字。
@@ -1814,11 +1824,11 @@ async def daily_tag_matrix(
# 作品是按发布时间倒序取回来的,明细按时间正序更好读(1、2、3…)。 # 作品是按发布时间倒序取回来的,明细按时间正序更好读(1、2、3…)。
bucket["details"].reverse() bucket["details"].reverse()
# 博主的**第一条视频**发布时间。查全库,不受上面 days 窗口的限制 —— 一个号最早的 # 兜底:库里这个博主**已有作品里最新的**发布时间。首选是采集时从主页拿到的
# 作品很可能在窗口之外,而「这个号做了多久」看的就是它。 # 「第一条视频」(它可能根本不在监控目标里),主页那次没问到时才用它。
first_rows = ( tracked_rows = (
await session.execute( await session.execute(
select(MonitorNote.creator_hash, func.min(MonitorNote.published_at)) select(MonitorNote.creator_hash, func.max(MonitorNote.published_at))
.where( .where(
MonitorNote.task_id.in_(task_ids), MonitorNote.task_id.in_(task_ids),
MonitorNote.published_at.is_not(None), MonitorNote.published_at.is_not(None),
@@ -1827,8 +1837,10 @@ async def daily_tag_matrix(
.group_by(MonitorNote.creator_hash) .group_by(MonitorNote.creator_hash)
) )
).all() ).all()
first_published: Dict[str, int] = { latest_tracked: Dict[str, int] = {
creator_hash: first_at for creator_hash, first_at in first_rows if first_at creator_hash: latest_at
for creator_hash, latest_at in tracked_rows
if latest_at
} }
creators = [ creators = [
@@ -1839,7 +1851,18 @@ async def daily_tag_matrix(
# 前端据此不画那个数字,而不是显示 0。 # 前端据此不画那个数字,而不是显示 0。
"fans": latest_fans.get(hash_, (None, 0))[0], "fans": latest_fans.get(hash_, (None, 0))[0],
"total_favorited": latest_likes.get(hash_, (None, 0))[0], "total_favorited": latest_likes.get(hash_, (None, 0))[0],
"first_published_at": first_published.get(hash_), # 两个来源取较新的一个:主页数据可能比库里的作品旧(快照是上一轮的)。
"latest_published_at": max(
[
value
for value in (
latest_video.get(hash_, (None, 0))[0],
latest_tracked.get(hash_),
)
if value
],
default=None,
),
} }
for hash_, name in known.items() for hash_, name in known.items()
] ]
+5 -4
View File
@@ -308,7 +308,7 @@
<div class="wrap" id="wrap"></div> <div class="wrap" id="wrap"></div>
<div id="tip"></div> <div id="tip"></div>
<div class="legend"> <div class="legend">
<span><b>名字左边</b> = 粉丝数 / 主页总获赞 / 第一条视频发布日期</span> <span><b>名字左边</b> = 粉丝数 / 主页总获赞 / 主页最新视频发布日期(可能不在监控目标里)</span>
<span><b>赞 / 评</b> = 当天这些作品的点赞 / 评论</span> <span><b>赞 / 评</b> = 当天这些作品的点赞 / 评论</span>
<span><b>左下角数字</b> = 当天作品条数</span> <span><b>左下角数字</b> = 当天作品条数</span>
<span><b>悬停后点标题</b> = 在抖音打开这条作品</span> <span><b>悬停后点标题</b> = 在抖音打开这条作品</span>
@@ -612,7 +612,7 @@
const fansKnown = creator.fans !== null && creator.fans !== undefined; const fansKnown = creator.fans !== null && creator.fans !== undefined;
const likesKnown = const likesKnown =
creator.total_favorited !== null && creator.total_favorited !== undefined; creator.total_favorited !== null && creator.total_favorited !== undefined;
const firstAt = creator.first_published_at; const firstAt = creator.latest_published_at;
const titleParts = []; const titleParts = [];
if (fansKnown) { if (fansKnown) {
const fans = document.createElement('span'); const fans = document.createElement('span');
@@ -636,9 +636,10 @@
const first = document.createElement('span'); const first = document.createElement('span');
first.className = 'first'; first.className = 'first';
first.textContent = parts.date; first.textContent = parts.date;
first.title = '第一条视频发布于 ' + parts.date + ' ' + parts.time; first.title =
'主页第一条(最新)视频发布于 ' + parts.date + ' ' + parts.time;
th.appendChild(first); th.appendChild(first);
titleParts.push('第一条视频 ' + parts.date); titleParts.push('最新视频 ' + parts.date);
} }
const nameSpan = document.createElement('span'); const nameSpan = document.createElement('span');
nameSpan.textContent = label; nameSpan.textContent = label;
+46 -5
View File
@@ -41,6 +41,12 @@ def fake_profile(monkeypatch):
monkeypatch.setattr(douyin_api, "author_profile", _profile_call) monkeypatch.setattr(douyin_api, "author_profile", _profile_call)
# 作品模式会为了「主页最新视频的时间」问一次作品列表;不挡住就会真连抖音。
async def _videos_call(sec_user_id, count=20, *, cookie="", identity=None):
return []
monkeypatch.setattr(douyin_api, "author_videos", _videos_call)
def _video(aweme_id: str, likes: str = "1") -> dict: def _video(aweme_id: str, likes: str = "1") -> dict:
return { return {
@@ -172,13 +178,18 @@ class TestNoteMode:
「粘贴作品链接的监控」今天本来是能用的,别让它因为这一处走错而废掉。 「粘贴作品链接的监控」今天本来是能用的,别让它因为这一处走错而废掉。
""" """
async def must_not_be_called(*args, **kwargs): async def only_by_creator_id(sec_user_id, count=20, *, cookie="", identity=None):
raise AssertionError("作品模式不该去拉博主的作品列表") # 可以为了「主页最新视频」问一次作品列表,但**只能用详情里的 sec_uid 问**,
# 不能拿作品目标 id 去当 sec_uid —— 那必然失败,而且报错很难看懂。
assert sec_user_id == "MS4wLjABAAAAtestsecuid"
return []
async def fake_detail(aweme_id, *, cookie="", identity=None): async def fake_detail(aweme_id, *, cookie="", identity=None):
return _video(aweme_id) record = _video(aweme_id)
record["creator_id"] = "MS4wLjABAAAAtestsecuid"
return record
monkeypatch.setattr(douyin_api, "author_videos", must_not_be_called) monkeypatch.setattr(douyin_api, "author_videos", only_by_creator_id)
monkeypatch.setattr(douyin_api, "video_detail", fake_detail) monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
result = await _collect( result = await _collect(
@@ -252,6 +263,33 @@ class TestNoteMode:
# 详情里没有作品总数,留 None 而不是 0。 # 详情里没有作品总数,留 None 而不是 0。
assert profiles[0]["works"] is None assert profiles[0]["works"] is None
@pytest.mark.asyncio
async def test_the_latest_video_time_comes_from_the_profile(self, monkeypatch, tmp_path):
"""主页第一条视频可能不在监控目标里 —— 单独问一次,用它的发布时间。"""
async def fake_detail(aweme_id, *, cookie="", identity=None):
record = _video(aweme_id)
record.update(
{"creator_id": "MS4wLjABAAAAtestsecuid", "creator_fans": 10}
)
return record
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
assert sec_user_id == "MS4wLjABAAAAtestsecuid"
return [{"create_time": 1793000000}]
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
await _collect(
tmp_path, mode="note", want_comments=False, targets=[_Target("111")]
)
profiles = _read(
list((tmp_path / "douyin" / "jsonl").glob("*_profile_*.jsonl"))[0]
)
assert profiles[0]["latest_published_at"] == 1793000000 * 1000
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_no_stats_means_no_profile_row(self, monkeypatch, tmp_path): async def test_no_stats_means_no_profile_row(self, monkeypatch, tmp_path):
"""精简版 author(字段全缺)不该写一条全 NULL 的快照。""" """精简版 author(字段全缺)不该写一条全 NULL 的快照。"""
@@ -382,7 +420,10 @@ class TestCreatorProfile:
await _collect(tmp_path, want_comments=False) await _collect(tmp_path, want_comments=False)
assert self._profiles(tmp_path) == [_profile()] profile = self._profiles(tmp_path)[0]
# 作品列表里的最新一条也带出来了(秒 -> 毫秒)。
assert profile.pop("latest_published_at") == 1790574515 * 1000
assert profile == _profile()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_the_profile_is_keyed_by_the_same_hash_as_the_works( async def test_the_profile_is_keyed_by_the_same_hash_as_the_works(
+26 -7
View File
@@ -263,6 +263,7 @@ async def _stat(
run_id: int = 1, run_id: int = 1,
fans: int | None = None, fans: int | None = None,
total_favorited: int | None = None, total_favorited: int | None = None,
latest_published_at: int | None = None,
) -> None: ) -> None:
async with monitor_db.get_session() as session: async with monitor_db.get_session() as session:
session.add( session.add(
@@ -275,6 +276,7 @@ async def _stat(
works_count=0, works_count=0,
fans=fans, fans=fans,
total_favorited=total_favorited, total_favorited=total_favorited,
latest_published_at=latest_published_at,
captured_at=captured_at or get_current_timestamp(), captured_at=captured_at or get_current_timestamp(),
) )
) )
@@ -340,29 +342,46 @@ async def test_the_creator_row_carries_the_total_likes_from_the_profile(db):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_the_first_video_date_comes_from_the_whole_table(db): async def test_the_latest_video_date_comes_from_the_profile(db):
"""第一条视频可能远在日期窗口之外 —— 要查全库,不能只看这 7 天。""" """主页第一条视频可能根本不在监控目标里 —— 采集时单独问过,就用它。"""
task_id = await _task() task_id = await _task()
now = get_current_timestamp() - 1000 now = get_current_timestamp() - 1000
first = now - 400 * DAY_MS tracked = now - 3 * DAY_MS
await _note(task_id, "old", "博主A", first) profile_latest = now - 60_000
await _note(task_id, "n1", "博主A", tracked)
await _stat(
task_id, "hash-a", "博主A", latest_published_at=profile_latest
)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["creators"][0]["latest_published_at"] == profile_latest
@pytest.mark.asyncio
async def test_it_falls_back_to_the_newest_tracked_note(db):
"""主页那次没问到(接口挡了/超时)时,退到库里最新的一条作品。"""
task_id = await _task()
now = get_current_timestamp() - 1000
await _note(task_id, "old", "博主A", now - 400 * DAY_MS)
await _note(task_id, "new", "博主A", now) await _note(task_id, "new", "博主A", now)
async with monitor_db.get_session() as session: async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7) data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["creators"][0]["first_published_at"] == first assert data["creators"][0]["latest_published_at"] == now
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_a_creator_without_works_has_no_first_video_date(db): async def test_a_creator_without_works_has_no_latest_video_date(db):
task_id = await _task() task_id = await _task()
await _stat(task_id, "hash-a", "博主A", fans=10) await _stat(task_id, "hash-a", "博主A", fans=10)
async with monitor_db.get_session() as session: async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7) data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["creators"][0]["first_published_at"] is None assert data["creators"][0]["latest_published_at"] is None
@pytest.mark.asyncio @pytest.mark.asyncio