Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor: filter media by canonical identity

Peach local maintenance75ef63230efa
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index b188a063b..d37a069c4 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -38,7 +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.
+- Item/detail/filter/search/facets/index/stats/top lists/related ranking use canonical relations. Flattened creator/studio fields remain only as response compatibility projections; do not use them for identity or matching.
- 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 3b10857e1..af1bdc2f8 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`, server PID observed as 7580; health mode is `fastapi`.
+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 58832; 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.
@@ -28,8 +28,9 @@ Runtime PIDs are observations, not configuration; always re-check them.
- `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.
+- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.
- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.
-- 38 isolated tests and tracked-script static compilation passed under Python 3.14.
+- 39 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, 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.
@@ -60,4 +61,4 @@ Runtime PIDs are observations, not configuration; always re-check them.
1. Add the first tracked online-follow source adapter; keep metadata scraping as a reviewable batch pipeline.
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.
+3. Replace remaining flattened creator/studio display projections only when the front end can consume canonical DTO fields without breaking compatibility.
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 47b5016a3..55be222bc 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -74,9 +74,15 @@ def q_items(contract: WebContract, args):
locs = [x for x in args["loc"].split(",") if x]
where.append("a.location IN (%s)" % ",".join("?" * len(locs))); par += locs
if args.get("creator"):
- where.append("a.creator = ?"); par.append(args["creator"])
+ where.append(
+ "EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE ae.asset_id=a.id AND e.kind='creator' AND e.canonical_name=?)"
+ ); par.append(args["creator"])
if args.get("studio"):
- where.append("a.studio = ?"); par.append(args["studio"])
+ where.append(
+ "EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE ae.asset_id=a.id AND e.kind='studio' AND e.canonical_name=?)"
+ ); par.append(args["studio"])
if args.get("tag"):
# 逗号分隔 = 组合筛选,全部满足(Beeg 的 /PinkLoving+Anal)
for tg in [x for x in args["tag"].split(",") if x]:
@@ -91,7 +97,12 @@ def q_items(contract: WebContract, args):
if args.get("orient"):
where.append("a.ctx_orient = ?"); par.append(args["orient"])
if args.get("q"):
- where.append("(a.name LIKE ? OR a.creator LIKE ? OR a.code LIKE ?)")
+ where.append(
+ "(a.name LIKE ? OR a.code LIKE ? OR EXISTS("
+ "SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE ae.asset_id=a.id AND e.kind IN ('creator','performer','studio') "
+ "AND e.canonical_name LIKE ?))"
+ )
s = f"%{args['q']}%"; par += [s, s, s]
if args.get("state") == "fresh":
where.append("(a.play_count IS NULL OR a.play_count=0) AND a.feedback IS NULL")
@@ -373,16 +384,20 @@ def q_index(contract: WebContract, kind, q="", limit=600):
"""全部创作者 / 全部标签的索引页数据。"""
c = contract.db()
if kind == "creators":
- sql = ("SELECT creator k, count(*) n FROM asset WHERE medium='video' "
- "AND creator IS NOT NULL AND creator<>'' ")
+ sql = ("SELECT e.id entity_id,e.canonical_name k,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' ")
par = []
- if q: sql += "AND creator LIKE ? "; par.append(f"%{q}%")
- sql += "GROUP BY creator ORDER BY n DESC LIMIT ?"; par.append(limit)
+ if q: sql += "AND e.canonical_name LIKE ? "; par.append(f"%{q}%")
+ sql += "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ?"; par.append(limit)
rows = [dict(r) for r in c.execute(sql, par)]
for r in rows:
- g = c.execute("SELECT id FROM asset WHERE medium='video' AND creator=? "
- "AND snapshot_path IS NOT NULL ORDER BY size DESC LIMIT 1",
- (r["k"],)).fetchone()
+ g = 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.size DESC LIMIT 1", (r.pop("entity_id"),),
+ ).fetchone()
r["rep"] = g[0] if g else None
else:
sql = ("SELECT e.canonical_name k, count(DISTINCT ae.asset_id) n "
@@ -412,9 +427,13 @@ def q_stats(contract: WebContract):
return r[0] if r else 0
out["attribution"] = {
"videos": v,
- "creator": one("SELECT count(*) FROM asset WHERE medium='video' AND creator IS NOT NULL AND creator<>''"),
+ "creator": one("SELECT count(DISTINCT ae.asset_id) 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'"),
"code": one("SELECT count(*) FROM asset WHERE medium='video' AND code IS NOT NULL AND code<>''"),
- "studio": one("SELECT count(*) FROM asset WHERE medium='video' AND studio IS NOT NULL AND studio<>''"),
+ "studio": one("SELECT count(DISTINCT ae.asset_id) 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'"),
"thumb": one("SELECT count(*) FROM asset WHERE medium='video' AND snapshot_path IS NOT NULL"),
"duration": one("SELECT count(*) FROM asset WHERE medium='video' AND duration IS NOT NULL"),
}
@@ -457,8 +476,10 @@ def q_facets(contract: WebContract):
"SUM(CASE WHEN play_count>0 THEN 1 ELSE 0 END) AS played "
"FROM asset WHERE medium='video' GROUP BY location ORDER BY n DESC")]
out["creators"] = [dict(r) for r in c.execute(
- "SELECT creator AS k, count(*) AS n FROM asset WHERE medium='video' "
- "AND creator IS NOT NULL AND creator<>'' GROUP BY creator ORDER BY n DESC LIMIT 60")]
+ "SELECT e.canonical_name AS k,count(DISTINCT ae.asset_id) AS 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 60")]
# 标签要分层 —— 原来一锅端,结果「演员:一个ren」和「1080P」「足交」混在一起。
# 三类分开:技术规格(画质/时长/画幅,筛选价值低)、内容维度(真正有用的)、演员(另立一栏)。
TECH = ("1080P", "720P", "4K", "2160P", "480P", "低画质", "高帧率",
@@ -481,8 +502,9 @@ def q_facets(contract: WebContract):
"SELECT count(*) total, COALESCE(sum(size),0) bytes, "
"SUM(CASE WHEN play_count>0 THEN 1 ELSE 0 END) played, "
"SUM(CASE WHEN feedback IS NOT NULL OR disposal IS NOT NULL THEN 1 ELSE 0 END) flagged, "
- "SUM(CASE WHEN creator IS NOT NULL AND creator<>'' THEN 1 ELSE 0 END) attributed "
- "FROM asset WHERE medium='video'").fetchone()
+ "SUM(EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE ae.asset_id=a.id AND e.kind='creator')) attributed "
+ "FROM asset a WHERE a.medium='video'").fetchone()
out["stats"] = dict(st)
c.close()
return out
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 3b8c4ccd9..b9b2b1012 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -170,5 +170,31 @@ class WebDataTests(unittest.TestCase):
self.assertEqual(related["items"][0]["id"], 2)
self.assertEqual(related["items"][0]["why"], "同创作者")
+ def test_creator_filters_indexes_and_stats_use_canonical_entities(self):
+ by_creator = rm_web.q_items(self.contract, {
+ "creator": "Canonical Creator", "limit": "10",
+ })
+ by_studio = rm_web.q_items(self.contract, {
+ "studio": "Canonical Studio", "limit": "10",
+ })
+ search = rm_web.q_items(self.contract, {
+ "q": "Canonical Creator", "limit": "10",
+ })
+ self.assertEqual(by_creator["total"], 2)
+ self.assertEqual(by_studio["total"], 2)
+ self.assertEqual(search["total"], 2)
+ self.assertEqual(rm_web.q_items(
+ self.contract, {"creator": "Alice", "limit": "10"},
+ )["total"], 0)
+
+ creators = rm_web.q_index(self.contract, "creators", limit=10)
+ self.assertEqual(creators["items"][0]["k"], "Canonical Creator")
+ self.assertEqual(creators["items"][0]["n"], 2)
+ stats = rm_web.q_stats(self.contract)
+ self.assertEqual(stats["attribution"]["creator"], 2)
+ self.assertEqual(stats["attribution"]["studio"], 2)
+ facets = rm_web.q_facets(self.contract)
+ self.assertEqual(facets["creators"][0]["k"], "Canonical Creator")
+
if __name__ == "__main__":
unittest.main()