Peach: Local-first video metadata scraper and media manager.
feat(web): 女优索引页加大图与紧凑两个版式
longmeidaoe36d214638be
diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex e6a4aca93..3a8d07058 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -269,6 +269,12 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")all_rows = [row for row in all_rows if row["cat"] == category]rows = all_rows[offset:offset + limit]has_more = offset + limit < len(all_rows)+ if kind in {"creators", "performers"}:+ #: 索引页的大图版式把头像裁成竖幅,几何居中会切掉脸。取景与资料页大图同一份+ #: sidecar、同一个换算,只是这里按行取;读的是文件,所以放在连接之外。+ entity_kind = "creator" if kind == "creators" else "performer"+ for row in rows:+ row["avatar_focus"] = contract.avatar_focus(entity_kind, row["entity_id"])result = {"kind": kind, "items": rows, "has_more": has_more}if kind == "tags":result["categories"] = category_countsdiff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 0338d2753..358e08f6d 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -1568,6 +1568,69 @@ class AvatarFocusTests(unittest.TestCase):self.assertIsNone(self.contract.avatar_focus("series", 14))+class PeopleIndexFocusTests(unittest.TestCase):+ """索引页大图版式的取景:与资料页大图同一份 sidecar,只是按行取。"""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name)+ self.db_path = str(fresh_ledger(str(root)))+ con = sqlite3.connect(self.db_path)+ con.execute(+ "INSERT INTO asset(id,location,path,name,medium,size,snapshot_path,first_seen)"+ " VALUES(1,'local',?,'one.mp4','video',100,?,'2026-08-14')",+ (r"R:\Media\one.mp4", r"R:\snap\1.jpg"),+ )+ con.executemany(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES(?,?,?,?,'2026-01-01','2026-01-01')",+ [(10, "tag", "足交", "足交"),+ (11, "performer", "Canonical Alice", "canonical alice"),+ (12, "creator", "Canonical Creator", "canonical creator")],+ )+ con.executemany(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)"+ " VALUES(?,?,?,?,1.0)",+ [(1, 10, "tag", "test"),+ (1, 11, "performer", "test"),+ (1, 12, "creator", "test")],+ )+ con.commit()+ con.close()+ self.avatars = root / "avatars"+ self.avatars.mkdir()+ self.contract = rm_web.WebContract(Path(self.db_path), avatar_root=self.avatars)++ def test_each_row_carries_the_focus_the_entity_page_would_use(self):+ (self.avatars / "performer-11.face.json").write_text(+ '{"focus":{"axis":"y","pct":30}}', encoding="utf-8")+ row = rm_web.q_index(self.contract, "performers")["items"][0]+ self.assertEqual(row["k"], "Canonical Alice")+ # 同一个实体,索引页大图和资料页大图必须取到同一个位置。+ self.assertEqual(row["avatar_focus"], {"axis": "y", "pct": 30})+ self.assertEqual(row["avatar_focus"], self.contract.avatar_focus("performer", 11))++ def test_a_row_without_a_sidecar_says_so_instead_of_dropping_the_key(self):+ # 没算过是常态:键仍然在,页面据此维持几何居中。+ row = rm_web.q_index(self.contract, "performers")["items"][0]+ self.assertIsNone(row["avatar_focus"])++ def test_creators_read_their_own_kind_not_the_performer_sidecar(self):+ (self.avatars / "performer-12.face.json").write_text(+ '{"focus":{"axis":"x","pct":80}}', encoding="utf-8")+ (self.avatars / "creator-12.face.json").write_text(+ '{"focus":{"axis":"y","pct":20}}', encoding="utf-8")+ row = rm_web.q_index(self.contract, "creators")["items"][0]+ self.assertEqual(row["k"], "Canonical Creator")+ self.assertEqual(row["avatar_focus"], {"axis": "y", "pct": 20})++ def test_the_tag_index_has_no_face_to_frame(self):+ tags = rm_web.q_index(self.contract, "tags")["items"]+ self.assertEqual([row["k"] for row in tags], ["足交"])+ self.assertNotIn("avatar_focus", tags[0])++class DuplicateDetectionTests(unittest.TestCase):"""同番号不等于重复:合集、分卷和混入的广告都会共用一个 code。"""diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 8d32950fe..3c95c0f91 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -4274,6 +4274,52 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("return state.jav==='1'||entityJavLayout")self.assertPageContains("const jav=javActive()&&!!it.is_jav,layout=javLayout()")+ def test_the_people_index_offers_a_big_and_a_compact_layout(self):+ """艺人索引页的两个版式,与 JAV 大图同一条思路、同一个控件。"""+ self.assertPageContains(+ "const PEOPLE_LAYOUTS=[['big','大图 · 竖幅头像','maximize'],"+ "['compact','紧凑 · 圆形头像','layout-grid']];")+ self.assertPageContains(+ "iconSwitchHtml('people-layout','艺人索引版式',PEOPLE_LAYOUTS,peopleIndexLayout(),")+ self.assertPageContains("{attr:'data-people-layout'}")+ # 只有艺人和创作者是头像网格;标签页那一屏没有图可放大。+ self.assertPageContains("${people?peopleLayoutButtons():''}")+ self.assertPageContains(+ "wireIconSwitch($('#index'),'data-people-layout',setPeopleIndexLayout);")+ self.assertPageContains(+ '`<div class="igrid" data-layout="${peopleIndexLayout()}">${peopleHtml(d.items)}</div>`')+ self.assertPageContains("peopleLayout:'big'", "默认与 JAV 版式、密度一致:大图为主")++ def test_the_big_people_layout_only_stretches_the_frame_it_does_not_change_columns(self):+ # JAV 大图那条规矩:宽度不变、高度拉长。列宽跟着改的话,窄屏会掉成一列。+ self.assertPageContains(+ '.igrid[data-layout="big"] .icell .ring{width:100%;height:auto;aspect-ratio:3/4;')+ self.assertPageContains(".igrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr))")+ self.assertPageLacks('.igrid[data-layout="big"]{grid-template-columns',+ "两个版式必须同列宽同列数")+ self.assertPageLacks('.igrid[data-layout="compact"]',+ "紧凑就是基础样式那一屏,不该再写一份")++ def test_switching_the_people_layout_neither_repaints_the_grid_nor_refetches(self):+ # 版式是纯展示层的事:改容器上的一个属性就够,和关注列表版式同一个做法。+ self.assertCode(+ "function setPeopleIndexLayout(value){\n"+ " appSettings.peopleLayout=value;\n"+ " saveSettings();\n"+ " document.querySelectorAll('.igrid')"+ ".forEach(grid=>{grid.dataset.layout=peopleIndexLayout()});\n"+ "}")++ def test_the_big_people_layout_frames_the_detected_face(self):+ # 3:4 竖幅按几何居中会把脸切掉。换算只有 faceOrigin 一份:资料页写进 img 的+ # style,索引页交给圆框上的 --face——那里的 img 是八处共用的 avatarInner 拼的。+ self.assertPageContains("function faceOrigin(f){")+ self.assertCode(" const origin=faceOrigin(f);\n"+ " return origin?` style=\"object-position:${origin}\"`:'';")+ self.assertPageContains("const face=faceOrigin(x.avatar_focus);")+ self.assertPageContains('<span class="ring"${face?` style="--face:${face}"`:\'\'}>')+ self.assertPageContains("object-position:var(--face,50% 50%)}")+def test_photo_lightbox_loads_swiper_lazily_with_thumbs_and_keyboard(self):self.assertPageContains("'/vendor/swiper/14.2.0/swiper-bundle.min.js'")self.assertPageContains("swiperLoader=Promise.all([")diff --git a/web/app.css b/web/app.cssindex d0821244c..6d0b03681 100644--- a/web/app.css+++ b/web/app.css@@ -366,11 +366,19 @@ body.entity-open .index{overflow-x:visible}.icell:hover{background:var(--hover)}.icell .ring{display:block;width:70px;height:70px;border-radius:50%;overflow:hidden;background:var(--sunk);position:relative}-.icell .ring img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;display:block}+.icell .ring img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;display:block;+ object-position:var(--face,50% 50%)}.icell .ring .ini{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:var(--fs-2xl);color:var(--muted);font-family:Bahnschrift,"Microsoft YaHei UI","Microsoft YaHei","PingFang SC",sans-serif}.icell .nm{font-size:var(--fs-xs);text-align:center;line-height:1.3;word-break:break-all}.icell .n{font-size:var(--fs-xs);color:var(--muted)}+/* 大图版式照 JAV 大图那条规矩:列宽和列数一个字都不动,只把圆框拉成 3:4 竖幅,+ 于是每屏人数不变、每张脸更大,窄屏也不会突然掉成一列。 */+.igrid[data-layout="big"] .icell{padding:6px 4px 10px}+.igrid[data-layout="big"] .icell .ring{width:100%;height:auto;aspect-ratio:3/4;+ border-radius:var(--surface-radius)}+.igrid[data-layout="big"] .icell .nm{font-size:var(--fs-sm)}+.index .ihead .iconswitch{flex:none}.tagwall{display:flex;flex-wrap:wrap;gap:7px}.tagmodes{display:flex;gap:4px;padding:3px;border:1px solid var(--line-soft);border-radius:var(--surface-radius);background:var(--surface)}.tagmodes button{border:0;border-radius:var(--control-radius);background:transparent;color:var(--muted);padding:6px 10px;cursor:pointer;display:inline-flex;align-items:center;gap:6px}diff --git a/web/app.js b/web/app.jsindex 53e72f82a..9b04f77a4 100644--- a/web/app.js+++ b/web/app.js@@ -261,7 +261,7 @@ const SORTS=[['seed','随机'],['rating','评分'],['o','高潮计数'],['plays'['big','体积'],['new','最近入库'],['played','最近看的']];const JAV_RELEASE_SORT=['release','发行时间'];const SORT_KEYS=[...SORTS,JAV_RELEASE_SORT].map(([key])=>key);-const DEFAULT_SETTINGS={batchSize:60,defaultSort:'seed',sortDefaultsVersion:2,hoverDelaySeconds:5,seekSeconds:10,searchHistoryLimit:10,relatedLimit:20,javLayout:'big',followLayout:'cozy',ambientMode:true,theaterMode:false,groupCollapse:true,sidebarOrder:DEFAULT_SIDEBAR_ORDER};+const DEFAULT_SETTINGS={batchSize:60,defaultSort:'seed',sortDefaultsVersion:2,hoverDelaySeconds:5,seekSeconds:10,searchHistoryLimit:10,relatedLimit:20,javLayout:'big',followLayout:'cozy',peopleLayout:'big',ambientMode:true,theaterMode:false,groupCollapse:true,sidebarOrder:DEFAULT_SIDEBAR_ORDER};let appSettings={...DEFAULT_SETTINGS};try{appSettings={...DEFAULT_SETTINGS,...JSON.parse(localStorage.getItem(SETTINGS_KEY)||'{}')}}catch(_e){}const allowedSetting=(value,allowed,fallback)=>allowed.includes(value)?value:fallback;@@ -1397,11 +1397,17 @@ function avatarInner(name,ref,repId,kind='performer'){/* 人脸取景:资料页圆框按检出的人脸中心取景(/api/entity 的 avatar_focus)。没检出或没算过返回空串维持几何居中;换回落图时必须撤掉——那是另一张照片,脸不在同一位置,见 entityhero img 的 `data-drop-style`。 */-function facePos(f){- return f&&f.axis==='x'?` style="object-position:${f.pct}% 50%"`- :f&&f.axis==='y'?` style="object-position:50% ${f.pct}%"`+/* 换算只有这一份。资料页把它写进 img 的 style;索引页大图版式要把它交给圆框上的+ CSS 变量——那里的 img 由共用的 avatarInner 拼,版式能改的容器只有圆框。 */+function faceOrigin(f){+ return f&&f.axis==='x'?`${f.pct}% 50%`+ :f&&f.axis==='y'?`50% ${f.pct}%`:'';}+function facePos(f){+ const origin=faceOrigin(f);+ return origin?` style="object-position:${origin}"`:'';+}/* 官方封套有两种形态,实测过:整张封套约 1.48(左侧是剧照拼贴,右侧才是正封),竖版正封约 0.70(本身就是正封,没有左半边可裁)。所以取景不能写死「取右边」,得等图片加载后按它自己的宽高比分流——服务端没存这个比例,也不该为此再存一份。 */@@ -4714,6 +4720,23 @@ function paintTagIndexSelection(){const count=panel.querySelector('[data-tag-selected]');if(count)count.textContent=`已选 ${selectedIndexTags.size} 个标签`;const apply=panel.querySelector('[data-tag-apply]');if(apply)apply.disabled=!selectedIndexTags.size;}+/* 艺人索引版式,思路同 JAV 大图:列宽不变、只把图从圆框拉成竖幅,一屏里的人数+ 不变而每张脸更大;紧凑就是圆头像那一屏。控件与 JAV 版式、关注列表版式共用+ iconSwitchHtml,切换只改容器上的 data-layout——版式是纯展示层的事,不重画列表,+ 也不重新请求。 */+const PEOPLE_LAYOUTS=[['big','大图 · 竖幅头像','maximize'],['compact','紧凑 · 圆形头像','layout-grid']];+function peopleIndexLayout(){+ return allowedSetting(appSettings.peopleLayout,PEOPLE_LAYOUTS.map(([k])=>k),'big');+}+function peopleLayoutButtons(){+ return iconSwitchHtml('people-layout','艺人索引版式',PEOPLE_LAYOUTS,peopleIndexLayout(),+ {attr:'data-people-layout'});+}+function setPeopleIndexLayout(value){+ appSettings.peopleLayout=value;+ saveSettings();+ document.querySelectorAll('.igrid').forEach(grid=>{grid.dataset.layout=peopleIndexLayout()});+}async function openIndex(kind,q,push=true){releaseHoverPreviews();const requestSeq=++indexRequestSeq;@@ -4758,14 +4781,18 @@ async function openIndex(kind,q,push=true){return Object.entries(groups).sort(([a],[b])=>a.localeCompare(b,'zh-CN')).map(([letter,items])=>`<section class="alphagroup"><h3>${letter}</h3><div class="alphalist">${items.map(x=>`<button class="alphatag ${onlineTags?'r34-'+(x.cat||'unknown'):(x.cat||'general')}" data-k="${esc(x.k)}" aria-pressed="${selectedIndexTags.has(x.k)}"><span>${esc(tagLabel(x.k))}</span><span class="n">${x.n.toLocaleString()}</span></button>`).join('')}</div></section>`).join('')};- const peopleHtml=items=>items.map(x=>`<button class="icell" data-k="${esc(x.k)}" data-kind="${entityKind}">- <span class="ring">${avatarInner(x.k,+ /* 取景挂在圆框上而不是 img 上:竖幅裁到 3:4 时几何居中会切掉脸,而 img 由八处+ 共用的 avatarInner 拼,两个版式都只能从容器这一侧改。 */+ const peopleHtml=items=>items.map(x=>{+ const face=faceOrigin(x.avatar_focus);+ return `<button class="icell" data-k="${esc(x.k)}" data-kind="${entityKind}">+ <span class="ring"${face?` style="--face:${face}"`:''}>${avatarInner(x.k,kind==='performers'&&x.entity_id?{id:x.entity_id}:null, x.rep)}</span>- <span class="nm">${esc(x.k)}</span><span class="n">${x.n.toLocaleString()}</span></button>`).join('');+ <span class="nm">${esc(x.k)}</span><span class="n">${x.n.toLocaleString()}</span></button>`}).join('');const tagHtml=items=>tagIndexMode==='alphabet'?`<div class="alphabet">${tagGroups(items)}</div>`:`<div class="tagwall index-tags">`+items.map(x=>`<button class="tg ${onlineTags?'r34-'+(x.cat||'unknown'):(x.cat||'general')}" data-k="${esc(x.k)}" aria-pressed="${selectedIndexTags.has(x.k)}">${esc(tagLabel(x.k))}<span class="n">${x.n.toLocaleString()}</span></button>`).join('')+`</div>`;- const body=people?`<div class="igrid">${peopleHtml(d.items)}</div>`:tagHtml(tagItems);+ const body=people?`<div class="igrid" data-layout="${peopleIndexLayout()}">${peopleHtml(d.items)}</div>`:tagHtml(tagItems);const categoryOptions=onlineTags?ONLINE_TAG_CATEGORIES:TAG_CATEGORIES;const visibleTagCategories=categoryOptions.filter(([key])=>key==='all'||Number(d.categories?.[key]||0)>0);const categoryFilters=kind==='tags'?`<div class="tagfilters" aria-label="标签类型">${visibleTagCategories.map(([key,label])=>@@ -4784,9 +4811,11 @@ async function openIndex(kind,q,push=true){<span class="mono" id="indexCount">${tagItems.length}${d.has_more?'+':''} 项</span>${kind==='tags'?`<div class="tagmodes"><button data-tag-scope="local" aria-pressed="${!onlineTags}">${icon('database')}本地</button><button data-tag-scope="online" aria-pressed="${onlineTags}">${icon('globe')}在线</button></div><div class="tagmodes"><button data-tag-view="cloud" aria-pressed="${tagIndexMode==='cloud'}">${icon('tags')}标签云</button><button data-tag-view="alphabet" aria-pressed="${tagIndexMode==='alphabet'}">${icon('list-filter')}字母表</button></div>`:''}+ ${people?peopleLayoutButtons():''}<div class="isearch"><input id="iq" placeholder="过滤…" value="${esc(q||'')}"></div></div>${filters}<div id="indexBody">${body}</div><button class="indexmore" id="indexMore" type="button" ${d.has_more?'':'hidden'}>载入更多</button>`;let it2; $('#iq').oninput=e=>{clearTimeout(it2);it2=setTimeout(()=>openIndex(kind,e.target.value.trim(),true),300)};+ wireIconSwitch($('#index'),'data-people-layout',setPeopleIndexLayout);$('#index').querySelectorAll('[data-tag-scope]').forEach(b=>b.onclick=()=>{if(tagIndexScope===b.dataset.tagScope)return;tagIndexScope=b.dataset.tagScope;