Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor: centralize Stash ledger import

Peach local maintenancef868f782a6e1
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 36553f85f..8ee1d3cc2 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -33,6 +33,7 @@ This is durable operating knowledge, not a per-session transcript.
- Ledger owns truth and behavior.
- Stash is a replaceable adapter; do not add new direct GraphQL helpers or private Stash FFmpeg paths.
+- All Stash calls use `StashClient`. Imports persist the stable Scene ID and provenance in `media_binding`; do not regress to `stash_scene_id` as the only external reference.
- Keep FastAPI and the front end logically separate but deploy as a monolith.
- External sources and AI are supported only through explicit adapters and declared data boundaries.
- AI provider layers are not equivalent: inference APIs and local coding/agent runtimes remain separate.
diff --git a/docs/STASH.md b/docs/STASH.md
index 020183ec1..a9e28823f 100644
--- a/docs/STASH.md
+++ b/docs/STASH.md
@@ -46,7 +46,8 @@ Peach 最终可以完全去 Stash,但现在不能直接卸载。Web 主链已
- `FFmpegResolver` 现在只接受环境变量、`R:\peach-data\tools\ffmpeg` 和 PATH;Stash 私有目录 fallback 已删除。
- FastAPI 已用 Starlette `FileResponse` 替换候选入口的手写 Range,并验证普通、指定区间、suffix、
越界 416、HEAD、ETag、Last-Modified。
-- 活跃代码中的 Stash 私有 FFmpeg 路径已归零;剩余 GraphQL transport 是集中 adapter 与 `scripts/ledger.py` 的一个待迁移 helper,仍不能宣称已经去 Stash。
+- 活跃代码中的 Stash 私有 FFmpeg 路径和重复 GraphQL transport 已归零;`scripts/ledger.py` 也复用集中 `StashClient`。Stash adapter 本身仍在使用,因此仍不能宣称已经去 Stash。
+- Stash 导入现在为每个资产写入 `media_binding(backend='stash', external_id=scene_id)`,并把原始 Studio/Performer/Tag 断言摘要保存在 `metadata_json`;标签来源规范为 `stash:tag` / `stash:performer`。
## 验收门槛
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 624dc81cf..50b9bf652 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -19,6 +19,7 @@ Runtime PIDs are observations, not configuration; always re-check them.
- FastAPI serves home, stable JSON contract, standard Range/HEAD media, thumbnails, posters, avatars and logos.
- 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.
- `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.
- 24 isolated tests passed under Python 3.14, including 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`.
@@ -29,6 +30,6 @@ Runtime PIDs are observations, not configuration; always re-check them.
## Next work
-1. Route the remaining `scripts/ledger.py` Stash import through the centralized adapter and formalize entity provenance.
+1. Replace flattened `演员:` tags with canonical performer/entity relations while keeping a compatibility projection for the current UI.
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.
diff --git a/scripts/ledger.py b/scripts/ledger.py
index 6b71539d8..adf29257f 100644
--- a/scripts/ledger.py
+++ b/scripts/ledger.py
@@ -15,11 +15,11 @@ r"""
设计边界见项目根目录 docs/ARCHITECTURE.md 与 docs/adr/。
默认本地自托管。扫描只读元数据;在线关注同步是正式能力,按来源单独控频和授权。
"""
-import os, sys, csv, json, sqlite3, time, urllib.request, urllib.error
+import os, sys, csv, json, sqlite3, time
-DB = os.path.expandvars(r"R:\peach-data\database\ledger.db")
-STASH = "http://127.0.0.1:9999/graphql"
+from peach.stash import StashClient, StashError
+DB = os.path.expandvars(r"R:\peach-data\database\ledger.db")
VIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg", ".m2ts"}
IMAGE = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
AUDIO = {".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus"}
@@ -56,6 +56,16 @@ CREATE TABLE IF NOT EXISTS quest(
id INTEGER PRIMARY KEY, keyword TEXT, origin TEXT,
created_at TEXT, resolved_at TEXT, outcome TEXT);
+CREATE TABLE IF NOT EXISTS media_binding(
+ asset_id INTEGER NOT NULL REFERENCES asset(id),
+ backend TEXT NOT NULL,
+ external_id TEXT NOT NULL,
+ priority INTEGER NOT NULL DEFAULT 100,
+ metadata_json TEXT NOT NULL DEFAULT '{}',
+ last_synced_at TEXT,
+ PRIMARY KEY(asset_id, backend),
+ UNIQUE(backend, external_id));
+
CREATE INDEX IF NOT EXISTS ix_asset_hash ON asset(hash_kind, hash);
CREATE INDEX IF NOT EXISTS ix_asset_size ON asset(size);
CREATE INDEX IF NOT EXISTS ix_asset_loc ON asset(location);
@@ -131,22 +141,18 @@ def cmd_scan(location, root):
c.close()
-def gq(q, v=None):
- b = {"query": q}
- if v: b["variables"] = v
- try:
- return json.loads(urllib.request.urlopen(urllib.request.Request(
- STASH, data=json.dumps(b).encode(), headers={"Content-Type": "application/json"}), timeout=120).read())["data"]
- except urllib.error.HTTPError as e:
- print("Stash 错误:", e.read().decode("utf-8", "ignore")[:200]); return None
-
-
-def cmd_stash():
+def cmd_stash(client=None):
c = conn(); c.executescript(SCHEMA)
- d = gq("""{findScenes(filter:{per_page:-1}){scenes{
- id title rating100 o_counter play_count
- files{path size duration width height video_codec frame_rate audio_codec}
- studio{name} performers{name} tags{name}}}}""")
+ client = client or StashClient(timeout=120)
+ try:
+ d = client.graphql("""{findScenes(filter:{per_page:-1}){scenes{
+ id title rating100 o_counter play_count
+ files{path size duration width height video_codec frame_rate audio_codec}
+ studio{name} performers{name} tags{name}}}}""")
+ except StashError as exc:
+ print("Stash 错误:", exc)
+ c.close()
+ return
if not d:
c.close()
return
@@ -176,11 +182,30 @@ def cmd_stash():
s.get("play_count") or 0, s.get("rating100"), s.get("o_counter") or 0,
int(s["id"]), now, now))
aid = c.execute("SELECT id FROM asset WHERE location='local' AND path=?", (f["path"],)).fetchone()[0]
+ provenance = {
+ "transport": "stash-graphql",
+ "studio": (s.get("studio") or {}).get("name"),
+ "performers": [p["name"] for p in s.get("performers") or []],
+ "tags": [t["name"] for t in s.get("tags") or []],
+ }
+ c.execute("""INSERT INTO media_binding(asset_id,backend,external_id,metadata_json,last_synced_at)
+ VALUES(?,'stash',?,?,?)
+ ON CONFLICT(asset_id,backend) DO UPDATE SET
+ external_id=excluded.external_id,
+ metadata_json=excluded.metadata_json,
+ last_synced_at=excluded.last_synced_at""",
+ (aid, str(s["id"]), json.dumps(provenance, ensure_ascii=False), now))
for t in s.get("tags") or []:
- c.execute("INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) VALUES(?,?,1.0,'stash')",
+ c.execute("""INSERT INTO asset_tag(asset_id,tag,confidence,source)
+ VALUES(?,?,1.0,'stash:tag')
+ ON CONFLICT(asset_id,tag) DO UPDATE SET
+ confidence=excluded.confidence,source=excluded.source""",
(aid, t["name"])); nt += 1
for p in s.get("performers") or []:
- c.execute("INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) VALUES(?,?,1.0,'performer')",
+ c.execute("""INSERT INTO asset_tag(asset_id,tag,confidence,source)
+ VALUES(?,?,1.0,'stash:performer')
+ ON CONFLICT(asset_id,tag) DO UPDATE SET
+ confidence=excluded.confidence,source=excluded.source""",
(aid, "演员:" + p["name"]))
c.commit()
print(f"✓ Stash: {len(scenes):,} 个场景,{nt:,} 条标签关联")
diff --git a/tests/test_rm_ledger.py b/tests/test_rm_ledger.py
index e808af543..62eb5cfde 100644
--- a/tests/test_rm_ledger.py
+++ b/tests/test_rm_ledger.py
@@ -3,9 +3,9 @@ import io
import sqlite3
import tempfile
import unittest
+from types import SimpleNamespace
from pathlib import Path
from contextlib import redirect_stdout
-from unittest.mock import patch
MODULE_PATH = Path(__file__).resolve().parents[1] / "scripts" / "ledger.py"
@@ -53,21 +53,28 @@ class LedgerSchemaTests(unittest.TestCase):
"performers": [{"name": "Performer A"}],
"tags": [{"name": "Tag A"}],
}]}}
- with patch.object(rm_ledger, "gq", return_value=response):
- with redirect_stdout(io.StringIO()):
- rm_ledger.cmd_stash()
+ client = SimpleNamespace(graphql=lambda *_args, **_kwargs: response)
+ with redirect_stdout(io.StringIO()):
+ rm_ledger.cmd_stash(client)
con = sqlite3.connect(self.db)
row = con.execute(
"SELECT creator,studio,stash_scene_id FROM asset WHERE path=?",
(r"R:\media\one.mp4",),
).fetchone()
- tags = {x[0] for x in con.execute(
- "SELECT tag FROM asset_tag WHERE asset_id=(SELECT id FROM asset WHERE path=?)",
+ tags = {x for x in con.execute(
+ "SELECT tag,source FROM asset_tag WHERE asset_id=(SELECT id FROM asset WHERE path=?)",
(r"R:\media\one.mp4",),
)}
+ binding = con.execute(
+ "SELECT backend,external_id,metadata_json FROM media_binding WHERE asset_id=(SELECT id FROM asset WHERE path=?)",
+ (r"R:\media\one.mp4",),
+ ).fetchone()
con.close()
self.assertEqual(row, ("Channel Owner", "Studio A", 42))
- self.assertEqual(tags, {"Tag A", "演员:Performer A"})
+ self.assertEqual(tags, {("Tag A", "stash:tag"),
+ ("演员:Performer A", "stash:performer")})
+ self.assertEqual(binding[:2], ("stash", "42"))
+ self.assertIn('"transport": "stash-graphql"', binding[2])
if __name__ == "__main__":