Peach: Local-first video metadata scraper and media manager.
fix(follow): rule34xxx 缺时长的视频在常规检查里继续补
longmeidao9013ab924cb9
diff --git a/scripts/backfill_rule34_details.py b/scripts/backfill_rule34_details.pyindex 7e4ffa1e3..5e13bda91 100644--- a/scripts/backfill_rule34_details.py+++ b/scripts/backfill_rule34_details.py@@ -15,6 +15,10 @@ posts DAPI 只回扁平标签和最后修改时间,三样东西要另外问:默认 dry-run,只写复核 CSV。`--apply` 必须同时给 `--backup`,与本仓库其它真实写入脚本一致。`--resume` 跳过同一份 CSV 里已经写入的条目,中断后用原命令加它接着跑。++`--duration-only` 只补 mp4 缺的时长:只挑 `duration` 为空的 mp4 条目,不问帖子页,+只读原文件头,也只写 `duration`。时长在视频 CDN 上,不受帖子页每秒一次的限流牵连,+授权只覆盖时长时用它,别的列一格不动。"""from __future__ import annotations@@ -64,6 +68,8 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--delay", type=float, default=DEFAULT_DELAY)parser.add_argument("--resume", action="store_true",help="跳过 --out 里已经写入的条目,接着上一趟跑")+ parser.add_argument("--duration-only", action="store_true",+ help="只补 mp4 缺的时长:不问帖子页,只读原文件头,只写 duration")return parser@@ -74,20 +80,23 @@ def written_ids(path: Path) -> set[int]:def pending_rows(connection: sqlite3.Connection, limit: int,- done: set[int] = frozenset()) -> list[dict]:+ done: set[int] = frozenset(), *, duration_only: bool = False) -> list[dict]:"""待补条目:rule34xxx 来源的全部条目,扣掉上一趟已经写入的。上传时间错没错,不问帖子页就看不出来——被改过的帖子 `change` 晚于上传,没改过的两者逐秒相同,账本里长得一样。所以每条都要问一遍,续跑靠 CSV 而不是账本里的值。+ 只补时长时缺不缺看账本就知道,只挑 `duration` 为空的 mp4。"""rows = []query = ("SELECT i.id, i.external_id, i.media_url, i.published_at, i.duration,"" i.metadata_json FROM follow_item i JOIN follow_source s ON s.id=i.source_id"- " WHERE s.provider='rule34xxx' ORDER BY i.id"+ " WHERE s.provider='rule34xxx'"+ + (" AND i.duration IS NULL" if duration_only else "")+ + " ORDER BY i.id")for row in connection.execute(query):- if row["id"] in done:+ if row["id"] in done or (duration_only and not _is_mp4(row["media_url"])):continuetry:metadata = json.loads(row["metadata_json"] or "{}")@@ -156,6 +165,23 @@ def inspect_row(connector, row: dict) -> tuple[dict, dict | None]:return entry, update or None+def inspect_duration(connector, row: dict) -> tuple[dict, dict | None]:+ """只补时长:读一次原文件头,读到就只写 `duration`。++ 读不到记「未取得」而不是写空:`moov` 在文件结尾、CDN 一时不通都会这样,+ 留给下一趟再问,不冒充测过。+ """+ entry = {"item_id": row["id"], "external_id": row["external_id"], "result": "",+ "published_before": row["published_at"] or "", "published_after": "",+ "duration": "", "tag_types_added": "", "written": "否", "note": ""}+ seconds = connector._video_seconds(row["media_url"])+ if not seconds:+ entry.update(result="未取得", note="时长未取得")+ return entry, None+ entry.update(result="取得", duration=seconds)+ return entry, {"duration": seconds}++def _is_mp4(url: str | None) -> bool:return str(url or "").lower().split("?")[0].endswith(".mp4")@@ -182,7 +208,7 @@ def run(args: argparse.Namespace) -> int:previous = [row for row in read_rows(args.out, missing_ok=True)if row.get("written") == "是"] if args.resume else []with open_readonly(args.db) as reader:- rows = pending_rows(reader, args.limit, done)+ rows = pending_rows(reader, args.limit, done, duration_only=args.duration_only)total = reader.execute("SELECT COUNT(*) FROM follow_item i JOIN follow_source s ON s.id=i.source_id"" WHERE s.provider='rule34xxx'").fetchone()[0]@@ -195,6 +221,8 @@ def run(args: argparse.Namespace) -> int:if args.apply:# 备份在任何写入之前由 `open_for_write` 落;分批提交,中断一次不至于整趟白跑。writer = open_for_write(args)+ # 服务的关注检查同时在写 follow_item;它的事务很短,等它提交而不是 5 秒就报锁。+ writer.execute("PRAGMA busy_timeout=60000")print(f"备份:{args.backup}", flush=True)before = writer.execute("SELECT COUNT(*) FROM follow_item").fetchone()[0]@@ -220,7 +248,7 @@ def run(args: argparse.Namespace) -> int:# 间隔按帖子页请求的起点算:文件头在另一个主机上,问它的时间落在这段间隔里。time.sleep(max(0.0, next_detail - time.monotonic()))next_detail = time.monotonic() + args.delay- entry, update = inspect_row(connector, row)+ entry, update = (inspect_duration if args.duration_only else inspect_row)(connector, row)log.append(entry)if entry["result"] == "未取得":counts["未取得"] += 1diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 3822e45e1..97581c309 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -1291,8 +1291,9 @@ class Rule34XxxConnector(_BaseConnector):provider = "rule34xxx"#: 一页 24 条时整页都能补上;额度存在是为了页面变长时请求数不跟着长。DEFAULT_ENRICH_BUDGET = 24- #: 详情页给的就是标签分类,所以补齐过的行 metadata 里一定有 `tag_types`。- ENRICHED_MARK = "tag_types"+ #: 第二阶段补两样:帖子页的标签分类(metadata 的 `tag_types`)和原文件头的时长。+ #: mp4 缺时长的行下次检查还会进第二阶段,判据在 `follow_store._ENRICHED_PREDICATES`。+ ENRICHED_MARK = "tag_types_duration"_TAG_RE = re.compile(r"^[^\s&?#]{1,100}$")#: 历史行存的是 250px 的 preview。官方 dapi 的 `sample_url` 与它用同一#: bucket/hash;2026-08-28 对生产历史行实测推导,结果是 1920x1080。@@ -1404,14 +1405,17 @@ class Rule34XxxConnector(_BaseConnector):def _enrich_one(self, candidate: FollowCandidate) -> FollowCandidate:detail = self._detail(str(candidate.external_id))+ # 文件头在另一个主机上,帖子页被限流挡回来不影响它,所以不论分类取没取到都问。+ duration = self._video_seconds(candidate.media_url)tag_types = detail.get("tag_types")if not tag_types:# 详情页这次没给出分类。保持 partial:上一轮取到的分类还在库里,# 覆盖成空会让「这条没有分类」和「这次没问到」在数据里长得一样。- return candidate+ # partial 行落库时时长只补空,所以读到的时长照样带上。+ return replace(candidate, duration=duration) if duration else candidatereturn replace(candidate, partial=False,published_at=detail.get("published_at") or candidate.published_at,- duration=self._video_seconds(candidate.media_url),+ duration=duration,extra={**candidate.extra, "tag_types": tag_types})#: 读时长只取文件开头这么多字节。站方转码出的 mp4 都是 faststart,`mvhd` 在开头diff --git a/src/peach/follow_store.py b/src/peach/follow_store.pyindex ab71f8470..b7dc8a7e5 100644--- a/src/peach/follow_store.py+++ b/src/peach/follow_store.py@@ -174,13 +174,16 @@ def _carry_image_dims(metadata: dict, previous_json: str | None) -> dict:#: `partial=True` 的候选(只有列表视图、详情这次没取)更新已有行时用的 SET 子句。#: 列表本来就权威的那几列照常更新;详情才能给出的 media_url、thumb_url、-#: published_at、duration、group_hint 一概不动,metadata 用 `json_patch` 并进去而+#: published_at、group_hint 一概不动,metadata 用 `json_patch` 并进去而#: 不是整块替换——否则跳过第二阶段就等于把上一轮取到的细节抹掉,而抹掉之后#: 「详情本来就没有」和「这次没去问」在数据里长得一模一样。+#: 时长只补空:rule34xxx 的时长读自原文件头,帖子页被限流挡回来时它照样取得到,+#: 这时候选仍是 partial,已有的时长不覆盖,空着的补上。_PARTIAL_UPDATE = (" title=excluded.title, url=excluded.url, version=excluded.version,"" release_key=excluded.release_key, variant_kind=excluded.variant_kind,"" variant_label=excluded.variant_label,"+ " duration=COALESCE(follow_item.duration, excluded.duration),"" metadata_json=json_patch(follow_item.metadata_json, excluded.metadata_json),"" last_seen_at=excluded.last_seen_at")@@ -190,7 +193,12 @@ _PARTIAL_UPDATE = (#: 由 `tests/test_follow_sources.py` 反过来核对每个连接器声明的键都在这里。_ENRICHED_PREDICATES = {"published_at": "published_at IS NOT NULL AND published_at<>''",- "tag_types": "json_extract(metadata_json,'$.tag_types') IS NOT NULL",+ # rule34xxx:分类只有帖子页给,时长只有原文件头给,两样都有才算补齐。只看分类的话,+ # 时长功能上线前补过分类的行、文件头那次没读到的行,常规检查永远不会再问。+ "tag_types_duration": (+ "json_extract(metadata_json,'$.tag_types') IS NOT NULL"+ " AND (duration IS NOT NULL OR (lower(COALESCE(media_url,'')) NOT LIKE '%.mp4'"+ " AND lower(COALESCE(media_url,'')) NOT LIKE '%.mp4?%'))"),"post_type": "json_extract(metadata_json,'$.post_type') IS NOT NULL","media_dims": "json_extract(metadata_json,'$.media_dims') IS NOT NULL",}diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex 69b3e0a0a..f34466bf2 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -1420,6 +1420,25 @@ class Rule34XxxConnectorTests(unittest.TestCase):self.assertEqual(head.headers["Range"], f"bytes=0-{budget - 1}")self.assertLessEqual(budget, 65536)+ def test_a_throttled_post_page_still_brings_the_file_head_duration(self):+ """文件头在另一个主机上,帖子页被挡回来不牵连它:时长照样带上,候选仍是 partial。"""+ video = minimal_mp4(timescale=1000, sample_delta=40, samples=250, keyframe_every=25)++ def transport(request, timeout, max_bytes):+ if request.url.startswith("https://api.rule34.xxx/"):+ return HttpResponse(200, {}, RULE34XXX_JSON)+ if request.url.startswith("https://api-cdn-mp4.rule34.xxx/"):+ return HttpResponse(206, {}, video)+ return HttpResponse(503, {}, b"slow down")++ result = Rule34XxxConnector(+ transport=transport, max_items=1, sleeper=lambda _: None,+ credential=Credential("rule34xxx", {"user_id": "42", "api_key": "sekret"}),+ ).fetch("lazyprocrastinator")+ self.assertEqual(result.candidates[0].duration, 10.0)+ self.assertTrue(result.candidates[0].partial)+ self.assertNotIn("tag_types", result.candidates[0].extra)+def test_a_throttled_detail_page_is_retried_not_read_as_no_types(self):"""站方公布的是每 60 秒 60 次,而列表页一页 24 条、每条都要单独打一次详情页。@@ -2109,7 +2128,7 @@ class EnrichPhaseTests(unittest.TestCase):self.assertEqual(follow_sources.enrichment_mark(""), "")self.assertEqual(follow_sources.enrichment_mark("kemono"), "","kemono 的探测是收录判定,在列表阶段做,不是第二阶段")- self.assertEqual(follow_sources.enrichment_mark("rule34xxx"), "tag_types")+ self.assertEqual(follow_sources.enrichment_mark("rule34xxx"), "tag_types_duration")def test_rule34xxx_is_not_marked_by_a_time_the_list_already_gave(self):"""rule34xxx 的上传时间来自列表的 `change`,第一次落库就有值。diff --git a/tests/test_follow_store.py b/tests/test_follow_store.pyindex e4a8a1955..8307dea55 100644--- a/tests/test_follow_store.py+++ b/tests/test_follow_store.py@@ -1142,9 +1142,45 @@ class EnrichedMarkTests(_StoreCase):published_at="2026-08-26T15:20:00Z", partial=True,extra={"tag": "tag"}),], provider="rule34xxx", ref="tag"), moment=MOMENT)- self.assertEqual(self.store.enriched_external_ids(source_id, "tag_types"),+ self.assertEqual(self.store.enriched_external_ids(source_id, "tag_types_duration"),frozenset({"1"}))+ def test_a_rule34xxx_video_without_duration_is_not_yet_enriched(self):+ """分类有了、mp4 的时长没读到,下次检查还要进第二阶段;图片不需要时长。"""+ source_id = self._source(provider="rule34xxx", ref="tag")+ types = {"tag_types": {"tifa": "general"}}+ self.store.record(source_id, _fetch([+ FollowCandidate(provider="rule34xxx", external_id="clip", title="a",+ media_url="https://api-cdn-mp4.rule34.xxx/images/1/a.mp4",+ extra=types),+ FollowCandidate(provider="rule34xxx", external_id="timed", title="b",+ media_url="https://api-cdn-mp4.rule34.xxx/images/1/b.mp4",+ duration=12.5, extra=types),+ FollowCandidate(provider="rule34xxx", external_id="still", title="c",+ media_url="https://api-cdn.rule34.xxx/images/1/c.jpeg",+ extra=types),+ ], provider="rule34xxx", ref="tag"), moment=MOMENT)+ self.assertEqual(self.store.enriched_external_ids(source_id, "tag_types_duration"),+ frozenset({"timed", "still"}))++ def test_a_partial_candidate_fills_an_empty_duration_without_overwriting(self):+ """帖子页被挡回来时候选仍是 partial,文件头读到的时长只补空着的那一格。"""+ source_id = self._source(provider="rule34xxx", ref="tag")+ self.store.record(source_id, _fetch([+ FollowCandidate(provider="rule34xxx", external_id="empty", title="a"),+ FollowCandidate(provider="rule34xxx", external_id="known", title="b",+ duration=30.0),+ ], provider="rule34xxx", ref="tag"), moment=MOMENT)+ self.store.record(source_id, _fetch([+ FollowCandidate(provider="rule34xxx", external_id="empty", title="a",+ partial=True, duration=10.0),+ FollowCandidate(provider="rule34xxx", external_id="known", title="b",+ partial=True, duration=99.0),+ ], provider="rule34xxx", ref="tag"), moment=MOMENT)+ durations = dict(self.connection.execute(+ "SELECT external_id, duration FROM follow_item WHERE source_id=?", (source_id,)))+ self.assertEqual(durations, {"empty": 10.0, "known": 30.0})+def test_an_unregistered_mark_is_refused_not_silently_matched(self):source_id = self._source()with self.assertRaises(ValueError):diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 292d1395d..61911e0fe 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -316,6 +316,47 @@ class OperationalScriptTests(unittest.TestCase):{"item_id": 1, "written": "否"}], fill_missing=True)self.assertEqual(backfill.written_ids(out), {2})+ def test_rule34_duration_only_backfill_touches_nothing_but_empty_durations(self):+ """授权只覆盖时长时:只挑缺时长的 mp4,不问帖子页,只写 `duration`。"""+ backfill = load_script("backfill_rule34_details")+ database = self.tmp_ledger()+ seeding = sqlite3.connect(database)+ seeding.execute(+ "INSERT INTO follow_item VALUES(3,1,'18622790','https://rule34.xxx/?id=3',"+ "'https://api-cdn.rule34.xxx/images/1/c.jpeg','2026-09-14T03:02:05Z',"+ "'exact',NULL,'{}')")+ seeding.commit()+ untouched = seeding.execute(+ "SELECT id, published_at, published_precision, metadata_json FROM follow_item"+ " ORDER BY id").fetchall()+ seeding.close()+ heads = []++ class Connector:+ def _detail(self, post_id):+ raise AssertionError("只补时长不该打帖子页")++ def _video_seconds(self, url):+ heads.append(url)+ return 60.054++ out = database.parent / "duration.csv"+ args = backfill.build_parser().parse_args(+ ["--db", str(database), "--apply", "--backup", str(database.parent / "b.db"),+ "--out", str(out), "--delay", "0", "--duration-only"])+ with mock.patch.object(backfill, "build_connector", return_value=Connector()), \+ redirect_stdout(io.StringIO()):+ self.assertEqual(backfill.run(args), 0)+ self.assertEqual(heads, ["https://api-cdn-mp4.rule34.xxx/images/1/b.mp4"])+ after = sqlite3.connect(database)+ self.addCleanup(after.close)+ self.assertEqual(dict(after.execute("SELECT id, duration FROM follow_item")),+ {1: 20.0, 2: 60.054, 3: None})+ self.assertEqual(after.execute(+ "SELECT id, published_at, published_precision, metadata_json FROM follow_item"+ " ORDER BY id").fetchall(), untouched)+ self.assertEqual(backfill.written_ids(out), {2})+def test_follow_image_dims_backfill_reads_archives_first_and_probes_headers_for_the_rest(self):"""图片墙的比例占位要每张图都有宽高;存量行里只有 fanbox 记过。