Peach: Local-first video metadata scraper and media manager.
feat: formalize external metadata batch jobs
Peach local maintenance946ad3fec5f8
diff --git a/README.md b/README.mdindex 3ce718381..8fa221a39 100644--- a/README.md+++ b/README.md@@ -53,3 +53,7 @@ cd R:\peach-app证书必须包含实际访问名(例如 `peach.local`)并被客户端信任;启用 TLS 时 mDNS 自动发布 HTTPS。当前运行态与下一任务只看 [`docs/STATUS.md`](docs/STATUS.md);跨 Codex/Claude 的固定接手方式只看 [`docs/HANDOFF.md`](docs/HANDOFF.md)。++## 批处理安全边界++`scripts/scrape_codes.py` 默认只把番号发送到已声明的元数据源并写复核 CSV;只有 `--apply` 才写 ledger。`scripts/clean_names.py` 默认只生成改名计划;`--apply` 会先备份 SQLite,并在数据库更新失败时把文件名回滚。两者导入模块时均无副作用,测试不得使用真实路径。diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 69afc9f5d..0d6c8b548 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -15,8 +15,7 @@ This is durable operating knowledge, not a per-session transcript.- Real ledger: `R:\peach-data\database\ledger.db`; WAL mode; normal browsing legitimately changes play/activity fields.- Tests must create temporary SQLite databases and temporary media files.- Before real migration: SQLite backup, asset/tag counts, `PRAGMA integrity_check`, migration version check, then service smoke test.-- Formal migrations `0000` and `0001` were applied to the real ledger on 2026-08-14. The verified pre-migration recovery point is `R:\peach-data\archive\ledger.pre-migrate-20260814-152821.db`; do not delete it until later migrations have their own verified recovery point.-- `0002_canonical_entities` exists and passes isolated tests but is still pending on the real ledger. Before applying it, create a new SQLite backup and repeat counts/integrity/version checks; never silently auto-apply it during Web startup.+- Formal migrations `0000`–`0002` were applied to the real ledger on 2026-08-14. The verified pre-0002 recovery point is `R:\peach-data\archive\ledger.pre-migrate-20260814-162004.db`; do not delete it until a later migration has its own verified recovery point.- Media and runtime data remain under `R:\media` and `R:\peach-data`; they are not repository assets.## Operations@@ -27,6 +26,7 @@ This is durable operating knowledge, not a per-session transcript.- FastAPI is the only Web server. `web_contract.py` contains the stable JSON surface; do not recreate a parallel `http.server` or dynamic legacy loader.- FFmpeg/ffprobe resolve from explicit environment overrides, then `R:\peach-data\tools\ffmpeg\bin`, then `PATH`. No active code may fall back to the Stash private directory.- Long-running inventory helpers are under `scripts/`; their scheduled tasks use `R:\peach-app\.venv\Scripts\python.exe`. They use absolute data paths and may be interrupted/restarted where their own locking contract allows it.+- Importing operational scripts must have no filesystem/network/database side effects. `scrape_codes.py` sends only catalog codes to declared metadata sources, writes a resumable review CSV, and dual-writes provenance only with `--apply`. `clean_names.py` previews first and creates a SQLite backup before every apply run.- Check ports 80, 8900 and 9999 before starting or switching services.- 115/PikPak playback depends on CloudDrive mounts `B:`/`A:`. Drive-letter visibility differs by Windows execution token; CloudDrive and Peach must see the same mount namespace. A running process or a drive check from another token proves nothing—test one known `/stream` through Peach. Restart CloudDrive only after proving no copy task and no active I/O.- Ledger snapshot paths written before the project/data split are rebased by an exact configured legacy prefix. Do not add basename searches or arbitrary path fallbacks.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 204e01ddf..956c1efa3 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,13 +4,13 @@ Last verified: 2026-08-14## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 46796; health mode is `fastapi`.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 39668; health mode is `fastapi`.- mDNS publisher: `peach.local` is published on `192.168.50.162` as HTTP, but an actual LAN client could not resolve it. Use `http://192.168.50.162/` until the client/router multicast path is fixed; no firewall/router change was made.- Stash: `127.0.0.1:9999`, PID observed as 35332.- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.- Runtime Python: 3.14.7. The removed system Python 3.12 invalidated the old venv, which was rebuilt and reverified before production start.-- Real ledger migrations: `0000` and `0001` applied. Code migration `0002_canonical_entities` is tested but deliberately pending on the real ledger until a fresh backup/maintenance window.-- Pre-migration backup: `R:\peach-data\archive\ledger.pre-migrate-20260814-152821.db`.+- Real ledger migrations: `0000`, `0001` and `0002` applied; zero pending.+- Current pre-0002 recovery point: `R:\peach-data\archive\ledger.pre-migrate-20260814-162004.db`.Runtime PIDs are observations, not configuration; always re-check them.@@ -20,20 +20,41 @@ Runtime PIDs are observations, not configuration; always re-check them.- The old `BaseHTTPRequestHandler`, dynamic legacy loader and automatic schema repair path are deleted. Default contract reads are read-only; activity/play/feedback writes are explicit.- FFmpeg/ffprobe are Peach-managed under `R:\peach-data\tools\ffmpeg`; resolver order is environment, managed bundle, then PATH. Active code has no Stash private binary fallback.- Stash transport is centralized in `StashClient`; ledger imports now write stable `media_binding` external IDs and explicit tag/performer provenance. The new importer was verified only against an isolated database and was not run on the real ledger.-- Migration `0002` adds canonical entity/alias/external-ref/asset-relation tables and backfills existing performer/tag/studio/creator projections. The Stash importer dual-writes canonical relations while retaining current flattened tags for UI compatibility; isolated tests only.+- Migration `0002` added canonical entity/alias/external-ref/asset-relation tables and backfilled existing performer/tag/studio/creator/series projections. After the post-migration external-metadata reconciliation, the real ledger has 8,603 entities and 131,877 relations. The Stash and external-metadata importers dual-write canonical relations while retaining flattened UI projections.- Passive `/api/providers` health discovery now exposes separate inference/agent capabilities without model calls, credential reads or secret values.- Snapshot rows still contain 10,714 pre-split `R:\Resources\Intake\snapshots` paths. Runtime now performs a strict legacy-prefix rebase to `R:\peach-data\generated\snapshots`; it does not mutate the real ledger.- `R:\peach-data` now separates `database/generated/sources/state/secrets/logs/archive/inbox/tools`; the old empty root Inbox and old Resources/Tools compatibility surface are removed.-- 29 isolated tests passed under Python 3.14, including canonical migration/import, provider registry, snapshot rebasing, HTTP/HTTPS mDNS publication and TLS argument boundaries.-- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check`.+- `web_contract.py` now uses an application-owned database/cache/write-lock context rather than module globals; separate app instances cannot leak databases or caches into each other.+- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.+- 34 isolated tests and tracked-script static compilation passed under Python 3.14.+- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.- Restarted production port 80 passed health, home, 24,980-item all-source list, 2,552-item local list and one-byte `206 Partial Content` Range smoke checks.- After deleting the legacy server, restarted production also passed real `stats`, `tops` and `facets` aggregate contract checks.- Optional SSL is supported with an explicit certificate/key pair. Production remains HTTP until a trusted local certificate is supplied.- The original Peach process could not see CloudDrive `A:`/`B:` even though CloudDrive was running. After confirming zero copy tasks and no I/O, CloudDrive and Peach were restarted in the same execution context. Asset 4289 (`669.mp4`) then passed `video/mp4`, 1 KiB `206 Range`, thumbnail and generated-poster API checks. Drive-letter visibility differs by Windows token, so the HTTP stream check is the authoritative service test.+## Batch jobs++- `scripts/scrape_codes.py` — code scraping via r18 → avsox → javbus cascade, resumable from+ `R:\peach-data\generated\code-scrape.csv`. All 1,104 non-FC2 codes were processed; 715 rows carry+ data (r18 672, javbus 43). Studio coverage went 1,105 → 1,158 of 1,434 total codes; the run added 2,538+ `asset_tag` rows with `source='r18'`. The 330 FC2 codes are skipped by default (`--include-fc2` to force)+ because a measured 117-code sample produced zero hits across all three sources.+- The completed scrape was reconciled once through the new dual-write path without new network calls. It added 577 previously empty series projections and brought the live ledger to 61,377 compatibility tag links. Recovery point: `R:\peach-data\archive\ledger.pre-metadata-reconcile-20260814-163027.db`.+- `scripts/clean_names.py` — strips pirate-site promo domains and residual noise from filenames, updating+ disk and ledger `path`/`name` together. 274 of 287 candidates renamed, 0 failures, 5 sources already+ gone, 8 skipped on name collision; 2 promo names remain behind collisions. Verified by re-listing every+ renamed path after the cloud write cache flushed. Backup: `R:\peach-data\archive\ledger.pre-rename-20260814-161656.db`.+ The script deliberately does not strip ` (3)` sequence markers (16,278 in the library; removing them+ collides 1,520 Telegram exports) and does not touch `name.mp4.jpg` thumbnails (only 2 true `.mp4.mp4` cases).+- Probe backlog is empty. Free sheet backlog (115/local) is empty: the 20 residual rows were rechecked+ three times and 17 are dead ledger rows, not pending work. PikPak sheets still hold 4,740 items and+ are metered, so they need a traffic budget decision before running.+- 12,204 videos still have no content tag.+## Next work-1. Back up the real ledger, apply `0002`, verify counts/integrity, then restart and smoke-test production.-2. Split `web_contract.py` globals into explicit repository/application objects before enabling multiple workers.-3. Implement the first real online-source and AI provider adapters behind the existing boundaries.+1. Switch performer/studio/tag reads from flattened compatibility fields to canonical `asset_entity` queries.+2. Add the first tracked online-follow source adapter; keep metadata scraping as a reviewable batch pipeline.+3. Implement an OpenCode Go inference health/model adapter without enabling automatic ledger writes.diff --git a/docs/adr/0006-external-metadata-batch-boundary.md b/docs/adr/0006-external-metadata-batch-boundary.mdnew file mode 100644index 000000000..9766cf15d--- /dev/null+++ b/docs/adr/0006-external-metadata-batch-boundary.md@@ -0,0 +1,28 @@+# ADR-0006:外部元数据批处理边界++- 状态:Accepted+- 日期:2026-08-14++## 背景++Peach 需要在线补充番号的 performer、studio、series 和内容分类,但外部站点协议、限流和可用性不稳定,返回结果也不能直接成为 ledger 真相。++## 决策++- 外部元数据作为显式、可恢复的批处理能力,不进入 Web 请求热路径或应用启动流程。+- 只向已声明来源发送标准化番号;不发送本地文件路径、文件名、媒体内容、播放行为或凭据。+- 抓取先写可续跑 CSV,只有显式 `--apply` 才写 ledger。+- 写入同时包含 source/confidence/provenance,并双写规范 `entity`/`asset_entity` 与当前 UI 兼容投影。+- 对 403/429/503 做来源级冷却;HTML 来源视为易变 adapter,失败不得阻塞 Peach。+- 导入脚本本身无副作用,网络和真实数据库操作只发生在 `main()` 的显式命令路径。++## 被否决的方案++- 页面打开时同步刮削。+- 未复核即覆盖人工字段。+- 把文件路径、完整文件名或媒体上传给第三方做匹配。+- 把易变 HTML 结构当作核心领域协议。++## 影响++元数据到达存在延迟,并需维护来源解析器;换来的是可追溯、可重跑、可限速和可逐源替换,外部故障不会影响本地播放。diff --git a/scripts/clean_names.py b/scripts/clean_names.pynew file mode 100644index 000000000..f07624339--- /dev/null+++ b/scripts/clean_names.py@@ -0,0 +1,221 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""+文件名净化 —— 去掉盗版站塞进文件名的推广域名与残留噪声。++只做可逆、无歧义的改写。刻意不做的几件事(都验证过会出事):+ * 不删 " (3)" 这类序号:库里 16278 条,去掉后 1520 条与同目录文件直接撞名,+ Telegram 导出全靠它区分同秒落地的文件。+ * 不动 "xxx.mp4.jpg":那是该 mp4 的缩略图,不是双后缀(真的双后缀只有 2 条)。+ * 不重排番号/不套命名模板:那依赖刮削完整度,属于另一件事。++先出 CSV 供人工核对,加 --apply 才落盘;改名同时同步 ledger 的 path/name。++用法:+ python scripts/clean_names.py [--location local|115|pikpak] [--apply]+"""+from __future__ import annotations++import csv+import argparse+from datetime import datetime+import os+import re+import sqlite3+import time++DEFAULT_DB = r"R:\peach-data\database\ledger.db"+DEFAULT_OUT = r"R:\peach-data\generated\name-clean.csv"+DEFAULT_LOG_DIR = r"R:\peach-data\logs"+DEFAULT_BACKUP_DIR = r"R:\peach-data\archive"+_logf = None+++def configure_log(log_dir: str) -> None:+ global _logf+ os.makedirs(log_dir, exist_ok=True)+ path = os.path.join(log_dir, time.strftime("clean-names-%Y%m%d-%H%M%S.log"))+ _logf = open(path, "w", encoding="utf-8", buffering=1)+++def log(msg: str) -> None:+ line = f"[{time.strftime('%H:%M:%S')}] {msg}"+ print(line, flush=True)+ if _logf is not None:+ _logf.write(line + "\n")+++TLD = r"(?:com|net|la|xyz|cc|me|top|vip|club|info|org|tv|app|co|pw|gg|cn)"+VIDEO_EXT = {"mp4", "mkv", "avi", "wmv", "mov", "ts", "m4v", "flv", "rmvb"}++# 站点前缀:域名后面常跟 @ - _ 空格,或直接连着广告语+RE_PREFIX = re.compile(+ rf"^\s*[\[\【@]?\s*(?:www\.)?[0-9A-Za-z][-0-9A-Za-z]{{1,30}}\.{TLD}"+ rf"(?:\d{{6,}})?\s*[@\-_\]\】、,,]?\s*", re.I)+# 尾部域名:紧贴扩展名之前+RE_SUFFIX = re.compile(+ rf"[-_@\s]+(?:www\.)?[0-9A-Za-z][-0-9A-Za-z]{{2,25}}\.{TLD}\s*(?=\.[A-Za-z0-9]{{2,4}}$)", re.I)+# 中文推广尾巴(域名已被上面吃掉后剩下的宣传语)+RE_ADCOPY = re.compile(+ r"[-_\s]*(?:全网最火爆成人游戏|成人手游|最新地址|开车地址|每日更新|无码破解|"+ r"免费看片|请记住本站|更多资源|中文成人网站?)[^.]*(?=\.[A-Za-z0-9]{2,4}$)")+++def propose(name: str) -> str:+ """返回净化后的文件名;无需改动则原样返回。"""+ stem, dot, ext = name.rpartition(".")+ if not dot or not stem: # 没有扩展名、或形如 ".mp4" 的空主干,都不碰+ return name++ new = RE_PREFIX.sub("", name, count=1)+ new = RE_SUFFIX.sub("", new)+ new = RE_ADCOPY.sub("", new)++ # 同类双后缀 .mp4.mp4(.mp4.jpg 这种缩略图命名不算)+ dbl = re.search(r"\.([A-Za-z0-9]{2,4})\.([A-Za-z0-9]{2,4})$", new)+ if dbl and dbl.group(1).lower() == dbl.group(2).lower():+ new = new[: dbl.start()] + "." + dbl.group(2)++ # 首尾空白 / 扩展名前的空格和点+ new = re.sub(r"\s+(?=\.[A-Za-z0-9]{2,4}$)", "", new.strip())+ new = re.sub(r"^[\s._\-—]+", "", new)++ # 净化到只剩扩展名、或只剩 "(1)" 这种序号,说明规则吃过头了,放弃这条+ if not new or new.startswith(".") or new == name:+ return name+ body = os.path.splitext(new)[0]+ if not re.sub(r"[\s()\[\]【】.\-_—]", "", body):+ return name+ # 只剩 "(2)" 这种括号序号,等于把名字删没了+ if re.fullmatch(r"[\s\-_.]*\(\d+\)[\s\-_.]*", body):+ return name+ if os.path.splitext(new)[1].lower() != os.path.splitext(name)[1].lower():+ return name+ return new+++FIELDS = ["id", "location", "dir", "old", "new", "status"]+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="preview or apply conservative filename cleanup")+ parser.add_argument("--db", default=DEFAULT_DB)+ parser.add_argument("--out", default=DEFAULT_OUT)+ parser.add_argument("--log-dir", default=DEFAULT_LOG_DIR)+ parser.add_argument("--backup-dir", default=DEFAULT_BACKUP_DIR)+ parser.add_argument("--location", choices=("local", "115", "pikpak"))+ parser.add_argument("--apply", action="store_true")+ return parser+++def write_plan(path: str, plan: list[dict]) -> None:+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)+ with open(path, "w", encoding="utf-8-sig", newline="") as handle:+ writer = csv.DictWriter(handle, fieldnames=FIELDS)+ writer.writeheader()+ writer.writerows(plan)+++def backup_database(db_path: str, backup_dir: str) -> str:+ if not os.path.isfile(db_path):+ raise FileNotFoundError(db_path)+ os.makedirs(backup_dir, exist_ok=True)+ destination = os.path.join(+ backup_dir, "ledger.pre-rename-" + datetime.now().strftime("%Y%m%d-%H%M%S-%f") + ".db",+ )+ source = sqlite3.connect(db_path)+ target = sqlite3.connect(destination)+ try:+ source.backup(target)+ finally:+ target.close()+ source.close()+ return destination+++def main(argv: list[str] | None = None) -> int:+ args_ns = build_parser().parse_args(argv)+ configure_log(args_ns.log_dir)+ target = (args_ns.db if args_ns.apply else+ "file:" + os.path.abspath(args_ns.db).replace("\\", "/") + "?mode=ro")+ conn = sqlite3.connect(target, uri=not args_ns.apply)+ where = "WHERE name IS NOT NULL"+ sql_args: list = []+ if args_ns.location:+ where += " AND location = ?"+ sql_args.append(args_ns.location)+ rows = conn.execute(f"SELECT id, location, path, name FROM asset {where}", sql_args).fetchall()+ log(f"扫描 {len(rows)} 条" + (f"(location={args_ns.location})" if args_ns.location else ""))++ # 同目录已占用的名字,用来挡撞名+ taken: dict[str, set[str]] = {}+ for _, _, path, name in rows:+ taken.setdefault(os.path.dirname(path).lower(), set()).add(name.lower())++ plan = []+ for aid, loc, path, name in rows:+ new = propose(name)+ if new == name:+ continue+ d = os.path.dirname(path)+ status = "collide" if new.lower() in taken[d.lower()] else "ready"+ plan.append({"id": aid, "location": loc, "dir": d,+ "old": name, "new": new, "status": status})+ if status == "ready":+ taken[d.lower()].add(new.lower())++ ready = [p for p in plan if p["status"] == "ready"]+ log(f"待净化 {len(plan)} 条,其中可执行 {len(ready)},撞名跳过 {len(plan) - len(ready)}")+ write_plan(args_ns.out, plan)++ if args_ns.apply:+ backup = backup_database(args_ns.db, args_ns.backup_dir)+ log(f"数据库备份 → {backup}")+ ok = fail = gone = 0+ for item in ready:+ src = os.path.join(item["dir"], item["old"])+ dst = os.path.join(item["dir"], item["new"])+ if not os.path.exists(src):+ item["status"] = "missing"+ gone += 1+ continue+ if os.path.exists(dst):+ item["status"] = "collide"+ fail += 1+ continue+ try:+ os.rename(src, dst)+ except Exception as exc:+ item["status"] = f"error:{type(exc).__name__}"+ log(f" 失败 {src} -> {item['new']} : {exc}")+ fail += 1+ continue+ try:+ conn.execute(+ "UPDATE asset SET path=?, name=? WHERE id=?", (dst, item["new"], item["id"]),+ )+ conn.commit()+ except Exception as exc:+ conn.rollback()+ try:+ os.rename(dst, src)+ item["status"] = f"db-error-rolled-back:{type(exc).__name__}"+ except Exception:+ item["status"] = f"db-error-manual-repair:{type(exc).__name__}"+ log(f" 数据库失败 {src} -> {item['new']} : {exc}")+ fail += 1+ continue+ item["status"] = "done"+ ok += 1+ log(f"改名完成 {ok},失败 {fail},源已不存在 {gone}")+ conn.close()++ write_plan(args_ns.out, plan)+ log(f"→ {args_ns.out}")+ if not args_ns.apply:+ log("未加 --apply,只出清单未改名。")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/ledger.py b/scripts/ledger.pyindex 6e9da9621..edc9814f6 100644--- a/scripts/ledger.py+++ b/scripts/ledger.py@@ -18,6 +18,7 @@ r"""import os, sys, csv, json, sqlite3, timefrom peach.stash import StashClient, StashError+from peach.entities import upsert_asset_entityDB = os.path.expandvars(r"R:\peach-data\database\ledger.db")VIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg", ".m2ts"}@@ -143,42 +144,6 @@ def ctx_from(size, w=None, h=None, dur=None):return length, orient, quality-def upsert_entity(c, *, kind, name, now, source, asset_id, role,- external_id=None, metadata=None):- canonical = str(name or "").strip()- if not canonical:- return None- normalized = canonical.casefold()- payload = json.dumps(metadata or {}, ensure_ascii=False)- c.execute("""INSERT INTO entity(kind,canonical_name,normalized_name,metadata_json,created_at,updated_at)- VALUES(?,?,?,?,?,?)- ON CONFLICT(kind,normalized_name) DO UPDATE SET- canonical_name=excluded.canonical_name,- metadata_json=excluded.metadata_json,- updated_at=excluded.updated_at""",- (kind, canonical, normalized, payload, now, now))- entity_id = c.execute(- "SELECT id FROM entity WHERE kind=? AND normalized_name=?", (kind, normalized)- ).fetchone()[0]- c.execute("""INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence,- metadata_json,first_seen_at,last_seen_at)- VALUES(?,?,?,?,1.0,?,?,?)- ON CONFLICT(asset_id,entity_id,role,source) DO UPDATE SET- metadata_json=excluded.metadata_json,- last_seen_at=excluded.last_seen_at""",- (asset_id, entity_id, role, source, payload, now, now))- if external_id is not None:- c.execute("""INSERT INTO entity_external_ref(- entity_id,provider,external_kind,external_id,metadata_json,last_synced_at)- VALUES(?,'stash',?,?,?,?)- ON CONFLICT(provider,external_kind,external_id) DO UPDATE SET- entity_id=excluded.entity_id,- metadata_json=excluded.metadata_json,- last_synced_at=excluded.last_synced_at""",- (entity_id, kind, str(external_id), payload, now))- return entity_id--def cmd_init():c = conn(); c.executescript(SCHEMA); c.commit(); c.close()print(f"✓ 建库完成 {DB}")@@ -274,27 +239,33 @@ def cmd_stash(client=None):last_synced_at=excluded.last_synced_at""",(aid, str(s["id"]), json.dumps(provenance, ensure_ascii=False), now))studio = s.get("studio") or {}- upsert_entity(c, kind="studio", name=studio.get("name"), now=now,- source="stash:studio", asset_id=aid, role="studio",- external_id=studio.get("id"), metadata=studio)+ upsert_asset_entity(+ c, kind="studio", name=studio.get("name"), now=now,+ source="stash:studio", asset_id=aid, role="studio",+ external_provider="stash", external_id=studio.get("id"), metadata=studio,+ )for t in s.get("tags") or []:c.execute("""INSERT INTO asset_tag(asset_id,tag,confidence,source)VALUES(?,?,1.0,'stash:tag')ON CONFLICT(asset_id,tag) DO UPDATE SETconfidence=excluded.confidence,source=excluded.source""",(aid, t["name"])); nt += 1- upsert_entity(c, kind="tag", name=t.get("name"), now=now,- source="stash:tag", asset_id=aid, role="tag",- external_id=t.get("id"), metadata=t)+ upsert_asset_entity(+ c, kind="tag", name=t.get("name"), now=now,+ source="stash:tag", asset_id=aid, role="tag",+ external_provider="stash", external_id=t.get("id"), metadata=t,+ )for p in s.get("performers") or []:c.execute("""INSERT INTO asset_tag(asset_id,tag,confidence,source)VALUES(?,?,1.0,'stash:performer')ON CONFLICT(asset_id,tag) DO UPDATE SETconfidence=excluded.confidence,source=excluded.source""",(aid, "演员:" + p["name"]))- upsert_entity(c, kind="performer", name=p.get("name"), now=now,- source="stash:performer", asset_id=aid, role="performer",- external_id=p.get("id"), metadata=p)+ upsert_asset_entity(+ c, kind="performer", name=p.get("name"), now=now,+ source="stash:performer", asset_id=aid, role="performer",+ external_provider="stash", external_id=p.get("id"), metadata=p,+ )c.commit()print(f"✓ Stash: {len(scenes):,} 个场景,{nt:,} 条标签关联")c.close()diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.pynew file mode 100644index 000000000..c3436ff92--- /dev/null+++ b/scripts/scrape_codes.py@@ -0,0 +1,368 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""+番号刮削 —— 给 ledger 里带 code 的资产补女优、厂牌、内容标签。++输入直接来自 ledger(不依赖任何中间 CSV);结果写回 ledger,+并落一份 CSV 到 generated/ 供人工核对。++多源级联(单源必被限流,实测 javbus 打到第 25 个就 403):+ 1. r18.dev JSON API,无 Cloudflare,有码主力,附带 categories 可直接转标签+ 2. avsox 无码 / FC2 主力+ 3. javbus 兜底,易 403,带 5 分钟冷却++可随时中断重启:CSV 里已有的番号直接跳过。+只写 asset.studio / asset.creator(当其为空时)与 asset_tag(source='r18'),+不覆盖已有的人工或视觉标注。++用法:+ python scripts/scrape_codes.py [--limit N] [--delay 1.2] [--apply]+ 不带 --apply 只抓取并落 CSV,不写库。+"""+from __future__ import annotations++import csv+import argparse+import json+import os+import random+import re+import sqlite3+import time+import urllib.error+import urllib.parse+import urllib.request++from peach.entities import upsert_asset_entity++DEFAULT_DB = r"R:\peach-data\database\ledger.db"+DEFAULT_OUT = r"R:\peach-data\generated\code-scrape.csv"+DEFAULT_LOG_DIR = r"R:\peach-data\logs"+_logf = None+++def configure_log(log_dir: str) -> None:+ global _logf+ os.makedirs(log_dir, exist_ok=True)+ path = os.path.join(log_dir, time.strftime("scrape-codes-%Y%m%d-%H%M%S.log"))+ _logf = open(path, "w", encoding="utf-8", buffering=1)+++def log(msg: str) -> None:+ line = f"[{time.strftime('%H:%M:%S')}] {msg}"+ print(line, flush=True)+ if _logf is not None:+ _logf.write(line + "\n")+++UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")+++def _get(url: str, headers: dict | None = None, timeout: int = 25) -> str:+ hdrs = {"User-Agent": UA, "Accept-Language": "zh-TW,zh;q=0.9,ja;q=0.8"}+ hdrs.update(headers or {})+ with urllib.request.urlopen(urllib.request.Request(url, headers=hdrs), timeout=timeout) as resp:+ return resp.read().decode("utf-8", "ignore")+++_TAG_RE = re.compile(r"<[^>]+>")+++def _text(fragment: str) -> str:+ return re.sub(r"\s+", " ", _TAG_RE.sub("", fragment)).strip()+++def _name_of(value) -> str:+ if isinstance(value, dict):+ return value.get("name", "") or ""+ return value or ""+++BLANK = {"performers": "", "studio": "", "label": "", "series": "",+ "title": "", "categories": "", "source": ""}+++def from_r18(code: str) -> dict | None:+ payload = json.loads(_get(+ "https://r18.dev/videos/vod/movies/detail/-/dvd_id="+ f"{urllib.parse.quote(code)}/json"))+ actors = [a.get("name", "").strip() for a in (payload.get("actresses") or []) if a.get("name")]+ if not actors and not payload.get("maker"):+ return None+ return {+ "performers": "|".join(actors),+ "studio": _name_of(payload.get("maker")),+ "label": _name_of(payload.get("label")),+ "series": _name_of(payload.get("series")),+ "title": (payload.get("title") or "")[:200],+ "categories": "|".join(c.get("name", "") for c in (payload.get("categories") or []))[:300],+ "source": "r18",+ }+++def from_avsox(code: str) -> dict | None:+ search = _get("https://avsox.click/cn/search/" + urllib.parse.quote(code))+ hit = re.search(r'href="(https?://[^"]*/cn/movie/[^"]+)"', search)+ if not hit:+ return None+ page = _get(hit.group(1))+ actors = [_text(x) for x in re.findall(+ r'class="avatar-box"[^>]*>.{0,400}?<span>([^<]{1,30})</span>', page, re.S)]+ maker = re.search(r"制作商.{0,300}?<a[^>]*>([^<]{1,60})</a>", page, re.S)+ title = re.search(r"<h3>(.*?)</h3>", page, re.S)+ if not (actors or maker):+ return None+ out = dict(BLANK)+ out.update({+ "performers": "|".join(dict.fromkeys(a for a in actors if a)),+ "studio": maker.group(1).strip() if maker else "",+ "title": _text(title.group(1))[:200] if title else "",+ "source": "avsox",+ })+ return out+++def from_javbus(code: str) -> dict | None:+ page = _get("https://www.javbus.com/" + urllib.parse.quote(code),+ headers={"Cookie": "existmag=all"})+ actors = [_text(b) for b in re.findall(r'class="star-name"[^>]*>(.*?)</span>', page, re.S)]+ if not actors:+ actors = [x.strip() for x in re.findall(+ r'href="[^"]*/star/[^"]*"[^>]*>([^<]{1,30})</a>', page)]+ out = dict(BLANK)+ out["performers"] = "|".join(dict.fromkeys(a for a in actors if a))+ for key, field in (("製作商", "studio"), ("發行商", "label"), ("系列", "series")):+ hit = re.search(key + r'.{0,200}?href="[^"]*"[^>]*>([^<]{1,60})</a>', page, re.S)+ if hit:+ out[field] = hit.group(1).strip()+ title = re.search(r"<h3>(.*?)</h3>", page, re.S)+ if title:+ out["title"] = _text(title.group(1))[:200]+ out["source"] = "javbus"+ return out if (out["performers"] or out["studio"]) else None+++def normalise(code: str) -> str:+ """FC2PPV-1234567 → FC2-PPV-1234567 ; ABW123 → ABW-123 ; IPVR00296 → IPVR-296"""+ value = code.upper().replace("_", "-").replace(" ", "-")+ if value.startswith("FC2"):+ digits = re.search(r"(\d{5,})", value)+ return f"FC2-PPV-{digits.group(1)}" if digits else value+ shape = re.match(r"^([A-Z]+)-?(\d+)$", value)+ if not shape:+ return value+ digits = shape.group(2)+ if len(digits) > 3 and digits.startswith("0"):+ digits = digits.lstrip("0").zfill(3)+ return f"{shape.group(1)}-{digits}"+++def chain(code: str):+ """FC2 / 无码走 avsox 优先,其余 r18 优先。"""+ if code.startswith("FC2") or re.match(r"^\d{6}[-_]\d{3}$", code):+ return (("avsox", from_avsox), ("javbus", from_javbus), ("r18", from_r18))+ return (("r18", from_r18), ("avsox", from_avsox), ("javbus", from_javbus))+++# r18 分类 → 本地内容标签(只映射有意义的,其余丢弃)+CATEGORY_MAP = {+ "Foot Fetish": "足系", "Legs": "美腿", "Pantyhose": "丝袜", "Stockings": "丝袜",+ "Creampie": "中出内射", "Squirting": "潮吹", "Blowjob": "口交", "Deep Throat": "深喉",+ "Facial": "颜射", "Cum Swallowing": "吞精", "Handjob": "手交",+ "Big Tits": "乳系", "Beautiful Tits": "乳系", "Small Tits": "贫乳", "Titty Fuck": "乳交",+ "Slender": "苗条", "Chubby": "丰满", "Beautiful Girl": "高颜值",+ "Office Lady": "秘书OL", "School Girls": "学生", "Nurse": "护士",+ "Uniform": "制服", "Cosplay": "角色扮演", "Maid": "女仆", "Swimsuit": "泳装",+ "Married Woman": "人妻", "Mature Woman": "人妻", "Big Tits Lover": "乳系",+ "Threesome / Foursome": "多人", "Orgy": "多人", "Lesbian": "百合",+ "Anal": "肛交", "Bondage": "调教", "Torture": "调教", "Training": "调教",+ "Slut": "痴女", "Nymphomaniac": "痴女", "Cuckold": "绿帽NTR", "Voyeur": "偷拍偷窥",+ "Hidden Camera": "偷拍偷窥", "Amateur": "素人", "Massage": "按摩", "Bath": "浴室",+ "Outdoor": "户外露出", "Car Sex": "车震", "Ass Lover": "美臀", "Butt": "美臀",+ "Glasses": "眼镜", "Virtual Reality": "VR", "POV": "主观视角", "Restraint": "调教",+ "Incest": "近亲", "Cheating Wife": "绿帽NTR",+}++FIELDS = ["code", "query", "performers", "studio", "label", "series",+ "title", "categories", "source", "status", "size_gb", "videos"]+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="scrape code metadata into a review CSV")+ parser.add_argument("--db", default=DEFAULT_DB)+ parser.add_argument("--out", default=DEFAULT_OUT)+ parser.add_argument("--log-dir", default=DEFAULT_LOG_DIR)+ parser.add_argument("--limit", type=int, default=0)+ parser.add_argument("--delay", type=float, default=1.2)+ parser.add_argument("--apply", action="store_true")+ parser.add_argument("--include-fc2", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)+ configure_log(args.log_dir)+ conn = sqlite3.connect("file:" + os.path.abspath(args.db).replace("\\", "/") + "?mode=ro", uri=True)+ codes = [(row[0].upper().strip(), float(row[1]), int(row[2])) for row in conn.execute(+ "SELECT code, COALESCE(sum(size),0)/1073741824.0, count(*) FROM asset "+ "WHERE medium='video' AND code IS NOT NULL AND code<>'' "+ "GROUP BY code ORDER BY 2 DESC")]+ conn.close()++ done: set[str] = set()+ if os.path.exists(args.out):+ with open(args.out, encoding="utf-8-sig") as handle:+ done = {row["code"] for row in csv.DictReader(handle)}+ log(f"已有结果 {len(done)} 条,跳过")++ todo = [c for c in codes if c[0] not in done]+ if not args.include_fc2:+ before = len(todo)+ todo = [c for c in todo if not c[0].upper().startswith("FC2")]+ if before != len(todo):+ log(f"跳过 {before - len(todo)} 个 FC2(历史命中率 0%,要跑加 --include-fc2)")+ if args.limit:+ todo = todo[:args.limit]+ log(f"库里番号 {len(codes)} 个,待查 {len(todo)} 个,间隔 {args.delay}s,"+ f"预计 {len(todo) * args.delay * 1.4 / 60:.0f} 分钟")++ handle = open(args.out, "a", newline="", encoding="utf-8-sig")+ writer = csv.DictWriter(handle, fieldnames=FIELDS)+ if not done:+ writer.writeheader()++ cooldown: dict[str, float] = {}+ hit = miss = 0+ by_source: dict[str, int] = {}+ started = time.time()++ for index, (code, size_gb, videos) in enumerate(todo, 1):+ query = normalise(code)+ record = dict(BLANK)+ record.update({"code": code, "query": query, "status": "",+ "size_gb": round(size_gb, 2), "videos": videos})+ for source_name, fetch in chain(query):+ if time.time() < cooldown.get(source_name, 0):+ continue+ try:+ found = fetch(query)+ except urllib.error.HTTPError as exc:+ if exc.code in (403, 429, 503):+ cooldown[source_name] = time.time() + 300+ log(f" {source_name} 限流 {exc.code},冷却 5 分钟")+ continue+ except Exception:+ continue+ if found:+ record.update(found)+ record["status"] = "ok" if found["performers"] else "no_actress"+ by_source[source_name] = by_source.get(source_name, 0) + 1+ break+ time.sleep(0.4)+ if record["performers"]:+ hit += 1+ else:+ miss += 1+ record["status"] = record["status"] or "not_found"+ writer.writerow(record)+ handle.flush()+ if index % 25 == 0:+ elapsed = time.time() - started+ log(f"{index}/{len(todo)} 命中 {hit} 未果 {miss} "+ f"剩余 {(len(todo) - index) * elapsed / index / 60:.0f} 分钟 源:{by_source}")+ time.sleep(args.delay + random.uniform(0, 0.5))++ handle.close()+ total = hit + miss+ log(f"完成:查 {total} 个,拿到女优 {hit} 个"+ f"({hit / max(total, 1) * 100:.0f}%) 源分布:{by_source}")+ log(f"→ {args.out}")++ if not args.apply:+ log("未加 --apply,只落 CSV 未写库。")+ return 0++ return write_back(args.db, args.out)+++def write_back(db_path: str = DEFAULT_DB, out_path: str = DEFAULT_OUT) -> int:+ """把已复核 CSV 双写为兼容投影和规范实体关系。"""+ with open(out_path, encoding="utf-8-sig") as handle:+ rows = [r for r in csv.DictReader(handle) if r.get("status") in ("ok", "no_actress")]+ conn = sqlite3.connect(db_path, timeout=60)+ conn.execute("PRAGMA busy_timeout=60000")+ cur = conn.cursor()+ studios = performers = series_count = tags = 0+ for row in rows:+ code = row["code"]+ ids = [r[0] for r in cur.execute(+ "SELECT id FROM asset WHERE medium='video' AND code=?", (code,))]+ if not ids:+ continue+ marks = ",".join("?" * len(ids))+ if row.get("studio"):+ studios += cur.execute(+ f"UPDATE asset SET studio=? WHERE id IN ({marks}) "+ "AND (studio IS NULL OR studio='')",+ [row["studio"], *ids]).rowcount+ performer_names = [name.strip() for name in (row.get("performers") or "").split("|")+ if name.strip()]+ lead = performer_names[0] if performer_names else ""+ if lead:+ performers += cur.execute(+ f"UPDATE asset SET creator=? WHERE id IN ({marks}) "+ "AND (creator IS NULL OR creator='')",+ [lead, *ids]).rowcount+ if row.get("series"):+ series_count += cur.execute(+ f"UPDATE asset SET series=? WHERE id IN ({marks}) "+ "AND (series IS NULL OR series='')",+ [row["series"], *ids]).rowcount+ mapped = [CATEGORY_MAP[c] for c in (row.get("categories") or "").split("|")+ if c in CATEGORY_MAP]+ mapped = list(dict.fromkeys(mapped))+ if mapped:+ cur.executemany(+ "INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) "+ "VALUES(?,?,?,?)",+ [(aid, tag, 0.9, "r18") for aid in ids for tag in mapped])+ tags += len(ids) * len(mapped)+ source = row.get("source") or "external"+ metadata = {"code": code, "query": row.get("query", ""), "source": source}+ for aid in ids:+ upsert_asset_entity(+ conn, kind="studio", name=row.get("studio"), asset_id=aid,+ role="studio", source=f"{source}:studio", confidence=0.9,+ metadata=metadata,+ )+ upsert_asset_entity(+ conn, kind="series", name=row.get("series"), asset_id=aid,+ role="series", source=f"{source}:series", confidence=0.9,+ metadata=metadata,+ )+ for name in performer_names:+ cur.execute(+ "INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) "+ "VALUES(?,?,?,?)", (aid, "演员:" + name, 0.9, f"{source}:performer"),+ )+ upsert_asset_entity(+ conn, kind="performer", name=name, asset_id=aid,+ role="performer", source=f"{source}:performer", confidence=0.9,+ metadata=metadata,+ )+ for tag in mapped:+ upsert_asset_entity(+ conn, kind="tag", name=tag, asset_id=aid, role="tag",+ source="r18", confidence=0.9, metadata=metadata,+ )+ conn.commit()+ log(f"写回 ledger:厂牌 {studios} 行,创作者 {performers} 行,"+ f"系列 {series_count} 行,标签约 {tags} 条")+ conn.close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/entities.py b/src/peach/entities.pynew file mode 100644index 000000000..0c22fc522--- /dev/null+++ b/src/peach/entities.py@@ -0,0 +1,58 @@+from __future__ import annotations++import json+from datetime import datetime, timezone+from sqlite3 import Connection+++def normalize_entity_name(name: str) -> str:+ return str(name).strip().casefold()+++def upsert_asset_entity(+ connection: Connection, *, kind: str, name: str | None, asset_id: int,+ role: str, source: str, confidence: float = 1.0,+ external_provider: str | None = None, external_id: str | int | None = None,+ metadata: dict | None = None, now: str | None = None,+) -> int | None:+ """写入规范实体关系;调用方负责事务和兼容投影。"""+ canonical = str(name or "").strip()+ if not canonical:+ return None+ stamp = now or datetime.now(timezone.utc).isoformat()+ normalized = normalize_entity_name(canonical)+ payload = json.dumps(metadata or {}, ensure_ascii=False)+ connection.execute(+ """INSERT INTO entity(kind,canonical_name,normalized_name,metadata_json,created_at,updated_at)+ VALUES(?,?,?,?,?,?)+ ON CONFLICT(kind,normalized_name) DO UPDATE SET+ canonical_name=excluded.canonical_name,+ metadata_json=excluded.metadata_json,+ updated_at=excluded.updated_at""",+ (kind, canonical, normalized, payload, stamp, stamp),+ )+ entity_id = connection.execute(+ "SELECT id FROM entity WHERE kind=? AND normalized_name=?", (kind, normalized),+ ).fetchone()[0]+ connection.execute(+ """INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence,+ metadata_json,first_seen_at,last_seen_at)+ VALUES(?,?,?,?,?,?,?,?)+ ON CONFLICT(asset_id,entity_id,role,source) DO UPDATE SET+ confidence=excluded.confidence,+ metadata_json=excluded.metadata_json,+ last_seen_at=excluded.last_seen_at""",+ (asset_id, entity_id, role, source, confidence, payload, stamp, stamp),+ )+ if external_provider and external_id is not None:+ connection.execute(+ """INSERT INTO entity_external_ref(+ entity_id,provider,external_kind,external_id,metadata_json,last_synced_at)+ VALUES(?,?,?,?,?,?)+ ON CONFLICT(provider,external_kind,external_id) DO UPDATE SET+ entity_id=excluded.entity_id,+ metadata_json=excluded.metadata_json,+ last_synced_at=excluded.last_synced_at""",+ (entity_id, external_provider, kind, str(external_id), payload, stamp),+ )+ return int(entity_id)diff --git a/tests/test_scripts.py b/tests/test_scripts.pynew file mode 100644index 000000000..ca4648673--- /dev/null+++ b/tests/test_scripts.py@@ -0,0 +1,104 @@+import csv+import importlib.util+import io+import sqlite3+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path++from peach.migrations import upgrade+++ROOT = Path(__file__).resolve().parents[1]+MIGRATIONS = ROOT / "migrations"+++def load_script(name: str):+ path = ROOT / "scripts" / f"{name}.py"+ spec = importlib.util.spec_from_file_location(f"test_{name}", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class OperationalScriptTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.clean_names = load_script("clean_names")+ cls.scrape_codes = load_script("scrape_codes")++ def test_import_has_no_filesystem_or_log_side_effect(self):+ self.assertIsNone(self.clean_names._logf)+ self.assertIsNone(self.scrape_codes._logf)++ def test_filename_cleanup_is_conservative(self):+ propose = self.clean_names.propose+ self.assertEqual(propose("[email protected]"), "sample.mp4")+ self.assertEqual(propose("sample.mp4.mp4"), "sample.mp4")+ self.assertEqual(propose("sample.mp4.jpg"), "sample.mp4.jpg")+ self.assertEqual(propose("(3).mp4"), "(3).mp4")++ def test_code_normalization(self):+ normalise = self.scrape_codes.normalise+ self.assertEqual(normalise("fc2ppv-1234567"), "FC2-PPV-1234567")+ self.assertEqual(normalise("abw123"), "ABW-123")+ self.assertEqual(normalise("ipvr00296"), "IPVR-296")++ def test_scrape_writeback_dual_writes_projection_and_entities(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.execute(+ "INSERT INTO asset(id,location,path,name,medium,code) "+ "VALUES(1,'local','one.mp4','one.mp4','video','ABC-001')"+ )+ connection.commit()+ connection.close()++ output = root / "review.csv"+ row = {+ "code": "ABC-001", "query": "ABC-001", "performers": "Alice|Bob",+ "studio": "Studio A", "label": "", "series": "Series A", "title": "",+ "categories": "Foot Fetish|Anal", "source": "r18", "status": "ok",+ "size_gb": "1", "videos": "1",+ }+ with output.open("w", encoding="utf-8-sig", newline="") as handle:+ writer = csv.DictWriter(handle, fieldnames=self.scrape_codes.FIELDS)+ writer.writeheader()+ writer.writerow(row)++ with redirect_stdout(io.StringIO()):+ self.scrape_codes.write_back(str(db), str(output))++ connection = sqlite3.connect(db)+ asset = connection.execute(+ "SELECT creator,studio,series FROM asset WHERE id=1"+ ).fetchone()+ tags = {row[0] for row in connection.execute(+ "SELECT tag FROM asset_tag WHERE asset_id=1"+ )}+ relations = set(connection.execute(+ "SELECT e.kind,e.canonical_name,ae.role,ae.source "+ "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "+ "WHERE ae.asset_id=1"+ ))+ connection.close()++ self.assertEqual(asset, ("Alice", "Studio A", "Series A"))+ self.assertEqual(tags, {"演员:Alice", "演员:Bob", "足系", "肛交"})+ self.assertTrue({+ ("studio", "Studio A", "studio", "r18:studio"),+ ("series", "Series A", "series", "r18:series"),+ ("performer", "Alice", "performer", "r18:performer"),+ ("performer", "Bob", "performer", "r18:performer"),+ ("tag", "足系", "tag", "r18"),+ ("tag", "肛交", "tag", "r18"),+ } <= relations)+++if __name__ == "__main__":+ unittest.main()