Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(seed): 种子在扫描结算后自动导入,只换自己写过的行,冲突与重复身份交人(ADR-0075)

longmeidaoca92c11943ae
diff --git a/.claude/skills/peach-ledger-write/SKILL.md b/.claude/skills/peach-ledger-write/SKILL.md
index e18bb4d66..b67751fec 100644
--- a/.claude/skills/peach-ledger-write/SKILL.md
+++ b/.claude/skills/peach-ledger-write/SKILL.md
@@ -39,8 +39,9 @@ description: 在用户说迁移、migrate、--apply、合并实体、merge_entit
只产候选,人复核后才 `approved`;撤不回的(合并、改规范名)判据再确定也要授权。
- 运维脚本默认 dry-run:`scrape_codes.py` 默认只写复核 CSV,`clean_names.py` 默认只生成
改名计划且 `--apply` 前备份 SQLite 并在数据库更新失败时回滚文件名。
-- 种子包(ADR-0073):`seed_pack.py import` 只给已有实体填空、不造实体,归属 `auto:seed@<版本>`;
- `export` 只读,数据包单独提交,推不推公开仓库由用户看字段决定。
+- 种子包(ADR-0073、0075):导入只给已有实体填空、不造实体,只换 `auto:seed@…` 自己写过的归属、
+ 片商与资料行,与人写的不一致记 `seed-landing.csv`;归属 `auto:seed@<版本>`。`export` 只读,
+ 数据包单独提交,推不推公开仓库由用户看字段决定。
## 实体合并
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2583667a7..3acee2eaf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,10 @@ Removed / Fixed / Security。
## [未发布]
+### 新增
+
+- **馆藏**:随版本附带实体事实种子(女优与厂牌的别名、站上编号、官网与社媒链接、资料表、所属事务所与 label 的片商)。扫描结束后自动补进账本里已有的实体,只填空;旧版种子写下的会被新版换掉,与人工判断不一致的记进复核产物,可整批撤回。
+
## [0.34.2] - 2026-09-20
### 修复
diff --git a/README.en.md b/README.en.md
index 23cced0dc..46daf02aa 100644
--- a/README.en.md
+++ b/README.en.md
@@ -81,6 +81,8 @@ FFmpeg and ffprobe are installed separately: without them you can still browse a
Media stays in its original folders by default; organizing is an explicit action you start yourself, with a preview first and a rollback afterwards. The catalog, identities, viewing history and human decisions stay in a local SQLite ledger. External metadata and AI output enter as candidates with provenance and confidence; credentials stay outside Git, logs and API responses. Peach is for single-user self-hosting and does not provide a public-site or team permission model.
+Each release ships a seed of entity facts: aliases, site identifiers, official and social links, profiles, agency memberships and label-to-maker relations for performers, studios and agencies, with no images. After a scan it only fills blanks on entities already in your ledger; the only rows it replaces are the ones an older seed wrote itself. Anything that disagrees with a human decision goes to a review file, and every batch can be reverted.
+
## Documentation
Using Peach: [Windows testing](docs/TESTING_DESKTOP.md) · [Operations](docs/OPERATIONS.md) · [Sources](docs/SOURCING.md) · [Project status](docs/STATUS.md) · [Changelog](CHANGELOG.md) · [Security policy](SECURITY.md)
diff --git a/README.md b/README.md
index 3857d80cf..5343c669f 100644
--- a/README.md
+++ b/README.md
@@ -81,6 +81,8 @@ FFmpeg 与 ffprobe 需自行安装:缺少时仍可浏览和播放浏览器兼
媒体默认保留在原目录,整理是用户显式发起、可预览可回滚的操作;馆藏、身份、观看记录和人工决定保存在本机 SQLite ledger;外部元数据与 AI 结果先作为带来源和置信度的候选,凭据不进入 Git、日志或 API 返回。Peach 面向单人自托管,不提供公开站点或团队权限模型。
+随版本附带一份实体事实种子(女优、厂牌与事务所的别名、站上编号、官网与社媒链接、资料表、所属事务所与 label 的片商,不含任何图像)。扫描结束后它只给账本里已有的实体填空,换掉的只有旧版种子自己写下的行,与人工判断不一致的记进复核产物,整批可撤回。
+
## 文档
使用:[Windows 测试版](docs/TESTING_DESKTOP.md) · [运行与配置](docs/OPERATIONS.md) · [来源采集](docs/SOURCING.md) · [项目状态](docs/STATUS.md) · [变更日志](CHANGELOG.md) · [安全政策](SECURITY.md)
diff --git a/docs/REUSE.md b/docs/REUSE.md
index f3ee8ad38..f6f20a3c4 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -243,7 +243,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP
- macOS Ledger 同步在共享根判为 `offline` 时先经 NetFS 挂载 `peach-sync` 再重判,挂载失败才保留离线结果,不弹阻塞认证框。
- 浏览历史增量采集使用 SQLite backup API 与 `browserexport`,也接受 Google Takeout ZIP;原始 URL 与标题只留本机私有目录,聚合候选不写 ledger。
- 首次设置的可选历史引导转到 `/taste?onboarding=1`,继续使用现有读取与导入入口。指南链接按 [Google 导出说明](https://support.google.com/accounts/answer/3024190?hl=zh-Hans) 和 [browserexport](https://github.com/purarue/browserexport) 官方说明核验(2026-09-06);沿用 `browserexport==0.4.4`,未新增依赖或解析器。
-- 实体的公开事实随仓库分发(ADR-0073):`scripts/seed_pack.py export` 只读账本生成 `resources/seed/entities.json`(女优、厂牌、事务所的别名、站上编号、官网社媒链接、资料表、所属事务所;不带图像、本机路径、Stash 编号),同一账本同一版本逐字节一致;`import` 默认 dry-run,只给本机已有实体填空、不造实体,归属 `auto:seed@<版本>`,`revert_auto_landing.py --source auto:seed` 五张表一起撤。
+- 实体的公开事实随仓库分发(ADR-0073、ADR-0075):`scripts/seed_pack.py export` 只读账本生成 `resources/seed/entities.json`(女优、厂牌、事务所的别名、站上编号、官网社媒链接、资料表、所属事务所、label 的片商;不带图像、本机路径、Stash 编号),同一账本同一版本逐字节一致。导入由扫描结算声明的 `seed-import:<版本>` 后继跑(`seed_followup`),命令行 `import` 默认 dry-run;只给本机已有实体填空、不造实体,旧种子写的归属、片商与资料可被新版换掉,与人写的不一致记 `conflicts`、一条对上两位记 `duplicates`,两者写进 `seed-landing.csv`;归属 `auto:seed@<版本>`,`revert_auto_landing.py --source auto:seed` 六张表一起撤。
- 数据管理首屏直接复用实际 `cleanupfieldset` 正文和操作条,只有计数等待取数;资源同步与重复文件网盘操作根据 `/api/sources` 已配置来源显示,离线来源保留入口。资源同步的扫描和执行复核均限于已配置 115/PikPak,空文件夹和按目录清理仍支持本地磁盘。
## 必须复用的成熟实现
diff --git a/docs/STATUS.md b/docs/STATUS.md
index b0a9c0e3e..3f32aa3d3 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -6,11 +6,11 @@
## 运行态
-- 女优头像 545 张,脸宽中位数 320px,37 张带水印待复核;被顶掉的整套留在 `avatars-superseded/`(见 `SOURCING.md`)。
+- 女优头像 545 张(中位脸宽 320px,37 张带水印待复核);被顶掉的在 `avatars-superseded/`。
- 数据管理页「整理」(ADR-0039)可预览、执行、回滚上一批,真实库未执行过。
- 产地是独立维度,JAV 是它的投影:`region` 为空时按厂牌、创作者、番号逐层推断,不落库;韩国 MIB 已不算 JAV。
-- Windows 是 ledger writer,入口是源码托盘(`pythonw -m peach.tray`,子服务用 venv 的 `peach.exe`),重启 `restart_windows_tray.py --source`;代码与数据在内置盘,外置盘只供 `R:\media`。
+- Windows 是 ledger writer,入口是源码托盘(`pythonw -m peach.tray`),重启 `restart_windows_tray.py --source`;代码与数据在内置盘,外置盘只供 `R:\media`。
- 托盘须普通权限启动:提权令牌看不到 CloudDrive 的 `A:`/`B:`,会误报脱盘。
- Windows HTTP `0.0.0.0:80`,HTTPS 为当前 LAN IPv4 的 443,mDNS 名见 `[server].mdns_name`;线上版本 `0.33.0`、`ledger_sync=writer`,项目 CA 严格校验的 `/healthz` 通过。
- 经正式域名访问时 `/healthz` 返回 `configurable=true`;配置读写与选文件夹共用本机连接判据;托盘负责配置重载与正式 HTTPS 地址、端口。
@@ -18,15 +18,16 @@
- 文件检查覆盖本地与网盘,来源等分,确认用共享弹层;CloudDrive 分档建议共用首启与配置入口;来源接口需登录(401)。
- 可选密码:首启可跳过,配置页可改可关,登录可记住设备。
- macOS 是 reader,代码与 `peach-data` 在内置盘;`peach.local` 经 8900/8443 和 pf 提供 80/443,GET 正常、写入返回 409。
-- 两端各用本机 CA,私钥与凭据不跨机同步;代码走 Git、账本走单写者复制、图片走 Syncthing。本机坐标在 `<数据根>/config.toml`;ADR-0023 第 1~3 阶段已在 Windows 生效。
+- 两端各用本机 CA,私钥与凭据不跨机同步;代码走 Git、账本单写者复制、图片走 Syncthing;本机坐标在 `<数据根>/config.toml`。
- Windows 真实 ledger `peach-data/database/ledger.db`,2026-09-13 已应用到 `0031`;`asset_subtitle` 195 行(孤立 19),175 部带字幕轨,`asset` 80,761 行。
- Mac ledger 已授权从共享副本显式拉取并恢复 `in-sync`;`sources` 已迁内置盘,`archive`、`tools` 仍可指向外置盘。
- 前端按 ADR-0031 逐页迁往 `frontend/` 的 React + Tailwind + BoardUI 源码,只有 React 一档;产物进 Git,经 `/dist/{name}` 提供;改前端需 Node 24+(`docs/FRONTEND.md`)。
- 本机运行 Python 3.14;`requires-python` 下限 3.12,CI 同时测 3.12 与 3.14;Windows FFmpeg/ffprobe 位于 `peach-data/tools/ffmpeg`,macOS 走 PATH。
- amane 桥(ADR-0048)装在 `peach-data/tools/amane-bridge/`,四类番号链都经它问。
- 发行名 `peach`,目录名 `peach-app`。macOS 落后 master 一组有顺序的操作(待办「待执行的操作」第 30 条),做完前别重启菜单栏:无口令的 `peach serve --host 0.0.0.0` 会拒绝启动。
-- 扫描与采集显示项目、动作与等待时长;无进展 120 秒预警,单项外部动作(资料 90 秒、封面 240 秒)超预算跳过并计入可重试,「重试未完成项」重跑原任务失败集合。问题写入 `state/library-processing-<job_id>.issues.jsonl`,接口按 `job_id` 分页。
+- 扫描与采集显示项目与等待时长;无进展 120 秒预警,单项外部动作(资料 90 秒、封面 240 秒)超预算跳过并可重试;问题写入 `state/library-processing-<job_id>.issues.jsonl`。
- 女优资料表 `performer_profile`(ADR-0067)与番号样张表(ADR-0068)待迁 `0036`、`0037`;补女优资料后继每轮存量至多 16 条。
+- 实体种子(ADR-0075)由扫描结算的 `seed-import` 后继导入,只填空并换旧种子行;不一致与重复身份在 `generated/seed-landing.csv`。
- Cloudflare 公网入口默认关闭,配置页启停,须先设访问密码;临时链接地址只写状态文件,命名隧道限源码环境、令牌只存设置文件。整站 `X-Robots-Tag: noindex` 加 `/robots.txt`。
- FC2PPV-DB 与 JAVten 经本机 Chrome 过 Cloudflare 验证(ADR-0065),profile 在 `secrets/browser/`,不再贴 Cookie。
diff --git a/docs/adr/0073-entity-facts-ship-as-a-seed-pack.md b/docs/adr/0073-entity-facts-ship-as-a-seed-pack.md
index 0e12c249a..be87e192d 100644
--- a/docs/adr/0073-entity-facts-ship-as-a-seed-pack.md
+++ b/docs/adr/0073-entity-facts-ship-as-a-seed-pack.md
@@ -1,6 +1,6 @@
# ADR-0073:实体的公开事实随仓库分发,导入只给已有实体填空
-- 状态:Accepted
+- 状态:Accepted;第三、四条与「触发时机」由 [ADR-0075](0075-seed-pack-refreshes-its-own-rows-and-lands-after-scans.md) 修订
- 日期:2026-09-25
- 修订:ADR-0024 第四条(共享清单的维护者结论不自动升级本机 ledger 真相)
- 关系:ADR-0024 第五条(新建空库不因此获得另一用户的实体)继续成立;ADR-0026 的法人/自然人分界;ADR-0052 的归属与撤回契约
diff --git a/docs/adr/0075-seed-pack-refreshes-its-own-rows-and-lands-after-scans.md b/docs/adr/0075-seed-pack-refreshes-its-own-rows-and-lands-after-scans.md
new file mode 100644
index 000000000..881f95bb6
--- /dev/null
+++ b/docs/adr/0075-seed-pack-refreshes-its-own-rows-and-lands-after-scans.md
@@ -0,0 +1,57 @@
+# ADR-0075:种子包在扫描结算后自动导入,只换自己写过的行,冲突与重复身份交人
+
+- 状态:Accepted
+- 日期:2026-09-25
+- 修订:ADR-0073 第三条(只填空)、第四条(撤回覆盖的表)与「触发时机」未决项
+- 关系:ADR-0040 的后继形态;ADR-0049/0051 的 `label_maker`;ADR-0052 的归属与撤回契约
+
+## 背景
+
+ADR-0073 把实体的公开事实做成随仓库走的种子包,导入只填空、只有命令行。用户 2026-09-25 问:
+「后续种子是如何更新的,我们做出修改会自动更新吗,女优移籍、退役、厂牌合并等等如何更新」。
+按 v1 的口径三种变化都传不过去:所属事务所一人一行,对方机器已有归属就不动;退役写在资料表的
+`active_until`,对方已有资料行就整行不动;label 归哪家片商根本不在包里,厂牌合并更不在。
+
+另一件事同一天核出来:`Prestige` 与 `PRESTIGE PREMIUM` 共用写法 `プレステージプレミアム`,种子把两位
+都认出来就整条跳过并计进「对不上」。跳过是对的(ADR-0073 第三条),但只给一个数,人不知道该去看谁。
+账本里其实早有 `label_maker` 记着 PRESTIGE PREMIUM 归 Prestige,问题只是片商名下多挂了一条 label 的
+别名;这类「两位实体是不是一位」的判断合并不可逆,必须交人。
+
+## 决策
+
+**一、种子自己写过的行允许被新版种子换掉。** 所属事务所、label 的片商、资料表这三处是会随时间变的
+事实。导入时本机那一行的 `source` 是 `auto:seed@<任何版本>`,包里指向不同就整行改成新批次;资料表
+另加一道:包里的 `fetched_at` 要比本机那行的晚。来源是 `user:manual`、`review:*`、本机后继的 `auto:*`
+一律不碰。这是 ADR-0052 已有的口径:自动写入者只能覆盖自己写的,不能改人的判断。别名、编号、链接是
+集合,照旧只增不减,包里没有而本机有的不动——缺席不是事实。
+
+**二、与人的判断不一致的记进 `conflicts`,不覆盖也不静默。** 本机那一行不是种子写的、包里说的又不一样,
+导入报告里多一条 `{entity, field, ours, source, theirs}`。后继把它写成 `candidate_root/seed-landing.csv`,
+活动页摘要只给条数。复核产物每次整份重写:种子导入是全量的,上一轮的项这一轮要么还在、要么已解决。
+
+**三、一条包项对上两位本机实体的记进 `duplicates`,由人合并。** 报告里带两位的规范名;包里带着旧名当
+别名已经足够匹配,实体合并不由种子做。`matches` 返回集合,`match_entity` 只在恰一位时给 id。
+
+**四、`label_maker` 进包,与所属事务所共用一段导入逻辑。** 两张表都是「主键在自己一侧、转手是覆盖」
+(ADR-0049)。导入前两端都要唯一命中,label 可以再挂 label(ADR-0051),沿上级走会绕回自己的不写。
+`scripts/revert_auto_landing.py --source auto:seed` 六张表一起撤。
+
+**五、触发点是扫描与采集的结算,不是启动。** ADR-0040 第一条只许任务结果声明后继,`_entity_followups`
+最先声明一条 `seed-import:<版本>`,排在 64 条名额之前。派的条件两个之一:这一轮登记了包里那三类的新
+实体,或这个版本还没有一条成功的任务记录。新机器空库导入什么都不发生(ADR-0024 第五条),扫完库、实体
+建出来,下一次结算就补上;同一版本因此会跑多次,`land` 幂等。
+
+**六、导出仍是显式的一次命令与一个数据提交。** 维护者账本的改动不自动变成种子;发版前手动导出,
+内容没变就不改文件。包的更新走版本,不走时间戳。
+
+## 不做什么
+
+- 不做「点一下就解决」的冲突界面。复核产物是 CSV,与别名、资料两条后继同一形态。
+- 不在导入时合并实体、改规范名、删任何行。
+
+## 后果
+
+- 移籍与退役:维护者账本改了、重新导出并发版,对方机器上由种子补的归属与资料跟着变;由人或本机后继写的
+ 不变,包里的新说法出现在复核产物里。
+- 厂牌合并:不传。合并后旧名进包当别名,对方机器上两条实体都对上时列进重复身份明细,由人决定。
+- 用户升级 Peach 后不必跑命令行;活动页多一条「导入实体种子」,摘要里是补了多少、换了多少、有几条不一致。
diff --git a/scripts/revert_auto_landing.py b/scripts/revert_auto_landing.py
index b40bf1d26..bfaaca817 100644
--- a/scripts/revert_auto_landing.py
+++ b/scripts/revert_auto_landing.py
@@ -5,7 +5,7 @@
`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` 同样(ADR-0073)。
+种子包补的所属事务所 `entity_membership.source` 与 label 的片商 `label_maker.source` 同样(ADR-0073、ADR-0075)。
判据错了一批,就按它们认出来一起撤掉,不必一条条找。
撤回是删除,不是恢复旧值:补厂牌后继只在盘上一张图都没有、账本里一条官网都没有时才写,
@@ -96,6 +96,17 @@ def planned_memberships(connection, source: str, batch: str) -> list[dict]:
" JOIN entity a ON a.id=m.agency_id WHERE " + clause + " ORDER BY m.member_id", values)]
+def planned_makers(connection, source: str, batch: str) -> list[dict]:
+ """这个来源写下的 label 归属片商(`source` 列存批次号)。"""
+ clause, values = _batch_clause("l.source", source, batch)
+ return [{"label_id": row["label_id"], "entity": row["canonical_name"], "maker": row["maker"],
+ "source": row["source"]}
+ for row in connection.execute(
+ "SELECT l.label_id,e.canonical_name,m.canonical_name AS maker,l.source"
+ " FROM label_maker l JOIN entity e ON e.id=l.label_id"
+ " JOIN entity m ON m.id=l.maker_id WHERE " + clause + " ORDER BY l.label_id", values)]
+
+
def planned_refs(connection, source: str, batch: str) -> list[dict]:
"""这个来源登记的站上编号(`metadata_json` 里记着 `source` 与 `batch`)。"""
found = []
@@ -146,6 +157,7 @@ def main(argv: list[str] | None = None) -> int:
profiles = planned_profiles(connection, args.source, args.batch)
refs = planned_refs(connection, args.source, args.batch)
memberships = planned_memberships(connection, args.source, args.batch)
+ makers = planned_makers(connection, args.source, args.batch)
files = planned_files(args.logo_root, args.source, args.batch)
samples = sample_images.planned_revert(connection, args.source, args.batch)
for link in links:
@@ -158,12 +170,14 @@ def main(argv: list[str] | None = None) -> int:
print(f" - 编号 {ref['entity'][:20]:<20} {ref['provider']} {ref['id']} {ref['batch']}")
for membership in memberships:
print(f" - 归属 {membership['entity'][:20]:<20} {membership['agency'][:30]} {membership['source']}")
+ for maker in makers:
+ print(f" - 片商 {maker['entity'][:20]:<20} {maker['maker'][:30]} {maker['source']}")
for path in files:
print(f" - 标识 {path.name}")
for sample in samples:
print(f" - 样张 {sample['code']:<20} {sample['count']} 张 {sample['source']}")
print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "编号": len(refs),
- "归属": len(memberships), "标识文件": len(files),
+ "归属": len(memberships), "片商": len(makers), "标识文件": len(files),
"样张": sum(sample["count"] for sample in samples)})
if not args.apply:
print("dry-run;确认无误后加 --apply --backup <路径>")
@@ -183,6 +197,9 @@ def main(argv: list[str] | None = None) -> int:
connection.executemany(
"DELETE FROM entity_membership WHERE member_id=? AND source=?",
[(membership["member_id"], membership["source"]) for membership in memberships])
+ connection.executemany(
+ "DELETE FROM label_maker WHERE label_id=? AND source=?",
+ [(maker["label_id"], maker["source"]) for maker in makers])
removed_samples = sample_images.revert(connection, args.source, args.batch)
integrity, orphans = verify_after_write(connection)
finally:
@@ -194,7 +211,8 @@ def main(argv: list[str] | None = None) -> int:
target.unlink()
removed += 1
print({"删除链接": len(links), "删除别名": len(aliases), "删除资料": len(profiles),
- "删除编号": len(refs), "删除归属": len(memberships), "删除样张": removed_samples,
+ "删除编号": len(refs), "删除归属": len(memberships), "删除片商": len(makers),
+ "删除样张": removed_samples,
"删除文件": removed,
"integrity_check": integrity, "foreign_key_check": orphans})
return 0
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index c78fbcdba..adfbac405 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -95,7 +95,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_link_repair.py",
"test_resource_identification.py",
"test_agency_entity.py", "test_agency_reject.py", "test_label_maker.py",
- "test_seed_pack.py"),
+ "test_seed_pack.py", "test_seed_followup.py"),
"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py",
"test_scan.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",
"test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py",
@@ -106,7 +106,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_fsutil.py", "test_desktop_settings.py",
"test_job_status.py", "test_jobs.py", "test_task_runs.py", "test_followups.py",
"test_task_center_integration.py", "test_reference_updates.py",
- "test_repo_hygiene.py", "test_seed_pack.py",
+ "test_repo_hygiene.py", "test_seed_pack.py", "test_seed_followup.py",
"test_review_csv.py", "test_jav_code_domain.py", "test_organize.py",
"test_link_repair.py",
"test_subprocess_encoding.py", "test_module_layering.py",
@@ -185,9 +185,11 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"src/peach/studio_icons.py": ("catalog", "metadata", "web"),
"src/peach/studio_sites.py": ("catalog", "metadata"),
"scripts/revert_auto_landing.py": ("catalog", "metadata", "tooling"),
- # 实体事实种子包(ADR-0073):导出导入的逻辑与命令行,测试都在 `test_seed_pack.py`。
+ # 实体事实种子包(ADR-0073):导出导入的逻辑与命令行,测试都在 `test_seed_pack.py`;
+ # 扫描结算后自动导入的后继(ADR-0075)在 `test_seed_followup.py`。
"src/peach/seed_pack.py": ("metadata", "tooling"),
"scripts/seed_pack.py": ("metadata", "tooling"),
+ "src/peach/seed_followup.py": ("metadata", "tooling"),
# 补女优资料后继的解析与读写层、一次补完的脚本,测试都在 `test_performer_profile_followup.py`。
"scripts/run_performer_profiles.py": ("metadata",),
"src/peach/avwikidb.py": ("metadata",),
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index 455914c26..b5dc13461 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -1436,14 +1436,16 @@ 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,
- studio_followup)
+ seed_followup, studio_followup)
from .followups import Attempts, attempts_root
from .task_runs import MAX_FOLLOWUPS
generated = config.directory('generated')
attempts = Attempts(attempts_root(generated))
try:
with database.read_connection() as connection:
- found = avatar_followup.plan(
+ # 随版本附带的实体种子(ADR-0075)排在最前:一轮至多一条,永远在名额之内。
+ found = seed_followup.plan(connection, since_entity_id=watermark)
+ found += avatar_followup.plan(
connection, generated / 'avatars', since_entity_id=watermark,
covered_asset_ids=[asset_id for asset_id, count in covered if count])
found += studio_followup.plan(connection, generated / 'logos',
diff --git a/src/peach/seed_followup.py b/src/peach/seed_followup.py
new file mode 100644
index 000000000..7baaa5da8
--- /dev/null
+++ b/src/peach/seed_followup.py
@@ -0,0 +1,116 @@
+"""导入实体种子后继:扫描结算后把随版本附带的种子包补进账本(ADR-0075)。
+
+种子包是仓库里的一份 JSON(`seed_pack.DEFAULT_PACK`),导入只给本机已有实体填空、换掉种子
+自己写过的旧行(`seed_pack.land`)。这条后继由扫描与采集在结算时声明(ADR-0040 第一条),
+派的条件是两个里有一个:这一轮登记了新的女优、厂牌或事务所,或这个版本的包还没有成功导入过。
+同一版本因此会跑多次;`land` 幂等,多跑一次只是没有东西可补。
+
+与本机不一致的事实、对上本机两位实体的包项写进 `candidate_root` 下的 `seed-landing.csv`,
+活动页只给条数。
+"""
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+from . import seed_pack
+from .followups import Followup, FollowupType, register
+
+TASK_KEY = "seed-import"
+TASK_LABEL = "导入实体种子"
+REVIEW_FILE = "seed-landing.csv"
+FIELDS = ("kind", "entity", "field", "ours", "source", "theirs", "detail", "batch")
+#: 活动页摘要里的计数键与它们的中文名,按这个顺序拼结论。
+SUMMARY_LABELS = (("aliases", "别名"), ("refs", "编号"), ("links", "链接"), ("profiles", "资料"),
+ ("memberships", "归属"), ("makers", "片商"), ("refreshed", "换新"))
+
+
+def followup_key(version: str) -> str:
+ return f"{TASK_KEY}:{version}"
+
+
+def pack_version(path: Path | None = None) -> str | None:
+ """随仓库走的那份包的版本;没有包或包读不出来就当没有。"""
+ path = Path(path) if path is not None else seed_pack.DEFAULT_PACK
+ if not path.is_file():
+ return None
+ try:
+ return str(seed_pack.load(path)["version"])
+ except (OSError, ValueError):
+ return None
+
+
+def landed(connection: sqlite3.Connection, key: str) -> bool:
+ """这个版本有没有成功导入过:看任务记录里同 key 的后继有没有走到成功。"""
+ return connection.execute(
+ "SELECT 1 FROM task_run WHERE followup_key=? AND status='succeeded' LIMIT 1", (key,)).fetchone() is not None
+
+
+def _new_entities(connection: sqlite3.Connection, since_entity_id: int) -> bool:
+ marks = ",".join("?" * len(seed_pack.KINDS))
+ return connection.execute(
+ f"SELECT 1 FROM entity WHERE id>? AND kind IN ({marks}) LIMIT 1",
+ (int(since_entity_id), *seed_pack.KINDS)).fetchone() is not None
+
+
+def plan(connection: sqlite3.Connection, *, since_entity_id: int, pack_path: Path | None = None) -> list[Followup]:
+ """这一轮该不该派:包的版本没成功导过,或这一轮登记了包里那三类的新实体。"""
+ version = pack_version(pack_path)
+ if version is None:
+ return []
+ key = followup_key(version)
+ if landed(connection, key) and not _new_entities(connection, since_entity_id):
+ return []
+ return [Followup(key=key, task_key=TASK_KEY, label=f"{TASK_LABEL}:{version}")]
+
+
+def _rows(report: dict) -> list[dict]:
+ rows = [{"kind": item["kind"], "entity": item["entity"], "field": item["field"], "ours": item["ours"],
+ "source": item["source"], "theirs": item["theirs"], "batch": report["batch"],
+ "detail": "包里说的与本机不一致;本机这条不是种子写的,种子不动它"}
+ for item in report["conflicts"]]
+ rows += [{"kind": item["kind"], "entity": "、".join(item["entities"]), "field": "identity", "ours": "",
+ "source": "", "theirs": item["name"], "batch": report["batch"],
+ "detail": "包里一条对上本机两位,可能是重复身份;合并不可逆,由人决定"}
+ for item in report["duplicates"]]
+ return rows
+
+
+def record_review(root: Path, report: dict) -> Path:
+ """复核产物整份换成这一轮的:种子导入每次都是全量,上一轮留下的项这一轮要么还在、要么已解决。"""
+ from .review_csv import write_rows
+ path = Path(root) / REVIEW_FILE
+ write_rows(path, FIELDS, _rows(report), atomic=True, fill_missing=True)
+ return path
+
+
+def outcome(report: dict) -> str:
+ parts = [f"{label} {report[key]}" for key, label in SUMMARY_LABELS if report.get(key)]
+ if report["conflicts"]:
+ parts.append(f"不一致 {len(report['conflicts'])}")
+ if report["duplicates"]:
+ parts.append(f"重复身份 {len(report['duplicates'])}")
+ return "、".join(parts) if parts else f"没有可补的(对上 {report['matched']} 位)"
+
+
+def run(contract, key: str, handle) -> dict:
+ """把随仓库走的包补进账本。
+
+ 包的路径只有 `seed_pack.DEFAULT_PACK` 一处:测试把它换成临时目录里的小包,否则仓库里的真包
+ 会给测试账本里的真人名补上站上编号,后面的后继就真的去联网了。
+ """
+ pack = seed_pack.load(seed_pack.DEFAULT_PACK)
+ if handle is not None:
+ handle.progress(label=f"{TASK_LABEL}:{pack['version']}", throttle=0)
+ with contract.database.write_transaction() as connection:
+ report = seed_pack.land(connection, pack)
+ if seed_pack.written(report):
+ contract.cache_bust()
+ record_review(contract.candidate_root, report)
+ return {"outcome": outcome(report), "version": report["version"], "matched": report["matched"],
+ "unmatched": report["unmatched"], **{key: report[key] for key, _label in SUMMARY_LABELS},
+ "conflicts": len(report["conflicts"]), "duplicates": len(report["duplicates"])}
+
+
+#: 写账本:别名、编号、链接、资料、归属与片商都进账本,走写账本那一条串行通道(ADR-0040 第三条)。
+TYPE = register(FollowupType(task_key=TASK_KEY, label=TASK_LABEL, writes_ledger=True, run=run))
diff --git a/src/peach/seed_pack.py b/src/peach/seed_pack.py
index 9b16f7773..13c769c1c 100644
--- a/src/peach/seed_pack.py
+++ b/src/peach/seed_pack.py
@@ -1,13 +1,17 @@
-"""实体事实的种子包:一台机器账本里的公开事实随仓库走,另一台机器只给已有实体填空(ADR-0073)。
+"""实体事实的种子包:一台机器账本里的公开事实随仓库走,另一台机器只给已有实体填空(ADR-0073、ADR-0075)。
导出的是女优、厂牌与事务所名下**能在公开站点上重新查到**的文字事实:别名、站上编号、
-官网与社媒链接、女优资料表、所属事务所。不导任何图像字节、本机路径、刮削残片
-(`entity.metadata_json`、资料的 `raw_json`、链接的 `evidence`)与 Stash 的编号——那些
-要么是本机的,要么是别的用户账本里不可能对上的。
+官网与社媒链接、女优资料表、所属事务所、label 归哪家片商。不导任何图像字节、本机路径、
+刮削残片(`entity.metadata_json`、资料的 `raw_json`、链接的 `evidence`)与 Stash 的编号——
+那些要么是本机的,要么是别的用户账本里不可能对上的。
导入按 ADR-0024 第五条:不造实体。包里的一位女优只有在本机账本已经登记了她(规范名、
别名或站上编号对得上)时才补,补的每一格都是空格(ADR-0052 第三条),归属串 `auto:seed`、
批次 `auto:seed@<版本>`,`scripts/revert_auto_landing.py --source auto:seed` 整批撤回。
+
+会变的事实(所属事务所、label 的片商、资料表)里由种子自己写下的行,新版种子可以整行换掉
+(ADR-0075);人或本机后继写的行不动,包里说的不一样就记进 `conflicts` 等人看。一条对上本机
+两位实体的记进 `duplicates`:那是本机账本里的重复身份信号,合并不可逆,不由种子动手。
"""
from __future__ import annotations
@@ -31,7 +35,13 @@ KINDS = ("performer", "studio", "agency")
EXCLUDED_PROVIDERS = frozenset({"stash"})
#: 导出的链接类型:目录页与来源引用是采集残迹,不是这个人或这家公司自己的地址。
LINK_KINDS = ("official", "social")
-COUNT_KEYS = ("entities", "aliases", "refs", "links", "profiles", "memberships")
+COUNT_KEYS = ("entities", "aliases", "refs", "links", "profiles", "memberships", "makers")
+#: 一对一指向的两张表:包里的键 → (表, 自己那列, 对面那列, 对面的实体种类, 报告里的计数键)。
+#: 所属事务所与 label 的片商都是「主键在自己一侧,转手是覆盖」的形态(ADR-0049),导入共用一段逻辑。
+POINTERS = {
+ "agency": ("entity_membership", "member_id", "agency_id", "agency", "memberships"),
+ "maker": ("label_maker", "label_id", "maker_id", "studio", "makers"),
+}
def batch_of(version: str) -> str:
@@ -55,6 +65,11 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _name(connection: sqlite3.Connection, entity_id: int) -> str:
+ row = connection.execute("SELECT canonical_name FROM entity WHERE id=?", (entity_id,)).fetchone()
+ return str(row[0]) if row else str(entity_id)
+
+
# -- 导出 ----------------------------------------------------------------------
@@ -113,10 +128,12 @@ def _profile(connection: sqlite3.Connection, entity_id: int) -> dict | None:
"fetched_at": str(found["fetched_at"])}
-def _agency(connection: sqlite3.Connection, entity_id: int) -> dict | None:
+def _pointer(connection: sqlite3.Connection, entity_id: int, field: str) -> dict | None:
+ """这位指向的那一个(所属事务所、label 的片商):对面的规范名与这条关系的来源;种子写的不导。"""
+ table, own, other, _kind, _count = POINTERS[field]
row = connection.execute(
- "SELECT a.canonical_name,m.source FROM entity_membership m JOIN entity a ON a.id=m.agency_id"
- " WHERE m.member_id=?", (entity_id,)).fetchone()
+ f"SELECT t.canonical_name,p.source FROM {table} p JOIN entity t ON t.id=p.{other} WHERE p.{own}=?",
+ (entity_id,)).fetchone()
if row is None or _ours(row[1]):
return None
return {"name": str(row[0]), "source": str(row[1])}
@@ -132,12 +149,13 @@ def export_pack(connection: sqlite3.Connection, *, version: str) -> dict:
item = {"kind": str(kind), "name": str(name), "aliases": _aliases(connection, entity_id, str(kind)),
"refs": _refs(connection, entity_id), "links": _links(connection, entity_id)}
if kind == "performer":
- profile, agency = _profile(connection, entity_id), _agency(connection, entity_id)
- if profile:
- item["profile"] = profile
- if agency:
- item["agency"] = agency
- if not (item["aliases"] or item["refs"] or item["links"] or "profile" in item or "agency" in item):
+ item.update({key: value for key, value in (("profile", _profile(connection, entity_id)),
+ ("agency", _pointer(connection, entity_id, "agency")))
+ if value})
+ elif kind == "studio":
+ item.update({key: value for key, value in (("maker", _pointer(connection, entity_id, "maker")),)
+ if value})
+ if not (item["aliases"] or item["refs"] or item["links"] or {"profile", "agency", "maker"} & set(item)):
continue
entities.append(item)
counts["entities"] += 1
@@ -146,6 +164,7 @@ def export_pack(connection: sqlite3.Connection, *, version: str) -> dict:
counts["links"] += len(item["links"])
counts["profiles"] += "profile" in item
counts["memberships"] += "agency" in item
+ counts["makers"] += "maker" in item
return {"format": FORMAT, "version": version, "source": SOURCE, "counts": counts, "entities": entities}
@@ -164,11 +183,8 @@ def load(path) -> dict:
# -- 导入 ----------------------------------------------------------------------
-def match_entity(connection: sqlite3.Connection, item: dict) -> int | None:
- """包里这一条对应本机哪个实体:规范名、每个写法、每个站上编号各自去认,认出来的必须是同一位。
-
- 认出两位就返回 None,哪怕其中一位是规范名逐字相同:名字对上 A、编号却挂在 B 名下,说明
- 本机账本里这两条里至少有一条是错的,指错人比漏补糟得多,这样的留给人看。"""
+def matches(connection: sqlite3.Connection, item: dict) -> set[int]:
+ """包里这一条按规范名、每个写法、每个站上编号各自去认,认出来的本机实体 id 全部返回。"""
kind = item["kind"]
keys = [normalize_entity_name(name) for name in
(item["name"], *(alias["alias"] for alias in item.get("aliases") or []))]
@@ -184,6 +200,15 @@ def match_entity(connection: sqlite3.Connection, item: dict) -> int | None:
found |= {int(row[0]) for row in connection.execute(
f"SELECT e.id FROM entity_external_ref r JOIN entity e ON e.id=r.entity_id"
f" WHERE e.kind=? AND ({clause})", (kind, *values))}
+ return found
+
+
+def match_entity(connection: sqlite3.Connection, item: dict) -> int | None:
+ """包里这一条对应本机哪个实体:认出来的必须是同一位。
+
+ 认出两位就返回 None,哪怕其中一位是规范名逐字相同:名字对上 A、编号却挂在 B 名下,说明
+ 本机账本里这两条里至少有一条是错的,指错人比漏补糟得多,这样的留给人看。"""
+ found = matches(connection, item)
return found.pop() if len(found) == 1 else None
@@ -253,56 +278,100 @@ def _land_links(connection, entity_id: int, item: dict, batch: str, stamp: str)
return written
-def _land_profile(connection, entity_id: int, item: dict, batch: str) -> int:
- """资料只给没有资料的那位写:`write_profile` 会整行替换自动来源的行,本机后继刚刮的
- 比种子新,不能被盖掉。"""
+def _land_profile(connection, entity_id: int, item: dict, batch: str, report: dict) -> None:
+ """资料只给没有资料行的写;种子自己写的那一行,包里取回时间更晚才整行换掉。本机后继刮的
+ 资料比种子新,也由它自己按期刷新,`write_profile` 对自动来源的整行替换在这里不碰它。"""
profile = item.get("profile")
- if not profile or item["kind"] != "performer" or read_profile(connection, entity_id) is not None:
- return 0
+ if not profile or item["kind"] != "performer":
+ return
+ current = read_profile(connection, entity_id)
+ if current is not None and not (_ours(current.get("source"))
+ and str(profile.get("fetched_at") or "") > str(current.get("fetched_at") or "")):
+ return
fields = dict(profile.get("fields") or {})
fields["raw"] = {}
- return int(write_profile(connection, entity_id, fields, source=batch,
- source_url=str(profile.get("source_url") or ""),
- fetched_at=str(profile.get("fetched_at") or "") or None))
-
-
-def _land_membership(connection, entity_id: int, item: dict, batch: str, stamp: str) -> int:
- """所属事务所只在本机已经有这家事务所、这位又还没有归属时写;不造事务所实体。"""
- agency = item.get("agency")
- if not agency or item["kind"] != "performer":
- return 0
- if connection.execute("SELECT 1 FROM entity_membership WHERE member_id=?", (entity_id,)).fetchone():
- return 0
- agency_id = match_entity(connection, {"kind": "agency", "name": agency["name"]})
- if agency_id is None:
- return 0
- connection.execute(
- "INSERT OR IGNORE INTO entity_membership(member_id,agency_id,source,confidence,checked_at)"
- " VALUES(?,?,?,1.0,?)", (entity_id, agency_id, batch, stamp))
- return connection.execute("SELECT changes()").fetchone()[0]
+ write_profile(connection, entity_id, fields, source=batch,
+ source_url=str(profile.get("source_url") or ""),
+ fetched_at=str(profile.get("fetched_at") or "") or None)
+ report["refreshed" if current is not None else "profiles"] += 1
+
+
+def _loops(connection, table: str, own: str, other: str, start: int, target: int, limit: int = 32) -> bool:
+ """从对面那位沿同一张表往上走会不会绕回自己:label 的片商可以再有片商(ADR-0051),成环不写。"""
+ current, depth = target, 0
+ while current is not None and depth < limit:
+ if current == start:
+ return True
+ row = connection.execute(f"SELECT {other} FROM {table} WHERE {own}=?", (current,)).fetchone()
+ current, depth = (int(row[0]) if row else None), depth + 1
+ return False
+
+
+def _land_pointer(connection, entity_id: int, item: dict, field: str, batch: str, stamp: str,
+ report: dict) -> None:
+ """所属事务所与 label 的片商:本机没有就写,种子自己写的指向变了就换成新批次,人写的
+ 与包里不一致就记进 `conflicts`。不造对面那个实体,对面对不上就什么都不做。"""
+ fact = item.get(field)
+ if not fact:
+ return
+ table, own, other, kind, count = POINTERS[field]
+ target = match_entity(connection, {"kind": kind, "name": fact["name"]})
+ if target is None or target == entity_id or _loops(connection, table, own, other, entity_id, target):
+ return
+ row = connection.execute(
+ f"SELECT p.{other},p.source,t.canonical_name FROM {table} p JOIN entity t ON t.id=p.{other}"
+ f" WHERE p.{own}=?", (entity_id,)).fetchone()
+ if row is None:
+ connection.execute(f"INSERT INTO {table}({own},{other},source,confidence,checked_at) VALUES(?,?,?,1.0,?)",
+ (entity_id, target, batch, stamp))
+ report[count] += 1
+ elif int(row[0]) == target:
+ return
+ elif _ours(row[1]):
+ connection.execute(f"UPDATE {table} SET {other}=?,source=?,checked_at=? WHERE {own}=?",
+ (target, batch, stamp, entity_id))
+ report["refreshed"] += 1
+ else:
+ report["conflicts"].append({"kind": item["kind"], "entity": _name(connection, entity_id), "field": field,
+ "ours": str(row[2]), "source": str(row[1]), "theirs": str(fact["name"])})
+
+
+def _land_one(connection, entity_id: int, item: dict, version: str, batch: str, stamp: str, report: dict) -> None:
+ report["aliases"] += _land_aliases(connection, entity_id, item, version, batch)
+ report["refs"] += _land_refs(connection, entity_id, item, batch, stamp)
+ report["links"] += _land_links(connection, entity_id, item, batch, stamp)
+ _land_profile(connection, entity_id, item, batch, report)
+ for field in POINTERS:
+ _land_pointer(connection, entity_id, item, field, batch, stamp, report)
+
+
+def written(report: dict) -> int:
+ """这次导入动了多少行:补上的加换掉的。"""
+ return sum(int(report.get(key, 0)) for key in (*COUNT_KEYS[1:], "refreshed"))
def land(connection: sqlite3.Connection, pack: dict) -> dict:
- """把包里的事实补进这本账,返回逐类计数。调用方负责事务与备份;dry-run 走 `plan`。"""
+ """把包里的事实补进这本账,返回逐类计数与两张明细(`conflicts`、`duplicates`)。
+ 调用方负责事务与备份;dry-run 走 `plan`。同一包再跑一遍不会再动任何一行。"""
version, batch, stamp = str(pack["version"]), batch_of(str(pack["version"])), _now()
report = {"version": version, "batch": batch, "matched": 0, "unmatched": 0,
- **dict.fromkeys(COUNT_KEYS[1:], 0)}
+ **dict.fromkeys(COUNT_KEYS[1:], 0), "refreshed": 0, "conflicts": [], "duplicates": []}
for item in pack.get("entities") or []:
- entity_id = match_entity(connection, item)
- if entity_id is None:
+ found = matches(connection, item)
+ if len(found) > 1:
+ report["duplicates"].append({"kind": item["kind"], "name": item["name"],
+ "entities": sorted(_name(connection, entity_id) for entity_id in found)})
+ continue
+ if not found:
report["unmatched"] += 1
continue
report["matched"] += 1
- report["aliases"] += _land_aliases(connection, entity_id, item, version, batch)
- report["refs"] += _land_refs(connection, entity_id, item, batch, stamp)
- report["links"] += _land_links(connection, entity_id, item, batch, stamp)
- report["profiles"] += _land_profile(connection, entity_id, item, batch)
- report["memberships"] += _land_membership(connection, entity_id, item, batch, stamp)
+ _land_one(connection, found.pop(), item, version, batch, stamp, report)
return report
def plan(connection: sqlite3.Connection, pack: dict) -> dict:
- """dry-run:在只读账本的内存副本上跑一遍 `land`,交出同样的计数,本机账本一字不动。"""
+ """dry-run:在只读账本的内存副本上跑一遍 `land`,交出同样的报告,本机账本一字不动。"""
scratch = sqlite3.connect(":memory:")
try:
connection.backup(scratch)
diff --git a/src/peach/task_runs.py b/src/peach/task_runs.py
index ffe441188..9dd78eb2d 100644
--- a/src/peach/task_runs.py
+++ b/src/peach/task_runs.py
@@ -92,6 +92,7 @@ TASK_LABELS = {
"feed-check": "订阅源拉取",
"feed-scrape": "取新作资料",
"timeline-thumbnails": "视频缩略图采集",
+ "seed-import": "导入实体种子",
}
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index cf31ddd5d..763700454 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -163,6 +163,7 @@ class WebContract:
from . import performer_alias_followup # noqa: F401 登记补女优别名后继
from . import performer_profile_followup # noqa: F401 登记补女优资料后继
from . import sample_followup # noqa: F401 登记补番号样张后继
+ from . import seed_followup # noqa: F401 登记导入实体种子后继
from . import studio_followup # noqa: F401 登记补厂牌官网与标识后继
from .followups import FollowupRunner
self.followups = FollowupRunner(self)
diff --git a/tests/test_followups.py b/tests/test_followups.py
index 0e91514b8..baf8caabd 100644
--- a/tests/test_followups.py
+++ b/tests/test_followups.py
@@ -10,6 +10,7 @@ from types import SimpleNamespace
from unittest import mock
from peach import followups as followups_module
+from peach import seed_followup, seed_pack
from peach import task_runs as task_runs_module
from peach.avatar_followup import TASK_KEY as AVATAR_TASK_KEY
from peach.avatar_followup import followup_key, parse_key, plan
@@ -1047,8 +1048,23 @@ class ProcessLibraryTests(LedgerTestCase):
这里不桩 `avatar_followup`:跑的就是补头像那条后继本身。图库索引在临时数据根下是空的,
封面目录也是空的,于是它两档都给不出图并正常收尾——判不准不装图,本来就是这条后继的判据。
+ 实体种子换成临时目录里的一份小包(`seed()`):仓库里的真包会给这位真人补上 avwikidb 编号,
+ 补头像那条就会真的去站上找单人作品,结论随当天有没有网而变。
"""
+ def seed(self) -> Path:
+ """一份只给 `涼森れむ` 补一条别名的种子包,替掉仓库里的真包。"""
+ pack = self.root / 'seed.json'
+ pack.write_text(seed_pack.dump({
+ 'format': 1, 'version': '2026-09-25', 'source': 'auto:seed', 'counts': {},
+ 'entities': [{'kind': 'performer', 'name': '涼森れむ', 'refs': [], 'links': [],
+ 'aliases': [{'alias': '鈴森れむ', 'source': 'r18:performer'}]}],
+ }), encoding='utf-8')
+ patcher = mock.patch.object(seed_pack, 'DEFAULT_PACK', pack)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ return pack
+
def sample(self):
from peach.settings_file import PeachConfig
@@ -1076,6 +1092,7 @@ class ProcessLibraryTests(LedgerTestCase):
@windows_ledger_roots
def test_a_scrape_declares_dispatches_and_runs_its_avatar_followups(self):
_media, config = self.sample()
+ self.seed()
result = process_library(config, self.db, self.root / 'generated',
self.root / 'covers',
provider_factory=mock.Mock(return_value=self.provider()),
@@ -1085,10 +1102,12 @@ class ProcessLibraryTests(LedgerTestCase):
entity_id = connection.execute(
"SELECT id FROM entity WHERE kind='performer'"
" AND canonical_name='涼森れむ'").fetchone()[0]
- # 一、刮削自己声明了后继,实体身份就在 key 里:补头像、补别名、补女优资料各一条。
+ # 一、刮削自己声明了后继:随仓库走的实体种子一条排最前(ADR-0075),再是这位新女优的
+ # 补头像、补别名、补女优资料各一条,实体身份就在 key 里。
from peach import performer_alias_followup, performer_profile_followup
self.assertEqual([item['key'] for item in result['followups']],
- [followup_key('performer', entity_id),
+ [seed_followup.followup_key('2026-09-25'),
+ followup_key('performer', entity_id),
performer_alias_followup.followup_key(entity_id),
performer_profile_followup.followup_key(entity_id)])
@@ -1097,7 +1116,7 @@ class ProcessLibraryTests(LedgerTestCase):
queued = self.store.enqueue_followups(
parent.id, [(item['key'], item['task_key'], item['label'])
for item in result['followups']])['queued']
- self.assertEqual(len(queued), 3)
+ self.assertEqual(len(queued), 4)
# 三、真的被跑掉,收在终态。补别名、补女优资料的各站都换成取不到页的替身,不联网。
class Offline:
@@ -1119,12 +1138,16 @@ class ProcessLibraryTests(LedgerTestCase):
with mock.patch.object(performer_alias_followup, 'open_sites', return_value=offline), \
mock.patch.object(performer_profile_followup, 'open_sites',
return_value=profile_offline):
- self.assertEqual(FollowupRunner(contract).drain(), 3)
- done = self.store.get(queued[0])
+ self.assertEqual(FollowupRunner(contract).drain(), 4)
+ seeded = self.store.get(queued[0])
+ self.assertEqual((seeded.status, seeded.result_summary['outcome']), ('succeeded', '别名 1'))
+ self.assertTrue((self.root / 'generated' / seed_followup.REVIEW_FILE).exists(),
+ '种子导入跑完留下复核产物,哪怕这一轮没有可看的项')
+ done = self.store.get(queued[1])
self.assertEqual(done.status, 'succeeded')
self.assertEqual(done.result_summary['outcome'], '图库里没有这个名字,封面上没有能截的脸')
- self.assertEqual(self.store.get(queued[1]).result_summary['outcome'], '未取得')
- self.assertEqual(self.store.get(queued[2]).status, 'succeeded')
+ self.assertEqual(self.store.get(queued[2]).result_summary['outcome'], '未取得')
+ self.assertEqual(self.store.get(queued[3]).status, 'succeeded')
self.assertFalse((self.root / 'generated' / 'avatars'
/ f'performer-{entity_id}.img').exists())
diff --git a/tests/test_seed_followup.py b/tests/test_seed_followup.py
new file mode 100644
index 000000000..7d34ed19d
--- /dev/null
+++ b/tests/test_seed_followup.py
@@ -0,0 +1,125 @@
+"""导入实体种子后继:扫描结算时按版本与新实体决定派不派,跑一次把包补进账本并留下复核产物(ADR-0075)。"""
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+from peach import seed_followup, seed_pack
+from peach.entities import normalize_entity_name
+from peach.repository import LedgerDatabase
+from peach.review_csv import read_rows
+from peach.task_runs import TaskRunStore
+from support.ledger import fresh_ledger
+
+VERSION = "2026-09-25"
+STAMP = "2026-09-25T00:00:00Z"
+PACK = {"format": 1, "version": VERSION, "source": "auto:seed", "counts": {}, "entities": [
+ {"kind": "performer", "name": "天川そら", "aliases": [{"alias": "春山心愛", "source": "r18:performer"}],
+ "refs": [], "links": [{"kind": "social", "label": "X", "url": "https://x.com/amakawa_sora_"}],
+ "agency": {"name": "STARTUP", "source": "minnano-av:所属事務所"}},
+ {"kind": "studio", "name": "PRESTIGE PREMIUM", "aliases": [], "refs": [], "links": [],
+ "maker": {"name": "Prestige", "source": "review:label-maker-20260923.csv"}},
+]}
+
+
+class Case(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.database = LedgerDatabase(fresh_ledger(self.root))
+ self.store = TaskRunStore(self.database, host="test-host")
+ self.pack = self.root / "entities.json"
+ self.pack.write_text(seed_pack.dump(PACK), encoding="utf-8")
+ patcher = mock.patch.object(seed_pack, "DEFAULT_PACK", self.pack)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.candidates = self.root / "candidates"
+ self.candidates.mkdir()
+ self.busts = 0
+ self.contract = SimpleNamespace(database=self.database, candidate_root=self.candidates,
+ cache_bust=self._bust)
+
+ def _bust(self) -> None:
+ self.busts += 1
+
+ def add(self, kind: str, name: str) -> int:
+ with self.database.write_transaction() as connection:
+ connection.execute(
+ "INSERT INTO entity(kind,canonical_name,normalized_name,metadata_json,created_at,updated_at)"
+ " VALUES(?,?,?,'{}',?,?)", (kind, name, normalize_entity_name(name), STAMP, STAMP))
+ return int(connection.execute("SELECT last_insert_rowid()").fetchone()[0])
+
+ def plan(self, since_entity_id: int):
+ with self.database.read_connection() as connection:
+ return seed_followup.plan(connection, since_entity_id=since_entity_id)
+
+ def finished_run(self, key: str) -> None:
+ """任务记录里留一条这个 key 的成功后继:父任务派它,通道认领,跑完。"""
+ parent = self.store.start("library-processing", trigger="manual")
+ self.store.enqueue_followups(parent.id, [(key, seed_followup.TASK_KEY, "x")])
+ child = self.store.claim_followup([seed_followup.TASK_KEY])
+ self.store.finish(child.id, "succeeded", summary={})
+ self.store.finish(parent.id, "succeeded", summary={})
+
+
+class PlanTests(Case):
+ def test_without_a_pack_nothing_is_planned(self):
+ with self.database.read_connection() as connection:
+ self.assertEqual(seed_followup.plan(connection, since_entity_id=0,
+ pack_path=self.root / "missing.json"), [])
+
+ def test_a_version_never_landed_is_planned_even_without_new_entities(self):
+ found = self.plan(since_entity_id=10 ** 9)
+ self.assertEqual([(item.key, item.task_key, item.label) for item in found],
+ [(f"seed-import:{VERSION}", "seed-import", f"导入实体种子:{VERSION}")])
+
+ def test_a_landed_version_is_planned_again_only_when_new_entities_appear(self):
+ self.finished_run(seed_followup.followup_key(VERSION))
+ self.assertEqual(self.plan(since_entity_id=10 ** 9), [], "导过、又没有新实体,不再派")
+ her = self.add("performer", "天川そら")
+ self.assertEqual(len(self.plan(since_entity_id=her - 1)), 1, "这一轮登记了新女优,再派一次给她补")
+ self.add("tag", "标签不算")
+ self.assertEqual(self.plan(since_entity_id=her), [], "只有标签这类包里没有的种类,不派")
+
+
+class RunTests(Case):
+ def test_run_lands_the_pack_and_writes_the_review_file(self):
+ her, kmp = self.add("performer", "天川そら"), self.add("studio", "K M Produce")
+ self.add("agency", "STARTUP")
+ label, maker = self.add("studio", "PRESTIGE PREMIUM"), self.add("studio", "Prestige")
+ with self.database.write_transaction() as connection:
+ connection.execute("INSERT INTO label_maker(label_id,maker_id,source,confidence,checked_at)"
+ " VALUES(?,?,?,1.0,?)", (label, kmp, "review:user", STAMP))
+ summary = seed_followup.run(self.contract, seed_followup.followup_key(VERSION), None)
+ self.assertEqual((summary["matched"], summary["aliases"], summary["links"], summary["memberships"],
+ summary["makers"], summary["conflicts"], summary["duplicates"]), (2, 1, 1, 1, 0, 1, 0))
+ self.assertEqual(summary["outcome"], "别名 1、链接 1、归属 1、不一致 1")
+ self.assertEqual(self.busts, 1, "动了账本就清一次聚合缓存")
+ with self.database.read_connection() as connection:
+ self.assertEqual(connection.execute("SELECT maker_id FROM label_maker WHERE label_id=?",
+ (label,)).fetchone()[0], kmp, "人复核过的片商不被种子改")
+ self.assertEqual(connection.execute("SELECT count(*) FROM entity_alias WHERE entity_id=?",
+ (her,)).fetchone()[0], 1)
+ rows = read_rows(self.candidates / seed_followup.REVIEW_FILE)
+ self.assertEqual([(row["entity"], row["field"], row["ours"], row["theirs"]) for row in rows],
+ [("PRESTIGE PREMIUM", "maker", "K M Produce", "Prestige")])
+ again = seed_followup.run(self.contract, seed_followup.followup_key(VERSION), None)
+ self.assertEqual((again["aliases"], again["links"], again["memberships"], again["refreshed"]), (0, 0, 0, 0),
+ "同一包再跑一遍没有东西可补")
+ self.assertEqual(self.busts, 1, "没动账本就不清缓存")
+ self.assertTrue(again["outcome"].startswith("不一致 1"), again["outcome"])
+
+ def test_two_local_entities_for_one_pack_item_become_a_duplicate_row(self):
+ self.add("performer", "天川そら")
+ self.add("performer", "春山心愛")
+ summary = seed_followup.run(self.contract, seed_followup.followup_key(VERSION), None)
+ self.assertEqual((summary["matched"], summary["duplicates"]), (0, 1))
+ rows = read_rows(self.candidates / seed_followup.REVIEW_FILE)
+ self.assertEqual([(row["field"], row["entity"], row["theirs"]) for row in rows],
+ [("identity", "天川そら、春山心愛", "天川そら")])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_seed_pack.py b/tests/test_seed_pack.py
index 7947ef902..0590bd080 100644
--- a/tests/test_seed_pack.py
+++ b/tests/test_seed_pack.py
@@ -1,4 +1,5 @@
-"""实体事实种子包:导出只带公开事实且逐字节稳定,导入只给已有实体填空,整批可撤(ADR-0073)。
+"""实体事实种子包:导出只带公开事实且逐字节稳定,导入只给已有实体填空、只换种子自己写过的行,
+整批可撤(ADR-0073、ADR-0075)。
全程两本临时账本:一本当导出方,一本当另一台机器。
"""
@@ -68,6 +69,11 @@ def membership(connection, member_id: int, agency_id: int, source: str) -> None:
" VALUES(?,?,?,1.0,?)", (member_id, agency_id, source, STAMP))
+def label_maker(connection, label_id: int, maker_id: int, source: str) -> None:
+ connection.execute("INSERT INTO label_maker(label_id,maker_id,source,confidence,checked_at)"
+ " VALUES(?,?,?,1.0,?)", (label_id, maker_id, source, STAMP))
+
+
PROFILE = {"kana": "あまかわそら", "birth_date": "1998-10-10", "height_cm": 164, "cup": "G",
"tags": ["巨乳", "美肌"], "raw": {"名前": "天川そら", "サイズ": "T164 / B87"}}
@@ -81,13 +87,17 @@ class SeedPackCase(unittest.TestCase):
self.addCleanup(self.target.close)
def seeded_source(self) -> dict:
- """导出方账本:一位有全套事实的女优、她的事务所、一家带别名的厂牌、一位只有名字的女优。"""
+ """导出方账本:一位有全套事实的女优、她的事务所、一家带别名的厂牌、一个归属片商的 label、
+ 一位只有名字的女优。"""
con = self.source
with con:
sora = entity(con, "performer", "天川そら")
agency = entity(con, "agency", "STARTUP")
studio = entity(con, "studio", "S1 NO.1 STYLE")
+ maker = entity(con, "studio", "Prestige")
+ label = entity(con, "studio", "PRESTIGE PREMIUM")
entity(con, "performer", "只有名字")
+ label_maker(con, label, maker, "review:label-maker-20260923.csv")
alias(con, sora, "春山心愛", "r18:performer")
alias(con, sora, "Amakawa Sora", "r18:performer")
alias(con, sora, "そら", "javdb-actor-page@javdb-20260912")
@@ -114,11 +124,14 @@ class ExportTests(SeedPackCase):
def test_pack_carries_public_facts_and_nothing_local(self):
pack = self.seeded_source()
self.assertEqual(pack["version"], VERSION)
- self.assertEqual(pack["counts"], {"entities": 2, "aliases": 3, "refs": 1, "links": 3,
- "profiles": 1, "memberships": 1})
+ self.assertEqual(pack["counts"], {"entities": 3, "aliases": 3, "refs": 1, "links": 3,
+ "profiles": 1, "memberships": 1, "makers": 1})
by_name = {item["name"]: item for item in pack["entities"]}
- self.assertEqual(list(by_name), ["天川そら", "S1 NO.1 STYLE"], "按种类与归一名排序")
+ self.assertEqual(list(by_name), ["天川そら", "PRESTIGE PREMIUM", "S1 NO.1 STYLE"], "按种类与归一名排序")
self.assertNotIn("STARTUP", by_name, "事务所自己没有可补的事实,只作为她的归属出现")
+ self.assertNotIn("Prestige", by_name, "片商自己没有可补的事实,只作为 label 的归属出现")
+ self.assertEqual(by_name["PRESTIGE PREMIUM"]["maker"],
+ {"name": "Prestige", "source": "review:label-maker-20260923.csv"})
sora = by_name["天川そら"]
self.assertEqual([(a["alias"], a["source"]) for a in sora["aliases"]],
[("二宮そら", "javdb-actor-page@javdb-20260912"), ("春山心愛", "r18:performer")],
@@ -146,12 +159,13 @@ class ExportTests(SeedPackCase):
class ImportTests(SeedPackCase):
def seeded_target(self) -> dict[str, int]:
- """另一台机器:账本里她叫「春山心愛」,事务所已登记,厂牌只有名字;「天川そら」这条包里
- 的另一位 `未登记` 本机没有。"""
+ """另一台机器:账本里她叫「春山心愛」,事务所已登记,厂牌、label 与片商都只有名字;
+ 包里的另一位 `未登记` 本机没有。"""
con = self.target
with con:
ids = {"her": entity(con, "performer", "春山心愛"), "agency": entity(con, "agency", "STARTUP"),
- "studio": entity(con, "studio", "S1 NO.1 STYLE"), "other": entity(con, "performer", "别人")}
+ "studio": entity(con, "studio", "S1 NO.1 STYLE"), "other": entity(con, "performer", "别人"),
+ "label": entity(con, "studio", "PRESTIGE PREMIUM"), "maker": entity(con, "studio", "Prestige")}
return ids
def test_only_existing_entities_get_their_blanks_filled(self):
@@ -161,8 +175,9 @@ class ImportTests(SeedPackCase):
ids = self.seeded_target()
with self.target:
report = seed_pack.land(self.target, pack)
- self.assertEqual(report, {"version": VERSION, "batch": BATCH, "matched": 2, "unmatched": 1,
- "aliases": 3, "refs": 1, "links": 3, "profiles": 1, "memberships": 1})
+ self.assertEqual(report, {"version": VERSION, "batch": BATCH, "matched": 3, "unmatched": 1,
+ "aliases": 3, "refs": 1, "links": 3, "profiles": 1, "memberships": 1,
+ "makers": 1, "refreshed": 0, "conflicts": [], "duplicates": []})
her = ids["her"]
rows = self.target.execute("SELECT alias,source FROM entity_alias WHERE entity_id=? ORDER BY alias",
(her,)).fetchall()
@@ -188,7 +203,10 @@ class ImportTests(SeedPackCase):
studio_alias = self.target.execute("SELECT alias,source FROM entity_alias WHERE entity_id=?",
(ids["studio"],)).fetchone()
self.assertEqual(tuple(studio_alias), ("S1", BATCH))
- self.assertEqual(self.target.execute("SELECT count(*) FROM entity").fetchone()[0], 4, "不造实体")
+ maker = self.target.execute("SELECT maker_id,source FROM label_maker WHERE label_id=?",
+ (ids["label"],)).fetchone()
+ self.assertEqual(tuple(maker), (ids["maker"], BATCH), "label 归哪家片商也补上,来源是批次号")
+ self.assertEqual(self.target.execute("SELECT count(*) FROM entity").fetchone()[0], 6, "不造实体")
def test_seed_never_overwrites_what_the_ledger_already_holds(self):
pack = self.seeded_source()
@@ -199,10 +217,18 @@ class ImportTests(SeedPackCase):
membership(self.target, ids["her"], ids["agency"], "review:user")
link(self.target, ids["her"], "social", "https://X.com/amakawa_sora_")
alias(self.target, ids["her"], "二宮そら", "user:manual")
+ kmp = entity(self.target, "studio", "K M Produce")
+ label_maker(self.target, ids["label"], kmp, "review:user")
with self.target:
report = seed_pack.land(self.target, pack)
self.assertEqual((report["profiles"], report["refs"], report["memberships"], report["links"],
- report["aliases"]), (0, 1, 0, 2, 2))
+ report["aliases"], report["makers"], report["refreshed"]), (0, 1, 0, 2, 2, 0, 0))
+ self.assertEqual(report["conflicts"],
+ [{"kind": "studio", "entity": "PRESTIGE PREMIUM", "field": "maker", "ours": "K M Produce",
+ "source": "review:user", "theirs": "Prestige"}],
+ "人复核过的片商与包里不一致:不动,记进明细等人看")
+ self.assertEqual(self.target.execute("SELECT maker_id FROM label_maker WHERE label_id=?",
+ (ids["label"],)).fetchone()[0], kmp)
self.assertEqual(self.target.execute("SELECT count(*) FROM entity_link WHERE entity_id=?",
(ids["her"],)).fetchone()[0], 2,
"本机那条主机大写的同一地址不再补一条只差大小写的")
@@ -215,6 +241,30 @@ class ImportTests(SeedPackCase):
self.assertEqual([tuple(row) for row in rows], [("二宮そら", "user:manual"), ("天川そら", BATCH)],
"已有的写法保留原来源,只补缺的那个")
+ def test_a_newer_seed_replaces_what_an_older_seed_wrote(self):
+ pack = self.seeded_source()
+ ids = self.seeded_target()
+ with self.target:
+ old_agency = entity(self.target, "agency", "旧事务所")
+ old_maker = entity(self.target, "studio", "旧片商")
+ membership(self.target, ids["her"], old_agency, "auto:seed@2026-01-01")
+ label_maker(self.target, ids["label"], old_maker, "auto:seed@2026-01-01")
+ write_profile(self.target, ids["her"], {"kana": "旧种子写的", "raw": {}}, source="auto:seed@2026-01-01",
+ source_url="https://example/", fetched_at="2026-01-01T00:00:00Z")
+ with self.target:
+ report = seed_pack.land(self.target, pack)
+ self.assertEqual((report["memberships"], report["makers"], report["profiles"], report["refreshed"],
+ report["conflicts"]), (0, 0, 0, 3, []), "旧种子写的三行都换成新批次,不算新补也不算冲突")
+ self.assertEqual(tuple(self.target.execute("SELECT agency_id,source FROM entity_membership WHERE member_id=?",
+ (ids["her"],)).fetchone()), (ids["agency"], BATCH))
+ self.assertEqual(tuple(self.target.execute("SELECT maker_id,source FROM label_maker WHERE label_id=?",
+ (ids["label"],)).fetchone()), (ids["maker"], BATCH))
+ profile = read_profile(self.target, ids["her"])
+ self.assertEqual((profile["kana"], profile["source"]), ("あまかわそら", BATCH))
+ with self.target:
+ again = seed_pack.land(self.target, pack)
+ self.assertEqual(seed_pack.written(again), 0, "同一包再跑一遍不再动任何一行")
+
def test_a_name_on_one_entity_and_a_number_on_another_matches_nobody(self):
pack = self.seeded_source()
ids = self.seeded_target()
@@ -222,7 +272,9 @@ class ImportTests(SeedPackCase):
ref(self.target, ids["other"], "minnano-av", "295275")
with self.target:
report = seed_pack.land(self.target, pack)
- self.assertEqual((report["matched"], report["unmatched"]), (1, 1), "只有厂牌对上了")
+ self.assertEqual((report["matched"], report["unmatched"], report["duplicates"]),
+ (2, 0, [{"kind": "performer", "name": "天川そら", "entities": ["别人", "春山心愛"]}]),
+ "两家厂牌对上了;她那条认出两位,记进重复身份明细")
for entity_id in (ids["her"], ids["other"]):
self.assertEqual(self.target.execute("SELECT count(*) FROM entity_alias WHERE entity_id=?",
(entity_id,)).fetchone()[0], 0, "名字与编号各指一位,谁都不动")
@@ -236,7 +288,8 @@ class ImportTests(SeedPackCase):
second = entity(self.target, "performer", "二宮そら")
with self.target:
report = seed_pack.land(self.target, pack)
- self.assertEqual((report["matched"], report["unmatched"]), (0, 2))
+ self.assertEqual((report["matched"], report["unmatched"], report["duplicates"]),
+ (0, 2, [{"kind": "performer", "name": "天川そら", "entities": ["二宮そら", "春山心愛"]}]))
for entity_id in (first, second):
self.assertEqual(self.target.execute("SELECT count(*) FROM entity_alias WHERE entity_id=?",
(entity_id,)).fetchone()[0], 0, "两位都对得上就谁都不动")
@@ -246,10 +299,10 @@ class ImportTests(SeedPackCase):
self.seeded_target()
before = self.target.execute("SELECT count(*) FROM entity_alias").fetchone()[0]
report = seed_pack.plan(self.target, pack)
- self.assertEqual((report["matched"], report["aliases"], report["profiles"]), (2, 3, 1))
+ self.assertEqual((report["matched"], report["aliases"], report["profiles"]), (3, 3, 1))
self.assertEqual(self.target.execute("SELECT count(*) FROM entity_alias").fetchone()[0], before)
- def test_a_seed_batch_is_reverted_across_all_five_tables(self):
+ def test_a_seed_batch_is_reverted_across_all_six_tables(self):
pack = self.seeded_source()
ids = self.seeded_target()
with self.target:
@@ -262,6 +315,7 @@ class ImportTests(SeedPackCase):
with contextlib.redirect_stdout(io.StringIO()) as out:
self.assertEqual(revert.main(base), 0)
self.assertIn("'归属': 1", out.getvalue())
+ self.assertIn("'片商': 1", out.getvalue())
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(revert.main([*base, "--apply", "--backup", str(self.root / "backup.db")]), 0)
con = connect(db)
@@ -269,8 +323,8 @@ class ImportTests(SeedPackCase):
counts = [con.execute(sql).fetchone()[0] for sql in (
"SELECT count(*) FROM entity_alias", "SELECT count(*) FROM entity_external_ref",
"SELECT count(*) FROM entity_link", "SELECT count(*) FROM performer_profile",
- "SELECT count(*) FROM entity_membership")]
- self.assertEqual(counts, [1, 0, 0, 0, 0], "只剩人写的那条别名")
+ "SELECT count(*) FROM entity_membership", "SELECT count(*) FROM label_maker")]
+ self.assertEqual(counts, [1, 0, 0, 0, 0, 0], "只剩人写的那条别名")
class ScriptTests(SeedPackCase):
@@ -286,7 +340,7 @@ class ScriptTests(SeedPackCase):
script.main(["export", "--db", str(self.root / "source.db"), "--version", VERSION, "--out", str(out)])
self.assertEqual((json.loads(first.getvalue())["changed"], json.loads(second.getvalue())["changed"]),
(True, False))
- self.assertEqual(seed_pack.load(out)["counts"]["entities"], 2)
+ self.assertEqual(seed_pack.load(out)["counts"]["entities"], 3)
with self.target:
entity(self.target, "performer", "天川そら")
self.target.close()