Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: add profile taste feedback

Peach local maintenance259a034f5c40
diff --git a/migrations/0006_asset_preference.sql b/migrations/0006_asset_preference.sql
new file mode 100644
index 000000000..e1a91b6bd
--- /dev/null
+++ b/migrations/0006_asset_preference.sql
@@ -0,0 +1,12 @@
+CREATE TABLE IF NOT EXISTS asset_preference(
+ profile_id TEXT NOT NULL REFERENCES profile(id) ON DELETE CASCADE,
+ asset_id INTEGER NOT NULL REFERENCES asset(id) ON DELETE CASCADE,
+ liked INTEGER NOT NULL DEFAULT 0 CHECK(liked IN (0,1)),
+ reason TEXT NOT NULL DEFAULT '',
+ source TEXT NOT NULL DEFAULT 'web',
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY(profile_id,asset_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_asset_preference_profile_liked
+ON asset_preference(profile_id,liked,updated_at DESC);
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 1af0795e5..9142e22c2 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -246,6 +246,10 @@ def q_item(contract: WebContract, aid):
"SELECT id,location,path,name,creator,studio,code,size,duration,width,height,"
"ctx_length,ctx_orient,snapshot_path,play_count,leave_ratio,feedback,disposal,"
"rating,o_count,play_seconds,max_reached,seek_count,"
+ "COALESCE((SELECT p.liked FROM asset_preference p WHERE p.asset_id=asset.id "
+ "AND p.profile_id='local-default'),0) AS liked,"
+ "COALESCE((SELECT p.reason FROM asset_preference p WHERE p.asset_id=asset.id "
+ "AND p.profile_id='local-default'),'') AS like_reason,"
"EXISTS(SELECT 1 FROM watch_queue w WHERE w.asset_id=asset.id "
"AND w.profile_id='local-default') AS watch_later FROM asset WHERE id=?", (aid,)).fetchone()
if not r:
@@ -726,6 +730,45 @@ def w_watch_later(contract: WebContract, body):
return {"ok": True, "watch_later": queued}
+def w_preference(contract: WebContract, body):
+ """保存 profile 级正向偏好;与看过、不喜欢和稍后看保持独立。"""
+ contract.cache_bust()
+ aid = int(body["id"])
+ liked = 1 if bool(body.get("liked")) else 0
+ reason = body.get("reason", "")
+ if not isinstance(reason, str):
+ raise TypeError("reason must be a string")
+ if len(reason) > 2000:
+ raise ValueError("reason is limited to 2000 characters")
+ with contract.write_lock:
+ c = contract.db(write=True)
+ if not c.execute("SELECT 1 FROM asset WHERE id=?", (aid,)).fetchone():
+ c.close()
+ raise ValueError("asset not found")
+ if not liked and not reason:
+ c.execute(
+ "DELETE FROM asset_preference WHERE profile_id='local-default' AND asset_id=?",
+ (aid,),
+ )
+ else:
+ c.execute(
+ "INSERT INTO asset_preference(profile_id,asset_id,liked,reason,source,updated_at) "
+ "VALUES('local-default',?,?,?,'web',strftime('%Y-%m-%dT%H:%M:%fZ','now')) "
+ "ON CONFLICT(profile_id,asset_id) DO UPDATE SET "
+ "liked=excluded.liked,reason=excluded.reason,source=excluded.source,"
+ "updated_at=excluded.updated_at",
+ (aid, liked, reason),
+ )
+ c.commit()
+ row = c.execute(
+ "SELECT liked,reason FROM asset_preference "
+ "WHERE profile_id='local-default' AND asset_id=?", (aid,),
+ ).fetchone()
+ c.close()
+ return {"ok": True, "liked": bool(row["liked"]) if row else False,
+ "like_reason": row["reason"] if row else ""}
+
+
def dispatch_api_get(contract: WebContract, path, args):
"""Dispatch the stable JSON read contract used by the current web client."""
if path == "/api/items":
@@ -759,4 +802,6 @@ def dispatch_api_post(contract: WebContract, path, body):
return w_feedback(contract, body)
if path == "/api/watch-later":
return w_watch_later(contract, body)
+ if path == "/api/preference":
+ return w_preference(contract, body)
raise KeyError(path)
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index e05a50e9f..da20ef267 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -35,6 +35,8 @@ CREATE TABLE asset_entity(
UNIQUE(asset_id,entity_id,role,source));
CREATE TABLE watch_queue(profile_id TEXT,asset_id INTEGER,added_at TEXT,source TEXT,
PRIMARY KEY(profile_id,asset_id));
+CREATE TABLE asset_preference(profile_id TEXT,asset_id INTEGER,liked INTEGER,reason TEXT,
+ source TEXT,updated_at TEXT,PRIMARY KEY(profile_id,asset_id));
CREATE TABLE media_binding(
asset_id INTEGER,backend TEXT,external_id TEXT,metadata_json TEXT,last_synced_at TEXT,
PRIMARY KEY(asset_id,backend),UNIQUE(backend,external_id));
@@ -127,6 +129,23 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("path", data["items"][0])
self.assertEqual(response.headers["cache-control"], "no-store")
+ async def test_preference_is_an_independent_authenticated_write(self):
+ denied = await self.client.post(
+ "/api/preference", json={"id": 1, "liked": True, "reason": "镜头自然"},
+ )
+ self.assertEqual(denied.status_code, 401)
+ saved = await self.client.post(
+ "/api/preference?t=secret",
+ json={"id": 1, "liked": True, "reason": "镜头自然"},
+ )
+ self.assertEqual(saved.status_code, 200)
+ self.assertEqual(saved.json(), {
+ "ok": True, "liked": True, "like_reason": "镜头自然",
+ })
+ detail = await self.client.get("/api/item?t=secret&id=1")
+ self.assertTrue(detail.json()["liked"])
+ self.assertEqual(detail.json()["like_reason"], "镜头自然")
+
async def test_provider_health_is_authenticated_and_secret_free(self):
denied = await self.client.get("/api/providers")
self.assertEqual(denied.status_code, 401)
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index cae778a40..04ed19505 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -24,7 +24,7 @@ class MigrationTests(unittest.TestCase):
backup = self.root / "before.db"
done = upgrade(self.db, MIGRATIONS, backup)
self.assertEqual([m.version for m in done],
- ["0000", "0001", "0002", "0003", "0004", "0005"])
+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006"])
self.assertTrue(backup.exists())
con = sqlite3.connect(self.db)
tables = {row[0] for row in con.execute(
@@ -37,9 +37,9 @@ class MigrationTests(unittest.TestCase):
self.assertTrue({"asset", "profile", "media_binding", "activity_event",
"provider_profile", "entity", "entity_alias",
"entity_external_ref", "asset_entity", "entity_link",
- "entity_search_term", "watch_queue", "asset_search",
+ "entity_search_term", "watch_queue", "asset_preference", "asset_search",
"schema_migration"} <= tables)
- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005"])
+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006"])
self.assertEqual(upgrade(self.db, MIGRATIONS), [])
self.assertEqual(plan(self.db, MIGRATIONS)[1], [])
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index c7aca5462..5f6a36c2c 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -64,6 +64,8 @@ CREATE TABLE entity_link(id INTEGER PRIMARY KEY,entity_id INTEGER,link_kind TEXT
CREATE TABLE entity_search_term(entity_id INTEGER,term TEXT,purpose TEXT,source TEXT,created_at TEXT);
CREATE TABLE watch_queue(profile_id TEXT,asset_id INTEGER,added_at TEXT,source TEXT,
PRIMARY KEY(profile_id,asset_id));
+CREATE TABLE asset_preference(profile_id TEXT,asset_id INTEGER,liked INTEGER,reason TEXT,
+ source TEXT,updated_at TEXT,PRIMARY KEY(profile_id,asset_id));
"""
@@ -163,6 +165,23 @@ class WebDataTests(unittest.TestCase):
)["feedback"])
self.assertEqual(self.row()["disposal"], "pending")
+ def test_like_and_reason_are_independent_profile_preferences(self):
+ saved = rm_web.w_preference(self.contract, {
+ "id": 1, "liked": True, "reason": "喜欢自然的节奏和镜头",
+ })
+ self.assertTrue(saved["liked"])
+ self.assertEqual(saved["like_reason"], "喜欢自然的节奏和镜头")
+ item = rm_web.q_item(self.contract, 1)
+ self.assertTrue(item["liked"])
+ self.assertEqual(item["like_reason"], "喜欢自然的节奏和镜头")
+ self.assertIsNone(self.row()["feedback"])
+
+ cleared = rm_web.w_preference(self.contract, {
+ "id": 1, "liked": False, "reason": "",
+ })
+ self.assertFalse(cleared["liked"])
+ self.assertEqual(cleared["like_reason"], "")
+
def test_application_contract_instances_do_not_share_cache(self):
other = rm_web.WebContract(Path(self.tmp.name) / "other.db")
self.assertEqual(self.contract.cached("same", lambda: "first"), "first")
diff --git a/web/index.html b/web/index.html
index 9d8021b6a..fa911b125 100644
--- a/web/index.html
+++ b/web/index.html
@@ -42,7 +42,7 @@ body{background:var(--ground);color:var(--ink);
font-weight:600;letter-spacing:.02em}
.mono{font-family:"Cascadia Mono",Consolas,ui-monospace,monospace;
font-variant-numeric:tabular-nums;font-size:11px}
-button,input{font:inherit;color:inherit}
+button,input,textarea{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--tungsten);outline-offset:2px}
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
/* 滚动条:全站统一,不用浏览器默认。细、无箭头、无轨道底色,悬停才提亮。 */
@@ -340,6 +340,24 @@ main{padding:14px 16px 90px}
.fb .dislike[aria-pressed="true"]{border-color:var(--drop);color:var(--drop)}
.fb .seen[aria-pressed="true"]{border-color:var(--muted)}
.fb .dispose[aria-pressed="true"]{border-color:var(--meter);color:var(--meter)}
+.preference{border:1px solid var(--line);border-radius:6px;padding:10px;margin:1px 0 8px;
+ background:color-mix(in srgb,var(--surface) 78%,transparent)}
+.preference-head{display:flex;align-items:center;gap:8px;margin-bottom:8px}
+.likebtn{display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:8px 13px;
+ border:1px solid var(--line);border-radius:999px;background:transparent;cursor:pointer;font-weight:650}
+.likebtn svg{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:1.9;
+ stroke-linecap:round;stroke-linejoin:round}
+.likebtn[aria-pressed="true"]{color:#fff;background:var(--tungsten);border-color:var(--tungsten)}
+.preference .weight{font-size:10px;color:var(--muted)}
+.preference textarea{display:block;width:100%;min-height:62px;resize:vertical;padding:8px 9px;
+ color:var(--ink);background:var(--ground);border:1px solid var(--line);border-radius:5px;
+ line-height:1.45}
+.preference textarea:focus{border-color:var(--tungsten);outline:0}
+.preference-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:7px}
+.preference-foot span{color:var(--muted);font-size:10px}
+.savepreference{border:0;border-radius:5px;padding:6px 12px;background:var(--ink);color:var(--ground);
+ cursor:pointer;font-size:11px}
+.savepreference:disabled{opacity:.55;cursor:default}
.obtn{width:100%;padding:9px;border:1px solid var(--line);background:transparent;
border-radius:4px;cursor:pointer;margin-bottom:11px}
.obtn:hover{border-color:var(--tungsten)}
@@ -1105,6 +1123,16 @@ async function openItem(id){
<span class="k">看过了</span><span class="d">只降近期</span></button>
<button class="dispose" data-kind="dispose" aria-pressed="${it.disposal==='pending'}">
<span class="k">标记待删</span><span class="d">不删文件</span></button></div>
+ <div class="preference">
+ <div class="preference-head">
+ <button class="likebtn" id="likeBtn" aria-pressed="${!!it.liked}">
+ <svg viewBox="0 0 24 24"><path d="M7 10v10H3V10h4Zm0 9h10.2a2 2 0 0 0 1.9-1.4l1.7-5.5A2 2 0 0 0 18.9 9H14l.7-3.3A2.2 2.2 0 0 0 12.6 3L7 10Z"/></svg>
+ <span>${it.liked?'已喜欢':'喜欢'}</span></button>
+ <span class="weight">独立增加推荐权重</span></div>
+ <textarea id="likeReason" maxlength="2000" placeholder="为什么喜欢?例如节奏、人物、镜头、氛围……">${esc(it.like_reason||'')}</textarea>
+ <div class="preference-foot"><span id="preferenceState">原文仅保存在本机</span>
+ <button class="savepreference" id="savePreference">保存原因</button></div>
+ </div>
<button class="obtn" data-kind="o">记一次高潮 <b class="mono" id="oCount">${it.o_count||0}</b></button>
<button class="obtn" id="stageLater" aria-pressed="${!!it.watch_later}">${it.watch_later?'✓ 已加入稍后看':'+ 稍后看'}</button>
<div class="hint mono">前三个只打标记,随时可撤。删除永远走「先出 CSV 再执行」,不在这个页面里。</div>
@@ -1129,6 +1157,19 @@ async function openItem(id){
body:JSON.stringify({id:it.id})});it.watch_later=r.watch_later;
$('#stageLater').setAttribute('aria-pressed',r.watch_later);
$('#stageLater').textContent=r.watch_later?'✓ 已加入稍后看':'+ 稍后看'};
+ const savePreference=async()=>{
+ const btn=$('#savePreference'),like=$('#likeBtn'),stateText=$('#preferenceState');
+ btn.disabled=true;stateText.textContent='保存中…';
+ try{const r=await api('/api/preference',{method:'POST',body:JSON.stringify({
+ id:it.id,liked:like.getAttribute('aria-pressed')==='true',reason:$('#likeReason').value})});
+ it.liked=r.liked;it.like_reason=r.like_reason;
+ like.setAttribute('aria-pressed',r.liked);like.querySelector('span').textContent=r.liked?'已喜欢':'喜欢';
+ stateText.textContent='已保存 · AI 不会直接改写原文';
+ }catch(e){stateText.textContent='保存失败 · 请重试'}finally{btn.disabled=false}
+ };
+ $('#likeBtn').onclick=async()=>{const b=$('#likeBtn');
+ b.setAttribute('aria-pressed',b.getAttribute('aria-pressed')!=='true');await savePreference()};
+ $('#savePreference').onclick=savePreference;
const vv=$('#vid');
vv.addEventListener('play',()=>{if(!$('#stage').dataset.c){$('#stage').dataset.c='1';
api('/api/play',{method:'POST',body:JSON.stringify({id:it.id})})}});