Peach: Local-first video metadata scraper and media manager.
feat(metadata): add source policy and health reports
longmeidao1eed1ee09d50
diff --git a/README.md b/README.mdindex 7dcf6078d..fd899da0b 100644--- a/README.md+++ b/README.md@@ -367,6 +367,18 @@ cookie 并重定向到不含口令的干净 URL;新设备不要再复制带口`scripts/scrape_codes.py` 只把规范化番号交给固定版本 Javinizer-Go,逐来源保存原始 JSON,并为演员、厂牌、系列、发行日期和内容标签生成字段候选;官方/官方镜像标签来源优先。它没有整批 `--apply`,只有 `/review` 中明确选中某个来源值并批准才写 ledger。`scripts/clean_names.py` 默认只生成改名计划;`--apply` 会先备份 SQLite,并在数据库更新失败时把文件名回滚。两者导入模块时均无副作用,测试不得使用真实路径。+来源策略必须显式选择,默认行为保持 `baseline=r18dev`;`--sources` 是兼容入口,不能和 `--profile` 同时使用。`fc2` profile 只处理 FC2,其他 profile 默认排除 FC2。每批都会生成 source health CSV:++```powershell+# 默认 baseline;候选、错误和健康报告都写到显式复核目录+& .\.venv\Scripts\python.exe scripts\scrape_codes.py --db .\review\ledger.db --out .\review\metadata-field-candidates.csv --health .\review\metadata-source-health.csv++# 显式选择类别;不会自动批准或写回 ledger+& .\.venv\Scripts\python.exe scripts\scrape_codes.py --db .\review\ledger.db --profile censored --out .\review\censored-candidates.csv+& .\.venv\Scripts\python.exe scripts\scrape_codes.py --db .\review\ledger.db --profile uncensored --out .\review\uncensored-candidates.csv+& .\.venv\Scripts\python.exe scripts\scrape_codes.py --db .\review\ledger.db --profile fc2 --out .\review\fc2-candidates.csv+```+历史创作者投影使用逐项只读审计,不再把目录名直接当身份:```powershelldiff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex ff5c2d25a..1c1004d81 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -123,7 +123,7 @@ Claude 的 `.claude/settings.json` 已配置 Stop、StopFailure、SessionEnd hoo- **标签添加弹窗(2026-08-15)**:用户提供 macOS 标签管理弹窗截图,未提供产品名或可访问 URL,源码证据为 `未取得`。Peach 只复用截图可证实的交互层级:搜索、最近使用、全部标签、已选状态和键盘上下/Enter/Escape;不声称像素或源码级复刻。- **YouTube 详情参考(2026-08-17)**:实时取得 `https://www.youtube.com/watch?v=dQw4w9WgXcQ` 当前页面 HTML;页面使用 `Roboto`、暗色详情播放器与高对比控制条,播放器资源预加载 `hqdefault.jpg`,当前页面 bundle 版本由 WIZ 配置标识为 `youtube.web-front-end-critical_20260811.08_p0`。用户同时提供详情/卡片截图。Peach 只复用可复现的层级原则:详情操作采用连续圆角操作组、hover 提亮、active 使用蓝色语义;播放区 ambient 使用模糊画面并向上下渐隐。未复制 YouTube 品牌、播放器源码或登录能力。- **YouTube Shorts 播放/动作栏参考(2026-08-17)**:实时取得 `https://www.youtube.com/shorts/BJynPKgwfyA`,页面 `INNERTUBE_CLIENT_VERSION=2.20260813.05.00`;协作浏览器快照未取得,但运行时 DOM/CSS 可复核。`#shorts-player` 为 `396×704`,视频 `object-fit:cover`;右侧动作容器宽 `72px`、左右内边距 `12px`;动作按钮为 `48×48px`、`rgba(255,255,255,.1)`、圆角 `24px`,文字位于独立的垂直标签容器;全屏按钮同为 `48px` 圆形。Peach 复用 48px tonal 圆形和克制的动作层级;横屏片源全视口 cover,竖屏片源按真实宽高切到 contain 保留完整画面,并保留自己的 Lucide 图标、色彩 token、横竖屏混流和业务反馈语义。-- **Javinizer-Go 元数据 Provider(2026-08-22)**:取得官方仓库 `https://github.com/javinizer/javinizer-go`、v1.5.1 release 与 tag commit `f57985c8c98a0ad7283f72854c249b8612300637`;macOS arm64 SHA-256 `6197d78c…f179d`、Windows amd64 SHA-256 `4d5b0bc6…1abca` 均与发布值一致。Windows 必须锁定 subprocess UTF-8,且 r18dev 要显式绑定 `scrapers.r18dev.proxy.profile` 才走 7897。`IPX-535` 已验证真实单来源 JSON;Peach 只发送规范番号、逐源留原始证据,并为演员/厂牌/系列/发行日期/内容标签形成字段候选,官方 tag 优先,批准后才写 ledger,不使用其 organizer。+- **Javinizer-Go 元数据 Provider(v1.5.1,tag `f57985c8c98a0ad7283f72854c249b8612300637`)**:Peach 只发送规范番号并逐 source 查询,不调用 organizer、不新增站点 scraper。`metadata_policy.py` 固定14源白名单、baseline/censored/uncensored/fc2 profile、五字段独立顺序与 policy version;`--sources` 保持兼容且不能与 `--profile` 混用。候选携带 profile/rank/source kind/official/provenance,批准后才写 ledger;每批另写 source health,区分快照、联网、空结果、错误与403/429/503/retryable来源级冷却。## 智能体用量与任务路由- 调度看官方配额窗口,不看 API 等价美元估算。Codex 使用 App Server `account/rateLimits/read`;Claude 使用 Claude Code 已登录用量界面。不得打印、复制或保存 OAuth token。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 24486ef5c..514662cc0 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -25,7 +25,7 @@| 位图 | Pillow | 头像/Logo 质量和来源策略 || 搜索 | SQLite FTS5 | 索引字段、排序、profile 感知筛选 || 女优姓名对照 | `li-peifeng/Jav-Actors-Mapping` 的固定 revision,仅作私有输入(仓库未声明许可证,不随 Peach 分发) | 精确匹配、冲突复核、别名、来源与真实 ledger 写入 |-| JAV 元数据查询 | Javinizer-Go v1.5.1 单来源 JSON CLI(MIT) | 只发送规范番号;逐源原始证据、发行日期/实体/标签字段候选、官方 tag 优先、重复值硬门槛、人工批准和 ledger 投影 |+| JAV 元数据查询 | Javinizer-Go v1.5.1 单来源 JSON CLI(MIT) | 只发送规范番号;Peach 管 source profile、逐字段优先级、原始证据、健康统计、候选复核与批准后的 ledger 投影 || 媒体探测/转码 | Peach 管理的 FFmpeg/ffprobe | 任务策略和 Media Engine 编排 || HTML5/HLS/DASH 播放 | Video.js 8.23.9 + 内置 VHS(Apache-2.0,本地固定版本) | 流方案、授权、稳定时长、回退顺序和统计面板 || 照片灯箱轮播 | Swiper 14.1.0(MIT,本地固定版本,按需 `<script>` 注入)的 Thumbs / Keyboard / Zoom 模块 | 图集来源与顺序、缩略图缓存与计费口径、瀑布流本身(CSS `column-count`,不经过 Swiper) |@@ -60,7 +60,7 @@已完成:共享 Media/Job/HTTP 边界、feedparser、Pillow、Beautiful Soup、FTS5、可安全导入的批处理脚本和按任务范围终止进程。1. Video.js 已接管详情播放;`MediaEngine.stream_plan` 已让 115/PikPak 原生 MP4 使用 HLS 临时短片段,仍需补自适应码率、多路清单和生产验收。CloudDrive 的虚拟盘固定块预取仍属于来源层成本。-2. Javinizer-Go 已接管番号元数据查询适配;扩展新来源时优先启用其现有 scraper,Stash 保留为媒体绑定和后续对账适配器。+2. Javinizer-Go 已接管番号元数据查询适配;来源扩展只加入 Peach policy 白名单/profile 与健康统计,优先启用其现有 scraper,不在 Peach 分叉站点解析器。3. 将剩余 status/suggest/ledger 应用逻辑移到 repository/application 端口,再删除旧 CLI 表面。4. Peach 不做 token/成本日志扫描器,也不绑定 T3 Code 私有 RPC;使用其界面、CodexBar 和官方实时配额入口。5. 「模仿/参考/对齐」不等于允许凭记忆近似。先取得并登记可复现证据;否则标记 `未取得`,不得作为忠实复刻发布。2026-08-17 的 YouTube 详情与 Shorts 动作栏参考已登记在 `docs/HANDOFF.md`,Peach 只复用可测量的层级、尺寸和状态语义。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 71c122822..2d52804c3 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -162,6 +162,7 @@- 2026-08-21 macOS 最新基线:`./scripts/test.sh` 全量 468 项通过、3 项跳过;Windows 当前状态提交`& .\scripts\test.ps1` 全量 460 项通过、12 项按平台跳过;上下文预算检查通过。- 2026-08-22 Javinizer-Go P0 已部署到 Windows:真实 ledger limit=10 生成 43 组(演员10、厂牌10、系列4、发行日期10、标签9)及10份 raw JSON,错误0。2026-08-24 复核时这43组仍为候选,`metadata_fields` 批准数0,因此真实 `release_date` 仍为0条、`javinizer:*:tag` 仍为0条;旧 `r18` 标签已有2,371条。详情已经消费 `release_date` 与批准后的内容标签,人工批准后直接显示。+- Javinizer-Go P1 来源策略层已实现:锁定 v1.5.1 的14源白名单,新增 baseline(默认仍仅 r18dev)、censored、uncensored、fc2 显式 profile;兼容 `--sources`,冲突与未知 source 在联网前拒绝。五个 Peach 字段分别按 policy 排序,候选携带 source profile、policy version、field rank、source kind 与显式 official。每批无论有无错误都写 `metadata-source-health-*.csv`,按 source 区分快照复用、联网成功、空结果、错误、冷却跳过、耗时与五字段命中。没有批量批准、自动写库或 schema 迁移。- Windows 无外置盘生产验收:HTTP 与严格 CA HTTPS `/healthz` 返回 200,账本、FFmpeg、115 和PikPak 可用,只有 `local` 来源离线;115 HTTP 与 PikPak 严格 HTTPS 各完成 1 KiB `206` Range。- 双机同时在线时账本世代 18、状态 `in-sync`;`peach-win.local` 与 `peach.local` 分别只由diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.pyindex da6f9eac6..b7c1e895c 100644--- a/scripts/scrape_codes.py+++ b/scripts/scrape_codes.py@@ -26,6 +26,12 @@ from peach.metadata import (MetadataProviderError,extract_peach_fields,)+from peach.metadata_policy import (+ PEACH_FIELDS,+ MetadataPolicy,+ resolve_policy,+ sort_candidates,+)_logf = None@@ -35,15 +41,15 @@ FIELD_LABELS = {}FIELDS = ["item_key", "code", "query", "field", "field_label", "current_value",- "candidates_json", "source_count", "status", "size_gb", "videos", "fetched_at",+ "candidates_json", "source_count", "source_profile", "policy_version",+ "status", "size_gb", "videos", "fetched_at",]ERROR_FIELDS = ["code", "query", "source", "kind", "status_code", "retryable", "message"]-TAG_SOURCE_PRIORITY = {- "dmm": 100, "mgstage": 100, "tokyohot": 100, "aventertainment": 100,- "caribbeancom": 100, "fc2": 100, "r18dev": 90, "libredmm": 90,- "javstash": 70, "javdb": 50, "javbus": 40, "javlibrary": 40,- "jav321": 30, "dlgetchu": 30,-}+HEALTH_FIELDS = [+ "source", "profile", "attempted", "snapshot_reused", "fetched", "succeeded",+ "empty", "errors", "retryable_errors", "cooldown_skips", "blocked", "elapsed_ms",+ *PEACH_FIELDS, "last_error_kind", "last_error_status", "last_error_message",+]# Javinizer r18dev genre -> Peach's reviewed content taxonomy. Unknown source values@@ -192,7 +198,11 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--log-dir", type=Path, default=LOG_DIR)parser.add_argument("--config", type=Path, default=STATE_DIR / "javinizer-provider" / "config.yaml")parser.add_argument("--binary", type=Path)- parser.add_argument("--sources", default="r18dev", help="enabled Javinizer scraper names")+ source_group = parser.add_mutually_exclusive_group()+ source_group.add_argument("--profile", choices=("baseline", "censored", "uncensored", "fc2"),+ help="explicit Peach source preset; default baseline")+ source_group.add_argument("--sources", help="compatible comma-separated Javinizer scraper names")+ parser.add_argument("--health", type=Path, default=None)parser.add_argument("--limit", type=int, default=0)parser.add_argument("--delay", type=float, default=1.2)parser.add_argument("--refresh", action="store_true", help="ignore reusable raw snapshots")@@ -200,19 +210,56 @@ def build_parser() -> argparse.ArgumentParser:return parser+def _health_output(output: Path) -> Path:+ name = output.name.replace("metadata-field-candidates-", "metadata-source-health-", 1)+ if name == output.name:+ name = output.stem + "-health.csv"+ return output.with_name(name)+++def _health_rows(policy: MetadataPolicy) -> dict[str, dict[str, object]]:+ return {source: {+ "source": source, "profile": policy.profile, "attempted": 0,+ "snapshot_reused": 0, "fetched": 0, "succeeded": 0, "empty": 0,+ "errors": 0, "retryable_errors": 0, "cooldown_skips": 0,+ "blocked": 0, "elapsed_ms": 0,+ **{field: 0 for field in PEACH_FIELDS},+ "last_error_kind": "", "last_error_status": "", "last_error_message": "",+ } for source in policy.sources}+++def _write_health(path: Path, rows: dict[str, dict[str, object]]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_suffix(path.suffix + ".tmp")+ with temporary.open("w", encoding="utf-8-sig", newline="") as handle:+ writer = csv.DictWriter(handle, fieldnames=HEALTH_FIELDS)+ writer.writeheader()+ for source in rows:+ writer.writerow(rows[source])+ os.replace(temporary, path)++def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None = None) -> int:- args = build_parser().parse_args(argv)+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ policy = resolve_policy(profile=args.profile, sources=args.sources)+ except ValueError as error:+ parser.error(str(error))+ explicit_sources = args.sources is not None+ if args.profile == "fc2" and args.include_fc2:+ parser.error("fc2 profile 已只处理 FC2,不能再加 --include-fc2")output = args.out or _default_output()error_name = output.name.replace("metadata-field-candidates-", "metadata-source-errors-", 1)if error_name == output.name:error_name = output.stem + "-errors.csv"errors_path = args.errors or output.with_name(error_name)+ health_path = args.health or _health_output(output)output.parent.mkdir(parents=True, exist_ok=True)errors_path.parent.mkdir(parents=True, exist_ok=True)configure_log(args.log_dir)- sources = [source.strip() for source in args.sources.split(",") if source.strip()]- if not sources:- raise ValueError("至少指定一个 Javinizer-Go source")+ sources = list(policy.sources)+ health = _health_rows(policy)adapter = provider or JavinizerGoProvider.create(args.binary, args.config)connection = sqlite3.connect(args.db.resolve().as_uri() + "?mode=ro", uri=True)@@ -225,11 +272,12 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None)if _is_explicit_code(str(row[0]))]- if not args.include_fc2:- codes = [row for row in codes if not row[0].upper().startswith("FC2")]+ codes = [row for row in codes if policy.allows_code(+ row[0], include_fc2=args.include_fc2, explicit_sources=explicit_sources,+ )]if args.limit:codes = codes[:max(args.limit, 0)]- log(f"字段候选批次:番号 {len(codes)},来源 {','.join(sources)};只读查询,不写 ledger")+ log(f"字段候选批次:profile {policy.profile},番号 {len(codes)},来源 {','.join(sources)};只读查询,不写 ledger")blocked_sources: set[str] = set()groups_written = errors_written = 0@@ -243,12 +291,21 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | Noneby_field: dict[str, list[dict]] = {}fetched_at = datetime.now(timezone.utc).isoformat()for source in sources:+ source_health = health[source]+ source_health["attempted"] += 1if source in blocked_sources:+ source_health["cooldown_skips"] += 1continuesnapshot = args.raw_dir / query / f"{source}.json"+ started = time.perf_counter()payload = None if args.refresh else _read_snapshot(snapshot)+ reused = payload is not Nonetry:- payload = payload or adapter.query(query, source)+ if reused:+ source_health["snapshot_reused"] += 1+ else:+ source_health["fetched"] += 1+ payload = adapter.query(query, source)if not snapshot.is_file() or args.refresh:_write_snapshot(snapshot, code=query, source=source, result=payload)except MetadataProviderError as error:@@ -259,19 +316,35 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None"message": str(error),})error_handle.flush(); errors_written += 1- if error.retryable or error.status_code in {429, 503}:+ source_health["errors"] += 1+ source_health["retryable_errors"] += int(error.retryable)+ source_health["last_error_kind"] = error.kind+ source_health["last_error_status"] = error.status_code or ""+ source_health["last_error_message"] = str(error)[:500]+ if error.retryable or error.status_code in {403, 429, 503}:blocked_sources.add(source)+ source_health["blocked"] = 1log(f"{source} 暂时不可用,本批后续番号进入来源级冷却:{error}")continue- for field, extracted in extract_peach_fields(payload, CATEGORY_MAP).items():- tag_priority = TAG_SOURCE_PRIORITY.get(source, 10) if field == "tags" else 0+ finally:+ source_health["elapsed_ms"] += round((time.perf_counter() - started) * 1000)+ extracted_fields = extract_peach_fields(payload, CATEGORY_MAP)+ source_health["succeeded"] += 1+ if not extracted_fields:+ source_health["empty"] += 1+ for field, extracted in extracted_fields.items():+ source_health[field] += 1+ source_spec = policy.source(source)candidate = {"candidate_key": _candidate_key(query, field, source, extracted["value"]),"source": source,"source_url": str(payload.get("source_url") or ""),"confidence": 0.9 if source == "r18dev" else 0.75,- "priority": tag_priority,- "official": bool(field == "tags" and tag_priority >= 90),+ "profile": policy.profile,+ "policy_version": policy.version,+ "field_rank": policy.field_rank(field, source),+ "source_kind": source_spec.kind,+ "official": source_spec.official,"value": extracted["value"],"display_value": extracted["display_value"],"warnings": extracted["warnings"],@@ -281,26 +354,25 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | Noneif args.delay > 0:time.sleep(args.delay + random.uniform(0, min(0.4, args.delay / 3)))for field, candidates in by_field.items():- if field == "tags":- candidates.sort(key=lambda item: (- -int(item.get("priority") or 0),- -float(item.get("confidence") or 0),- str(item.get("source") or ""),- ))+ candidates = sort_candidates(field, candidates, policy)candidate_writer.writerow({"item_key": f"{query}:{field}", "code": code, "query": query,"field": field, "field_label": FIELD_LABELS[field],"current_value": "、".join(_current_values(connection, code, field)),"candidates_json": json.dumps(candidates, ensure_ascii=False, separators=(",", ":")),- "source_count": len(candidates), "status": "candidate",+ "source_count": len(candidates), "source_profile": policy.profile,+ "policy_version": policy.version, "status": "candidate","size_gb": round(size_gb, 2), "videos": videos, "fetched_at": fetched_at,})groups_written += 1candidate_handle.flush()+ _write_health(health_path, health)if index % 25 == 0:log(f"{index}/{len(codes)}:已落 {groups_written} 个字段组,错误 {errors_written}")connection.close()+ _write_health(health_path, health)log(f"完成:{groups_written} 个字段候选组 → {output}")+ log(f"来源健康 → {health_path}")if errors_written:log(f"来源错误 {errors_written} 条 → {errors_path}")close_log()diff --git a/src/peach/metadata_policy.py b/src/peach/metadata_policy.pynew file mode 100644index 000000000..661d35488--- /dev/null+++ b/src/peach/metadata_policy.py@@ -0,0 +1,142 @@+"""Pure Javinizer-Go source policy owned by Peach."""+from __future__ import annotations++from dataclasses import dataclass+from typing import Iterable, Mapping, Sequence+++POLICY_VERSION = "metadata-source-policy-v1"+PEACH_FIELDS = ("performers", "studio", "series", "release_date", "tags")+REGISTERED_SOURCES = (+ "r18dev", "libredmm", "dmm", "javlibrary", "javdb", "javbus", "jav321",+ "mgstage", "tokyohot", "aventertainment", "caribbeancom", "dlgetchu",+ "fc2", "javstash",+)+++@dataclass(frozen=True)+class SourceSpec:+ name: str+ kind: str++ @property+ def official(self) -> bool:+ return self.kind in {"official", "official_mirror"}+++SOURCE_SPECS = {+ name: SourceSpec(name, kind) for name, kind in {+ "r18dev": "official_mirror", "libredmm": "official_mirror",+ "dmm": "official", "mgstage": "official", "tokyohot": "official",+ "aventertainment": "official", "caribbeancom": "official",+ "dlgetchu": "official", "fc2": "official",+ "javlibrary": "community", "javdb": "community", "javbus": "community",+ "jav321": "community", "javstash": "community",+ }.items()+}++PROFILE_SOURCES = {+ "baseline": ("r18dev",),+ "censored": (+ "dmm", "libredmm", "r18dev", "mgstage", "aventertainment",+ "dlgetchu", "javlibrary", "javdb", "javbus", "jav321", "javstash",+ ),+ "uncensored": (+ "tokyohot", "caribbeancom", "javdb", "javlibrary", "javstash",+ ),+ "fc2": ("fc2",),+}++FIELD_SOURCE_ORDER = {+ "performers": (+ "dmm", "libredmm", "r18dev", "mgstage", "aventertainment",+ "caribbeancom", "tokyohot", "fc2", "javdb", "javbus",+ "javlibrary", "javstash", "jav321", "dlgetchu",+ ),+ "studio": (+ "dmm", "libredmm", "r18dev", "mgstage", "aventertainment",+ "caribbeancom", "tokyohot", "fc2", "javdb", "javbus",+ "javlibrary", "javstash", "jav321", "dlgetchu",+ ),+ "series": (+ "dmm", "libredmm", "r18dev", "mgstage", "aventertainment",+ "caribbeancom", "tokyohot", "fc2", "javdb", "javlibrary",+ "javbus", "javstash", "jav321", "dlgetchu",+ ),+ "release_date": (+ "dmm", "libredmm", "mgstage", "tokyohot", "aventertainment",+ "caribbeancom", "dlgetchu", "fc2", "r18dev", "javdb",+ "javlibrary", "javbus", "jav321", "javstash",+ ),+ "tags": (+ "dmm", "libredmm", "mgstage", "tokyohot", "aventertainment",+ "caribbeancom", "dlgetchu", "fc2", "r18dev", "javstash",+ "javdb", "javlibrary", "javbus", "jav321",+ ),+}+++@dataclass(frozen=True)+class MetadataPolicy:+ profile: str+ sources: tuple[str, ...]+ version: str = POLICY_VERSION++ def field_rank(self, field: str, source: str) -> int:+ order = FIELD_SOURCE_ORDER[field]+ try:+ return order.index(source) + 1+ except ValueError:+ return len(order) + 1++ def source(self, name: str) -> SourceSpec:+ return SOURCE_SPECS[name]++ def allows_code(self, code: str, *, include_fc2: bool = False,+ explicit_sources: bool = False) -> bool:+ is_fc2 = str(code or "").upper().startswith("FC2")+ if self.profile == "fc2":+ return is_fc2+ if not is_fc2:+ return True+ return include_fc2 or (explicit_sources and "fc2" in self.sources)+++def parse_sources(raw: str | Sequence[str]) -> tuple[str, ...]:+ values = raw.split(",") if isinstance(raw, str) else list(raw)+ sources = tuple(dict.fromkeys(str(value).strip() for value in values if str(value).strip()))+ if not sources:+ raise ValueError("至少指定一个 Javinizer-Go source")+ unknown = [source for source in sources if source not in SOURCE_SPECS]+ if unknown:+ raise ValueError("未知 Javinizer-Go source:" + ", ".join(unknown))+ return sources+++def resolve_policy(*, profile: str | None = None,+ sources: str | Sequence[str] | None = None) -> MetadataPolicy:+ if profile and sources is not None:+ raise ValueError("--profile 与 --sources 不能同时使用")+ if profile:+ if profile not in PROFILE_SOURCES:+ raise ValueError("未知 metadata source profile:" + profile)+ return MetadataPolicy(profile, PROFILE_SOURCES[profile])+ if sources is not None:+ return MetadataPolicy("custom", parse_sources(sources))+ return MetadataPolicy("baseline", PROFILE_SOURCES["baseline"])+++def sort_candidates(field: str, candidates: Iterable[Mapping[str, object]],+ policy: MetadataPolicy) -> list[dict]:+ if field not in PEACH_FIELDS:+ raise ValueError("未知 Peach 元数据字段:" + field)+ rows = [dict(candidate) for candidate in candidates]+ for row in rows:+ source = str(row.get("source") or "")+ row["field_rank"] = policy.field_rank(field, source)+ rows.sort(key=lambda row: (+ int(row["field_rank"]),+ -float(row.get("confidence") or 0),+ str(row.get("source") or ""),+ ))+ return rowsdiff --git a/tests/test_metadata_policy.py b/tests/test_metadata_policy.pynew file mode 100644index 000000000..d94a55e13--- /dev/null+++ b/tests/test_metadata_policy.py@@ -0,0 +1,60 @@+import unittest++from peach.metadata_policy import (+ FIELD_SOURCE_ORDER,+ POLICY_VERSION,+ PROFILE_SOURCES,+ REGISTERED_SOURCES,+ resolve_policy,+ sort_candidates,+)+++class MetadataPolicyTests(unittest.TestCase):+ def test_registry_matches_pinned_javinizer_v151_sources(self):+ self.assertEqual(set(REGISTERED_SOURCES), {+ "r18dev", "libredmm", "dmm", "javlibrary", "javdb", "javbus",+ "jav321", "mgstage", "tokyohot", "aventertainment",+ "caribbeancom", "dlgetchu", "fc2", "javstash",+ })+ self.assertTrue(POLICY_VERSION.startswith("metadata-source-policy-"))++ def test_default_and_named_profiles_are_explicit(self):+ self.assertEqual(resolve_policy().sources, ("r18dev",))+ for profile in ("baseline", "censored", "uncensored", "fc2"):+ self.assertEqual(resolve_policy(profile=profile).sources, PROFILE_SOURCES[profile])++ def test_unknown_source_and_conflicting_inputs_fail_early(self):+ with self.assertRaisesRegex(ValueError, "未知 Javinizer-Go source"):+ resolve_policy(sources="r18dev,imaginary")+ with self.assertRaisesRegex(ValueError, "不能同时"):+ resolve_policy(profile="baseline", sources="r18dev")++ def test_fc2_scope_is_never_guessed_for_other_profiles(self):+ baseline = resolve_policy(profile="baseline")+ self.assertFalse(baseline.allows_code("FC2-PPV-1234567"))+ self.assertTrue(resolve_policy(profile="fc2").allows_code("FC2-PPV-1234567"))+ self.assertFalse(resolve_policy(profile="fc2").allows_code("ABW-232"))+ custom = resolve_policy(sources="r18dev,fc2")+ self.assertTrue(custom.allows_code(+ "FC2-PPV-1234567", explicit_sources=True,+ ))++ def test_every_field_uses_policy_order_and_explicit_official_metadata(self):+ policy = resolve_policy(profile="censored")+ candidates = [+ {"source": "javbus", "confidence": 0.99},+ {"source": "r18dev", "confidence": 0.8},+ {"source": "dmm", "confidence": 0.7},+ ]+ for field in FIELD_SOURCE_ORDER:+ ordered = sort_candidates(field, candidates, policy)+ self.assertEqual(ordered[0]["source"], "dmm", field)+ self.assertEqual(+ [row["field_rank"] for row in ordered],+ sorted(row["field_rank"] for row in ordered),+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex c3cf1c17e..73b17247c 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -611,9 +611,25 @@ class OperationalScriptTests(unittest.TestCase):self.assertEqual([candidate["source"] for candidate in tag_candidates],["r18dev", "javbus"], "官方 tag 来源必须排在社区来源前")self.assertTrue(tag_candidates[0]["official"])+ self.assertEqual(tag_candidates[0]["profile"], "custom")+ self.assertEqual(tag_candidates[0]["policy_version"],+ "metadata-source-policy-v1")+ self.assertEqual(tag_candidates[0]["field_rank"], 9)+ self.assertEqual(tag_candidates[0]["source_kind"], "official_mirror")+ self.assertTrue(all(row["source_profile"] == "custom" for row in rows))self.assertTrue((raw / "ABC-001" / "r18dev.json").is_file())self.assertTrue((raw / "ABC-001" / "javbus.json").is_file())+ health = output.with_name("metadata-source-health-20260822.csv")+ with health.open(encoding="utf-8-sig", newline="") as handle:+ health_rows = {row["source"]: row for row in csv.DictReader(handle)}+ self.assertEqual(set(health_rows), {"javbus", "r18dev"})+ self.assertEqual(health_rows["r18dev"]["profile"], "custom")+ self.assertEqual(health_rows["r18dev"]["attempted"], "1")+ self.assertEqual(health_rows["r18dev"]["fetched"], "1")+ self.assertEqual(health_rows["r18dev"]["succeeded"], "1")+ self.assertEqual(health_rows["r18dev"]["release_date"], "1")+connection = sqlite3.connect(db)asset = connection.execute("SELECT creator,studio,series FROM asset WHERE id=1"@@ -623,6 +639,72 @@ class OperationalScriptTests(unittest.TestCase):self.assertEqual(asset, (None, None, None))self.assertEqual(relation_count, 0)+ def test_metadata_health_distinguishes_snapshot_empty_error_and_cooldown(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ db = root / "ledger.db"+ sqlite3.connect(db).close(); upgrade(db, MIGRATIONS)+ connection = sqlite3.connect(db)+ connection.executemany(+ "INSERT INTO asset(id,location,path,name,medium,code,size) "+ "VALUES(?,'local',?,?,'video',?,?)",+ [(1, "1.mp4", "1.mp4", "ABC-001", 3_000),+ (2, "2.mp4", "2.mp4", "DEF-002", 2_000),+ (3, "3.mp4", "3.mp4", "GHI-003", 1_000)],+ )+ connection.commit(); connection.close()+ raw = root / "raw"+ snapshot = raw / "ABC-001" / "r18dev.json"+ snapshot.parent.mkdir(parents=True)+ snapshot.write_text(__import__("json").dumps({+ "result": {"source": "r18dev", "maker": "Studio A"},+ }), encoding="utf-8")++ class HealthProvider:+ def __init__(self): self.calls = []+ def query(self, code, source):+ self.calls.append((code, source))+ if source == "javbus" and code == "DEF-002":+ raise self_error(+ "rate limited", kind="rate_limited", status_code=429,+ retryable=True, temporary=True,+ )+ if source == "javbus":+ return {"source": source}+ return {"source": source, "maker": "Studio A"}++ self_error = self.scrape_codes.MetadataProviderError+ provider = HealthProvider()+ output = root / "metadata-field-candidates-health.csv"+ health = root / "health.csv"+ with redirect_stdout(io.StringIO()):+ result = self.scrape_codes.main([+ "--db", str(db), "--out", str(output), "--health", str(health),+ "--raw-dir", str(raw), "--log-dir", str(root / "logs"),+ "--delay", "0", "--sources", "r18dev,javbus",+ ], provider=provider)+ self.assertEqual(result, 0)+ with health.open(encoding="utf-8-sig", newline="") as handle:+ rows = {row["source"]: row for row in csv.DictReader(handle)}+ self.assertEqual(rows["r18dev"]["snapshot_reused"], "1")+ self.assertEqual(rows["r18dev"]["fetched"], "2")+ self.assertEqual(rows["javbus"]["attempted"], "3")+ self.assertEqual(rows["javbus"]["fetched"], "2")+ self.assertEqual(rows["javbus"]["succeeded"], "1")+ self.assertEqual(rows["javbus"]["empty"], "1")+ self.assertEqual(rows["javbus"]["errors"], "1")+ self.assertEqual(rows["javbus"]["retryable_errors"], "1")+ self.assertEqual(rows["javbus"]["cooldown_skips"], "1")+ self.assertEqual(rows["javbus"]["blocked"], "1")+ self.assertEqual(rows["javbus"]["last_error_status"], "429")++ connection = sqlite3.connect(db)+ self.assertEqual(connection.execute(+ "SELECT count(*) FROM asset_entity").fetchone()[0], 0)+ self.assertEqual(connection.execute(+ "SELECT count(*) FROM review_decision").fetchone()[0], 0)+ connection.close()+def test_creator_tag_review_queue_requires_approval_and_backup(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)