Peach: Local-first video metadata scraper and media manager.
feat(links): 目录型社媒采集(laoshi.ink、bstar-pro)+ X 验活,共用判据抽到 peach.social_links
longmeidao25e23ae1194a
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex e4716d179..ef0d9093d 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -27,6 +27,7 @@- **外链圆标取站点自己声明的那一份,不是根目录猜到的第一份**。`/link-mark` 原来只取 `/favicon.ico`,取到就收工,结果普遍糊。现在顺序是首页 `<link rel=icon|apple-touch-icon|mask-icon>` 与 `msapplication-TileImage` → web app manifest 的 `icons[]` → 老规矩位置(`/apple-touch-icon.png`、`/favicon.ico`),排序按「主机覆盖表 → 矢量 → 位图按尺寸 → 根路径猜测 → mask-icon」。两条排序规则各有实测反例:矢量必须压过任何位图且与 `rel` 无关,因为 threads 把 512 viewBox 的成品图标声明成 `rel="icon"`,按 `rel` 分层会让根目录那个 180 位图赢;声明过的必须压过根路径猜测,因为 T-POWERS 根目录的 `/apple-touch-icon.png` 是带文字的横向锁定图,而它 `<link>` 里声明的那个才是紧凑标识,两个都是 180,并列时字标会因为路径短而排前。`rel="mask-icon"` 按规范是纯黑剪影,当成品图标用会得到一枚全黑方块,所以永远排最后,轮到它时走的是字形通道。发现流程按设计只读声明,不去正文里翻图;确实需要指定来源的(av-event 的吉祥物只出现在年龄确认页正文、FANZA 的资产托在 p-smith.com)走 `site_icons.HOST_OVERRIDES`,每加一行都要写清为什么发现流程不够,否则那张表会长成一份没人更新的手工 favicon 清单。一次发现最多真的下载 `MAX_FETCH` 个候选:取回来了却不合格才算用掉一次,404 不算。- **「最高清」不等于「最合适」,判据是内容外接框而不是画布**。FANZA 是这条的反例:`p-smith.com/apple-touch-icon/fanza.png` 是 200×200,但内容是一条约 4:1 的「FANZA」字标,塞进 32 px 圆里就是一条糊掉的红杠;48×48 的 `pinned/favicon_r18.ico` 只有单个「F」,反而清楚。所以排序之后还有一道内容比例闸门(`link_marks.MAX_CONTENT_ASPECT`),宽扁字标不参加小圆标的竞选——它属于厂牌页那个大 logo 位(`/logo`),那里 `logo/fanza_r18.svg` 才是对的。同一个品牌在两个位置用两份资产不是不一致,是两个位置本来就要两种东西。过闸门后再分两条通道:成品方形图标(threads 那枚黑底圆角白字)**原样放行**,圆由 CSS 的 `.entitylinkicon` 裁,服务端再画一次只会把人家设计好的底色换掉;透明单色字形才做「品牌色圆底 + 白色主体」。- **反色圆标的锯齿有三层成因,少修一层都还是毛的**。2026-09-02 用户指出 `/link-mark?id=753` 边缘全是台阶:遮罩用了 `alpha >= 128` 的二值化(把源图自带的抗锯齿中间值一刀砍光)、这张二值图在源分辨率 48×48 上生成再拉到 64(把台阶一起放大)、字形没有与圆做 `composite`(白像素溢出圆外,圆边被啃出缺口)。现在 alpha 原样当连续遮罩,整套合成在 8 倍超采样画布上做完再一次性 LANCZOS 缩下来,成品尺寸 64 → 128(容器 32 px CSS,3x 屏要 96 px)。改了取图规则或合成方式必须同时加 `link_marks.RENDER_VERSION`:缓存保鲜期是 30 天,不换键的话代码换了用户看到的仍是旧那一张。+- **补女优社媒走「目录型来源整站抓一遍、离线比名、复核 CSV 装入」,不逐人搜索**。2026-09-02 起用 `scripts/harvest_directory_links.py`:laoshi.ink 按 sitemap 抓全部女优页(ld+json `sameAs` 加正文外链)、bstar-pro.com 过一次年龄门抓 models 列表与每页,HTML 按 URL sha1 缓存在 `peach-data/state/directory-links/<来源>/`,重跑不再打外站;页面上的名字(中文名、日文名、别名)按 `peach.social_links.name_key`(NFKC、casefold、去空白)与账本 `canonical_name` 及 `name_chain` 匹配,一页命中两个实体记 `需人工消歧` 而不是猜。站点自己的社媒账号(laoshi 首页那几枚)先从每页外链里减掉,否则会给每个女优装上站方的 X。判词四种:`ok` 进装入队列、`已有`(同平台同 handle,不分主机写法与大小写)、`conflict`(账本同平台是另一个 handle)、`未取得`(页面失败或没有社媒)。**来源本身可能是过期数据**:目录站抄的 X 账号很多已封停、本人早换新号,所以 X 的 `ok`/`conflict` 行都用登出页 og 标签验活(活号有 `og:title` 和指向 `profile_images` 的 `og:image`;不存在的 handle 只回一个没有任何 og 的 JS 壳,看不出死活),拿不到 og 时再不走缓存地取对照账号 `x.com/X`:对照正常才敢判「疑似失效」,对照也空就是限流写「未取得」。`conflict` 行还顺带验账本里的旧号,旧号失效、新号活着的就是用户说的「一般都会有新的」。Instagram/TikTok/YouTube 登出页什么都不给,只能写「未验」。判据(平台名单、handle 归一、`twitter.com→x.com` 别名、标签写法、X 死活)集中在 `peach.social_links`,`normalize_link_hosts.py`、`harvest_performer_links.py` 都从它取;`harvest_social_avatars.py` 和 `import_stash_entities.py` 还各留着一份旧抄本。装入用 `install_entity_links.py` 吃 `directory-links-<日期>.csv`,`-review.csv` 是全部判词供人看,两者都不直接写账本。javdatabase.com、javmodel.com 走代理与直连都连不上,未取得;Instagram↔X 互补要等 laoshi 数据装入后从账本自身做,不在采集脚本里。- 人工复核入口固定为 `/review`,候选 API 为 `GET /api/review`、`POST /api/review/decision`。候选来自 writer 本机 `peach-data/generated` 下的 CSV;每项尽量带代表封面与原视频入口,审核状态写 `review_decision`。元数据与创作者标签批准后写相应真相/投影,Logo、头像、身份和媒体失败只记录决定;封面抓取的成功、尺寸和缺失是机械状态,不进入人工复核。双机同时在线时,reader 的 `GET /api/review` 只通过 Peach CA 严格校验的 HTTPS 读取 writer 已归一化 JSON,先确认目标 `/healthz` 是 `ledger_sync=writer`,绕过外网代理并原子缓存到本机 `review/writer-review.json`;macOS 合并文件 CA 与系统/登录钥匙串中受信任的同名 Peach CA,只读取公钥证书,不导出私钥。launchd 主体被本地网络权限挡住时,使用系统 `/usr/bin/curl` 经回环 Stash 代理发起同一严格请求;仅限 HTTPS、8 MiB 上限,令牌走 stdin,非回环代理拒绝。writer 临时离线时只展示上次缓存。reader 永远禁用批准、跳过和拒绝,关注管理也禁用新增、检查、移除和凭据修改,并链接到 writer。不得为修复空页面而同步整个 `generated`、SQLite/WAL,或把真实写入端点加入 reader 白名单。## 无摩擦接手diff --git a/docs/STATUS.md b/docs/STATUS.mdindex a87dcb18f..150b48729 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -71,6 +71,7 @@- 2026-09-02 外链圆标改成「按站点声明取最清晰的那一份」,并修掉反色圆标的锯齿。旧实现只取 `/favicon.ico`,取到就收工,所以用户看到的普遍是糊的;现在按首页 `<link>`/`msapplication-TileImage` → web app manifest `icons[]` → 老规矩位置发现候选,排序为「主机覆盖表 → 矢量 → 位图按尺寸 → 根路径猜测 → mask-icon」。两条排序规则各由一个实测反例逼出来:threads 把 512 viewBox 的成品图标声明成 `rel="icon"`,按 `rel` 分层会让根目录那个 180 位图赢;T-POWERS 根目录 `/apple-touch-icon.png` 是带文字的横向锁定图(内容比 1.83)而 `<link>` 声明的才是紧凑标识(1.25),两个都是 180,并列时字标因路径短排前。SVG 光栅化引入固定依赖 `resvg-py==0.5.0`(abi3 轮子,两个平台都有官方预编译,不必装 cairo 原生库),已登记进 `docs/REUSE.md`。「最高清」不等于「最合适」:FANZA 的 `apple-touch-icon/fanza.png` 是 200×200 但内容是约 4:1 的字标,48×48 的 `pinned/favicon_r18.ico` 才是单个「F」,因此排序后还有一道内容外接框比例闸门,宽扁字标留给厂牌页的 `/logo`。锯齿有三层成因(`alpha >= 128` 二值化、在源 48×48 上生成再拉到 64、字形未与圆 `composite`),现在 alpha 原样当连续遮罩、整套在 8 倍超采样画布上合成再 LANCZOS 缩下来、成品 64 → 128;`link_marks.RENDER_VERSION` 随渲染规则变更递增,否则 30 天缓存会让代码换了用户仍看旧图。8 个真实站点端到端实测全部产出 128×128:fanza/av-event/threads 取到的正是用户指名的那三份资产,t-powers 取回紧凑标识,接触表确认边缘平滑、圆外无溢出。Windows 正式全量 1720 项通过、13 项按平台跳过,`catalog` 665 项通过。本轮未写真实 ledger、未替换生产入口、未部署,生产页面的浏览器实测未取得。- 2026-09-02 新增 `scripts/normalize_link_hosts.py`,把 `entity_link` 里的 `twitter.com`/`www.twitter.com`/`mobile.twitter.com` 收成 `x.com`:同一实体只有旧写法的行原地改写 `url`/`hostname`(id、label、metadata 保留),两种写法都有的删掉旧写法那一行(`UNIQUE(entity_id,url)` 不允许并存,留下的行承载同一个 handle)。真实账本 dry-run:630 条链接,290 条改写、6 条删除(白咲碧、朝倉ゆら、未步奈奈、武藤あやか、水野优香、白石琴音,各自保留的 x.com 行号已在计划表点名),全部 `link_kind='social'`,无内部重复;写入后应为 624 条、357 条 `x.com`、0 条旧主机。`--apply` 必须同时给 `--backup`,写后核对改写数、删除数、差值、残留、`integrity_check` 和 `foreign_key_check`。`catalog` 675 项通过。**尚未 `--apply`,等用户授权。**顺带发现实体 7513(creator)与 7786(performer)的 `canonical_name` 含零宽字符 U+200C,未处理。+- 2026-09-02 女优社媒补全改成目录型采集并首轮跑完(只读账本,未写入)。新增 `scripts/harvest_directory_links.py` 与共用判据模块 `peach.social_links`(平台名单、handle 归一、`twitter.com→x.com` 别名、标签写法、X 登出页死活;`normalize_link_hosts.py`、`harvest_performer_links.py` 改从它取)。laoshi.ink 按 sitemap 抓 686 页、bstar-pro.com 过年龄门抓 22 页,HTML 全部缓存在 `peach-data/state/directory-links/`,重跑零网络。账本可比对 performer 556 位;laoshi 686 页里 471 页的人不在账本、135 页命中但页面没有社媒、41 条已有、15 条 ok、24 条 conflict、2 页需人工消歧(`阿部乃美久/あべみかこ` 同时对上账本的 `鶴乃ゆい` 与 `阿部乃美久`,`初美沙希/しずく` 同时对上 `初美沙希` 与 `雫`——这两组更像是同一人的两个实体,待用户判定是否合并);bstar 22 页 9 条 ok、4 条已有、站方自己的 3 枚社媒已剔除。**来源过期是事实**:36 个 X handle 验活,16 个活、20 个疑似失效。24 条 conflict 全是 X,laoshi 给的号里 15 个已失效(多为 404),而账本旧号 23 个仍活,只有 `乙爱丽丝` 两边都失效;剩下 9 个「活」的 laoshi 号里至少 `@kanoyura`(显示名「吉成賢司」)、`@matumoto_arrows`(「すみれ@🚹🚽出勤中」)、`@tsukino_luna`(「月野るな|人と人生を読み解く人」)已被别人接手,显示名已写进 evidence 供用户判断,脚本不替用户选边。最终安装队列 19 条(7 条 X 全部验活为「活」、4 条 Instagram、2 条 TikTok、3 条 YouTube、3 条 Bstar 事务所页),5 条 ok 的 X 因疑似失效被拦在队列外。「活」只证明账号存在,不证明是本人:队列里 `@chika_arimura`、`@yu_shinoda`、`@maririka_cmore` 的显示名自称「応援アカウント」(粉丝号),`@Hiromi_anejapan` 显示名与 `筱田步美` 对不上,装入前按 evidence 里的显示名逐条看;产物 `peach-data/review/directory-links-20260902.csv`(装入队列)与 `-review.csv`(230 行全部判词)。laoshi 首页没有站方社媒可减、bstar 减掉 3 枚,`--no-probe` 与 `--limit` 可做无网复跑。javdatabase.com、javmodel.com 代理与直连都不通,未取得。本轮未写真实 ledger、未装入任何链接、未替换生产入口。- 2026-09-01 Python 版本口径收敛到实际运行的 3.14,CI 从 4 个 job 减为 2 个。`requires-python` 原本写 `>=3.12`,CI 矩阵按这个声明测「下限 + 实际版本」,但这个下限没有使用者:README 让两台机器都用 3.14 建 venv,本机实测 3.14.7,Peach 不发 PyPI 也没有第三方按 `requires-python` 安装。历史上唯一一次 3.12 单独红(run 33368707206,Windows 3.12 失败而 3.14 通过)是预览并发生成那条计时敏感用例的偶发,不是版本不兼容。同时把「测试里的临时目录先 resolve」写进 AGENTS.md 硬门槛:这个坑一周内烧了两个分支且没有任何脚本或测试守它。AGENTS.md 87/90 行仍在预算内。Windows 正式全量 1638 项通过、13 项按平台跳过。本轮未写真实 ledger、未替换生产入口。- 2026-09-01 播放统计补上滚动历史,并修掉 GitHub Actions 上四个 job 全红。连接速度、网络活动、缓冲健康各保留 24 个 1 秒采样槽,新样本从右侧进入;缓冲健康低于 5 秒红、5–15 秒橙、其余浅绿,以 30 秒为健康上限。这部分从未集成的 `agent/codex/player-buffer-bars`(证据采集于 2026-08-29)移植,分支落后 552 个提交已废弃;原分支另一半「强化 Video.js 时间轴」**未采纳**,master 的时间轴此后已按更新的 `youtube-player-controls-user-screenshot` 实测证据重做,照搬会回退已上线结果。CI 四个 job(Windows/macOS × 3.12/3.14)失败原因完全相同且与 Python 版本无关:测试拿未 resolve 的临时目录去比对被测代码 resolve 后的真实路径,而 runner 的临时目录都是别名(macOS /var 软链到 /private/var,Windows 的 RUNNER~1 短名展开成 runneradmin),本机没有这层别名所以一直全绿。已用目录 junction 在本机复现原始失败(含 `restart_tray` 相同的 `StopIteration`)并验证修复。`test_agent_worktree` 的两项同类失败属并发中的另一分支,本轮未动这两个文件。Windows 正式全量 1636 项通过、13 项按平台跳过。本轮未写真实 ledger、未替换生产入口,播放统计的真实画面验收未取得。- 2026-09-01 修复 JAV 大图混排与番号显示清洁:根因不是多女优头像,而是 `PBD390` 等缺连字符的历史 code 被判成非 JAV,封面比例退回 16:9;现在只有片商、发行日或 performer/studio/series 实体证据成立时才接受紧凑番号,`RAIKUN325` 等账号仍排除。API 保留原始 `name`/`code`,另给规范 `display_code`、清洁后的文件名回退标题和 `edition_badges`;`-C`/`-CH`/`-SUB` 显示框选“中字”,`-U`/`-UC`/`Uncen` 显示“无码”,`AI去码`/破解证据显示“无码破解”,不再把后缀或括号推广域名当标题。真实 ledger 只读全库审计覆盖 2282 条带 code 视频:1413 条确认 JAV,16 条缺连字符但有发行证据,301 条有版本徽章;三张截图目标分别投影为 `PBD-390`、`CJOD-175 + 中字`、`CJOD-158`。文件名清理 dry-run 扫描 75499 条并产出 49 条 115 改名计划,目标含 `PBD00390.mp4 → PBD-390.mp4`、`CJOD-158[fuckbe.com].mp4 → CJOD-158.mp4`,无撞名;两次运行前后 ledger SHA-256 均为 `8FBA698C5CC362A762DD9A45A62074A283DD3448A5E758DA2DA75F43144E8D85`。正式全量 1433 项通过,13 项按平台跳过;真实改名、0023 迁移与生产部署尚未执行,修改后实际浏览器画面未取得。@@ -169,7 +170,7 @@## 下一批工作-0. 另行授权后运行 `scripts/normalize_link_hosts.py --database <ledger> --apply --backup <落点>`,把 296 条 twitter 写法收成 x.com(290 改写、6 删除);随后集成 `agent/claude/social-links-and-marks`、重启托盘,在真实浏览器验收 `/link-mark` 的清晰度与边缘。社媒补全(laoshi.ink、javdatabase、javmodel、事务所官网、Instagram↔X 互补)尚未开工,产物应是复核 CSV,经 `install_entity_links.py` 装入。+0. 另行授权后运行 `scripts/normalize_link_hosts.py --database <ledger> --apply --backup <落点>`,把 296 条 twitter 写法收成 x.com(290 改写、6 删除);脚本现从 `peach.social_links` 取别名表,要在含该模块的检出里运行。随后集成 `agent/claude/social-links-and-marks`、重启托盘,在真实浏览器验收 `/link-mark` 的清晰度与边缘。用户复核 `peach-data/review/directory-links-20260902.csv` 后用 `install_entity_links.py` 装入;`-review.csv` 里 `conflict` 且账本旧号「疑似失效」的行由用户决定换号。后续可对账本现有全部 X 链接跑一遍同样的验活,把已封停的旧号清出资料页。javdatabase.com、javmodel.com 未取得,Instagram↔X 互补待装入后从账本自身补。1. 另行授权后先备份 ledger,修正 4 组已核实姓名:恢复 `星谷瞳`、`福山美佳`、`平沢すず` 的规范名;从 `かわいゆい` 移除错误的 `河合ゆい` 别名与 r18 外部引用,清退错误头像及 provenance 后重新生成候选;同步 actor tag/检索投影,并核对受影响行数、`integrity_check`、外键和只读 API。2. 另行授权后先备份 ledger,再把 `follow_item` 181、184、185 从 `seen` 恢复为 `new`,复核状态计数、完整性与新哈希。3. 继续按复用审计依次替换 PID 锁和 Rule34Video 媒体页;每项固定版本/revision、首个消费者和隔离测试同批落地。diff --git a/scripts/harvest_directory_links.py b/scripts/harvest_directory_links.pynew file mode 100644index 000000000..b65224e49--- /dev/null+++ b/scripts/harvest_directory_links.py@@ -0,0 +1,555 @@+"""目录型来源的社媒采集:整站翻一遍,按名字对回账本,X 账号再验一次活。++minnano-av 采集器是「拿名字去搜」。laoshi.ink(686 位)和事务所官网 bstar-pro(22 位)+反过来:页面数有限,一次全部抓下来缓存在本地,再拿每页的名字去账本里找人。比对不花+网络,同一批页面能反复对比;「同名多人」「同平台另有账号」都能在离线阶段判出来,+不会静默装错人。++来源本身可能是旧数据(用户 2026-09-02 指出:抄来的 X / Instagram 账号点进去已经封停,+本人一般早换了新号)。所以采到的 X 账号逐个取登出页验活:有 og:title 且 og:image 指向+profile_images 才算活。Instagram / TikTok / YouTube 登出页给不出可靠信号,标「未验」。+只有「活」和「未验」的进安装队列;「疑似失效」只进复核表。冲突行两边都验,证据里写明+账本旧号是死是活——旧号死、新号活,就是用户说的「一般都会有新的」。++判定(verdict):+ ok 账本唯一命中,该平台该账号账本还没有+ 已有 同账号已在账本(twitter.com/x.com 视为同一主机,handle 不分大小写)+ conflict 同平台账本另有账号——用户要的「交叉对比」,只报不装+ 需人工消歧 页面名字对上不止一位 performer+ 未取得 页面抓不到,或命中的人页面上没有社交链接++输出两份 CSV:`<output>` 只含可装的 ok 行,直接喂 install_entity_links.py;+`<stem>-review.csv` 含全部判定,是复核产物。++laoshi.ink 与 bstar-pro.com 直连(经代理握手失败,站点本身可达);x.com 走代理。+bstar-pro 的 models.html 有年龄门:同一会话先 `POST age_check=yes`,之后的 GET 才给列表。+"""+from __future__ import annotations++import argparse+import hashlib+import html as html_lib+import json+import re+import sqlite3+import sys+import time+from collections import Counter+from pathlib import Path+from urllib.parse import urljoin, urlsplit++import httpx++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))++from peach.config import STATE_DIR # noqa: E402+from peach.http import HttpRequest, HttpxTransport # noqa: E402+from peach.jobs import job_main # noqa: E402+from peach.review_csv import write_rows # noqa: E402+from peach.social_links import ( # noqa: E402+ canonical_url, classify, handle, load_performers, name_key, platform, under,+ x_profile_state,+)++USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/128.0 Safari/537.36")+HREF = re.compile(r'href=["\']([^"\']+)["\']')+TAG = re.compile(r"<[^>]+>")+FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "evidence",+ "source", "page", "matched_name", "verdict", "alive")+SOURCES = ("laoshi", "bstar")+ALIVE, GONE, UNVERIFIED, UNKNOWN = "活", "疑似失效", "未验", "未取得"++LAOSHI = "https://laoshi.ink/"+LAOSHI_OWN = ("laoshi.ink",)+LAOSHI_ACTOR = re.compile(r"https://laoshi\.ink/actresses/actor-\d+\.html")+LAOSHI_TITLE = re.compile(r"<title>(.*?)</title>", re.S)+LAOSHI_FACT = re.compile(r"<span>([^<]+)</span>\s*<strong>(.*?)</strong>", re.S)+LAOSHI_NAME_FIELDS = ("中文名", "日文名", "别名")+LAOSHI_BLANK = {"", "待补充", "暂无", "-", "—", "无"}+LD_JSON = re.compile(r'<script type="application/ld\+json">(.*?)</script>', re.S)++BSTAR = "https://bstar-pro.com/"+BSTAR_OWN = ("bstar-pro.com",)+BSTAR_MODELS = BSTAR + "models.html"+BSTAR_LABEL = "Bstar"+BSTAR_ENTRY = re.compile(r'<a href="(model\.html\?mid=\d+)"[^>]*>(.*?)</a>', re.S)+BSTAR_ALT = re.compile(r'alt="([^"]*)"')+BSTAR_SPAN = re.compile(r"<span[^>]*>(.*?)</span>", re.S)+BSTAR_GATE = re.compile(r'name=["\']age_check["\']')++X_PROFILE = "https://x.com/{}"+#: 对照账号:X 官方号,登出页永远有 og:image。用来区分「账号没了」和「我们被限流」。+X_CONTROL = "X"+++# ---------------------------------------------------------------- 取页++class HttpStatusError(RuntimeError):+ def __init__(self, status: int):+ super().__init__(f"HTTP {status}")+ self.status = status+++class Site:+ """一个来源的取页器:本地缓存优先,未命中才走网络并按间隔限速。++ 缓存按 URL 的 sha1 落在 `STATE_DIR/directory-links/<来源>/`。686 页抓一次要十来分钟,+ 而名字比对规则改一行就得重跑;没有缓存,每次调规则都是一次完整重抓。+ """++ def __init__(self, cache_dir: Path, interval: float, timeout: float, *,+ refresh: bool = False, via_proxy: bool = False, transport=None):+ self.cache_dir, self.interval, self.timeout, self.refresh = cache_dir, interval, timeout, refresh+ self.transport = transport or HttpxTransport(+ httpx.Client(trust_env=via_proxy, follow_redirects=True))+ self._last = 0.0+ self.fetched = self.cached = 0++ def request(self, method: str, url: str, body: bytes | None = None,+ headers: dict[str, str] | None = None) -> str:+ wait = self.interval - (time.monotonic() - self._last)+ if wait > 0:+ time.sleep(wait)+ self._last = time.monotonic()+ response = self.transport(+ HttpRequest(method, url, {"User-Agent": USER_AGENT, **(headers or {})}, body=body),+ self.timeout, 8 << 20)+ if response.status != 200:+ raise HttpStatusError(response.status)+ return response.body.decode("utf-8", "replace")++ def cache_path(self, url: str) -> Path:+ return self.cache_dir / (hashlib.sha1(url.encode("utf-8")).hexdigest()[:20] + ".html")++ def get(self, url: str, refresh: bool = False) -> str:+ path = self.cache_path(url)+ if not (refresh or self.refresh) and path.exists():+ self.cached += 1+ return path.read_text("utf-8")+ text = self.request("GET", url)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, "utf-8")+ self.fetched += 1+ return text++ def close(self) -> None:+ self.transport.close()+++# ---------------------------------------------------------------- 解析++def clean(text: str) -> str:+ return re.sub(r"\s+", " ", html_lib.unescape(TAG.sub(" ", text)).replace("\xa0", " ")).strip()+++def dedupe(items: list[str]) -> list[str]:+ return list(dict.fromkeys(item for item in items if item))+++def split_names(text: str) -> list[str]:+ """`别名` 一栏可能塞好几个名字;分隔符不分中日文标点。不按空格拆——罗马字里有空格。"""+ return [part.strip() for part in re.split(r"[、,,//||;;]", text)+ if part.strip() and part.strip() not in LAOSHI_BLANK]+++def external_links(html: str, own_hosts: tuple[str, ...], base: str = "") -> list[str]:+ """页面上的站外绝对链接,去掉本站与相对路径。++ bstar-pro 的页脚有 `href="/https://x.com/bstar_pro/"` 这种写坏的相对路径,+ urljoin 之后落在本站主机上,正好被本站过滤掉——不必单独处理。+ """+ out = []+ for href in HREF.findall(html):+ url = html_lib.unescape(href).strip()+ if base:+ url = urljoin(base, url)+ parts = urlsplit(url)+ if parts.scheme not in {"http", "https"} or not parts.hostname:+ continue+ if under(parts.hostname.casefold(), own_hosts):+ continue+ out.append(url)+ return dedupe(out)+++def laoshi_listing(sitemap_xml: str) -> list[str]:+ """sitemap 里的女优页;站内搜索是纯前端 JS,服务端没有可用的检索入口。"""+ return sorted(set(LAOSHI_ACTOR.findall(sitemap_xml)))+++def laoshi_names(html: str) -> list[str]:+ """标题 `中文名(日文名 / Romaji)` 加「基本资料」里的中文名、日文名、别名。++ 标题有时只有一种写法(`桃園怜奈`、`西田カリナ(Karina Nishida)`),所以两处都取;+ 「待补充」这类占位词不是名字。+ """+ names: list[str] = []+ title = LAOSHI_TITLE.search(html)+ if title:+ head = clean(title.group(1)).split("|")[0].split("|")[0]+ main, _, rest = (re.split(r"([((])", head, maxsplit=1) if re.search(r"[((]", head)+ else (head, "", ""))+ names += split_names(main) + split_names(rest.rstrip("))"))+ for label, value in LAOSHI_FACT.findall(html):+ if clean(label) in LAOSHI_NAME_FIELDS:+ names += split_names(clean(value))+ return dedupe(names)+++def _same_as(node) -> list[str]:+ found: list[str] = []+ if isinstance(node, dict):+ same = node.get("sameAs")+ if isinstance(same, str):+ found.append(same)+ elif isinstance(same, list):+ found += [item for item in same if isinstance(item, str)]+ for value in node.values():+ found += _same_as(value)+ elif isinstance(node, list):+ for item in node:+ found += _same_as(item)+ return found+++def laoshi_links(html: str) -> list[str]:+ """ld+json 的 sameAs 加正文外链。sameAs 是站方明确声明的「本人主页」,正文锚点作补充。"""+ urls: list[str] = []+ for block in LD_JSON.findall(html):+ try:+ urls += _same_as(json.loads(block))+ except ValueError:+ continue+ return dedupe(urls + external_links(html, LAOSHI_OWN))+++def bstar_gated(html: str) -> bool:+ return bool(BSTAR_GATE.search(html)) and not BSTAR_ENTRY.search(html)+++def bstar_listing(html: str) -> list[tuple[str, list[str]]]:+ """models.html → [(模特页 URL, [日文名, 罗马字])]。名字来自缩略图 alt 与两行说明。"""+ out: list[tuple[str, list[str]]] = []+ seen: set[str] = set()+ for href, inner in BSTAR_ENTRY.findall(html):+ url = urljoin(BSTAR, html_lib.unescape(href))+ if url in seen:+ continue+ seen.add(url)+ names: list[str] = []+ alt = BSTAR_ALT.search(inner)+ if alt:+ names.append(clean(alt.group(1)))+ names += [clean(span) for span in BSTAR_SPAN.findall(inner)]+ out.append((url, dedupe(names)))+ return out+++# ---------------------------------------------------------------- 采集++def page_record(source: str, url: str, names: list[str], links: list[str], *,+ official: tuple[str, str] | None = None, note: str = "") -> dict:+ return {"source": source, "page": url, "names": names, "links": links,+ "official": official, "note": note}+++def failed(source: str, url: str, exc: Exception) -> dict:+ return page_record(source, url, [], [], note=f"未取得:{type(exc).__name__}: {exc}"[:160])+++def collect_laoshi(site: Site, limit: int = 0) -> tuple[list[str], list[dict]]:+ """返回(站点自身的社交链接, 页面记录)。首页上的账号是站方的,不是任何女优的。"""+ site_links = [url for url in external_links(site.get(LAOSHI), LAOSHI_OWN) if platform(url)]+ urls = laoshi_listing(site.get(LAOSHI + "sitemap.xml"))+ if limit:+ urls = urls[:limit]+ pages = []+ for url in urls:+ try:+ html = site.get(url)+ pages.append(page_record("laoshi", url, laoshi_names(html), laoshi_links(html)))+ except Exception as exc: # 单页失败只记未取得,不拖垮整批+ pages.append(failed("laoshi", url, exc))+ return site_links, pages+++def bstar_pass_gate(site: Site) -> None:+ site.request("POST", BSTAR_MODELS, body=b"age_check=yes",+ headers={"Content-Type": "application/x-www-form-urlencoded"})+++def bstar_page(site: Site, url: str) -> str:+ html = site.get(url)+ if bstar_gated(html):+ bstar_pass_gate(site)+ html = site.get(url, refresh=True)+ if bstar_gated(html):+ raise RuntimeError("年龄门没过")+ return html+++def collect_bstar(site: Site, limit: int = 0) -> tuple[list[str], list[dict]]:+ """事务所官网:列表页给名字,模特页给 SNS。列表页上的账号是事务所的,要从每页里减掉。"""+ listing = bstar_page(site, BSTAR_MODELS)+ site_links = [url for url in external_links(listing, BSTAR_OWN, BSTAR) if platform(url)]+ entries = bstar_listing(listing)+ if limit:+ entries = entries[:limit]+ pages = []+ for url, names in entries:+ try:+ html = bstar_page(site, url)+ pages.append(page_record("bstar", url, names, external_links(html, BSTAR_OWN, BSTAR),+ official=(url, BSTAR_LABEL)))+ except Exception as exc:+ pages.append(failed("bstar", url, exc))+ return site_links, pages+++COLLECTORS = {"laoshi": collect_laoshi, "bstar": collect_bstar}+++# ---------------------------------------------------------------- 判定++def row(**values) -> dict:+ record = {field: "" for field in FIELDS}+ record.update(values)+ return record+++def index_names(performers: list[dict]) -> dict[str, set[int]]:+ index: dict[str, set[int]] = {}+ for record in performers:+ for name in [record["name"], *record["chain"]]:+ key = name_key(name)+ if key:+ index.setdefault(key, set()).add(record["entity_id"])+ return index+++def load_existing(connection: sqlite3.Connection) -> tuple[dict, dict]:+ """账本现有链接 → ({entity_id: {(平台, handle): url}}, {entity_id: {url}})。"""+ handles: dict[int, dict[tuple[str, str], str]] = {}+ urls: dict[int, set[str]] = {}+ for entity_id, url in connection.execute("SELECT entity_id, url FROM entity_link"):+ urls.setdefault(entity_id, set()).add(url)+ name, account = platform(url), handle(url)+ if name and account:+ handles.setdefault(entity_id, {})[(name, account)] = url+ return handles, urls+++def judge(pages: list[dict], site_links: list[str], performers: list[dict],+ existing_handles: dict, existing_urls: dict) -> tuple[list[dict], Counter]:+ """页面记录 → 复核行。会把本轮判 ok 的账号记进 existing_handles,后来的来源据此判已有/冲突。++ 冲突只对「进这页之前」账本已有的账号判:同一页上列两个 X 账号是主号加副号,+ 不是两处资料打架。+ """+ by_id = {record["entity_id"]: record for record in performers}+ index = index_names(performers)+ ignore = {(platform(url), handle(url)) for url in site_links}+ rows: list[dict] = []+ stats: Counter = Counter()+ for page in pages:+ base = {"kind": "performer", "source": page["source"], "page": page["page"]}+ if page["note"]:+ rows.append(row(**base, verdict="未取得", evidence=page["note"]))+ stats["页面未取得"] += 1+ continue+ matched: set[int] = set()+ used: list[str] = []+ for name in page["names"]:+ ids = index.get(name_key(name))+ if ids:+ matched |= ids+ used.append(name)+ socials = []+ seen: set[tuple[str, str]] = set()+ for url in page["links"]:+ key = (platform(url), handle(url))+ if not key[0] or not key[1] or key in ignore or key in seen:+ continue+ seen.add(key)+ socials.append((canonical_url(url), *key))+ if not matched:+ stats["页面不在账本"] += 1+ continue+ matched_name = "、".join(used)+ if len(matched) > 1:+ names = "、".join(by_id[entity_id]["name"] for entity_id in sorted(matched))+ for url, _, _ in socials:+ link_kind, label = classify(url)+ rows.append(row(**base, link_kind=link_kind, label=label, url=url,+ matched_name=matched_name, verdict="需人工消歧",+ evidence=f"页面名「{matched_name}」对上多位:{names}"))+ stats["需人工消歧"] += 1+ continue+ entity_id = matched.pop()+ record = by_id[entity_id]+ base.update(entity_id=entity_id, name=record["name"], matched_name=matched_name)+ where = f"{page['source']} {page['page']};页面名「{matched_name}」对上账本「{record['name']}」"+ if not socials and not page["official"]:+ rows.append(row(**base, verdict="未取得", evidence=f"{where};页面上没有社交链接"))+ stats["命中但无社媒"] += 1+ continue+ held = existing_handles.setdefault(entity_id, {})+ prior = dict(held)+ for url, name, account in socials:+ link_kind, label = classify(url)+ item = row(**base, link_kind=link_kind, label=label, url=url)+ if (name, account) in prior:+ item.update(verdict="已有", evidence=f"{where};账本已有 {prior[(name, account)]}")+ else:+ others = [held_url for (held_name, _), held_url in prior.items() if held_name == name]+ if others:+ item.update(verdict="conflict",+ evidence=f"{where};账本同平台另有 {'、'.join(others)},需交叉核对")+ else:+ item.update(verdict="ok", evidence=where)+ held[(name, account)] = url+ rows.append(item)+ stats[item["verdict"]] += 1+ if page["official"]:+ url, label = page["official"]+ if url in existing_urls.get(entity_id, set()):+ rows.append(row(**base, link_kind="official", label=label, url=url,+ verdict="已有", evidence=f"{where};账本已有此页"))+ stats["已有"] += 1+ else:+ rows.append(row(**base, link_kind="official", label=label, url=url,+ verdict="ok", evidence=f"{where};本人在事务所官网的页面"))+ existing_urls.setdefault(entity_id, set()).add(url)+ stats["ok"] += 1+ return rows, stats+++# ---------------------------------------------------------------- 验活++def probe_x(site: Site, account: str, memo: dict[str, tuple[str, str]]) -> tuple[str, str]:+ """X 账号活不活 → (状态, 显示名)。同一账号只查一次。"""+ key = account.casefold()+ if key not in memo:+ try:+ state, display = x_profile_state(site.get(X_PROFILE.format(account)))+ if state == "unknown":+ # 实测 2026-09-02:不存在的账号登出页也是 200,只是没有任何 og 标签——和限流+ # 回的 JS 壳长得一样。同一时刻不走缓存再取对照账号:对照有 og,这个就是真没了;+ # 对照也没有,是我们被限流,只能记未取得。+ control, _ = x_profile_state(site.get(X_PROFILE.format(X_CONTROL), refresh=True))+ state = "gone" if control == "alive" else "unknown"+ display = "登出页无资料,对照账号正常" if state == "gone" else "登出页无资料,对照账号也无(限流)"+ memo[key] = ({"alive": ALIVE, "gone": GONE}.get(state, UNKNOWN), display)+ except HttpStatusError as exc:+ memo[key] = (GONE if exc.status == 404 else UNKNOWN, f"HTTP {exc.status}")+ except Exception as exc:+ memo[key] = (UNKNOWN, type(exc).__name__)+ return memo[key]+++def probe_rows(rows: list[dict], existing_handles: dict, site: Site | None) -> Counter:+ """给 ok / conflict 的社交行填 `alive`;冲突行连账本那边的旧号一起验,证据里写明。++ site 为 None 表示本轮不验(`--no-probe`),全部标未验——列不能空着,空着看不出+ 是「没验」还是「验了没结论」。+ """+ memo: dict[str, tuple[str, str]] = {}+ stats: Counter = Counter()+ for item in rows:+ if item["verdict"] not in {"ok", "conflict"} or item["link_kind"] != "social":+ continue+ name = platform(item["url"])+ if name != "X" or site is None:+ item["alive"] = UNVERIFIED+ continue+ state, display = probe_x(site, handle(item["url"]), memo)+ item["alive"] = state+ stats[state] += 1+ if display:+ item["evidence"] += (f";X 显示名「{display}」" if state == ALIVE else f";X 验活:{display}")+ if item["verdict"] == "conflict":+ olds = [url for (held_name, _), url in existing_handles.get(item["entity_id"], {}).items()+ if held_name == "X" and handle(url) != handle(item["url"])]+ for old in olds:+ old_state, _ = probe_x(site, handle(old), memo)+ item["evidence"] += f";账本旧号 {old}:{old_state}"+ return stats+++def installable(rows: list[dict]) -> list[dict]:+ """只有 ok 且没被验成失效的行进安装队列。"""+ return [item for item in rows if item["verdict"] == "ok" and item["alive"] != GONE]+++# ---------------------------------------------------------------- 入口++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--database", type=Path, required=True)+ parser.add_argument("--output", type=Path, required=True,+ help="安装队列 CSV;复核表写到同目录的 <stem>-review.csv")+ parser.add_argument("--source", choices=("all", *SOURCES), default="all")+ parser.add_argument("--min-assets", type=int, default=1)+ parser.add_argument("--limit", type=int, default=0, help="每个来源最多看几页(试跑用)")+ parser.add_argument("--interval", type=float, default=1.2)+ parser.add_argument("--x-interval", type=float, default=2.0)+ parser.add_argument("--timeout", type=float, default=25.0)+ parser.add_argument("--refresh", action="store_true", help="忽略本地缓存重新抓")+ parser.add_argument("--no-probe", action="store_true", help="不去 x.com 验活")+ parser.add_argument("--cache-dir", type=Path, default=STATE_DIR / "directory-links")+ parser.add_argument("--lock", type=Path, default=STATE_DIR / ".directory-links.lock")+ return parser+++def run(args) -> int:+ connection = sqlite3.connect(f"file:{args.database}?mode=ro", uri=True)+ try:+ performers = load_performers(connection, args.min_assets)+ existing_handles, existing_urls = load_existing(connection)+ finally:+ connection.close()+ print(f"账本可比对 performer {len(performers)} 位")++ rows: list[dict] = []+ totals: Counter = Counter()+ sources = SOURCES if args.source == "all" else (args.source,)+ for source in sources:+ site = Site(args.cache_dir / source, args.interval, args.timeout, refresh=args.refresh)+ try:+ site_links, pages = COLLECTORS[source](site, args.limit)+ except Exception as exc:+ print(f"[{source}] 未取得:{type(exc).__name__}: {exc}")+ continue+ finally:+ site.close()+ source_rows, stats = judge(pages, site_links, performers, existing_handles, existing_urls)+ rows += source_rows+ totals.update(stats)+ print(f"[{source}] 页面 {len(pages)},网络 {site.fetched} / 缓存 {site.cached},"+ f"站方账号 {len(site_links)} 条已剔除,{dict(stats)}")++ x_site = None if args.no_probe else Site(args.cache_dir / "x", args.x_interval, args.timeout,+ refresh=args.refresh, via_proxy=True)+ try:+ alive = probe_rows(rows, existing_handles, x_site)+ finally:+ if x_site is not None:+ x_site.close()+ print(f"X 验活 {dict(alive)}" if x_site is not None else "本轮未验活")++ order = {"conflict": 0, "ok": 1, "需人工消歧": 2, "已有": 3, "未取得": 4}+ rows.sort(key=lambda item: (order.get(item["verdict"], 9), str(item["name"]), item["url"]))+ review = args.output.with_name(args.output.stem + "-review.csv")+ queue = installable(rows)+ write_rows(args.output, FIELDS, queue)+ write_rows(review, FIELDS, rows)+ print({"安装队列": len(queue), "复核行": len(rows), **totals,+ "output": str(args.output), "review": str(review)})+ return 0+++if __name__ == "__main__":+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")+ raise SystemExit(job_main(build_parser, run))diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.pyindex b5d2aa2cc..767630a7e 100644--- a/scripts/harvest_performer_links.py+++ b/scripts/harvest_performer_links.py@@ -25,12 +25,13 @@ from urllib.parse import quote, urlsplitsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))-from peach.catalog_rules import is_jav_code # noqa: E402-from peach.entities import name_chain # noqa: E402from peach.config import STATE_DIR # noqa: E402+from peach.entities import name_chain # noqa: E402,F401 测试从本模块取 name_chainfrom peach.http import HttpRequest, HttpxTransport # noqa: E402from peach.jobs import job_main # noqa: E402from peach.review_csv import write_rows # noqa: E402+# 平台判据与选人规则和目录型采集器共用,定义在 peach.social_links;这里只保留 minnano-av 的解析。+from peach.social_links import classify, load_performers, under # noqa: E402,F401SEARCH = "https://www.minnano-av.com/search_result.php?search_scope=actress&search_word="USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "@@ -38,9 +39,6 @@ USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "ACTRESS_PAGE = re.compile(r"/actress(\d+)\.html")FIELD = re.compile(r"<td[^>]*>\s*<span[^>]*>(.*?)</span>(.*?)</td>", re.S)HREF = re.compile(r'href=["\']([^"\']+)["\']')-SOCIAL_HOSTS = ("x.com", "twitter.com", "instagram.com", "tiktok.com", "youtube.com")-# 博客也是本人的社交存在,但它没有 handle 概念,标签另算。-BLOG_HOSTS = ("ameblo.jp", "lineblog.me", "note.com", "livedoor.jp", "hatenablog.com")LINK_LABELS = {"ブログ", "公式サイト", "Twitter", "SNS"}FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "evidence","actress_id", "agency", "verdict")@@ -79,71 +77,6 @@ def profile_text(html: str, label: str) -> str:return ""-def under(host: str, domains: tuple[str, ...]) -> bool:- """host 是否就是这些域名之一或它们的子域。-- 直接用 `endswith` 会把 `notx.com` 判成 x.com——后缀匹配必须落在点边界上,- 否则任何人注册一个以平台名结尾的域名就能让链接被标成官方社交账号。- """- return any(host == domain or host.endswith("." + domain) for domain in domains)---PLATFORM_NAMES = {("x.com", "twitter.com"): "X", ("instagram.com",): "Instagram",- ("tiktok.com",): "TikTok", ("youtube.com",): "YouTube"}---def classify(url: str, agency: str = "") -> tuple[str, str]:- """(link_kind, label)。label 就是资料页上那行链接文字,所以要说清点过去是什么。-- 事务所页面用事务所名当标签(`T-POWERS` 而不是通用的「官方网站」):用户要的正是- 厂商链接,而这个名字资料表里已经给了,退回通用词等于把取到的信息扔掉。- """- host = (urlsplit(url).hostname or "").casefold().removeprefix("www.")- if under(host, SOCIAL_HOSTS):- handle = urlsplit(url).path.strip("/").split("/")[0]- platform = next((name for hosts, name in PLATFORM_NAMES.items() if under(host, hosts)),- host)- return "social", (f"{platform} @{handle}" if handle else platform)- if under(host, BLOG_HOSTS):- return "social", "博客"- return "official", (agency.strip() or "官方网站")---def load_performers(connection: sqlite3.Connection, minimum: int) -> list[dict]:- """有作品的 performer,跳过确定不是 JAV 的。-- minnano-av 是 JAV 资料库,拿中文素人创作者去查必然落空,还会把真正的缺口盖住——- 和 `audit_performer_portraits.py` 跳过非 JAV 是同一条理由,判据复用同一个函数。- 看不见作品是未知不是反面证据,照查;看得见但没有一个 JAV 番号才跳过。- """- codes: dict[int, list[str]] = {}- counts: dict[int, int] = {}- for entity_id, total, joined in connection.execute(- "SELECT ae.entity_id, count(*), group_concat(DISTINCT a.code) "- "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "- "WHERE a.medium='video' GROUP BY ae.entity_id"):- counts[entity_id] = int(total or 0)- codes[entity_id] = [code for code in str(joined or "").split(",") if code]- aliases: dict[int, list[str]] = {}- for entity_id, alias in connection.execute(- "SELECT entity_id, alias FROM entity_alias ORDER BY confidence DESC, alias"):- aliases.setdefault(entity_id, []).append(alias)- out = []- for entity_id, name in connection.execute(- "SELECT id, canonical_name FROM entity WHERE kind='performer'"):- total = counts.get(entity_id, 0)- if total < minimum:- continue- # 「作品可见却一个 JAV 番号都没有」是非 JAV 的反面证据(中文素人创作者正是这个- # 形态);「一个作品都看不见」只是未知,照查不误。按非空番号判会把前者也当成未知,- # 查一遍落空后混进未取得,把真正查不到的 JAV 女优盖住。- if total and not any(is_jav_code(code) for code in codes.get(entity_id, ())):- continue- out.append({"entity_id": entity_id, "name": name, "assets": total,- "chain": name_chain(name, aliases.get(entity_id, []))})- return sorted(out, key=lambda record: -record["assets"])--def scan(http, name: str, timeout: float) -> tuple[list[dict], str, str, str]:"""返回(链接行, actress_id, 所属事务所, 判定说明)。"""response = http(HttpRequest("GET", search_url(name), {"User-Agent": USER_AGENT}),diff --git a/scripts/normalize_link_hosts.py b/scripts/normalize_link_hosts.pyindex 6b74e3fdb..5ae0ebdc5 100644--- a/scripts/normalize_link_hosts.py+++ b/scripts/normalize_link_hosts.py@@ -24,31 +24,18 @@ import sqlite3import sysfrom datetime import datetime, timezonefrom pathlib import Path-from urllib.parse import urlsplit, urlunsplit+from urllib.parse import urlsplit-#: 旧主机 → 现主机。只放**同一家站点改名**的情况,不是通用的域名清洗表。-#:-#: twitter.com 与 x.com 是同一个站在 2023 年的改名,路径原样可用(实测 status 永久链接-#: 也照样解析)。别把「看起来相似的站」放进来:那是两个站,不是一个站的两种写法。-HOST_ALIASES: dict[str, str] = {- "twitter.com": "x.com",- "www.twitter.com": "x.com",- "mobile.twitter.com": "x.com",-}+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))++# 别名表和改写规则与采集器共用(采集到 twitter.com 也要收成 x.com),定义在 peach.social_links。+from peach.social_links import HOST_ALIASES, canonical_url # noqa: E402def target_url(url: str) -> str:- """旧主机 → 新主机后的地址;不涉及别名表就返回空串。-- 只换 netloc 并把 scheme 提到 https,路径、查询和片段原样保留——handle 大小写在 X 上- 不敏感,但它是用户当初复核过的写法,没有理由在这里替他改掉。- """- parts = urlsplit(url.strip())- host = (parts.hostname or "").lower()- new_host = HOST_ALIASES.get(host)- if not new_host:- return ""- return urlunsplit(("https", new_host, parts.path, parts.query, parts.fragment))+ """旧主机 → 新主机后的地址;不涉及别名表就返回空串。"""+ new_url = canonical_url(url)+ return new_url if new_url != url else ""def plan(connection: sqlite3.Connection) -> list[dict]:diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 03f23110a..7a5ce22db 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -37,7 +37,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_duplicate_identity_merge.py", "test_entity_merge.py","test_stash_entity_import.py", "test_migrations.py","test_entity_link_install.py", "test_studio_site_harvest.py",- "test_performer_link_harvest.py",+ "test_performer_link_harvest.py", "test_directory_link_harvest.py","test_link_rediscovery.py"),"tooling": ("test_scripts.py", "test_agent_worktree.py", "test_dependency_policy.py","test_restart_windows_tray.py",diff --git a/src/peach/social_links.py b/src/peach/social_links.pynew file mode 100644index 000000000..1453307e3--- /dev/null+++ b/src/peach/social_links.py@@ -0,0 +1,198 @@+"""社媒链接的共用判据:哪些主机算社交平台、链接文字怎么写、两条链接是不是同一个账号、+X 登出页能不能看出账号还活着、哪些 performer 值得去外站查。++此前 `harvest_performer_links` 和 `import_stash_entities` 各抄了一份 `SOCIAL_HOSTS` 与+`classify`,平台名单一改就得改两处。目录型采集(laoshi.ink、事务所官网)是第三个使用者,+再抄一份说不过去。这里只放判据,不放任何来源的解析——来源怎么翻页、怎么过年龄门,+留在各自的脚本里。+"""+from __future__ import annotations++import html+import re+import sqlite3+import unicodedata+from urllib.parse import urlsplit, urlunsplit++from .catalog_rules import is_jav_code+from .entities import name_chain++SOCIAL_HOSTS = ("x.com", "twitter.com", "instagram.com", "tiktok.com", "youtube.com")+#: 博客也是本人的社交存在,但它没有 handle 概念,标签另算。+BLOG_HOSTS = ("ameblo.jp", "lineblog.me", "note.com", "livedoor.jp", "hatenablog.com")+PLATFORM_NAMES = {("x.com", "twitter.com"): "X", ("instagram.com",): "Instagram",+ ("tiktok.com",): "TikTok", ("youtube.com",): "YouTube"}+#: 这些首段不是 handle,是平台的路径前缀:`youtube.com/channel/UC…`、`youtube.com/c/名字`。+PATH_PREFIXES = frozenset({"channel", "c", "user"})+#: 这些首段是平台功能页,不是任何人的账号:`x.com/intent/follow?…`、`instagram.com/p/…`。+NON_HANDLES = frozenset({+ "intent", "search", "hashtag", "i", "home", "share", "explore", "p", "reel", "reels",+ "stories", "watch", "shorts", "playlist", "results", "embed", "tag", "tags", "login",+ "signup", "accounts", "privacy", "tos", "about", "settings",+})+#: 旧主机 → 现主机。只放**同一家站点改名**的情况,不是通用的域名清洗表。+#:+#: twitter.com 与 x.com 是同一个站在 2023 年的改名,路径原样可用(实测 status 永久链接+#: 也照样解析)。别把「看起来相似的站」放进来:那是两个站,不是一个站的两种写法。+HOST_ALIASES: dict[str, str] = {+ "twitter.com": "x.com",+ "www.twitter.com": "x.com",+ "mobile.twitter.com": "x.com",+}+#: X 登出页在账号封停或不存在时正文里会出现的字样(英文、日文两种界面)。+X_GONE_MARKERS = ("Account suspended", "アカウントは凍結", "This account doesn’t exist",+ "This account doesn't exist", "このアカウントは存在しません")+META_TAG = re.compile(r"<meta\b[^>]*>", re.I)+ATTR = re.compile(r'([\w:-]+)\s*=\s*"([^"]*)"')+++def under(host: str, domains: tuple[str, ...]) -> bool:+ """host 是否就是这些域名之一或它们的子域。++ 直接用 `endswith` 会把 `notx.com` 判成 x.com——后缀匹配必须落在点边界上,+ 否则任何人注册一个以平台名结尾的域名就能让链接被标成官方社交账号。+ """+ return any(host == domain or host.endswith("." + domain) for domain in domains)+++def host_of(url: str) -> str:+ return (urlsplit(url).hostname or "").casefold().removeprefix("www.")+++def canonical_url(url: str) -> str:+ """改过名的站点换成现主机;不涉及别名表就原样返回。++ 只换 netloc 并把 scheme 提到 https,路径、查询和片段原样保留——handle 大小写在 X 上+ 不敏感,但它是用户当初复核过的写法,没有理由在这里替他改掉。+ """+ parts = urlsplit(url.strip())+ new_host = HOST_ALIASES.get((parts.hostname or "").lower())+ if not new_host:+ return url+ return urlunsplit(("https", new_host, parts.path, parts.query, parts.fragment))+++def platform(url: str) -> str:+ """平台名(`X`、`Instagram`…);不是社交平台就返回空串。"""+ host = host_of(url)+ if not under(host, SOCIAL_HOSTS):+ return ""+ return next((name for hosts, name in PLATFORM_NAMES.items() if under(host, hosts)), host)+++def account_segment(url: str) -> str:+ """路径里代表账号的那一段,保留原大小写;功能页返回空串。++ 多数平台是第一段;YouTube 的 `/channel/UC…` 和 `/c/名字` 第一段只是前缀,取第二段。+ `@setokan.channel` 的 `@` 是 YouTube 的写法不是账号名的一部分,去掉。+ """+ parts = [part for part in urlsplit(url).path.split("/") if part]+ if not parts:+ return ""+ first = parts[0].casefold()+ if first in NON_HANDLES:+ return ""+ if first in PATH_PREFIXES:+ return parts[1].lstrip("@") if len(parts) > 1 else ""+ return parts[0].lstrip("@")+++def handle(url: str) -> str:+ """比较两条链接是不是同一个账号用的键。++ 统一 casefold——X 的 handle 不分大小写,`@Yua_Mikami` 和 `@yua_mikami` 是同一个人,+ 不能算成冲突。+ """+ return account_segment(url).casefold()+++def classify(url: str, agency: str = "") -> tuple[str, str]:+ """(link_kind, label)。label 就是资料页上那行链接文字,所以要说清点过去是什么。++ 事务所页面用事务所名当标签(`T-POWERS` 而不是通用的「官方网站」):用户要的正是+ 厂商链接,而这个名字资料表里已经给了,退回通用词等于把取到的信息扔掉。+ """+ name = platform(url)+ if name:+ shown = account_segment(url)+ # `youtube.com/channel/UC…` 的那串是频道 ID 不是名字,写进标签只是一行乱码。+ if name == "YouTube" and re.fullmatch(r"UC[\w-]{22}", shown):+ shown = ""+ return "social", (f"{name} @{shown}" if shown else name)+ if under(host_of(url), BLOG_HOSTS):+ return "social", "博客"+ return "official", (agency.strip() or "官方网站")+++def name_key(name: str) -> str:+ """名字比对用的键:全角半角归一、去空白、不分大小写。++ 目录站写 `三上悠亜`,账本别名也是 `三上悠亜`,但中间可能多一个全角空格或半角空格;+ 罗马字则常见 `Yua Mikami` 与 `YUA MIKAMI` 两种写法。键只用来找候选,最终装入的+ 名字仍是账本里的那一个。+ """+ folded = unicodedata.normalize("NFKC", str(name or "")).casefold()+ return re.sub(r"\s+", "", folded)+++def meta_content(body: str, prop: str) -> str:+ """`<meta property="og:…" content="…">` 的 content,属性顺序不限。"""+ for tag in META_TAG.findall(body):+ attrs = {key.casefold(): value for key, value in ATTR.findall(tag)}+ if attrs.get("property") == prop or attrs.get("name") == prop:+ return html.unescape(attrs.get("content", ""))+ return ""+++def x_profile_state(body: str) -> tuple[str, str]:+ """X 登出页 HTML → (状态, 显示名)。状态取 alive / gone / unknown 三值。++ 用户 2026-09-02 指出:目录站抄来的 X 账号很多已经封停,本人早换了新号。登出页+ 对活着的账号会给 og:title(显示名)和指向 profile_images 的 og:image;封停或不存在+ 的账号两者都没有,正文有时还直接写着「Account suspended」。什么 og 都没有的页面+ 是 JS 壳或限流页,看不出死活,只能 unknown,不能把限流当成封停。+ """+ if any(marker in body for marker in X_GONE_MARKERS):+ return "gone", ""+ title = meta_content(body, "og:title")+ image = meta_content(body, "og:image")+ if title and "profile_images" in image:+ return "alive", title.strip()+ if not title and not image:+ return "unknown", ""+ return "gone", title.strip()+++def load_performers(connection: sqlite3.Connection, minimum: int) -> list[dict]:+ """有作品的 performer,跳过确定不是 JAV 的。++ minnano-av 和 laoshi.ink 都是 JAV 资料库,拿中文素人创作者去查必然落空,还会把真正的+ 缺口盖住——和 `audit_performer_portraits.py` 跳过非 JAV 是同一条理由,判据复用同一个+ 函数。看不见作品是未知不是反面证据,照查;看得见但没有一个 JAV 番号才跳过。+ """+ codes: dict[int, list[str]] = {}+ counts: dict[int, int] = {}+ for entity_id, total, joined in connection.execute(+ "SELECT ae.entity_id, count(*), group_concat(DISTINCT a.code) "+ "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "+ "WHERE a.medium='video' GROUP BY ae.entity_id"):+ counts[entity_id] = int(total or 0)+ codes[entity_id] = [code for code in str(joined or "").split(",") if code]+ aliases: dict[int, list[str]] = {}+ for entity_id, alias in connection.execute(+ "SELECT entity_id, alias FROM entity_alias ORDER BY confidence DESC, alias"):+ aliases.setdefault(entity_id, []).append(alias)+ out = []+ for entity_id, name in connection.execute(+ "SELECT id, canonical_name FROM entity WHERE kind='performer'"):+ total = counts.get(entity_id, 0)+ if total < minimum:+ continue+ # 「作品可见却一个 JAV 番号都没有」是非 JAV 的反面证据(中文素人创作者正是这个+ # 形态);「一个作品都看不见」只是未知,照查不误。按非空番号判会把前者也当成未知,+ # 查一遍落空后混进未取得,把真正查不到的 JAV 女优盖住。+ if total and not any(is_jav_code(code) for code in codes.get(entity_id, ())):+ continue+ out.append({"entity_id": entity_id, "name": name, "assets": total,+ "chain": name_chain(name, aliases.get(entity_id, []))})+ return sorted(out, key=lambda record: -record["assets"])diff --git a/tests/test_directory_link_harvest.py b/tests/test_directory_link_harvest.pynew file mode 100644index 000000000..e26ad1dec--- /dev/null+++ b/tests/test_directory_link_harvest.py@@ -0,0 +1,396 @@+"""目录型社媒采集:整站翻一遍、按名字对回账本、X 账号验活;以及抽出来共用的社媒判据。"""+import importlib.util+import sys+import tempfile+import unittest+from pathlib import Path++REPO = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO / "src"))++from peach import social_links # noqa: E402+++def load_module():+ spec = importlib.util.spec_from_file_location(+ "harvest_directory_links", REPO / "scripts" / "harvest_directory_links.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++# 按 2026-09-02 实测的 laoshi.ink actor-001 复刻:标题带三种写法,ld+json 有 sameAs,+# 「基本资料」是 <span>标签</span><strong>值</strong>,别名可能是占位词「待补充」。+SITEMAP = """<?xml version="1.0"?><urlset>+<url><loc>https://laoshi.ink/actresses/actor-075.html</loc></url>+<url><loc>https://laoshi.ink/actresses/actor-001.html</loc></url>+<url><loc>https://laoshi.ink/korean/actor-003.html</loc></url>+<url><loc>https://laoshi.ink/actresses/actor-001.html</loc></url>+</urlset>"""++LAOSHI_PAGE = """<html><head>+<title>波多野结衣(波多野結衣 / Yui Hatano)|日本女优资料与职业履历 - 老师图鉴</title>+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "Person",+ "name": "波多野结衣", "sameAs": ["https://x.com/hatano_yui"]}]}</script>+</head><body>+<a href="/actresses/index.html">返回</a>+<a href="https://cdn.jsdelivr.net/npm/x.js">脚本</a>+<div class="spot-fact-table">+ <div><span>中文名</span><strong>波多野结衣</strong></div>+ <div><span>日文名</span><strong>波多野結衣</strong></div>+ <div><span>罗马音</span><strong>Yui Hatano</strong></div>+ <div><span>别名</span><strong>待补充</strong></div>+ <div><span>公开主页</span><strong>X / Twitter</strong></div>+</div>+<a href="https://x.com/hatano_yui" target="_blank">X</a>+<a href="https://x.com/intent/follow?screen_name=hatano_yui">关注</a>+</body></html>"""++LAOSHI_TWO_NAMES = """<html><head><title>西田カリナ(Karina Nishida)|资料 - 老师图鉴</title></head>+<body><div><span>别名</span><strong>西田卡莉娜、にしだカリナ</strong></div></body></html>"""++# 按 2026-09-02 实测的 bstar-pro.com 复刻:列表页要先过年龄门;页脚有写坏的相对路径。+BSTAR_GATE = '<form method="post"><input type="radio" name="age_check" value="yes"></form>'+BSTAR_LIST = """<ul>+ <li><a href="model.html?mid=355" class="model_img_hover"><img alt="瀬戸環奈">+ <span class="infoDate">瀬戸環奈</span><span>Kanna Seto</span></a></li>+ <li><a href="model.html?mid=360"><img alt="架空同名"><span>架空同名</span></a></li>+ <li><a href="model.html?mid=355">重复</a></li>+</ul>+<a href="https://x.com/bstar_pro/">X</a><a href="https://www.instagram.com/bstar_pro_">IG</a>"""+BSTAR_MODEL = """<ul class="sns_list">+ <li><a href="https://x.com/kanna_seto0510"></a></li>+ <li><a href="https://x.com/setokan_sub"></a></li>+ <li><a href="https://www.instagram.com/setokanna_/"></a></li>+ <li><a href="https://www.youtube.com/@setokan.channel"></a></li>+</ul>+<a href="https://s1s1s1.com/actress/detail/849776">S1</a>+<a href="https://x.com/bstar_pro/">事务所</a>+<a href="/https://www.instagram.com/bstar_pro_">写坏的</a>"""++X_ALIVE = """<html><head><meta content="瀬戸環奈 (@kanna_seto0510) / X" property="og:title">+<meta property="og:image" content="https://pbs.twimg.com/profile_images/1/abc_200x200.jpg"></head></html>"""+X_SUSPENDED = """<html><head><meta property="og:title" content="X"><meta property="og:image"+ content="https://abs.twimg.com/responsive-web/client-web/icon-ios.png"></head></html>"""+X_SHELL = "<html><head><title>X</title></head><body><div id='react-root'></div></body></html>"+++class FakeSite:+ """按 URL 查字典的取页器;模仿年龄门:POST 过之前 bstar 页面一律给门。"""++ def __init__(self, pages, gated=False, HttpStatusError=RuntimeError):+ self.pages, self.gated, self.opened = pages, gated, False+ self.posts = []+ self.fetched = self.cached = 0+ self.error = HttpStatusError++ def get(self, url, refresh=False):+ if self.gated and "bstar-pro.com" in url and not self.opened:+ return BSTAR_GATE+ if url not in self.pages:+ raise self.error(404)+ return self.pages[url]++ def request(self, method, url, body=None, headers=None):+ self.posts.append((method, url, body))+ if body and b"age_check=yes" in body:+ self.opened = True+ return ""++ def close(self):+ pass+++PERFORMERS = [+ {"entity_id": 1, "name": "波多野结衣", "chain": ["波多野結衣", "波多野结衣"]},+ {"entity_id": 2, "name": "濑户环奈", "chain": ["瀬戸環奈", "濑户环奈"]},+ {"entity_id": 3, "name": "架空同名", "chain": ["架空同名"]},+ {"entity_id": 4, "name": "另一位同名", "chain": ["架空同名", "另一位同名"]},+]+++class SharedJudgementTests(unittest.TestCase):+ """`peach.social_links` 是三个采集器共用的判据,行为定在这里。"""++ def test_handle_folds_case_and_skips_platform_prefixes(self):+ """`@Yua_Mikami` 和 `@yua_mikami` 是同一个人;YouTube 的 channel/ 只是路径前缀。"""+ self.assertEqual(social_links.handle("https://x.com/Yua_Mikami"), "yua_mikami")+ self.assertEqual(social_links.handle("https://www.youtube.com/channel/UCabc"), "ucabc")+ self.assertEqual(social_links.handle("https://www.youtube.com/@setokan.channel"),+ "setokan.channel")++ def test_platform_function_pages_are_not_accounts(self):+ """`x.com/intent/follow?…` 和 `instagram.com/p/…` 谁都能挂,不是任何人的账号。"""+ self.assertEqual(social_links.handle("https://x.com/intent/follow?screen_name=a"), "")+ self.assertEqual(social_links.handle("https://www.instagram.com/p/Cxyz/"), "")++ def test_classify_labels_youtube_by_channel_name_not_by_prefix(self):+ """`@名字` 进标签;`channel/UC…` 那串是频道 ID,写进标签只是一行乱码。"""+ self.assertEqual(social_links.classify("https://www.youtube.com/@setokan.channel"),+ ("social", "YouTube @setokan.channel"))+ self.assertEqual(social_links.classify("https://www.youtube.com/channel/UC78MKlRFJzLXiWlXcP7o1BQ"),+ ("social", "YouTube"))+ self.assertEqual(social_links.classify("https://twitter.com/alice_710_"),+ ("social", "X @alice_710_"))++ def test_canonical_url_only_renames_the_same_site(self):+ """twitter.com 是 x.com 的旧名,路径原样搬;别的站原样返回。"""+ self.assertEqual(social_links.canonical_url("http://twitter.com/A_b?x=1"),+ "https://x.com/A_b?x=1")+ self.assertEqual(social_links.canonical_url("https://www.instagram.com/a/"),+ "https://www.instagram.com/a/")++ def test_name_key_ignores_width_spacing_and_case(self):+ self.assertEqual(social_links.name_key("Yua Mikami"), social_links.name_key("yua mikami"))+ self.assertEqual(social_links.name_key("三上 悠亜"), social_links.name_key("三上悠亜"))++ def test_x_state_needs_a_profile_image_to_count_as_alive(self):+ """封停页也有 og 标签,只是 og:image 是 X 的图标不是 profile_images。++ 什么 og 都没有的是 JS 壳或限流页,看不出死活,不能把限流当成封停。+ """+ self.assertEqual(social_links.x_profile_state(X_ALIVE),+ ("alive", "瀬戸環奈 (@kanna_seto0510) / X"))+ self.assertEqual(social_links.x_profile_state(X_SUSPENDED)[0], "gone")+ self.assertEqual(social_links.x_profile_state(X_SHELL)[0], "unknown")+ self.assertEqual(social_links.x_profile_state("<p>Account suspended</p>")[0], "gone")+++class LaoshiParseTests(unittest.TestCase):+ def setUp(self):+ self.module = load_module()++ def test_listing_keeps_only_actress_pages_deduped_and_sorted(self):+ self.assertEqual(self.module.laoshi_listing(SITEMAP),+ ["https://laoshi.ink/actresses/actor-001.html",+ "https://laoshi.ink/actresses/actor-075.html"])++ def test_names_come_from_title_and_fact_table_without_placeholders(self):+ """「待补充」不是名字;标题括号里的日文名和罗马字都要拆出来。"""+ self.assertEqual(self.module.laoshi_names(LAOSHI_PAGE),+ ["波多野结衣", "波多野結衣", "Yui Hatano"])+ self.assertEqual(self.module.laoshi_names(LAOSHI_TWO_NAMES),+ ["西田カリナ", "Karina Nishida", "西田卡莉娜", "にしだカリナ"])++ def test_links_merge_same_as_with_anchors_and_drop_site_internal(self):+ """sameAs 与正文锚点指向同一账号时只留一条;站内与 CDN 链接不是这个人的。"""+ links = self.module.laoshi_links(LAOSHI_PAGE)+ self.assertIn("https://x.com/hatano_yui", links)+ self.assertEqual(links.count("https://x.com/hatano_yui"), 1)+ self.assertNotIn("/actresses/index.html", links)+ self.assertTrue(all("laoshi.ink" not in url for url in links))+++class BstarCollectTests(unittest.TestCase):+ def setUp(self):+ self.module = load_module()+ self.pages = {self.module.BSTAR_MODELS: BSTAR_LIST,+ "https://bstar-pro.com/model.html?mid=355": BSTAR_MODEL}++ def test_listing_pairs_each_model_page_with_its_names_once(self):+ self.assertEqual(self.module.bstar_listing(BSTAR_LIST)[0],+ ("https://bstar-pro.com/model.html?mid=355", ["瀬戸環奈", "Kanna Seto"]))+ self.assertEqual(len(self.module.bstar_listing(BSTAR_LIST)), 2)++ def test_the_age_gate_is_passed_once_and_the_page_refetched(self):+ """models.html 先给年龄门;POST age_check=yes 之后同一会话才给列表。"""+ site = FakeSite(self.pages, gated=True, HttpStatusError=self.module.HttpStatusError)+ site_links, pages = self.module.collect_bstar(site)+ self.assertEqual([post[0] for post in site.posts], ["POST"])+ self.assertEqual({url for url in site_links},+ {"https://x.com/bstar_pro/", "https://www.instagram.com/bstar_pro_"})+ self.assertEqual(pages[0]["names"], ["瀬戸環奈", "Kanna Seto"])+ self.assertEqual(pages[0]["official"], ("https://bstar-pro.com/model.html?mid=355", "Bstar"))++ def test_a_missing_model_page_becomes_未取得_not_a_crash(self):+ site = FakeSite(self.pages, HttpStatusError=self.module.HttpStatusError)+ _, pages = self.module.collect_bstar(site)+ self.assertTrue(pages[1]["note"].startswith("未取得:HttpStatusError: HTTP 404"), pages[1]["note"])+ self.assertEqual(pages[1]["links"], [])++ def test_the_broken_relative_footer_link_lands_on_the_own_host_and_is_dropped(self):+ links = self.module.external_links(BSTAR_MODEL, ("bstar-pro.com",), "https://bstar-pro.com/")+ self.assertNotIn("https://bstar-pro.com/https://www.instagram.com/bstar_pro_", links)+ self.assertIn("https://s1s1s1.com/actress/detail/849776", links)+++class JudgeTests(unittest.TestCase):+ def setUp(self):+ self.module = load_module()++ def page(self, source, url, names, links, official=None, note=""):+ return self.module.page_record(source, url, names, links, official=official, note=note)++ def judge(self, pages, site_links=(), existing=None, urls=None):+ return self.module.judge(pages, list(site_links), PERFORMERS, existing or {}, urls or {})++ def test_a_unique_match_yields_ok_rows_for_every_new_account_on_the_page(self):+ """同一页两个 X 账号是主号加副号,都装;事务所自己的账号减掉;非社交外链不算。"""+ page = self.page("bstar", "https://bstar-pro.com/model.html?mid=355", ["瀬戸環奈", "Kanna Seto"],+ ["https://x.com/kanna_seto0510", "https://x.com/setokan_sub",+ "https://www.instagram.com/setokanna_/", "https://x.com/bstar_pro/",+ "https://s1s1s1.com/actress/detail/849776"],+ official=("https://bstar-pro.com/model.html?mid=355", "Bstar"))+ rows, stats = self.judge([page], site_links=["https://x.com/bstar_pro/"])+ self.assertEqual([row["verdict"] for row in rows], ["ok"] * 4)+ self.assertEqual({row["label"] for row in rows},+ {"X @kanna_seto0510", "X @setokan_sub", "Instagram @setokanna_", "Bstar"})+ self.assertTrue(all(row["entity_id"] == 2 and row["name"] == "濑户环奈" for row in rows))+ self.assertIn("对上账本「濑户环奈」", rows[0]["evidence"])+ self.assertEqual(stats["ok"], 4)++ def test_the_same_account_in_the_old_host_shape_is_已有_not_a_duplicate(self):+ """账本存 `twitter.com/Hatano_Yui`,页面给 `x.com/hatano_yui`:同一个账号。"""+ existing = {1: {("X", "hatano_yui"): "https://twitter.com/Hatano_Yui"}}+ page = self.page("laoshi", "https://laoshi.ink/actresses/actor-001.html",+ ["波多野结衣", "波多野結衣"], ["https://x.com/hatano_yui"])+ rows, _ = self.judge([page], existing=existing)+ self.assertEqual([row["verdict"] for row in rows], ["已有"])+ self.assertIn("twitter.com/Hatano_Yui", rows[0]["evidence"])++ def test_a_different_account_on_a_platform_the_ledger_already_has_is_a_conflict(self):+ """这是用户要的「交叉对比」:两处资料说的不是同一个账号,只报不装。"""+ existing = {1: {("X", "old_hatano"): "https://x.com/old_hatano"}}+ page = self.page("laoshi", "https://laoshi.ink/actresses/actor-001.html",+ ["波多野結衣"], ["https://x.com/hatano_yui"])+ rows, stats = self.judge([page], existing=existing)+ self.assertEqual(rows[0]["verdict"], "conflict")+ self.assertIn("另有 https://x.com/old_hatano", rows[0]["evidence"])+ self.assertEqual(stats["conflict"], 1)++ def test_an_ok_from_one_source_makes_the_next_source_report_已有_or_conflict(self):+ """两个来源先后给同一个人:第二个来源看到第一个来源装进去的账号。"""+ existing = {}+ first = self.page("laoshi", "https://laoshi.ink/actresses/actor-001.html",+ ["波多野結衣"], ["https://x.com/hatano_yui"])+ second = self.page("bstar", "https://bstar-pro.com/model.html?mid=1",+ ["波多野結衣"], ["https://x.com/HATANO_YUI", "https://x.com/other"])+ rows, _ = self.judge([first, second], existing=existing)+ self.assertEqual([row["verdict"] for row in rows], ["ok", "已有", "conflict"])++ def test_a_name_matching_several_performers_is_需人工消歧_with_no_entity(self):+ page = self.page("laoshi", "https://laoshi.ink/actresses/actor-9.html",+ ["架空同名"], ["https://x.com/someone"])+ rows, _ = self.judge([page])+ self.assertEqual(rows[0]["verdict"], "需人工消歧")+ self.assertEqual(rows[0]["entity_id"], "")+ self.assertIn("架空同名、另一位同名", rows[0]["evidence"])++ def test_pages_not_in_the_ledger_are_counted_but_not_written(self):+ page = self.page("laoshi", "https://laoshi.ink/actresses/actor-8.html",+ ["不在库里的人"], ["https://x.com/nobody"])+ rows, stats = self.judge([page])+ self.assertEqual(rows, [])+ self.assertEqual(stats["页面不在账本"], 1)++ def test_a_matched_page_without_social_links_and_a_failed_page_both_leave_a_trace(self):+ """命中却没链接要写下来——否则看不出这个人在来源里是有页没号,还是根本没页。"""+ empty = self.page("laoshi", "https://laoshi.ink/actresses/actor-001.html", ["波多野結衣"], [])+ broken = self.page("laoshi", "https://laoshi.ink/actresses/actor-002.html", [], [],+ note="未取得:HttpStatusError: HTTP 503")+ rows, stats = self.judge([empty, broken])+ self.assertEqual([(row["verdict"], row["entity_id"]) for row in rows],+ [("未取得", 1), ("未取得", "")])+ self.assertEqual((stats["命中但无社媒"], stats["页面未取得"]), (1, 1))++ def test_the_official_page_is_已有_when_the_ledger_already_holds_it(self):+ url = "https://bstar-pro.com/model.html?mid=355"+ page = self.page("bstar", url, ["瀬戸環奈"], [], official=(url, "Bstar"))+ rows, _ = self.judge([page], urls={2: {url}})+ self.assertEqual([(row["link_kind"], row["verdict"]) for row in rows], [("official", "已有")])+++class ProbeTests(unittest.TestCase):+ def setUp(self):+ self.module = load_module()++ def rows(self):+ return [self.module.row(entity_id=2, link_kind="social", url="https://x.com/kanna_seto0510",+ verdict="ok"),+ self.module.row(entity_id=2, link_kind="social", url="https://x.com/gone_one",+ verdict="ok"),+ self.module.row(entity_id=2, link_kind="social", url="https://x.com/missing",+ verdict="conflict", evidence="e"),+ self.module.row(entity_id=2, link_kind="social",+ url="https://www.instagram.com/setokanna_/", verdict="ok"),+ self.module.row(entity_id=2, link_kind="official", url="https://bstar-pro.com/m",+ verdict="ok"),+ self.module.row(entity_id=1, link_kind="social", url="https://x.com/x", verdict="已有")]++ def test_only_live_or_unverifiable_ok_rows_enter_the_install_queue(self):+ """来源可能是旧数据:封停的 X 账号不能装;Instagram 登出页看不出死活,标未验照装。++ 实测不存在的账号登出页是 200 的 JS 壳,没有任何 og;只有对照账号同一时刻有 og,+ 才能说它是真没了。+ """+ site = FakeSite({"https://x.com/kanna_seto0510": X_ALIVE, "https://x.com/gone_one": X_SHELL,+ "https://x.com/old_hatano": X_SUSPENDED, "https://x.com/X": X_ALIVE},+ HttpStatusError=self.module.HttpStatusError)+ rows = self.rows()+ existing = {2: {("X", "old_hatano"): "https://x.com/old_hatano"}}+ stats = self.module.probe_rows(rows, existing, site)+ self.assertEqual([row["alive"] for row in rows], ["活", "疑似失效", "疑似失效", "未验", "", ""])+ self.assertIn("X 显示名「瀬戸環奈 (@kanna_seto0510) / X」", rows[0]["evidence"])+ self.assertIn("X 验活:登出页无资料,对照账号正常", rows[1]["evidence"])+ self.assertIn("账本旧号 https://x.com/old_hatano:疑似失效", rows[2]["evidence"])+ self.assertEqual(dict(stats), {"活": 1, "疑似失效": 2})+ queue = self.module.installable(rows)+ self.assertEqual([row["url"] for row in queue],+ ["https://x.com/kanna_seto0510", "https://www.instagram.com/setokanna_/",+ "https://bstar-pro.com/m"])++ def test_a_shell_page_is_未取得_when_the_control_account_is_also_a_shell(self):+ """对照账号也没有 og 说明是我们被限流了,不能把限流记成账号封停。"""+ site = FakeSite({"https://x.com/gone_one": X_SHELL, "https://x.com/X": X_SHELL},+ HttpStatusError=self.module.HttpStatusError)+ rows = [self.module.row(link_kind="social", url="https://x.com/gone_one", verdict="ok")]+ self.module.probe_rows(rows, {}, site)+ self.assertEqual(rows[0]["alive"], "未取得")+ self.assertIn("限流", rows[0]["evidence"])+ self.assertEqual(len(self.module.installable(rows)), 1)++ def test_a_404_is_gone_and_a_transport_error_is_unknown(self):+ """404 是账号不存在;连不上是我们的问题,不能记在账号头上。"""+ class Boom(FakeSite):+ def get(self, url, refresh=False):+ if "boom" in url:+ raise OSError("reset")+ return super().get(url, refresh)+ site = Boom({}, HttpStatusError=self.module.HttpStatusError)+ rows = [self.module.row(link_kind="social", url="https://x.com/missing", verdict="ok"),+ self.module.row(link_kind="social", url="https://x.com/boom", verdict="ok")]+ self.module.probe_rows(rows, {}, site)+ self.assertEqual([row["alive"] for row in rows], ["疑似失效", "未取得"])+ self.assertEqual(len(self.module.installable(rows)), 1)++ def test_without_a_probe_site_every_social_row_is_marked_unverified(self):+ rows = self.rows()+ self.module.probe_rows(rows, {}, None)+ self.assertEqual([row["alive"] for row in rows], ["未验", "未验", "未验", "未验", "", ""])+++class CacheTests(unittest.TestCase):+ def test_a_cached_page_is_served_without_touching_the_network(self):+ """规则改一行就得重比 686 页;没有缓存就是一次完整重抓。"""+ module = load_module()+ calls = []++ class Transport:+ def __call__(self, request, timeout, max_bytes):+ calls.append(request.url)+ return type("R", (), {"status": 200, "body": b"<p>hi</p>", "url": request.url})()++ def close(self):+ pass++ root = Path(tempfile.mkdtemp()).resolve()+ site = module.Site(root, 0, 5, transport=Transport())+ self.assertEqual(site.get("https://laoshi.ink/a"), "<p>hi</p>")+ self.assertEqual(site.get("https://laoshi.ink/a"), "<p>hi</p>")+ self.assertEqual((len(calls), site.fetched, site.cached), (1, 1, 1))+ site.get("https://laoshi.ink/a", refresh=True)+ self.assertEqual(len(calls), 2)+++if __name__ == "__main__":+ unittest.main()