Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(catalog): 刮削后按页名去日本资料站查创作者身份

longmeidaoff948a3870e8
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 8b4fc1430..0afcb6e41 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -26,7 +26,7 @@ FC2 卖家名册复用 `sources/fc2.py` 的 `label`、`seller_url` 来源契约
账号归属复用 `review_decision`、`creator_collection_base`、`write_owned_fields` 和全库归属审计。明确拒绝的资产与账号组合在自动摄取时跳过;用户写入保留复核入口。网黄博主只命中可信个人、内容创作者或发布账号断言,未分类账号保留全部名册入口。`attach_avatar_availability` 集中处理资料页、索引、搜索与统计的作品头像:发布账号缺少本人或出演职业证据时不提供作品帧兜底,已安装图片独立保留。来源核查清单、逐关系回执和备份存于 `peach-data/review/`。
-`entity_identity_research` 与 `apply_entity_identity_research.py` 复用规范实体写入、字段归属保护、只读预览、SQLite 备份及冻结计划。逐行撤回回执核对后续修改,新增实体有额外引用时拒绝删除;观看历史和人工判断不被回滚覆盖。资料站调研复用 `sources/seesaa.py` 的 `WikiPages`(缓存、限额、撞墙停网)、作品表解析 `rows()` 与 `person_profile`,以及 `performer_alias_followup` 的 EUC-JP 页名直取写法,不新增依赖。
+`entity_identity_research` 与 `apply_entity_identity_research.py` 复用规范实体写入、字段归属保护、只读预览、SQLite 备份及冻结计划。逐行撤回回执核对后续修改,新增实体有额外引用时拒绝删除;观看历史和人工判断不被回滚覆盖。资料站调研复用 `performer_alias_followup.WikiSitePages`(包着 `sources/seesaa.py` 的 `WikiPages`,加 404 记忆与按站冷却)、作品表解析 `rows()` 与 `person_profile`,以及 EUC-JP 页名直取写法,不新增依赖;`creator_identity_followup` 的后继壳照抄补厂牌、补别名两条。
## 播放器清晰度
diff --git a/docs/SOURCING.md b/docs/SOURCING.md
index fdfa7f423..75e0ea52b 100644
--- a/docs/SOURCING.md
+++ b/docs/SOURCING.md
@@ -668,9 +668,10 @@ Instagram 的独立用户登录会话未取得,自动适配器不进正式依
こすっち、スコッチ、UraLesbian 三个。
- **身份调研先按页名查日本资料站。** 通用搜索不收 sougouwiki、av_neme 这类站,只搜通用引擎得出的「未取得」
不算查过。`research_creator_identity_wikis.py` 只读账本,对身份待核验的创作者按规范名、去掉番号前缀的名字和
- 文件名前缀,用 EUC-JP 页名直取两站(取页层与 `scrape_codes` 共用 `WikiPages` 与页缓存)。同名页是 3 位以上出演者
- 的作品一览就记 `identity=release` 的 observed 并否掉 `unknown`;都不存在时 unknown 候选写明问过哪几页;
- 404 以外的取页失败是未取得,不进清单。清单交 `apply_entity_identity_research.py` 冻结预览、备份写入。
+ 文件名前缀,用 EUC-JP 页名直取两站(取页层是补别名后继的 `WikiSitePages`,页缓存、404 记忆与来源冷却与服务共用)。
+ 同名页是 3 位以上出演者的作品一览就记 `identity=release` 的 observed 并否掉 `unknown`;都不存在时 unknown 候选写明
+ 问过哪几页;没有页以外的取页失败是未取得,不进清单。清单交 `apply_entity_identity_research.py` 冻结预览、备份写入。
+ 处理任务结束时「查创作者身份」后继按同一判据自动问新登记和存量的创作者,命中直接落批次来源的 observed(ADR-0096)。
改实体类型仍是用户复核。裏DVD村(uradvd-mura.com)是带会员登录的 DVD/下载商店,没有按页名寻址的系列页,
未接入,只作人工查证线索。
diff --git a/docs/adr/0096-creator-identity-followup.md b/docs/adr/0096-creator-identity-followup.md
new file mode 100644
index 000000000..eceea613a
--- /dev/null
+++ b/docs/adr/0096-creator-identity-followup.md
@@ -0,0 +1,15 @@
+# ADR-0096:刮削后按页名去日本资料站查创作者身份
+
+状态:已接受。最后复核:2026-10-09。
+
+文件名里的创作者常常不是人。`COSH こすっち` 一直被当成个人账号,实际是スコッチ的系列;通用搜索不收 sougouwiki、av_neme 这类站,身份调研只搜通用引擎,查不出来。命令行那一趟(`scripts/research_creator_identity_wikis.py`)补上了这两站,但要人跑、人看、再交给 `apply_entity_identity_research.py` 写,新登记的创作者照样没人去问。
+
+处理任务结束时为创作者派一条「查创作者身份」后继(`creator_identity_followup`,ADR-0040):新登记的每个一条,存量每轮至多 `STOCK_SHARE` 条,在女优头像的存量之前取。目标是身份面上没有任何可信断言(observed 或 approved,任何来源、任何值)且名字不是结构目录或转载站的创作者;人复核过的一律不查,不会被另一个来源冲掉。
+
+判据与命令行那一趟逐字相同(`entity_identity_research.wiki_finding`):页名候选是规范名、去掉番号前缀的名字和文件名里的发行前缀,两站按 EUC-JP 直取;同名页是三位以上出演者的作品一览才算命中。命中按 ADR-0052 直接落 `identity=release` 的 observed,来源是批次号 `script:creator-identity-wiki@<任务行 id>`,由 `revert_auto_landing.py --source script:creator-identity-wiki` 整批撤回。人物页、出演者不足的页和不存在的页都不写,问过什么留在活动页那一行;没取到记「未取得」,24 小时后再派。
+
+后继不改实体类型。改成厂牌或系列要迁移作品关系,是人复核的那一步;observed 已经让它离开博主名册和作品画面头像(ADR-0095)。
+
+取页复用补别名后继的 `WikiSitePages`:页缓存、本条请求上限、站上没有的页记 30 天、403 与 429 按站名进来源冷却,两站共用 seesaawiki.jp 每 2 秒一次的主机间隔。没有新依赖。
+
+2026-10-09 对账本里 192 个身份待核验的创作者跑过一遍命令行:全部取到,没有作品一览命中;43 个中文名写不成站上编码,其余两站都没有同名页或只是人物页。剩下的多是西方与中文平台账号,这两站本来就不收。
diff --git a/scripts/research_creator_identity_wikis.py b/scripts/research_creator_identity_wikis.py
index 35c4248fc..cf14706d5 100644
--- a/scripts/research_creator_identity_wikis.py
+++ b/scripts/research_creator_identity_wikis.py
@@ -8,22 +8,20 @@ from __future__ import annotations
import argparse
import json
import sys
-from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'src'))
from peach import entity_identity_research as research # noqa: E402
-from peach.classification import is_repost_creator, is_structural_creator, numbered_cast_shape # noqa: E402
-from peach.config import DATABASE_PATH, SOURCES_DIR # noqa: E402
-from peach.entities import normalize_entity_name # noqa: E402
+from peach.config import DATABASE_PATH, GENERATED_DIR, SECRETS_DIR # noqa: E402
from peach.fsutil import atomic_write_text # noqa: E402
-from peach.scripting import HostLimiter, open_readonly # noqa: E402
-from peach.sources.seesaa import AV_NEME, SEESAA, WikiPages # noqa: E402
+from peach.performer_alias_followup import WikiSitePages # noqa: E402
+from peach.scripting import open_readonly # noqa: E402
+from peach.sources.seesaa import AV_NEME, SEESAA # noqa: E402
def targets(connection, entity_ids):
- """(实体 id, 规范名, 文件名前缀);默认是本来源记为身份待核验候选的创作者。"""
+ """(实体 id, 规范名, 文件名前缀);默认是本来源记为身份待核验候选、身份面还没有可信断言的创作者。"""
if entity_ids:
marks = ','.join('?' for _ in entity_ids)
rows = connection.execute(f"SELECT id,canonical_name FROM entity WHERE kind='creator' AND id IN ({marks})",
@@ -32,22 +30,11 @@ def targets(connection, entity_ids):
rows = connection.execute(
"SELECT e.id,e.canonical_name FROM entity e JOIN entity_classification ec ON ec.entity_id=e.id "
"WHERE e.kind='creator' AND ec.facet='identity' AND ec.value='unknown' AND ec.source=? "
- "AND ec.status='candidate' ORDER BY e.id", (research.SOURCE,)).fetchall()
- people = {normalize_entity_name(row[0]) for row in connection.execute(
- "SELECT canonical_name FROM entity WHERE kind='performer' UNION "
- "SELECT a.alias FROM entity_alias a JOIN entity e ON e.id=a.entity_id WHERE e.kind='performer'")}
- files = defaultdict(list)
- for entity_id, name in connection.execute(
- "SELECT ae.entity_id,a.name FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
- "WHERE ae.role='creator' AND a.medium='video'"):
- files[entity_id].append(str(name or ''))
- result = []
- for entity_id, name in rows:
- if is_structural_creator(name) or is_repost_creator(name):
- continue
- shape = numbered_cast_shape(files.get(entity_id, []), people)
- result.append((entity_id, name, [shape['prefix']] if shape and shape['prefix'] else []))
- return result
+ "AND ec.status='candidate' AND NOT " + research.settled_sql() + " ORDER BY e.id",
+ (research.SOURCE,)).fetchall()
+ rows = [(entity_id, name) for entity_id, name in rows if research.researchable(name)]
+ prefixes = research.filename_prefixes(connection, [entity_id for entity_id, _name in rows])
+ return [(entity_id, name, prefixes[entity_id]) for entity_id, name in rows]
def main():
@@ -55,7 +42,9 @@ def main():
parser.add_argument('--db', type=Path, default=DATABASE_PATH)
parser.add_argument('--output', type=Path, required=True, help='身份清单 JSON')
parser.add_argument('--entity', type=int, action='append', default=[], help='只查这些实体,可重复')
- parser.add_argument('--cache-dir', type=Path, default=SOURCES_DIR/'metadata'/'javinizer-go'/'seesaa-pages')
+ parser.add_argument('--cache-dir', type=Path, default=GENERATED_DIR/'provider-cache'/'seesaa-pages',
+ help='页缓存,缺省与补别名、查创作者身份两条后继共用')
+ parser.add_argument('--cooldown-root', type=Path, default=SECRETS_DIR, help='来源冷却记录,缺省与服务共用')
parser.add_argument('--max-requests', type=int, default=80, help='每站本批请求上限')
args = parser.parse_args()
connection = open_readonly(args.db)
@@ -63,10 +52,9 @@ def main():
todo = targets(connection, args.entity)
finally:
connection.close()
- # 两站同一主机,共用一个主机间隔。
- limiter = HostLimiter({}, default_interval=SEESAA.interval)
- pages = {'sougouwiki': WikiPages(args.cache_dir, config=SEESAA, limiter=limiter, max_requests=args.max_requests),
- 'av_neme': WikiPages(args.cache_dir, config=AV_NEME, limiter=limiter, max_requests=args.max_requests)}
+ # 两站同一主机,取页器共用补别名后继那一个主机间隔;撞墙记进来源冷却,服务那边也停。
+ pages = {config.name: WikiSitePages(args.cache_dir, args.cooldown_root, config=config,
+ max_requests=args.max_requests) for config in (SEESAA, AV_NEME)}
findings, unfetched = [], []
try:
for entity_id, name, prefixes in todo:
diff --git a/scripts/revert_auto_landing.py b/scripts/revert_auto_landing.py
index f79dc3096..83d152372 100644
--- a/scripts/revert_auto_landing.py
+++ b/scripts/revert_auto_landing.py
@@ -5,7 +5,8 @@
`entity_alias.source` 直接就是批次号 `<source>@<任务行 id>`(ADR-0055)。女优资料行的
`performer_profile.source` 同样是批次号,后继登记的站上编号在 `entity_external_ref.metadata_json`
里记 `source` 与 `batch`(ADR-0067),番号样张的 `code_sample_image.source` 也是批次号(ADR-0068),
-种子包补的所属事务所 `entity_membership.source` 与 label 的片商 `label_maker.source` 同样(ADR-0073、ADR-0075)。
+种子包补的所属事务所 `entity_membership.source` 与 label 的片商 `label_maker.source` 同样(ADR-0073、ADR-0075),
+查创作者身份后继写的身份断言 `entity_classification.source` 也是批次号(ADR-0096)。
判据错了一批,就按它们认出来一起撤掉,不必一条条找。
复核队列的自动否决记在 `review_decision.note` 里(`auto_rejected` 与 `rule`,ADR-0079),
@@ -39,6 +40,7 @@ id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接
revert_auto_landing.py --source auto:performer-alias
revert_auto_landing.py --source auto:performer-alias --batch auto:performer-alias@812
revert_auto_landing.py --source auto:performer-profile
+ revert_auto_landing.py --source script:creator-identity-wiki
revert_auto_landing.py --source auto:sample-images
revert_auto_landing.py --source auto:seed --batch auto:seed@2026-09-25
revert_auto_landing.py --source adr-0079-fc2-descriptive-performer
@@ -117,6 +119,19 @@ def planned_profiles(connection, source: str, batch: str) -> list[dict]:
values)]
+def planned_claims(connection, source: str, batch: str) -> list[dict]:
+ """这个来源写下的身份断言(`source` 列存批次号)。FC2 卖家那一批连同关系由 `fc2_sellers` 撤。"""
+ if source == fc2_sellers.SOURCE:
+ return []
+ clause, values = _batch_clause("c.source", source, batch)
+ return [{"entity_id": row["entity_id"], "entity": row["canonical_name"], "facet": row["facet"],
+ "value": row["value"], "source": row["source"]}
+ for row in connection.execute(
+ "SELECT c.entity_id,e.canonical_name,c.facet,c.value,c.source FROM entity_classification c"
+ " JOIN entity e ON e.id=c.entity_id WHERE " + clause + " ORDER BY c.entity_id,c.facet,c.value",
+ values)]
+
+
def planned_memberships(connection, source: str, batch: str) -> list[dict]:
"""这个来源写下的所属事务所(`source` 列存批次号)。"""
clause, values = _batch_clause("m.source", source, batch)
@@ -298,6 +313,7 @@ def main(argv: list[str] | None = None) -> int:
links = planned_links(connection, args.source, args.batch)
aliases = planned_aliases(connection, args.source, args.batch)
profiles = planned_profiles(connection, args.source, args.batch)
+ claims = planned_claims(connection, args.source, args.batch)
companies = company_profiles.planned_revert(connection, args.source, args.batch)
sellers = fc2_sellers.planned_revert(connection, args.source, args.batch)
creators = follow_creators.planned_revert(connection, args.source, args.batch)
@@ -319,6 +335,8 @@ def main(argv: list[str] | None = None) -> int:
print_profiles(profiles, companies)
for creator in creators:
print(f" - 建档 {creator['name'][:20]:<20} {creator['sources']} 个来源 {creator['batch']}")
+ for claim in claims:
+ print(f" - 断言 {claim['entity'][:20]:<20} {claim['facet']}={claim['value']} {claim['source']}")
for ref in refs:
print(f" - 编号 {ref['entity'][:20]:<20} {ref['provider']} {ref['id']} {ref['batch']}")
for membership in memberships:
@@ -335,8 +353,8 @@ def main(argv: list[str] | None = None) -> int:
for rehome in rehomes:
print(f" - 接回 {rehome['old_asset_id']:<8} → {rehome['new_asset_id']:<8} "
f"{rehome['name'][:40]} {rehome['batch']}")
- print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "公司资料": len(companies), "卖家": len(sellers),
- "关注建档": len(creators), "编号": len(refs),
+ print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "断言": len(claims),
+ "公司资料": len(companies), "卖家": len(sellers), "关注建档": len(creators), "编号": len(refs),
"归属": len(memberships), "片商": len(makers), "标识文件": len(files), "封面": len(covers),
"样张": sum(sample["count"] for sample in samples), "否决": len(rejections),
"标签": len(tags), "接回": len(rehomes), "想要入库": len(acquired)})
@@ -353,6 +371,9 @@ def main(argv: list[str] | None = None) -> int:
connection.executemany(
"DELETE FROM performer_profile WHERE entity_id=? AND source=?",
[(profile["entity_id"], profile["source"]) for profile in profiles])
+ connection.executemany(
+ "DELETE FROM entity_classification WHERE entity_id=? AND facet=? AND value=? AND source=?",
+ [(claim["entity_id"], claim["facet"], claim["value"], claim["source"]) for claim in claims])
connection.executemany(
"DELETE FROM entity_external_ref WHERE provider=? AND external_kind=?"
" AND external_id=?", [(ref["provider"], ref["kind"], ref["id"]) for ref in refs])
@@ -384,7 +405,7 @@ def main(argv: list[str] | None = None) -> int:
finally:
connection.close()
removed = remove_files(files, covers)
- print({"删除链接": len(links), "删除别名": len(aliases), "删除资料": len(profiles),
+ print({"删除链接": len(links), "删除别名": len(aliases), "删除资料": len(profiles), "删除断言": len(claims),
"删除编号": len(refs), "删除归属": len(memberships), "删除片商": len(makers),
"删除样张": removed_samples, "删除否决": len(rejections),
"删除标签": len(tags), "删除扁平标签": removed_tag_rows, "重开决定": reopened,
diff --git a/src/peach/creator_identity_followup.py b/src/peach/creator_identity_followup.py
new file mode 100644
index 000000000..9095096bb
--- /dev/null
+++ b/src/peach/creator_identity_followup.py
@@ -0,0 +1,177 @@
+"""刮削登记了新创作者之后,按页名去日本资料站查它是不是厂牌或系列(ADR-0096)。
+
+文件名里的「创作者」常常不是人:`COSH こすっち` 是スコッチ的一个系列,每部出演者都不同。
+通用搜索不收 sougouwiki、av_neme 这类站,命令行那一趟(`scripts/research_creator_identity_wikis.py`)
+要人跑、人看、再交给 `apply_entity_identity_research.py` 写。这条后继把判据确定的那一半接在刮削
+后面,判据一个字都没新加,全在 `entity_identity_research.wiki_finding`:
+
+1. 页名候选是规范名、去掉番号前缀的名字和文件名里的发行前缀(`lookup_keys`),两站各按
+ EUC-JP 直取,至多三个名字。
+2. 同名页是三位以上出演者的作品一览,就记 `identity=release` 的 observed;人物页、出演者不足
+ 的页和不存在的页都不写,只把这一轮问过什么留在活动页那一行上。
+3. 不改实体类型。改成厂牌或系列是人复核的那一步;observed 已经让它离开博主名册
+ (`entity_classification.index_scope`)。
+
+每条断言的来源都是批次号 `script:creator-identity-wiki@<任务行 id>`,判错了由
+`scripts/revert_auto_landing.py --source script:creator-identity-wiki` 整批撤回。
+
+身份面上已有可信断言(任何来源、任何值)的创作者一律不查,人复核过的不会被另一个来源冲掉。
+幂等:第一件事就看这一条,写入按 `(entity_id,facet,value,source)` 唯一。
+"""
+from __future__ import annotations
+
+import sqlite3
+import time
+from pathlib import Path
+
+from . import entity_identity_research as research
+from . import performer_alias_followup as alias
+from .entity_classification import write_claim
+from .followups import Attempts, Followup, FollowupType, attempts_root, register
+
+#: 这类后继在任务中心的身份,也是活动页上那一行的名字来源。
+TASK_KEY = "creator-identity"
+TASK_LABEL = "查创作者身份"
+
+#: 这条后继写下的断言来源都以它开头,后面接 `@<任务行 id>`;撤回按它认。
+SOURCE = "script:creator-identity-wiki"
+
+#: 每轮处理任务给存量创作者的名额,在女优头像的存量之前取。一条至多六次请求、两站共用
+#: seesaawiki.jp 每 2 秒一次;本机 2026-10-09 有 303 个创作者身份面没有可信断言,四十来轮轮遍。
+STOCK_SHARE = 8
+#: 结论是「未取得」时记号只保这么久:那一轮取决于站那天让不让进,不取决于名字。
+RETRY_UNFETCHED = 24 * 3600
+#: 入口判据的版本,进指纹。换了页名候选或作品一览判据就加一,跑过的创作者各再问一次。
+ENTRY_RULE = 1
+
+
+def followup_key(entity_id: int) -> str:
+ return f"{TASK_KEY}:{int(entity_id)}"
+
+
+def parse_key(key: str) -> int:
+ """把后继 key 拆回创作者 id。形状不对就抛——那说明排队的行不是这个版本写的。"""
+ prefix, _, raw = str(key).partition(":")
+ if prefix != TASK_KEY or not raw.isdigit():
+ raise ValueError(f"认不出这条查创作者身份后继:{key}")
+ return int(raw)
+
+
+def _label(name: str) -> str:
+ return f"{TASK_LABEL}:{name}" if name else TASK_LABEL
+
+
+def _open(connection: sqlite3.Connection, where: str, params: tuple) -> list[tuple[int, str]]:
+ """身份还没有可信断言、名字能拿去查的创作者,作品多的在前。"""
+ rows = connection.execute(
+ "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) AS assets FROM entity e"
+ " LEFT JOIN asset_entity ae ON ae.entity_id=e.id"
+ " WHERE e.kind='creator' AND " + where + " AND NOT " + research.settled_sql()
+ + " GROUP BY e.id ORDER BY assets DESC, e.id", params).fetchall()
+ return [(int(row[0]), str(row[1] or "")) for row in rows if research.researchable(row[1])]
+
+
+def plan(connection: sqlite3.Connection, *, since_entity_id: int) -> list[Followup]:
+ """这一轮新登记的创作者,一个一条后继。「新登记」按实体 id 的水位判,与补头像那条同一个水位。"""
+ return [Followup(key=followup_key(entity_id), task_key=TASK_KEY, label=_label(name))
+ for entity_id, name in _open(connection, "e.id>?", (int(since_entity_id),))]
+
+
+def fingerprint(connection: sqlite3.Connection, entity_id: int) -> str:
+ """会让这条后继结论变的量:名字、别名数、作品数(文件名前缀跟着变)与入口判据版本。"""
+ name = connection.execute("SELECT canonical_name FROM entity WHERE id=?", (int(entity_id),)).fetchone()
+ aliases = connection.execute("SELECT count(*) FROM entity_alias WHERE entity_id=?",
+ (int(entity_id),)).fetchone()[0]
+ assets = connection.execute("SELECT count(DISTINCT asset_id) FROM asset_entity WHERE entity_id=?",
+ (int(entity_id),)).fetchone()[0]
+ return f"{ENTRY_RULE}/{name[0] if name else ''}/{aliases}/{assets}"
+
+
+def stock(connection: sqlite3.Connection, attempts, *, limit: int, skip=()) -> list[Followup]:
+ """库里早就登记、身份至今没有可信断言的创作者,最多 `limit` 条(ADR-0053)。
+
+ 跑过一次、指纹没变的不再派(`attempts`)。
+ """
+ if limit <= 0:
+ return []
+ skip = set(skip)
+ found = []
+ for entity_id, name in _open(connection, "1", ()):
+ key = followup_key(entity_id)
+ if key in skip or attempts.settled(key, fingerprint(connection, entity_id)):
+ continue
+ found.append(Followup(key=key, task_key=TASK_KEY, label=_label(name)))
+ if len(found) >= limit:
+ break
+ return found
+
+
+def open_sites(contract) -> dict:
+ """两站的取页器,页缓存与冷却和补别名后继同一份。测试把这一步整个换掉,网络就一次都不出。"""
+ from .sources.seesaa import AV_NEME, SEESAA
+
+ cache = Path(contract.candidate_root) / "provider-cache" / "seesaa-pages"
+ cooldown = alias._cooldown_root(contract)
+ return {config.name: alias.WikiSitePages(cache, cooldown, config=config)
+ for config in (SEESAA, AV_NEME)}
+
+
+def run(contract, key: str, handle) -> dict:
+ """跑一条查创作者身份后继,再把它当时的指纹记进 `Attempts`,存量补派按它判。"""
+ summary = _run(contract, key, handle)
+ with contract.database.read_connection() as connection:
+ current = fingerprint(connection, parse_key(key))
+ outcome = str(summary.get("outcome", ""))
+ Attempts(attempts_root(contract.candidate_root)).record(
+ key, current, outcome, retry_after=RETRY_UNFETCHED if outcome == "未取得" else None)
+ return summary
+
+
+def _current(connection, entity_id: int):
+ """(规范名, 还要不要查);实体不在了交 None。"""
+ row = connection.execute("SELECT canonical_name FROM entity WHERE id=? AND kind='creator'",
+ (entity_id,)).fetchone()
+ if row is None:
+ return None
+ settled = connection.execute("SELECT " + research.settled_sql("?"), (entity_id,)).fetchone()[0]
+ return str(row[0] or ""), not settled and research.researchable(row[0])
+
+
+def _run(contract, key: str, handle) -> dict:
+ entity_id = parse_key(key)
+ batch = f"{SOURCE}@{getattr(handle, 'run_id', None) or time.strftime('%Y%m%dT%H%M%S')}"
+ with contract.database.read_connection() as connection:
+ current = _current(connection, entity_id)
+ if current is None:
+ # 实体被合并、删掉或改成厂牌了。这不是失败:那件事已经不存在了。
+ return {"outcome": "实体已不存在"}
+ name, open_ = current
+ if not open_:
+ return {"name": name, "outcome": "已有身份"}
+ keys = research.lookup_keys(name, research.filename_prefixes(connection, [entity_id])[entity_id])
+ if handle is not None:
+ handle.progress(label=_label(name), throttle=0)
+ sites = open_sites(contract)
+ try:
+ finding = research.wiki_finding(entity_id, name, keys, sites)
+ finally:
+ for pages in sites.values():
+ pages.close()
+ if finding is None:
+ return {"name": name, "outcome": "未取得", "keys": keys}
+ claims = [claim for claim in finding["claims"] if claim["status"] == "observed"]
+ if not claims:
+ return {"name": name, "outcome": "两站都没有作品一览", "asked": finding["claims"][0]["evidence"]}
+ with contract.database.write_transaction() as connection:
+ if _current(connection, entity_id) != (name, True):
+ return {"name": name, "outcome": "已变"}
+ for claim in claims:
+ write_claim(connection, entity_id=entity_id, source=batch, **claim)
+ contract.cache_bust()
+ return {"name": name, "outcome": "是厂牌或系列", "page": claims[0]["source_url"],
+ "evidence": claims[0]["evidence"]}
+
+
+#: 写账本:断言进 `entity_classification`。取页在事务外做,写的那一下很短,
+#: 但照样走写账本那一条串行通道(ADR-0040 第二条)。
+TYPE = register(FollowupType(task_key=TASK_KEY, label=TASK_LABEL, writes_ledger=True, run=run))
diff --git a/src/peach/entity_identity_research.py b/src/peach/entity_identity_research.py
index 4c79c528a..04a79fa6e 100644
--- a/src/peach/entity_identity_research.py
+++ b/src/peach/entity_identity_research.py
@@ -20,12 +20,49 @@ WIKI_ROOTS = {'sougouwiki': 'https://seesaawiki.jp/w/sougouwiki/', 'av_neme': 'h
LABEL_PAGE_CAST = 3
+def settled_sql(column='e.id'):
+ """身份面上已有可信断言(任何来源、任何值)或已核实是发行厂牌的实体;这些不再去查。"""
+ return (f"EXISTS (SELECT 1 FROM entity_classification ec WHERE ec.entity_id={column} "
+ "AND ec.status IN ('observed','approved') "
+ "AND (ec.facet='identity' OR (ec.facet='account_role' AND ec.value='studio')))")
+
+
+def researchable(name):
+ """结构目录与转载站名不是任何人的名字,拿去查页只会撞上同名的无关页。"""
+ from .classification import is_repost_creator, is_structural_creator
+ return not (is_structural_creator(name) or is_repost_creator(name))
+
+
def lookup_keys(name, prefixes=()):
"""资料站页名候选:规范名、去掉番号前缀的名字(`COSH こすっち` → `こすっち`)、文件名里的发行前缀。"""
keys = [name, re.sub(r'^[A-Z]{2,6}\s+(?=[^\x00-\x7f])', '', name), *prefixes]
return list(dict.fromkeys(key.strip() for key in keys if key and key.strip()))[:3]
+def filename_prefixes(connection, entity_ids):
+ """实体 id → 名下视频文件名里的发行前缀(`classification.numbered_cast_shape`),没有就是空表。"""
+ from collections import defaultdict
+ from .classification import numbered_cast_shape
+ from .entities import normalize_entity_name
+ ids = list(dict.fromkeys(int(entity_id) for entity_id in entity_ids))
+ if not ids:
+ return {}
+ people = {normalize_entity_name(row[0]) for row in connection.execute(
+ "SELECT canonical_name FROM entity WHERE kind='performer' UNION "
+ "SELECT a.alias FROM entity_alias a JOIN entity e ON e.id=a.entity_id WHERE e.kind='performer'")}
+ files = defaultdict(list)
+ for entity_id, _asset_id, name in connection.execute(
+ "SELECT DISTINCT ae.entity_id,a.id,a.name FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
+ "WHERE ae.role='creator' AND a.medium='video' AND ae.entity_id IN (" + ','.join('?' for _ in ids) + ")",
+ ids):
+ files[entity_id].append(str(name or ''))
+ result = {}
+ for entity_id in ids:
+ shape = numbered_cast_shape(files.get(entity_id, []), people)
+ result[entity_id] = [shape['prefix']] if shape and shape['prefix'] else []
+ return result
+
+
def _label_page(page, source):
"""作品一览页 → (作品数, 出演者数, 最常见番号前缀);人物页和出演者不足的页交 None。"""
from collections import Counter
@@ -43,12 +80,12 @@ def _label_page(page, source):
def wiki_finding(entity_id, name, keys, pages):
"""按页名直取 sougouwiki 与 av_neme,交回 `plan()` 能读的身份清单项。
- `pages` 是站名到 `sources.seesaa.WikiPages` 的映射。同名页是多位出演者的作品一览就记
+ `pages` 是站名到 `performer_alias_followup.WikiSitePages` 的映射:站上没有的页抛
+ `LookupError`,其余取页失败抛 `RuntimeError`。同名页是多位出演者的作品一览就记
`identity=release` 的 observed,并否掉 `identity=unknown`;页都不存在时只更新 unknown 候选
- 的证据,写明实际问过哪几页。404 以外的取页失败是未取得,交 None,不冻成「没有」。
+ 的证据,写明实际问过哪几页。没有页以外的取页失败是未取得,交 None,不冻成「没有」。
"""
from urllib.parse import quote
- from .metadata import MetadataProviderError
from .sources.seesaa import WIKI_SOURCES
queried = []
for wiki, root in WIKI_ROOTS.items():
@@ -61,10 +98,10 @@ def wiki_finding(entity_id, name, keys, pages):
continue
try:
page = pages[wiki].get(url)
- except MetadataProviderError as error:
- if error.status_code == 404:
- queried.append(f'{wiki}「{key}」(页不存在)')
- continue
+ except LookupError:
+ queried.append(f'{wiki}「{key}」(页不存在)')
+ continue
+ except RuntimeError:
return None
found = _label_page(page, source)
if not found:
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index 032a295e1..7a3b7c7c6 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -1424,11 +1424,12 @@ def _entity_followups(database, config, watermark, covered=()):
女优也算进来(`avatar_followup.plan`)。厂牌盘上没有图的派补厂牌后继
(`studio_followup.plan`),官网与标识在那一条里一起补。新女优另派一条补别名后继
(`performer_alias_followup.plan`,ADR-0055)与一条补女优资料后继
- (`performer_profile_followup.plan`,ADR-0067)。
+ (`performer_profile_followup.plan`,ADR-0067)。新创作者派一条查身份后继
+ (`creator_identity_followup.plan`,ADR-0096)。
这一轮的名额(`MAX_FOLLOWUPS`)先给新登记的,余下的给库里早就登记的存量(ADR-0053):
- 补别名与补女优资料各留出至多自己的 `STOCK_SHARE` 条,厂牌先取至多自己的那一份,
- 其余给女优头像。补别名的存量先排缺头像的女优(ADR-0072)。
+ 补别名与补女优资料各留出至多自己的 `STOCK_SHARE` 条,厂牌与创作者身份先各取至多自己的
+ 那一份,其余给女优头像。补别名的存量先排缺头像的女优(ADR-0072)。
存量每轮往前推一截,跑过又没变的不再派。
只声明,不执行:派发在调用方结算这一轮时发生,真正去跑的是 `followups` 那一层。
@@ -1436,8 +1437,8 @@ def _entity_followups(database, config, watermark, covered=()):
"""
if database is None or watermark is None:
return []
- from . import (avatar_followup, performer_alias_followup, performer_profile_followup,
- seed_followup, studio_followup)
+ from . import (avatar_followup, creator_identity_followup, performer_alias_followup,
+ performer_profile_followup, seed_followup, studio_followup)
from .followups import Attempts, attempts_root
from .task_runs import MAX_FOLLOWUPS
generated = config.directory('generated')
@@ -1453,6 +1454,7 @@ def _entity_followups(database, config, watermark, covered=()):
since_entity_id=watermark)
found += performer_alias_followup.plan(connection, since_entity_id=watermark)
found += performer_profile_followup.plan(connection, since_entity_id=watermark)
+ found += creator_identity_followup.plan(connection, since_entity_id=watermark)
taken = {item.key for item in found}
aliases = min(performer_alias_followup.STOCK_SHARE, max(0, MAX_FOLLOWUPS - len(found)))
profiles = min(performer_profile_followup.STOCK_SHARE,
@@ -1462,6 +1464,11 @@ def _entity_followups(database, config, watermark, covered=()):
limit=min(studio_followup.STOCK_SHARE,
max(0, MAX_FOLLOWUPS - len(found) - aliases - profiles)),
skip=taken)
+ found += creator_identity_followup.stock(
+ connection, attempts,
+ limit=min(creator_identity_followup.STOCK_SHARE,
+ max(0, MAX_FOLLOWUPS - len(found) - aliases - profiles)),
+ skip=taken)
found += avatar_followup.stock(connection, generated / 'avatars', attempts,
limit=MAX_FOLLOWUPS - len(found) - aliases - profiles,
skip=taken)
diff --git a/src/peach/performer_alias_followup.py b/src/peach/performer_alias_followup.py
index 27bff4388..f3ee1d542 100644
--- a/src/peach/performer_alias_followup.py
+++ b/src/peach/performer_alias_followup.py
@@ -119,6 +119,10 @@ class Unavailable(RuntimeError):
"""这一页没取到(网络、非 200、本条请求数用完)。"""
+class Missing(Unavailable, LookupError):
+ """站上没有这一页(404,或近期问过是 404)。"""
+
+
# -- 名字 --------------------------------------------------------------------
@@ -386,21 +390,24 @@ class MinnanoPages:
close()
-class AvNemePages:
- """av_neme 的取页:缓存、请求上限与撞墙判定都是 `sources.seesaa.WikiPages` 那一份,
- 这里只把它撞墙的那一下记进冷却,并在冷却期内一次都不问。
+class WikiSitePages:
+ """Seesaa 上一个 Wiki 的取页:缓存、请求上限与撞墙判定都是 `sources.seesaa.WikiPages` 那一份,
+ 这里只把它撞墙的那一下按站名记进冷却,并在冷却期内一次都不问。缺省是 av_neme。
站上没有的页(404)也记下(`missing.json`,保 `MISSING_TTL`):按页名直取会问到不存在的页,
- 同一位女优下一轮再跑不该为它再发一次请求。
+ 同一个名字下一轮再跑不该为它再发一次请求。没有的页抛 `Missing`,与没取到分开。
"""
MISSING_TTL = 30 * 86400
- def __init__(self, cache_dir: Path, cooldown_root: Path, transport=None):
- from .sources.seesaa import AV_NEME as CONFIG, WikiPages
+ def __init__(self, cache_dir: Path, cooldown_root: Path, transport=None, *, config=None,
+ max_requests: int = MAX_REQUESTS):
+ from .sources.seesaa import AV_NEME as DEFAULT, WikiPages
- self.pages = WikiPages(cache_dir, config=CONFIG, transport=transport, limiter=_LIMITER,
- max_requests=MAX_REQUESTS)
+ config = config or DEFAULT
+ self.site = config.name
+ self.pages = WikiPages(cache_dir, config=config, transport=transport, limiter=_LIMITER,
+ max_requests=max_requests)
self.cooldown_root = Path(cooldown_root)
self.missing_path = Path(cache_dir) / "missing.json"
@@ -415,11 +422,11 @@ class AvNemePages:
from .metadata import MetadataProviderError
from .scraping_access import pause_source, paused_until
- if paused_until(self.cooldown_root, AV_NEME):
+ if paused_until(self.cooldown_root, self.site):
raise Blocked("来源正在冷却")
missing = self._missing()
if time.time() - float(missing.get(url, 0)) < self.MISSING_TTL:
- raise Unavailable("站上没有这一页")
+ raise Missing("站上没有这一页")
try:
return self.pages.get(url)
except MetadataProviderError as error:
@@ -428,9 +435,10 @@ class AvNemePages:
missing[url] = time.time()
self.missing_path.parent.mkdir(parents=True, exist_ok=True)
self.missing_path.write_text(json.dumps(missing), encoding="utf-8")
+ raise Missing(str(error)) from None
raise Unavailable(str(error)) from None
limited = error.status_code == 429
- pause_source(self.cooldown_root, AV_NEME, refused=not limited)
+ pause_source(self.cooldown_root, self.site, refused=not limited)
raise Blocked("来源限流(429)" if limited else "来源拒绝访问或要求机器人验证") from None
def close(self) -> None:
@@ -509,7 +517,7 @@ def open_sites(contract) -> dict:
cache = Path(contract.candidate_root) / "provider-cache"
cooldown = _cooldown_root(contract)
return {MINNANO: MinnanoPages(cache / "minnano-av-pages", cooldown),
- AV_NEME: AvNemePages(cache / "seesaa-pages", cooldown),
+ AV_NEME: WikiSitePages(cache / "seesaa-pages", cooldown),
FC2CMADB: Fc2cmadbPages(cache / "fc2cmadb-actresses", cooldown)}
diff --git a/src/peach/task_runs.py b/src/peach/task_runs.py
index 1c44ecc77..9755e475c 100644
--- a/src/peach/task_runs.py
+++ b/src/peach/task_runs.py
@@ -99,6 +99,7 @@ TASK_LABELS = {
"jav-covers": "封面批量抓取",
"entity-avatar": "补实体头像",
"studio-mark": "补厂牌官网与标识",
+ "creator-identity": "查创作者身份",
"code-samples": "补番号样张",
"feed-check": "订阅源拉取",
"feed-scrape": "取新作资料",
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index c4b345c5c..272cbae9c 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -175,6 +175,7 @@ class WebContract:
#: 后继调度(ADR-0040)。导入 `avatar_followup` 就是它的登记动作:调度器本身
#: 不认识任何一种后继,登记表在 `followups.REGISTRY` 里。
from . import avatar_followup # noqa: F401 登记补头像后继
+ from . import creator_identity_followup # noqa: F401 登记查创作者身份后继
from . import feed_followup # noqa: F401 登记取新作资料后继
from . import follow_creators # noqa: F401 登记关注作者建档后继
from . import performer_alias_followup # noqa: F401 登记补女优别名后继
diff --git a/tests/test_creator_identity_followup.py b/tests/test_creator_identity_followup.py
new file mode 100644
index 000000000..2523956bc
--- /dev/null
+++ b/tests/test_creator_identity_followup.py
@@ -0,0 +1,222 @@
+"""查创作者身份后继:资料站作品一览直接落 observed,没有页与没取到都不写,写下的能整批撤回。
+
+全程临时账本、临时缓存;取页走真实的 `WikiSitePages`,传输换成按地址回页的替身,不联网。
+"""
+import contextlib
+import importlib.util
+import io
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+from urllib.parse import quote
+
+from peach import creator_identity_followup as followup
+from peach import entity_identity_research as research
+from peach import performer_alias_followup as alias
+from peach.entities import normalize_entity_name
+from peach.entity_classification import write_claim
+from peach.followups import Attempts, attempts_root
+from peach.http import HttpResponse
+from peach.repository import LedgerDatabase
+from peach.scraping_access import paused_until
+from peach.sources.seesaa import AV_NEME, SEESAA
+from support.ledger import fresh_ledger
+
+ROOT = Path(__file__).resolve().parents[1]
+STAMP = "2026-10-09T00:00:00.000Z"
+CAST = ("八ッ橋さい子", "本多由奈", "北川ゆず")
+
+
+def page_url(wiki: str, name: str) -> str:
+ return research.WIKI_ROOTS[wiki] + "d/" + quote(name.encode("euc_jp"))
+
+
+def work_table(*cast: str) -> bytes:
+ rows = "".join(f'<tr><td>COSH-00{index}</td><td>こすっち00{index}</td>'
+ f'<td><a href="{page_url("sougouwiki", name)}">{name}</a></td></tr>'
+ for index, name in enumerate(cast, 1))
+ return ('<meta charset="utf-8"><div id="page-body"><div class="user-area"><table>'
+ '<tr><th>NO</th><th>TITLE</th><th>ACTRESS</th></tr>' + rows + '</table></div></div>').encode()
+
+
+def load_revert():
+ spec = importlib.util.spec_from_file_location(
+ "revert_auto_landing_under_test", ROOT / "scripts" / "revert_auto_landing.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class Transport:
+ """按地址回页面的传输替身;没登记的回 404。"""
+
+ def __init__(self, pages: dict):
+ self.pages, self.calls = pages, []
+
+ def __call__(self, request, _timeout, _limit):
+ self.calls.append(request.url)
+ status, body = self.pages.get(request.url, (404, b""))
+ return HttpResponse(status, {}, body, request.url)
+
+ def close(self):
+ pass
+
+
+class NoWait:
+ def wait(self, _url):
+ pass
+
+
+class Case(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.db = fresh_ledger(self.root)
+ self.database = LedgerDatabase(self.db)
+ self.generated = self.root / "generated"
+ self.cooldown = self.root / "secrets"
+ self.busted = []
+ self.contract = SimpleNamespace(
+ database=self.database, candidate_root=self.generated,
+ follow_secrets_root=self.cooldown, cache_bust=lambda: self.busted.append(1))
+ self.transport = Transport({})
+ self.next_asset = 1
+
+ def entity(self, name: str, kind: str = "creator") -> int:
+ with self.database.write_transaction(notify=False) as connection:
+ cursor = connection.execute(
+ "INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)"
+ " VALUES(?,?,?,?,?)", (kind, name, normalize_entity_name(name), STAMP, STAMP))
+ return int(cursor.lastrowid)
+
+ def work(self, creator: int, filename: str) -> None:
+ asset_id, self.next_asset = self.next_asset, self.next_asset + 1
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute("INSERT INTO asset(id,location,path,name,medium) VALUES(?,'local',?,?,'video')",
+ (asset_id, f"R:\\media\\{asset_id}.mp4", filename))
+ connection.execute("INSERT INTO asset_entity(asset_id,entity_id,role,source)"
+ " VALUES(?,?,'creator','test')", (asset_id, creator))
+
+ def sites(self) -> dict:
+ cache = self.generated / "provider-cache" / "seesaa-pages"
+ return {config.name: alias.WikiSitePages(cache, self.cooldown, self.transport, config=config)
+ for config in (SEESAA, AV_NEME)}
+
+ def run_followup(self, entity_id: int, run_id: int = 7) -> dict:
+ handle = SimpleNamespace(run_id=run_id, progress=lambda **_kwargs: None)
+ with mock.patch.object(followup, "open_sites", side_effect=lambda _contract: self.sites()), \
+ mock.patch.object(alias, "_LIMITER", NoWait()):
+ return followup.run(self.contract, followup.followup_key(entity_id), handle)
+
+ def claims(self, entity_id: int) -> set[tuple[str, str, str]]:
+ with self.database.read_connection() as connection:
+ return {(row[0], row[1], row[2]) for row in connection.execute(
+ "SELECT value,status,source FROM entity_classification WHERE entity_id=? AND facet='identity'",
+ (entity_id,))}
+
+ def series_creator(self) -> int:
+ """名字查不到、文件名前缀查得到的创作者:三部三位不同出演者。"""
+ for name in CAST:
+ self.entity(name, "performer")
+ creator = self.entity("Scotch Amateur")
+ for index, name in enumerate(CAST, 1):
+ self.work(creator, f"こすっち00{index} {name}")
+ return creator
+
+
+class LandingTests(Case):
+ def test_a_work_list_under_the_filename_prefix_lands_as_observed_release(self):
+ creator = self.series_creator()
+ self.transport.pages[page_url("sougouwiki", "こすっち")] = (200, work_table(*CAST))
+ summary = self.run_followup(creator)
+ self.assertEqual(summary["outcome"], "是厂牌或系列")
+ self.assertEqual(self.claims(creator), {("release", "observed", f"{followup.SOURCE}@7")})
+ self.assertEqual(self.busted, [1])
+ self.assertIn(page_url("sougouwiki", "Scotch Amateur"), self.transport.calls)
+ # 有了可信身份,存量补派与再跑都不再问站。
+ asked = len(self.transport.calls)
+ self.assertEqual(self.run_followup(creator)["outcome"], "已有身份")
+ self.assertEqual(len(self.transport.calls), asked)
+ with self.database.read_connection() as connection:
+ self.assertEqual(followup.stock(connection, Attempts(self.root / "attempts"), limit=5), [])
+
+ def test_missing_pages_write_nothing_and_are_not_asked_again(self):
+ creator = self.entity("lucky")
+ summary = self.run_followup(creator)
+ self.assertEqual(summary["outcome"], "两站都没有作品一览")
+ self.assertIn("sougouwiki「lucky」(页不存在)", summary["asked"])
+ self.assertEqual(self.claims(creator), set())
+ asked = len(self.transport.calls)
+ self.assertEqual(asked, 2)
+ self.run_followup(creator)
+ self.assertEqual(len(self.transport.calls), asked)
+ with self.database.read_connection() as connection:
+ self.assertEqual(followup.stock(connection, Attempts(attempts_root(self.generated)), limit=5), [])
+
+ def test_a_refused_site_is_unfetched_cools_down_and_retries_later(self):
+ creator = self.entity("lucky")
+ self.transport.pages[page_url("sougouwiki", "lucky")] = (403, b"")
+ self.assertEqual(self.run_followup(creator)["outcome"], "未取得")
+ self.assertEqual(self.claims(creator), set())
+ self.assertTrue(paused_until(self.cooldown, SEESAA.name))
+ self.assertFalse(paused_until(self.cooldown, AV_NEME.name))
+ attempts = Attempts(attempts_root(self.generated), clock=lambda: 10 ** 10)
+ with self.database.read_connection() as connection:
+ self.assertEqual([item.key for item in followup.stock(connection, attempts, limit=5)],
+ [followup.followup_key(creator)])
+
+ def test_reviewed_identities_and_structural_names_are_never_queried(self):
+ reviewed = self.entity("Known Person")
+ with self.database.write_transaction(notify=False) as connection:
+ write_claim(connection, entity_id=reviewed, facet="identity", value="person",
+ source="user:identity-review", evidence="用户复核", status="approved")
+ self.entity("1080p")
+ fresh = self.entity("lucky")
+ with self.database.read_connection() as connection:
+ self.assertEqual([item.key for item in followup.plan(connection, since_entity_id=0)],
+ [followup.followup_key(fresh)])
+ self.assertEqual(self.run_followup(reviewed)["outcome"], "已有身份")
+ self.assertEqual(self.transport.calls, [])
+ self.assertEqual(self.run_followup(999), {"outcome": "实体已不存在"})
+
+
+class RevertTests(Case):
+ def test_a_batch_of_claims_is_reverted_without_touching_other_sources(self):
+ creator = self.series_creator()
+ self.transport.pages[page_url("sougouwiki", "こすっち")] = (200, work_table(*CAST))
+ self.run_followup(creator)
+ with self.database.write_transaction(notify=False) as connection:
+ write_claim(connection, entity_id=creator, facet="identity", value="unknown",
+ source=research.SOURCE, evidence="公开身份来源未取得")
+ revert = load_revert()
+ base = ["--db", str(self.db), "--source", followup.SOURCE]
+ with contextlib.redirect_stdout(io.StringIO()):
+ self.assertEqual(revert.main([*base, "--apply", "--backup", str(self.root / "backup.db")]), 0)
+ self.assertEqual(self.claims(creator), {("unknown", "candidate", research.SOURCE)})
+
+
+class AllocationTests(Case):
+ def test_new_and_stock_creators_get_identity_followups(self):
+ from peach import library_processing, performer_profile_followup, task_runs
+
+ old = [self.entity(f"account{index:02d}") for index in range(5)]
+ for entity_id in old:
+ self.work(entity_id, f"{entity_id}.mp4")
+ new = self.entity("newcomer")
+ config = SimpleNamespace(directory=lambda _name: self.generated)
+ # 一轮 8 条,补别名、补资料各留 1 条,创作者身份的存量取自己那 2 条。
+ with mock.patch.object(task_runs, "MAX_FOLLOWUPS", 8), \
+ mock.patch.object(alias, "STOCK_SHARE", 1), \
+ mock.patch.object(performer_profile_followup, "STOCK_SHARE", 1), \
+ mock.patch.object(followup, "STOCK_SHARE", 2):
+ found = library_processing._entity_followups(self.database, config, old[-1])
+ keys = [item["key"] for item in found if item["task_key"] == followup.TASK_KEY]
+ self.assertEqual(keys[0], followup.followup_key(new))
+ self.assertEqual(len(keys), 3)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_entity_classification.py b/tests/test_entity_classification.py
index 4e898d383..01ba5f87b 100644
--- a/tests/test_entity_classification.py
+++ b/tests/test_entity_classification.py
@@ -10,7 +10,7 @@ from peach.web_entity import q_index, q_entity, q_suggest
from peach.web_catalog import q_items
from peach.web_state import WebContract
from peach.web_catalog import attach_avatar_availability
-from peach.metadata import MetadataProviderError
+from peach.performer_alias_followup import Missing, Unavailable
from peach.sources.base import Page
from tests.support.ledger import fresh_ledger
@@ -33,9 +33,9 @@ class _Pages:
def get(self, url):
self.asked.append(url)
if url in self.failing:
- raise MetadataProviderError('Wiki 网络请求未取得', kind='unavailable', retryable=True)
+ raise Unavailable('Wiki 网络请求未取得')
if url not in self.listed:
- raise MetadataProviderError('Wiki HTTP 请求未取得', kind='unavailable', status_code=404, retryable=True)
+ raise Missing('站上没有这一页')
return Page(url, self.listed[url])
diff --git a/tests/test_performer_alias_followup.py b/tests/test_performer_alias_followup.py
index a37a6fecb..49713b876 100644
--- a/tests/test_performer_alias_followup.py
+++ b/tests/test_performer_alias_followup.py
@@ -243,7 +243,7 @@ class Case(unittest.TestCase):
cache = self.generated / "provider-cache"
return {alias.MINNANO: alias.MinnanoPages(cache / "minnano", self.cooldown, self.minnano,
limiter=NoWait()),
- alias.AV_NEME: alias.AvNemePages(cache / "seesaa", self.cooldown, self.av_neme),
+ alias.AV_NEME: alias.WikiSitePages(cache / "seesaa", self.cooldown, self.av_neme),
alias.FC2CMADB: alias.Fc2cmadbPages(cache / "fc2cmadb", self.cooldown, self.fc2cmadb,
limiter=NoWait())}