Peach: Local-first video metadata scraper and media manager.
Merge branch 'master' into agent/claude/image-flags-remaining-callsites
longmeidao239003a28858
diff --cc src/peach/web_entity.pyindex 00d610f80,3a8d07058..bc9b915c0--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@@ -287,13 -270,11 +287,18 @@@ def q_index(contract: WebContract, kindrows = all_rows[offset:offset + limit]has_more = offset + limit < len(all_rows)if kind in {"creators", "performers"}:++ entity_kind = "creator" if kind == "creators" else "performer"+ # 索引页一屏几十个圆头像,走的是和顶栏那排同一条两级链:规范实体图优先,+ # 取不到才回落到代表作头像。没有这两个标志就只能无条件出图、等 404 再把图摘掉,+ # `/performers` 桌面视口滚三屏实测 77 个取图请求里 5 个是这样的 404。+ # 判定在库连接之外做,它读的是目录索引而不是账本。+ for row in rows:+ row["has_image"] = contract.has_entity_image(entity_kind, row.get("entity_id"))+ attach_avatar_availability(contract, rows)+ #: 索引页的大图版式把头像裁成竖幅,几何居中会切掉脸。取景与资料页大图同一份+ #: 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 --cc src/peach/web_state.pyindex d58405a1e,e72fb13e9..e4857ffb0--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@@ -268,130 -259,12 +275,131 @@@ class WebContract# 大小写不敏感,改走索引不能顺手把这层容错丢了。return bool(key) and key.casefold() in self.cover_index()+ def logo_index(self) -> frozenset[str]:+ """厂牌标识目录扫一遍的索引:已装标识的 casefold(落盘名) 集合。++ 页面据此决定「输出 `<img>` 还是直接首字母垫底」。没有这份索引就只能每个厂牌+ 都先发一次 `/logo`、靠 404 把图换掉:首页顶栏一次渲染 30 个厂牌里 21 个是+ 404,而 404 那条响应不可缓存,每次重绘再打一遍。++ 判据必须和 `PreviewService.logo` 逐字一致——同一个 `logo_key`、同样大小写不+ 敏感、同样把 `.icon` / `.logo` 变体算作这个厂牌有图。松一格就是页面说有图却+ 取回 404(碎图),紧一格就是明明装了却永远只显示首字母。++ 代价和 `cover_index()` 一样:刚装上的标识最多一个 TTL 后才出现在页面上;+ 复核批准本来就会 `cache_bust()`,所以用户自己的动作看得到即时效果。+ """+ return self.cached("logo-index", self._scan_logo_root)++ def _scan_logo_root(self) -> frozenset[str]:+ """一次目录扫描收齐已装标识。目录不存在就是空集合,页面全部退回首字母。"""+ keys: set[str] = set()+ try:+ with os.scandir(self.logo_root) as entries:+ for entry in entries:+ name = entry.name.casefold()+ # `.ct` 边车和 SVG 原件不是 `/logo` 会取的文件,不算这个厂牌有图。+ if not name.endswith(".img") or not entry.is_file():+ continue+ stem = name[:-len(".img")]+ for variant in LOGO_VARIANTS:+ if stem.endswith(f".{variant}"):+ stem = stem[:-len(variant) - 1]+ break+ if stem:+ keys.add(stem)+ except OSError:+ return frozenset()+ return frozenset(keys)++ def has_logo(self, studio: str | None) -> bool:+ """这个厂牌是否已装标识。空名字一律为假——`/logo` 也拒绝空 studio。"""+ key = logo_key(studio or "")+ return bool(key) and key.casefold() in self.logo_index()++ def avatar_root_index(self) -> AvatarRootIndex:+ """头像目录扫一遍的索引:已装的实体图,加已经裁好的头像。++ 页面据此决定「输出 `<img>` 还是直接首字母垫底」。没有这份索引就只能无条件出图、+ 靠 404 把图摘掉:一个作品详情页是 9 个这样的 404(1 个厂牌实体图、4 个人物+ 实体图、4 个头像),而 `/entity-image` 和 `/avatar` 的 404 都不带缓存头,+ 每次重绘再打一整轮。++ 实体图和头像同处 `avatar_root`(`{kind}-{id}.img` 与 `{asset_id}.jpg`),+ 所以一次 `os.scandir` 一起收;分成两个缓存键就是同一个目录连扫两遍。++ 代价和 `cover_index()`、`logo_index()` 一样:刚装上的实体图最多一个 TTL 后+ 才出现在页面上;复核批准本来就会 `cache_bust()`,所以用户自己的动作看得到+ 即时效果。+ """+ return self.cached("avatar-root-index", self._scan_avatar_root)++ def _scan_avatar_root(self) -> AvatarRootIndex:+ """一次目录扫描同时收齐实体图和已裁头像。目录不存在就是两个空集合。"""+ entity_images: set[str] = set()+ generated: set[int] = set()+ try:+ with os.scandir(self.avatar_root) as entries:+ for entry in entries:+ name = entry.name.casefold()+ if name.endswith(".img"):+ # `.ct`、`.provenance.json`、`.face.json` 都是边车,不是+ # `/entity-image` 会取的文件,不算这个实体有图。+ if entry.is_file():+ entity_images.add(name[:-len(".img")])+ elif name.endswith(".jpg"):+ # 头像按资产 id 落盘。生成中途的 `<id>.<格>.tmp.jpg` 不算数,+ # 它随时会被删掉或改名。+ stem = name[:-len(".jpg")]+ if stem.isdigit() and entry.is_file():+ generated.add(int(stem))+ except OSError:+ return AvatarRootIndex(frozenset(), frozenset())+ return AvatarRootIndex(frozenset(entity_images), frozenset(generated))++ def has_entity_image(self, kind: str, entity_id) -> bool:+ """`/entity-image` 能不能取到这个实体的图。++ 判据必须和 `PreviewService.entity_image` 逐字一致——同一份 kind 白名单、同一个+ `entity_image_key`。松一格就是页面说有图却取回 404(碎图),紧一格就是明明+ 装了却永远只显示首字母。++ 索引的键 casefold 过:`is_file()` 在 Windows 与 macOS 的默认文件系统上大小写+ 不敏感,改走索引不能顺手把这层容错丢了。落盘名本来就全小写,这层只兜手工+ 摆进去的文件。+ """+ if kind not in ENTITY_IMAGE_KINDS or entity_id is None:+ return False+ try:+ key = entity_image_key(kind, entity_id)+ except (TypeError, ValueError):+ return False+ return key.casefold() in self.avatar_root_index().entity_images++ def has_avatar(self, asset_id, snapshot_path: str | None) -> bool:+ """`/avatar` 能不能取到这个代表作的头像。++ 和实体图不是一回事,判据也不能照抄:`/avatar` 是**按需生成**的,目录里没有+ 那张 jpg 只说明还没人要过,不说明取不到。只要接触印相还在盘上,第一次请求+ 就现裁一张出来。把「还没裁过」也判成没有,等于把点一下就有的头像永远关掉——+ 真缺和没抓过是两回事。++ 所以判据是「已经裁好了」或「印相还在,裁得出来」,和 `has_thumb` 同一个+ `has_snapshot`。剩下的 404 只有生成本身失败那一种(没有 ffmpeg、六格全黑),+ 那要真去跑一遍 ffmpeg 才知道,预测不了;那条兜底链照旧留着兜。+ """+ try:+ key = int(asset_id)+ except (TypeError, ValueError):+ return False+ return key in self.avatar_root_index().generated or self.has_snapshot(snapshot_path)+def cover_frame(self, code: str | None) -> dict | None:- """封面的取景提示:人脸中心。没算过或没检出就返回 None。+ """封面的取景提示:人脸中心的两个轴。没算过或没检出就返回 None。- 只用来做纵向微调,横向仍由版式决定——横向靠几何规则已经稳定。- 取不到时前端退回固定取景,不影响显示。+ 双页封套的横向锚点仍由版式决定(正封贴着右边缘,几何规则已经稳定),人脸+ 横向只用在 16:9 官方剧照上——那种图在大图容器里只会横向裁,写死的居中会把+ 偏在一侧的人整个切掉。取不到时前端退回固定取景,不影响显示。"""key = normalise_code_key(code)return self.cover_index().get(key.casefold()) if key else Nonediff --cc tests/test_rm_web.pyindex e04cb18e4,4662bc8e4..330af1765--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@@ -11,9 -11,8 +11,9 @@@ from contextlib import contextmanagefrom pathlib import Pathfrom unittest import mock- from peach import web_batch, web_catalog, web_stats+ from peach import catalog_rules, web_batch, web_catalog, web_statsfrom peach import web_contract as rm_web+from peach.previews import entity_image_key, logo_keyfrom support.ledger import fresh_ledgerdiff --cc web/app.jsindex c240dd0e7,4226acecc..54583091e--- a/web/app.js+++ b/web/app.js@@@ -4736,11 -4930,14 +4966,15 @@@ async function openIndex(kind,q,push=trreturn 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>+ x.entity_id?{id:x.entity_id,has_image:x.has_image}:null,+ x.has_avatar?x.rep:null, entityKind)}</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>`;