Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor: rank media by canonical entities

Peach local maintenance60ba75392562
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 0d6c8b548..b188a063b 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -38,6 +38,7 @@ This is durable operating knowledge, not a per-session transcript.
- 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.
- Canonical performer/studio/tag/creator truth belongs in `entity`, `entity_external_ref` and `asset_entity`. Flattened `asset_tag` rows are a temporary compatibility projection, not the target model.
+- Item/detail/facets/tag index/top lists/related ranking already use canonical relations. Remaining creator index/stats/filter compatibility reads are tracked in `docs/STATUS.md`; do not reintroduce compatibility reads into migrated paths.
- 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/STATUS.md b/docs/STATUS.md
index 3a4ea1415..3b10857e1 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -4,7 +4,7 @@ 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 39668; health mode is `fastapi`.
+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 7580; 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.
@@ -27,11 +27,12 @@ Runtime PIDs are observations, not configuration; always re-check them.
- `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.
- `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.
- Item, detail, tag index and facet reads now prefer canonical `asset_entity` performer/tag relations, with flattened `asset_tag` retained only as a staged compatibility fallback. Real-ledger timings were 0.143 s for a filtered item query, 0.118 s for facets and 0.025 s for the first 30 canonical tags.
+- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.
- 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.
+- 38 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.
+- Restarted production port 80 passed health, home, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `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.
@@ -58,5 +59,5 @@ Runtime PIDs are observations, not configuration; always re-check them.
## Next work
1. Add the first tracked online-follow source adapter; keep metadata scraping as a reviewable batch pipeline.
-2. Move creator/studio top lists and related-item ranking from compatibility text fields to canonical relations.
-3. Add reviewed inference requests behind the OpenCode Go adapter; AI output must remain a candidate and cannot write ledger truth directly.
+2. Add reviewed inference requests behind the OpenCode Go adapter; AI output must remain a candidate and cannot write ledger truth directly.
+3. Move the remaining creator index/stats/filter compatibility reads to canonical relations.
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 268cb7485..47b5016a3 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -283,10 +283,16 @@ def q_related(contract: WebContract, aid, limit=24):
"""接着看 —— 把口味接近的串成播放列表。
优先级:同创作者 > 共享标签最多 > 同厂牌。全部排除已标记不合口味的。"""
c = contract.db()
- r = c.execute("SELECT creator,studio,code,ctx_orient FROM asset WHERE id=?", (aid,)).fetchone()
+ r = c.execute("SELECT id FROM asset WHERE id=?", (aid,)).fetchone()
if not r:
c.close(); return {"items": []}
- tags = [x[0] for x in c.execute("SELECT tag FROM asset_tag WHERE asset_id=?", (aid,))]
+ entity_ids = {}
+ for kind in ("creator", "tag", "studio"):
+ entity_ids[kind] = [x[0] for x in c.execute(
+ "SELECT DISTINCT ae.entity_id FROM asset_entity ae "
+ "JOIN entity e ON e.id=ae.entity_id "
+ "WHERE ae.asset_id=? AND e.kind=?", (aid, kind),
+ )]
picked, seen = [], {aid}
def take(sql, par, why):
@@ -298,21 +304,31 @@ def q_related(contract: WebContract, aid, limit=24):
COLS = ("id,location,name,creator,studio,code,size,duration,width,height,"
"ctx_orient,snapshot_path,play_count,leave_ratio,feedback,disposal,o_count")
- base = (f"SELECT {COLS} FROM asset WHERE medium='video' AND id<>? "
- "AND (feedback IS NULL OR feedback<>'dislike') AND (disposal IS NULL)")
- if r["creator"]:
- take(base + " AND creator=? ORDER BY (play_count IS NULL OR play_count=0) DESC, random() LIMIT ?",
- (aid, r["creator"], limit), "同创作者")
+ base = (f"SELECT {COLS} FROM asset a WHERE a.medium='video' AND a.id<>? "
+ "AND (a.feedback IS NULL OR a.feedback<>'dislike') AND a.disposal IS NULL")
+ creators = entity_ids["creator"]
+ if creators:
+ qm = ",".join("?" * len(creators))
+ take(base + f" AND EXISTS (SELECT 1 FROM asset_entity ae WHERE ae.asset_id=a.id "
+ f"AND ae.entity_id IN ({qm})) "
+ "ORDER BY (a.play_count IS NULL OR a.play_count=0) DESC, random() LIMIT ?",
+ tuple([aid] + creators + [limit]), "同创作者")
+ tags = entity_ids["tag"]
if tags and len(picked) < limit:
qm = ",".join("?" * len(tags))
take(f"SELECT {COLS} FROM asset a WHERE a.medium='video' AND a.id<>? "
f"AND (a.feedback IS NULL OR a.feedback<>'dislike') AND a.disposal IS NULL "
- f"AND (SELECT count(*) FROM asset_tag t WHERE t.asset_id=a.id AND t.tag IN ({qm})) >= "
+ f"AND (SELECT count(DISTINCT ae.entity_id) FROM asset_entity ae "
+ f"WHERE ae.asset_id=a.id AND ae.entity_id IN ({qm})) >= "
f"{max(1, min(2, len(tags)))} "
"ORDER BY (a.play_count IS NULL OR a.play_count=0) DESC, random() LIMIT ?",
tuple([aid] + tags + [limit]), "标签接近")
- if r["studio"] and len(picked) < limit:
- take(base + " AND studio=? ORDER BY random() LIMIT ?", (aid, r["studio"], limit), "同厂牌")
+ studios = entity_ids["studio"]
+ if studios and len(picked) < limit:
+ qm = ",".join("?" * len(studios))
+ take(base + f" AND EXISTS (SELECT 1 FROM asset_entity ae WHERE ae.asset_id=a.id "
+ f"AND ae.entity_id IN ({qm})) ORDER BY random() LIMIT ?",
+ tuple([aid] + studios + [limit]), "同厂牌")
c.close()
for d in picked:
d["cost"] = COST.get(d["location"], "metered")
@@ -326,22 +342,30 @@ def q_tops(contract: WebContract, n=28):
头像不额外造图 —— 取该创作者一张有接触印相的代表作,
前端用 background-position:50% 50% 裁中心格做圆头像。"""
c = contract.db()
- def rep(field, val):
- r = c.execute(f"SELECT id FROM asset WHERE medium='video' AND {field}=? "
- "AND snapshot_path IS NOT NULL "
- "ORDER BY (play_count IS NULL), size DESC LIMIT 1", (val,)).fetchone()
+ def rep(entity_id):
+ r = c.execute(
+ "SELECT a.id FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
+ "WHERE ae.entity_id=? AND a.medium='video' AND a.snapshot_path IS NOT NULL "
+ "ORDER BY (a.play_count IS NULL), a.size DESC LIMIT 1", (entity_id,),
+ ).fetchone()
return r[0] if r else None
out = {}
out["performers"] = []
- for k, cnt in c.execute(
- "SELECT creator, count(*) n FROM asset WHERE medium='video' "
- "AND creator IS NOT NULL AND creator<>'' GROUP BY creator ORDER BY n DESC LIMIT ?", (n,)):
- out["performers"].append({"k": k, "n": cnt, "rep": rep("creator", k)})
+ for entity_id, k, cnt in c.execute(
+ "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n "
+ "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "JOIN asset a ON a.id=ae.asset_id "
+ "WHERE a.medium='video' AND e.kind='creator' "
+ "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?", (n,)):
+ out["performers"].append({"k": k, "n": cnt, "rep": rep(entity_id)})
out["studios"] = []
- for k, cnt in c.execute(
- "SELECT studio, count(*) n FROM asset WHERE medium='video' "
- "AND studio IS NOT NULL AND studio<>'' GROUP BY studio ORDER BY n DESC LIMIT ?", (n,)):
- out["studios"].append({"k": k, "n": cnt, "rep": rep("studio", k)})
+ for entity_id, k, cnt in c.execute(
+ "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n "
+ "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "JOIN asset a ON a.id=ae.asset_id "
+ "WHERE a.medium='video' AND e.kind='studio' "
+ "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?", (n,)):
+ out["studios"].append({"k": k, "n": cnt, "rep": rep(entity_id)})
c.close()
return out
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 725bc355c..3b8c4ccd9 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -86,12 +86,19 @@ class WebDataTests(unittest.TestCase):
con.executemany(
"INSERT INTO entity(id,kind,canonical_name,normalized_name) VALUES(?,?,?,?)",
[(10, "tag", "足交", "足交"),
- (11, "performer", "Canonical Alice", "canonical alice")],
+ (11, "performer", "Canonical Alice", "canonical alice"),
+ (12, "creator", "Canonical Creator", "canonical creator"),
+ (13, "studio", "Canonical Studio", "canonical studio")],
)
con.executemany(
"INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "
"VALUES(?,?,?,?,?)",
- [(1, 10, "tag", "test", 1.0), (1, 11, "performer", "test", 1.0)],
+ [(1, 10, "tag", "test", 1.0),
+ (1, 11, "performer", "test", 1.0),
+ (1, 12, "creator", "test", 1.0),
+ (2, 12, "creator", "test", 1.0),
+ (1, 13, "studio", "test", 1.0),
+ (2, 13, "studio", "test", 1.0)],
)
con.commit()
con.close()
@@ -153,5 +160,15 @@ class WebDataTests(unittest.TestCase):
self.assertEqual(self.contract.cached("same", lambda: "first"), "first")
self.assertEqual(other.cached("same", lambda: "second"), "second")
+ def test_top_lists_and_related_items_use_canonical_entities(self):
+ tops = rm_web.q_tops(self.contract, 10)
+ self.assertEqual(tops["performers"][0]["k"], "Canonical Creator")
+ self.assertEqual(tops["performers"][0]["n"], 2)
+ self.assertEqual(tops["studios"][0]["k"], "Canonical Studio")
+
+ related = rm_web.q_related(self.contract, 1, 10)
+ self.assertEqual(related["items"][0]["id"], 2)
+ self.assertEqual(related["items"][0]["why"], "同创作者")
+
if __name__ == "__main__":
unittest.main()