Peach: Local-first video metadata scraper and media manager.
fix(web): 人物那张脸也先问过再出图,不靠 404 摘
longmeidao1cc8e002f906
diff --git a/docs/SOURCING.md b/docs/SOURCING.mdindex ba14db6a3..1baad0403 100644--- a/docs/SOURCING.md+++ b/docs/SOURCING.md@@ -241,6 +241,26 @@门槛在 `tests/test_studio_icon_variants.py` 的 `LogoAvailabilityTests`(可用性与取图在同一个目录上必须给同一个答案)和 `tests/test_web_ui.py` 的两条页面源测试(取图位必须带 `studio=` 与 `variant=`,且必须先问过 `has_logo`)。+- **人的那张脸同一条规矩:先问过再出图。** `/entity-image` 与 `/avatar` 由 `WebContract` 的+ `has_entity_image()` / `has_avatar()` 判定,随资料下发为 `has_image` 与 `has_avatar`+ (`/api/tops` 的 `performers[]`/`studios[]`、`/api/items` 与 `/api/item` 的 `entity_refs`、+ `/api/entity` 的本体与 `related_performers`)。页面只有一处拼这两个地址——`web/app.js` 的+ `entityFaceImg()`,四个取图位(顶栏圆头像 `.av .ring`、身份格人物位、共演者小圆框、资料页+ 160 px 大位)共用它,两样都取不到就一个 `<img>` 都不出,首字母垫底直接露出来。旧写法一个作品+ 详情页实测 9 个 404(1 个厂牌实体图、4 个人物实体图、4 个头像),首页手机视口 2 个,同样不带缓存头。+ 两条判据形状不一样,不能混为一谈:+ - 实体图是纯粹的「在不在」。`avatar_root` 一次 `os.scandir` 出 casefold 索引+ (`avatar_root_index().entity_images`),落盘名统一走 `previews.entity_image_key`,+ kind 是名字的一部分——creator 的图写成 `performer-<id>.img` 是永远读不到的;认得的种类只有+ `previews.ENTITY_IMAGE_KINDS` 那几种。`.ct`、`.provenance.json`、`.face.json` 是边车,不算图。+ - 头像是按需生成的,「目录里没有」只说明还没裁过。所以 `has_avatar` = 已经裁好的 `<id>.jpg`+ **或** 印相还在盘上(同一个 `has_snapshot`)。把后者也判成没有,等于把「点一下就现裁一张」+ 那条路永远关掉。生成中途的 `<id>.<格>.tmp.jpg` 不算数。剩下预测不了的 404 只有生成本身失败+ 那一种(没有 ffmpeg、六格全黑),所以 `data-drop="self"` 兜底链一条都不能撤。+ 门槛在 `tests/test_previews.py` 的 `EntityImageAvailabilityTests` / `AvatarAvailabilityTests`+ (同一个临时目录上可用性与取图必须给同一个答案)、`tests/test_rm_web.py` 的四端点标志测试,以及+ `tests/test_web_ui.py` 的 `test_no_face_image_is_emitted_before_the_server_says_it_can_be_fetched`+ (页面源里每一处 `/entity-image`/`/avatar` 附近都得有可用性判据)。- 补方形小标要借 `link_marks` 的内容比闸门,但不能借它的尺寸下限。`MIN_DESIGNED_SIZE=96` 是为`/link-mark` 那种 128 px 圆标定的;JAV 厂牌站的 favicon 普遍只有 32×32 或 64×64,直接套 `render_mark`会把 HEYZO、Idea Pocket、MOODYZ、Prestige、Wanz Factory、Tameike Goro 六个全退掉,还在复核件上记成diff --git a/src/peach/previews.py b/src/peach/previews.pyindex 7d4a3bdba..0b47a2aae 100644--- a/src/peach/previews.py+++ b/src/peach/previews.py@@ -33,6 +33,22 @@ def logo_key(studio: str) -> str:return re.sub(r"[^A-Za-z0-9_-]", "_", studio)[:60]+#: `/entity-image` 认得的实体种类。取图和可用性判定必须认同一份清单:这边多认一种,+#: 页面就会为一个必然 404 的地址出 `<img>`;少认一种,装好的图从此不显示。+ENTITY_IMAGE_KINDS = ("performer", "studio", "creator", "series")+++def entity_image_key(kind: str, entity_id: int) -> str:+ """实体图的落盘名。++ 和 `logo_key` 同一个道理:`/entity-image` 取图、复核批准落地+ (`web_review._install_performer_avatar`)和「这个实体有没有图」的可用性判定+ 都按这个名字找文件,规则只能有一份。kind 也是名字的一部分——creator 实体写成+ `performer-<id>.img` 是永远读不到的。+ """+ return f"{kind}-{int(entity_id)}"++#: 预览生成的分片锁。一把模块级全局锁会让任何一个资产生成海报时,其他资产的#: 头像和海报全得排队,而 `avatar()` 持锁要连跑 6 次 ffmpeg(每次 20 秒上限),#: 最坏能把所有预览堵上两分钟。@@ -162,9 +178,9 @@ class PreviewService:def entity_image(self, kind: str, entity_id: int) -> tuple[Path, str]:"""返回已缓存的高清实体图;抓取与版权溯源由离线导入任务负责。"""- if kind not in {"performer", "studio", "creator", "series"}:+ if kind not in ENTITY_IMAGE_KINDS:raise PreviewUnavailable("invalid entity kind")- path = self.avatar_root / f"{kind}-{int(entity_id)}.img"+ path = self.avatar_root / f"{entity_image_key(kind, entity_id)}.img"if not path.is_file():raise PreviewUnavailable("entity image unavailable")content_type = "image/jpeg"diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex 1f183daaf..6f30ab779 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -225,7 +225,8 @@ def q_items(contract: WebContract, args):for aid, entity_id, kind, name in con_entities(contract, ids, qm):emap.setdefault(aid, {}).setdefault(kind, []).append(name)if kind == "performer":- performer_refs.setdefault(aid, []).append({"id": entity_id, "name": name})+ performer_refs.setdefault(aid, []).append(+ entity_ref(contract, "performer", entity_id, name))for r in rows:ts = tmap.get(r["id"], [])canonical = emap.get(r["id"], {})@@ -282,6 +283,37 @@ def con_entities(contract: WebContract, ids, qm):).fetchall()+def entity_ref(contract: WebContract, kind: str, entity_id, name: str) -> dict:+ """身份引用:id、名字,加上「实体图取不取得到」。++ 卡片头像、详情页身份格和沉浸模式的署名圈都读这一份,所以标志跟着引用走,不由+ 各处自己再问一遍。缺了它,这些位置只能无条件出 `<img>`、等 `/entity-image` 回+ 404 再把图摘掉——一个作品详情页实测就是 5 个这样的 404,而那条响应不带缓存头。+ """+ return {"id": entity_id, "name": name,+ "has_image": contract.has_entity_image(kind, entity_id)}+++def attach_avatar_availability(contract: WebContract, rows, key="rep",+ flag="has_avatar"):+ """给带代表作 id 的行标上「`/avatar` 取不取得到」。++ 判据要看接触印相在不在盘上,一次批量取路径——逐行查库就是 N+1,顶栏一次 30 行。+ 「还没裁过但印相还在」算取得到:`/avatar` 按需生成,把这种也判成没有等于把点一下+ 就有的头像永远关掉。+ """+ ids = sorted({int(row[key]) for row in rows if row.get(key)})+ paths: dict[int, str | None] = {}+ if ids:+ marks = ",".join("?" * len(ids))+ with contract.read_connection() as connection:+ paths = {row[0]: row[1] for row in connection.execute(+ f"SELECT id,snapshot_path FROM asset WHERE id IN ({marks})", ids)}+ for row in rows:+ rep = row.get(key)+ row[flag] = bool(rep) and contract.has_avatar(rep, paths.get(int(rep)))++def attach_card_performers(contract: WebContract, rows):"""给各类视频卡片补同一份表演者资料,避免首页/相关/复核卡片各说各话。"""if not rows:@@ -294,7 +326,8 @@ def attach_card_performers(contract: WebContract, rows):if kind != "performer":continuenames.setdefault(asset_id, []).append(name)- refs.setdefault(asset_id, []).append({"id": entity_id, "name": name})+ refs.setdefault(asset_id, []).append(+ entity_ref(contract, "performer", entity_id, name))for row in rows:row["performers"] = names.get(row["id"], [])[:CARD_PERFORMERS]row["performer_entities"] = refs.get(row["id"], [])[:CARD_PERFORMERS]@@ -575,7 +608,7 @@ def q_item(contract: WebContract, aid):for kind in ("creator", "performer", "studio", "series")}d["entity_refs"] = {- kind: [{"id": entity_id, "name": name}+ kind: [entity_ref(contract, kind, entity_id, name)for entity_id, item_kind, name in canonical if item_kind == kind]for kind in ("creator", "performer", "studio", "series")}@@ -757,6 +790,13 @@ def q_tops(contract: WebContract, n=28, jav=False, seed="", state=""):# 判定在库连接之外做,它读的是目录索引而不是账本。for studio in out["studios"]:studio["has_logo"] = contract.has_logo(studio["k"])+ # 女优那排同理,只是它有两级图:规范实体图优先,取不到才回落到代表作头像。+ # 两级都要标志,否则第一级空着的那些人会各打一个必然 404 的请求再回落。+ for performer in out["performers"]:+ performer["has_image"] = contract.has_entity_image("performer", performer["id"])+ # 厂牌那排自己不出头像,但两排的 `rep` 都会进前端的 REP 表,卡片头像回落时读的+ # 就是它——所以两排都得判。+ attach_avatar_availability(contract, out["performers"] + out["studios"])return outdiff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex d6bd6aae8..c6df2fa0b 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -15,7 +15,12 @@ from urllib.parse import urlsplitfrom .catalog_rules import LENGTH_TAGS, dir_expr, photo_set_title, tag_catfrom .entities import normalize_entity_name, resolve_entity-from .web_catalog import COST, tag_is_not_a_performer_name, tag_not_hidden+from .web_catalog import (+ COST,+ attach_avatar_availability,+ tag_is_not_a_performer_name,+ tag_not_hidden,+)from .web_state import WebContract@@ -120,6 +125,14 @@ def q_entity(contract: WebContract, args):# 省掉必然 404 的那一跳;别的实体没有这个位置,标志只对厂牌成立。if kind == "studio":d["has_logo"] = contract.has_logo(d["canonical_name"])+ # 大位那条链的后两环同样要随资料下发:实体图取不到就直接从代表作头像起步,两样+ # 都取不到就一个 `<img>` 都不出。判定在库连接之外做,它读的是目录索引。+ d["has_image"] = contract.has_entity_image(kind, d["id"])+ attach_avatar_availability(contract, [d], key="representative_asset_id")+ # 页脚那排共演者是同一个圆头像,用的也是同一条两级链。+ for person in d["related_performers"]:+ person["has_image"] = contract.has_entity_image("performer", person["id"])+ attach_avatar_availability(contract, d["related_performers"])return d# ────────────────────────────── 照片 ──────────────────────────────diff --git a/src/peach/web_review.py b/src/peach/web_review.pyindex 2d7b0127b..7ee2b5719 100644--- a/src/peach/web_review.py+++ b/src/peach/web_review.py@@ -32,7 +32,7 @@ from .entities import ()from .fsutil import atomic_write_bytesfrom .metadata_policy import SOURCE_SPECS-from .previews import logo_key+from .previews import entity_image_key, logo_keyfrom .review_csv import read_rows@@ -829,7 +829,7 @@ LOGO_CONTENT_TYPES = {#: 落盘名的规则归 `previews.logo_key`:取图、可用性判定和这里的批准落地必须同一套,-#: 各留一份正则曾经就是「装上了却取不到」的成因。名字沿用,导出的仍是同一个函数。+#: 各留一份正则的代价是「装上了却取不到」。名字沿用,导出的仍是同一个函数。studio_logo_key = logo_key@@ -891,7 +891,9 @@ def _install_performer_avatar(contract: ReviewContract, entity_id: str) -> int:"SELECT kind FROM entity WHERE id=?", (int(entity_id),)).fetchone()kind = (kind_row[0] if kind_row and kind_row[0] in {"performer", "creator"}else "performer")- destination = contract.avatar_root / f"{kind}-{int(entity_id)}.img"+ # 落盘名归 `previews.entity_image_key`:取图、可用性判定和这里的批准落地必须+ # 同一套,各留一份 f-string 迟早变成「装上了却取不到」。+ destination = contract.avatar_root / f"{entity_image_key(kind, entity_id)}.img"# 原子替换:中途失败不会留下半张图被 `/entity-image` 读到。atomic_write_bytes(destination, body)Path(f"{destination}.ct").write_text(content_type, encoding="utf-8")diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 079dc30a0..d58405a1e 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -19,7 +19,7 @@ import timefrom collections import OrderedDictfrom pathlib import Path-from typing import Sequence+from typing import NamedTuple, Sequencefrom .catalog_rules import normalise_code_keyfrom .config import (@@ -35,10 +35,23 @@ from .jobs import BackgroundJobfrom .media import remap_managed_path# `previews` 是取图那一侧,不是 web 域处理器:依赖方向仍然只有一个走法。落盘名的# 规则必须和 `/logo` 用的是同一个函数,否则可用性判定迟早和取图对不上。-from .previews import LOGO_VARIANTS, logo_key+from .previews import ENTITY_IMAGE_KINDS, LOGO_VARIANTS, entity_image_key, logo_keyfrom .repository import LedgerDatabase+class AvatarRootIndex(NamedTuple):+ """`avatar_root` 一次扫描的产物。两样东西同处一个目录,分开扫就是白扫两遍。++ `entity_images` 是已装实体图的 casefold 落盘名,`generated` 是已经裁好的头像+ 资产 id。两者的判据不一样,故意不合并成一个集合:实体图有就是有、没有就是没有,+ 而头像是按需生成的,「目录里没有」只说明还没裁过。+ """++ entity_images: frozenset[str]+ generated: frozenset[int]+++FAVICON = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0B0B0D"/><defs><linearGradient id="pg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FF9A76"/><stop offset="1" stop-color="#F2557B"/></linearGradient></defs><path d="M16 28c-5.7 0-9.7-3.6-9.7-8.6 0-4.3 2.8-7.6 6.5-7.6 1.4 0 2.4.5 3.2 1.1.8-.6 1.8-1.1 3.2-1.1 3.7 0 6.5 3.3 6.5 7.6C25.7 24.4 21.7 28 16 28z" fill="url(#pg)"/><path d="M16 13.4V27" stroke="#0B0B0D" stroke-width="1.1" opacity=".3" stroke-linecap="round"/><path d="M17.1 11.7c.6-2.8 2.8-4.6 5.6-4.8-.2 2.8-2.2 4.7-5.6 4.8z" fill="#5FB95F"/><path d="M16 11.9c0-1.9.5-3.4 1.5-4.5" stroke="#8A5A3B" stroke-width="1.5" stroke-linecap="round" fill="none"/></svg>')CACHE_TTL = 90@@ -258,9 +271,9 @@ class WebContract:def logo_index(self) -> frozenset[str]:"""厂牌标识目录扫一遍的索引:已装标识的 casefold(落盘名) 集合。- 页面据此决定「输出 `<img>` 还是直接首字母垫底」。以前无从判断,只能每个厂牌- 都先发一次 `/logo`、靠 404 再把图换掉:首页顶栏一次渲染 30 个厂牌就是 21 个- 404,而 404 那条响应不可缓存,每次重绘还要再打一遍。+ 页面据此决定「输出 `<img>` 还是直接首字母垫底」。没有这份索引就只能每个厂牌+ 都先发一次 `/logo`、靠 404 把图换掉:首页顶栏一次渲染 30 个厂牌里 21 个是+ 404,而 404 那条响应不可缓存,每次重绘再打一遍。判据必须和 `PreviewService.logo` 逐字一致——同一个 `logo_key`、同样大小写不敏感、同样把 `.icon` / `.logo` 变体算作这个厂牌有图。松一格就是页面说有图却@@ -297,6 +310,83 @@ class WebContract: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。diff --git a/tests/test_previews.py b/tests/test_previews.pyindex d9b1bbb81..96eae105b 100644--- a/tests/test_previews.py+++ b/tests/test_previews.py@@ -1,18 +1,24 @@-"""预览生成的并发行为。+"""预览生成的并发行为,以及「取不取得到」和真正取图的一致性。`previews.py` 此前没有直接对应的测试(检视报告把它列为覆盖盲区)。这里先补上最要紧的一条:生成锁的粒度。功能正确性由 `/api/entity`、`/logo` 等端点的既有-测试间接覆盖,本文件只管并发。+测试间接覆盖。++后半部分是另一件事。页面按 `WebContract.has_entity_image()` / `has_avatar()` 决定+要不要输出 `<img>`,这两个判据和 `PreviewService` 真正的取图必须在同一个目录上给出+同一个答案,所以这里把两边摆在一处对照着测。"""+import tempfileimport threadingimport unittestfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest import mock-from peach import previews-from peach.previews import PreviewService+from peach import previews, web_review+from peach.previews import PreviewService, PreviewUnavailable, entity_image_keyfrom peach.repository import MediaAsset+from peach.web_state import WebContractclass GenerateLockStripingTests(unittest.TestCase):@@ -133,3 +139,184 @@ class ParallelGenerationTests(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class EntityImageAvailabilityTests(unittest.TestCase):+ """「这个实体有没有图」必须和 `/entity-image` 真正的取图判据逐字一致。++ 判得松一格,页面就为一个必然 404 的地址出 `<img>`;紧一格,明明装了的图从此+ 只显示首字母。所以每条都对照着 `PreviewService.entity_image()` 测,不各测一半。+ """++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ root = Path(self.tmp.name).resolve()+ self.avatars = root / "avatars"+ self.avatars.mkdir()+ self.service = PreviewService(+ SimpleNamespace(), SimpleNamespace(), root / "snapshots", root / "posters",+ self.avatars, root / "logos")+ # 库文件不必存在:可用性判定只扫目录,一个字节都不查库。但 `avatar_root` 得+ # 显式指到临时目录,默认值是本机真实的 generated 树。+ self.contract = WebContract(root / "ledger.db", avatar_root=self.avatars)++ def tearDown(self):+ self.tmp.cleanup()++ def install(self, name):+ (self.avatars / name).write_bytes(b"x")++ def resolves(self, kind, entity_id):+ try:+ self.service.entity_image(kind, entity_id)+ except PreviewUnavailable:+ return False+ return True++ def assertAgrees(self, kind, entity_id):+ """可用性判定和取图在同一个目录上必须给同一个答案。"""+ available = self.contract.has_entity_image(kind, entity_id)+ self.assertEqual(available, self.resolves(kind, entity_id),+ f"{kind}-{entity_id}:可用性说 {available},取图不同意")+ return available++ def test_an_installed_image_is_available_and_a_missing_one_is_not(self):+ self.install("performer-11.img")+ self.assertTrue(self.assertAgrees("performer", 11))+ self.assertFalse(self.assertAgrees("performer", 12))++ def test_the_kind_is_part_of_the_name_not_just_the_id(self):+ """creator 的图落在 `creator-<id>.img`,拿 performer 去问不该命中。++ 两边少认一层 kind,就会出现「装的是 creator、页面按 performer 问」这种恒假,+ 那张图从此不显示。+ """+ self.install("creator-12.img")+ self.assertTrue(self.assertAgrees("creator", 12))+ self.assertFalse(self.assertAgrees("performer", 12))++ def test_a_sidecar_is_not_an_entity_image(self):+ """`.ct`、来源留档、人脸取景都躺在同一个目录里,但都不是取图会返回的文件。"""+ self.install("performer-11.img.ct")+ self.install("performer-11.provenance.json")+ self.install("performer-11.face.json")+ self.assertFalse(self.assertAgrees("performer", 11))++ def test_an_unknown_kind_is_never_available(self):+ """`/entity-image` 只认那几种实体,别的一律 404,页面不该发得出来。"""+ self.install("photo-11.img")+ self.assertFalse(self.assertAgrees("photo", 11))++ def test_a_missing_entity_id_is_never_available(self):+ """身份格里没规范到实体的那些格子没有 id,它们只有首字母。"""+ for entity_id in (None, "", "abc"):+ with self.subTest(entity_id=entity_id):+ self.assertFalse(self.contract.has_entity_image("performer", entity_id))++ def test_availability_is_case_insensitive_like_the_resolver(self):+ """`is_file()` 在 Windows 和 macOS 的默认文件系统上大小写不敏感,+ 索引不能顺手把这层容错丢掉。"""+ self.install("Performer-11.img")+ self.assertTrue(self.contract.has_entity_image("performer", 11))++ def test_a_missing_avatar_directory_is_an_empty_index(self):+ """目录还没建(新机器、干净数据目录)时全部退回首字母,不是报错。"""+ root = Path(self.tmp.name).resolve()+ contract = WebContract(root / "ledger.db", avatar_root=root / "nowhere")+ self.assertEqual(contract.avatar_root_index().entity_images, frozenset())+ self.assertFalse(contract.has_entity_image("performer", 11))++ def test_a_newly_installed_image_shows_up_after_the_cache_bust(self):+ """索引带 TTL,但复核批准会 `cache_bust()`:刚装上的图立刻可见。"""+ self.assertFalse(self.contract.has_entity_image("performer", 11))+ self.install("performer-11.img")+ self.contract.cache_bust()+ self.assertTrue(self.contract.has_entity_image("performer", 11))++ def test_the_install_path_and_the_resolver_share_one_key_rule(self):+ """批准落地写的文件名和取图找的文件名只能有一份实现。"""+ self.assertIs(web_review.entity_image_key, entity_image_key)+++class AvatarAvailabilityTests(unittest.TestCase):+ """头像不是有和没有两态:`/avatar` 按需生成,还没裁过不等于取不到。++ 真缺(印相不在盘上了)和没抓过(印相还在、只是没人要过)必须分开。把后者也判成+ 没有,等于把点一下就有的那条路永远关掉。+ """++ ASSET = 7++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ root = Path(self.tmp.name).resolve()+ self.avatars = root / "avatars"+ self.avatars.mkdir()+ self.snapshots = root / "snapshots"+ self.snapshots.mkdir()+ self.snapshot = self.snapshots / f"{self.ASSET}.jpg"+ repository = SimpleNamespace(media_asset=lambda asset_id: MediaAsset(+ id=asset_id, path=None,+ snapshot_path=str(self.snapshot) if self.snapshot.is_file() else None))+ tools = SimpleNamespace(ffmpeg=lambda: SimpleNamespace(path=Path("ffmpeg")))+ self.service = PreviewService(+ repository, tools, self.snapshots, root / "posters", self.avatars,+ root / "logos")+ self.contract = WebContract(+ root / "ledger.db", avatar_root=self.avatars, snapshot_root=self.snapshots)++ def tearDown(self):+ self.tmp.cleanup()++ def available(self):+ return self.contract.has_avatar(+ self.ASSET, str(self.snapshot) if self.snapshot.is_file() else None)++ def test_an_already_cut_avatar_is_available_and_needs_nothing_else(self):+ (self.avatars / f"{self.ASSET}.jpg").write_bytes(b"jpg")+ self.assertTrue(self.available())+ self.assertEqual(self.service.avatar(self.ASSET),+ self.avatars / f"{self.ASSET}.jpg")++ def test_an_asset_without_its_snapshot_is_never_available(self):+ """印相不在盘上就是真缺:可用性说没有,取图也确实取不到。"""+ self.assertFalse(self.available())+ with self.assertRaises(PreviewUnavailable):+ self.service.avatar(self.ASSET)++ def test_a_snapshot_still_on_disk_counts_before_anyone_ever_asks(self):+ """还没裁过但印相还在,算取得到——第一次请求就现裁一张出来。++ 这是「没抓过」不是「没有」。判成没有的话页面从此不出这个 `<img>`,+ 那张本来点一下就有的头像永远不会被生成。+ """+ self.snapshot.write_bytes(b"snapshot")+ self.assertFalse((self.avatars / f"{self.ASSET}.jpg").exists())+ self.assertTrue(self.available())++ def fake_run(command):+ Path(command[-1]).write_bytes(b"jpg")++ # 亮度探针走的是 `subprocess.run` 而不是 `_run`,不一起挡住的话六格全判成+ # 全黑,`avatar()` 会以「snapshot is too dark」拒绝。+ bright = SimpleNamespace(stdout=bytes([200]))+ with mock.patch.object(PreviewService, "_run", staticmethod(fake_run)):+ with mock.patch.object(previews.subprocess, "run", return_value=bright):+ self.assertTrue(self.service.avatar(self.ASSET).is_file())++ def test_a_half_finished_temporary_file_is_not_an_avatar(self):+ """生成中途的 `<id>.<格>.tmp.jpg` 随时会被改名或删掉,不算裁好了。"""+ (self.avatars / f"{self.ASSET}.11.tmp.jpg").write_bytes(b"jpg")+ self.assertFalse(self.available())++ def test_a_newly_cut_avatar_shows_up_after_the_cache_bust(self):+ self.assertFalse(self.available())+ (self.avatars / f"{self.ASSET}.jpg").write_bytes(b"jpg")+ self.contract.cache_bust()+ self.assertTrue(self.available())++ def test_a_missing_asset_id_is_never_available(self):+ self.snapshot.write_bytes(b"snapshot")+ for asset_id in (None, "", "abc"):+ with self.subTest(asset_id=asset_id):+ self.assertFalse(self.contract.has_avatar(asset_id, str(self.snapshot)))diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 5a51c35f2..32de2f02a 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -13,7 +13,7 @@ from unittest import mockfrom peach import web_batch, web_catalog, web_statsfrom peach import web_contract as rm_web-from peach.previews import logo_key+from peach.previews import entity_image_key, logo_keyfrom support.ledger import fresh_ledger@@ -74,7 +74,11 @@ class WebDataTests(unittest.TestCase):# 图」会随本机装了什么而变,测试跟着本机状态摇。self.logos = Path(self.tmp.name).resolve() / "logos"self.logos.mkdir()- self.contract = rm_web.WebContract(Path(self.db_path), logo_root=self.logos)+ # 实体图和已裁好的头像同处 `avatar_root`,同样得落在临时目录里。+ self.avatars = Path(self.tmp.name).resolve() / "avatars"+ self.avatars.mkdir()+ self.contract = rm_web.WebContract(+ Path(self.db_path), avatar_root=self.avatars, logo_root=self.logos)def tearDown(self):self.tmp.cleanup()@@ -100,7 +104,7 @@ class WebDataTests(unittest.TestCase):self.assertEqual(result["items"][0]["id"], 1)self.assertEqual(result["items"][0]["performers"], ["Canonical Alice"])self.assertEqual(result["items"][0]["performer_entities"], [- {"id": 11, "name": "Canonical Alice"},+ {"id": 11, "name": "Canonical Alice", "has_image": False},])self.assertEqual(result["items"][0]["tags"], ["足交"])self.assertIn("play_seconds", result["items"][0])@@ -160,7 +164,7 @@ class WebDataTests(unittest.TestCase):self.assertEqual(item["creator"], "Canonical Creator")self.assertEqual(item["entities"]["creator"], ["Canonical Creator"])self.assertEqual(item["entity_refs"]["creator"], [- {"id": 12, "name": "Canonical Creator"},+ {"id": 12, "name": "Canonical Creator", "has_image": False},])self.assertEqual(item["performers"], [])self.assertEqual(item["entity_refs"]["performer"], [])@@ -344,6 +348,74 @@ class WebDataTests(unittest.TestCase):flags(), {"pill": [True], "ref": [True], "flat": True, "hero": True},"装上之后三处都必须说有")+ def test_face_slots_say_up_front_whether_an_image_can_be_fetched(self):+ """四个取图位都要随资料下发「取不取得到」。++ 缺这个标志,页面只能无条件出 `<img>`、等 404 再换成首字母:一个作品详情页+ 实测 9 个这样的 404(1 个厂牌实体图、4 个人物实体图、4 个头像),首页手机+ 视口 2 个,而 `/entity-image` 与 `/avatar` 的 404 都不带缓存头,每次重绘再打+ 一整轮。++ 两级图的判据不一样,所以分成两个标志:实体图有就是有;头像是按需生成的,+ 「还没裁过但印相还在」仍然取得到,把它一起判成没有就等于把点一下就有的那条+ 路关掉。+ """+ def flags():+ item = rm_web.q_item(self.contract, 1)+ page = rm_web.q_entity(+ self.contract, {"kind": "performer", "name": "Canonical Alice"})+ tops = rm_web.q_tops(self.contract, 30)["performers"]+ cards = rm_web.q_items(self.contract, {"limit": "5", "offset": "0"})["items"]+ return {+ # 顶栏圆头像:实体图与代表作头像各一格。+ "top_image": [row["has_image"] for row in tops],+ "top_avatar": [row["has_avatar"] for row in tops],+ # 卡片署名圈的身份引用(`/api/items`)。+ "card": [ref["has_image"] for row in cards+ for ref in row["performer_entities"]],+ # 详情页身份格(`/api/item`)。+ "cell": [ref["has_image"] for ref in item["entity_refs"]["performer"]],+ # 资料页大位(`/api/entity`):同样是两级。+ "hero_image": page["has_image"],+ "hero_avatar": page["has_avatar"],+ }++ self.assertEqual(+ flags(),+ {"top_image": [False], "top_avatar": [False], "card": [False],+ "cell": [False], "hero_image": False, "hero_avatar": False},+ "一张图都没有时四处都必须说没有")++ (self.avatars / f"{entity_image_key('performer', 11)}.img").write_bytes(b"x")+ snapshot = Path(self.tmp.name).resolve() / "one.jpg"+ snapshot.write_bytes(b"x")+ con = sqlite3.connect(self.db_path)+ con.execute("UPDATE asset SET snapshot_path=? WHERE id=1", (str(snapshot),))+ con.commit()+ con.close()+ self.contract.cache_bust()+ self.assertEqual(+ flags(),+ {"top_image": [True], "top_avatar": [True], "card": [True],+ "cell": [True], "hero_image": True, "hero_avatar": True},+ "装上实体图、印相也在盘上之后,四处都必须说有")++ def test_a_representative_without_its_snapshot_is_not_an_avatar(self):+ """账本记着印相路径、盘上却没有那个文件时,`/avatar` 一样取不到。++ `rep` 的选取只看 `snapshot_path IS NOT NULL`,那是账本里的一行字符串;+ 真正决定取不取得到的是文件在不在,判据和卡片角上的 `has_thumb` 同一个。+ """+ con = sqlite3.connect(self.db_path)+ con.execute("UPDATE asset SET snapshot_path=? WHERE id=1",+ (str(Path(self.tmp.name).resolve() / "gone.jpg"),))+ con.commit()+ con.close()+ self.contract.cache_bust()+ tops = rm_web.q_tops(self.contract, 30)["performers"]+ self.assertEqual([row["rep"] for row in tops], [1], "代表作仍会被选出来")+ self.assertEqual([row["has_avatar"] for row in tops], [False])+def test_items_can_skip_repeated_total_count_on_later_pages(self):result = rm_web.q_items(self.contract, {"limit": "1", "offset": "0", "count": "0"},@@ -539,7 +611,7 @@ class WebDataTests(unittest.TestCase):self.assertTrue(item["liked"])self.assertEqual(item["like_reason"], "喜欢自然的节奏和镜头")self.assertEqual(item["entity_refs"]["performer"], [- {"id": 11, "name": "Canonical Alice"},+ {"id": 11, "name": "Canonical Alice", "has_image": False},])self.assertIsNone(self.row()["feedback"])@@ -1005,7 +1077,7 @@ class WebDataTests(unittest.TestCase):reverse_related = rm_web.q_related(self.contract, 2, 10)self.assertEqual(reverse_related["items"][0]["performer_entities"], [- {"id": 11, "name": "Canonical Alice"},+ {"id": 11, "name": "Canonical Alice", "has_image": False},])def _add_performers(self, asset_id, names, start_id=200):diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 914d755c7..005cf1e02 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -728,30 +728,53 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageLacks("jav-small")self.assertPageContains('<span class="watchcount">看过 ${it.play_count}</span>')- def test_every_card_avatar_falls_back_through_the_same_helper(self):- # kind 参数化后,创作者复核卡片也能走同一个兜底链;默认仍是 performer,+ def test_every_face_slot_builds_its_image_through_one_helper(self):+ # 顶栏圆头像、卡片署名、共演者、资料页大位共用 entityFaceImg;+ # `/entity-image` 和 `/avatar` 两个地址只在这一个函数里拼。+ self.assertPageContains(+ "function entityFaceImg({kind='performer',id=null,hasImage=false,rep=null,")+ self.assertPageContains("const useEntity=!!(id&&hasImage);")+ self.assertPageContains(+ "const src=useEntity?`/entity-image?kind=${kind}&id=${id}`:(rep?`/avatar?id=${rep}`:'');")+ # 一环都取不到就一个 `<img>` 都不出,首字母垫底直接露出来。+ self.assertPageContains("if(!src)return '';")+ # kind 参数化后,创作者复核卡片也能走同一条链;默认仍是 performer,# 既有调用点不受影响。self.assertPageContains("function avatarInner(name,ref,repId,kind='performer')")- self.assertPageContains("`/entity-image?kind=${kind}&id=${ref.id}`")# 兜底链声明在模板里,行为归 image-fallback 那条委托监听。- self.assertPageContains("imageFallbackAttrs({fallbacks})")- self.assertPageContains("`/avatar?id=${repId}`")+ self.assertPageContains("const fallbacks=useEntity&&rep?[`/avatar?id=${rep}`]:[];")+ self.assertPageContains("imageFallbackAttrs({dropStyle:dropStyle&&useEntity,fallbacks})")- def test_avatar_fallback_chains_end_by_removing_the_broken_image(self):- """取不到图的 <img> 必须被摘掉,不能只停在「不再重试」。+ def test_no_face_image_is_emitted_before_the_server_says_it_can_be_fetched(self):+ """先问再出图:没有可用性标志兜住的 `/entity-image`/`/avatar` 一处都不许有。- 留着它有两个后果:`.entityportrait:has(img)>span` 仍然匹配,首字母垫底- 永远回不来;浏览器还会把 alt 当内容画出来——资料页上就是整个艺人名横在- 头像圈里溢出(loliburin 实测 /entity-image 与 /avatar 双 404)。+ 无条件出图、等 404 再把图摘掉的代价是:一个作品详情页 9 个这样的 404(1 个+ 厂牌实体图、4 个人物实体图、4 个头像),首页手机视口 2 个。两个端点的 404 都+ 不带缓存头,每次重绘再打一整轮。+ """+ source = self.page+ gates = ("hasImage", "has_image", "useEntity", "has_avatar")+ for url in ("`/entity-image?kind=", "`/avatar?id="):+ start = 0+ while True:+ at = source.find(url, start)+ if at < 0:+ break+ start = at + 1+ before = source[max(0, at - 200):at]+ self.assertTrue(+ any(gate in before for gate in gates),+ f"{url} 附近没有可用性判据,这是一个必然 404 的 `<img>`:\n"+ f"{source[max(0, at - 200):at + 80]}")++ def test_face_fallback_chains_end_by_removing_the_broken_image(self):+ """还是取不到图的 <img> 必须被摘掉,不能只停在「不再重试」。++ 标志能挡掉「装都没装」,挡不掉生成本身失败(没有 ffmpeg、六格全黑)那一种,+ 所以兜底链一条都不能撤。留着它有两个后果:`.entityportrait:has(img)>span`+ 仍然匹配,首字母垫底永远回不来;浏览器还会把 alt 当内容画出来——资料页上+ 就是整个艺人名横在头像圈里溢出(loliburin 实测 /entity-image 与 /avatar 双 404)。"""- # 卡片头像、资料页大圆框、关联艺人小圆框声明的是同一套兜底数据;- # 「候选换完还是失败就收场」这一步由 advanceImageFallback 统一执行。- for chain in (- "`/avatar?id=${repId}`",- "`/avatar?id=${d.representative_asset_id}`",- "`/avatar?id=${x.rep}`",- ):- self.assertPageContains(chain)# 收场动作只有这一处实现,默认就是把 <img> 拿掉。self.assertPageContains("drop = 'self'")self.assertPageContains("image.remove();")@@ -778,8 +801,10 @@ class WebUiSourceTests(unittest.TestCase):# 资料页圆框按检出的人脸取景;换回落图时必须先摘掉内联 object-position——# 回落图是另一张照片,脸不在同一位置。self.assertPageContains("function facePos(f)")- self.assertPageContains('"${facePos(d.avatar_focus)}')- self.assertPageContains("imageFallbackAttrs({dropStyle:true,")+ self.assertPageContains("style:facePos(d.avatar_focus),dropStyle:true")+ # 取景是按实体图算出来的,所以内联 style 和 data-drop-style 只贴给第一环。+ self.assertPageContains("${useEntity?style:''}")+ self.assertPageContains("imageFallbackAttrs({dropStyle:dropStyle&&useEntity,fallbacks})")self.assertPageContains("if ('dropStyle' in image.dataset) image.removeAttribute('style');")def test_entity_link_favicons_do_not_leak_the_page_url_to_the_linked_site(self):@@ -1232,8 +1257,12 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageLacks("text-decoration:underline")def test_every_identity_cell_can_carry_its_own_portrait(self):- self.assertPageContains('item.id?`<img src="/entity-image?kind=performer&id=${item.id}"')- self.assertPageContains('<img src="/logo?studio=${encodeURIComponent(item.name)}&variant=icon"')+ # 人物格走和顶栏圆头像同一个 entityFaceImg;这一格没有代表作头像可退,+ # 装了实体图才出 `<img>`,否则就是首字母垫底。+ self.assertPageContains("? `<span>${esc(item.name.slice(0,1))}</span>${entityFaceImg(")+ self.assertPageContains("{id:item.id,hasImage:item.has_image})}")+ self.assertPageContains(+ '${item.has_logo?`<img src="/logo?studio=${encodeURIComponent(item.name)}&variant=icon"')def test_large_casts_stay_in_the_dom_behind_one_expander(self):# 收起的格子必须留在 DOM 里,展开只是取消 hidden,不重新请求也不丢身份。@@ -3129,7 +3158,7 @@ class WebUiSourceTests(unittest.TestCase):def test_every_studio_mark_waits_until_the_logo_is_known_to_exist(self):"""没装标识就一个 `<img>` 都不输出,不许靠 404 再把图换成首字母。- 三处取图位以前都是无条件出图:首页顶栏一排 30 个厂牌,实测 21 个 404,而+ 三处取图位无条件出图的代价是:首页顶栏一排 30 个厂牌里 21 个是 404,而`/logo` 的 404 那条响应不可缓存,每次重绘再打一整轮。判据 `has_logo` 由`/api/tops`、`/api/item`、`/api/entity` 随身份一起下发,和取图共用`previews.logo_key`。diff --git a/web/app.js b/web/app.jsindex e9f4fdc62..15fbcadb6 100644--- a/web/app.js+++ b/web/app.js@@ -1327,14 +1327,37 @@ function wireHover(el,it){window.addEventListener('pagehide',()=>releaseHoverPreviews());document.addEventListener('visibilitychange',()=>{if(document.hidden)releaseHoverPreviews()});-/* 头像内层:先垫首字母,再叠真实图。规范实体图优先,取不到才回落到旧头像缓存。 */+/* 实体那张脸:规范实体图优先,取不到退到代表作头像,两样都取不到就一个 `<img>`+ 都不出。四个位置(顶栏圆头像、卡片署名、共演者、资料页大位)共用这一份。++ 无条件出图、等 404 再把图摘掉的代价是:一个作品详情页 9 个这样的 404(1 个厂牌+ 实体图、4 个人物实体图、4 个头像),首页手机视口 2 个;`/entity-image` 与+ `/avatar` 的 404 都不带缓存头,每次重绘再打一整轮。`hasImage` 由 `/api/tops`、+ `/api/items`、`/api/item`、`/api/entity` 随资料下发,判据和取图同一个函数。++ `rep` 这一侧不带标志:调用方传进来的就该是「取得到的代表作」(顶栏在入 REP 表时+ 已经筛过)。`/avatar` 是按需生成的,还没裁过但印相还在也算取得到——那条点一下就+ 有的路不能一起关掉。++ 兜底链最后一环必须真的把 `<img>` 拿掉(`data-drop="self"`):留着取不到图的+ `<img>`,`:has(img)` 仍然匹配,首字母垫底回不来,浏览器还会把 alt 画出来。 */+function entityFaceImg({kind='performer',id=null,hasImage=false,rep=null,+ alt='',lazy=true,style='',dropStyle=false}={}){+ const useEntity=!!(id&&hasImage);+ const src=useEntity?`/entity-image?kind=${kind}&id=${id}`:(rep?`/avatar?id=${rep}`:'');+ if(!src)return '';+ const fallbacks=useEntity&&rep?[`/avatar?id=${rep}`]:[];+ // 人脸取景是按实体图算出来的,回落图是另一张照片,脸不在同一位置:只贴给第一环。+ return `<img src="${src}" alt="${alt}"${lazy?' loading="lazy"':''}${useEntity?style:''} `++ `${imageFallbackAttrs({dropStyle:dropStyle&&useEntity,fallbacks})}>`;+}+/* 头像内层:先垫首字母,再叠真实图。++ `has_image` 缺席时按「有图」处理:口味榜、复核卡片和索引页的调用方自己拼 ref,+ 还没有这个标志,读到 undefined 就照旧无条件出图,行为和加标志之前一模一样。 */function avatarInner(name,ref,repId,kind='performer'){- const src=ref?`/entity-image?kind=${kind}&id=${ref.id}`:(repId?`/avatar?id=${repId}`:'');- // 兜底链最后一环必须是把 <img> 拿掉(`data-drop="self"`):留着取不到图的 <img>,- // `:has(img)` 仍然匹配,首字母垫底回不来,浏览器还会把 alt 画出来。- const fallbacks=ref&&repId?[`/avatar?id=${repId}`]:[];return `<span class="ini">${esc((name||'?').slice(0,1))}</span>`+- (src?`<img src="${src}" alt="" loading="lazy" ${imageFallbackAttrs({fallbacks})}>`:'');+ entityFaceImg({kind,id:ref&&ref.id,hasImage:!!ref&&ref.has_image!==false,rep:repId});}/* 人脸取景:资料页圆框按检出的人脸中心取景(/api/entity 的 avatar_focus)。没检出或没算过返回空串维持几何居中;换回落图时必须撤掉——那是另一张照片,@@ -1905,19 +1928,20 @@ async function buildBars(){}// 顶部三层:女优圆头像 / 厂牌 / 内容标签- tops.performers.forEach(x=>{if(x.rep)REP[x.k]=x.rep});- tops.studios.forEach(x=>{if(x.rep)REP[x.k]=x.rep});+ /* REP 表只收真能取到头像的代表作:卡片署名圈回落时读的就是它,取不到的进了表+ 就是一个必然 404 的 `<img>`。`has_avatar` 说的是「已经裁好或印相还在」,不是+ 「目录里有没有那张 jpg」——`/avatar` 按需生成,还没抓过的那条路留着。 */+ tops.performers.forEach(x=>{if(x.rep&&x.has_avatar)REP[x.k]=x.rep});+ tops.studios.forEach(x=>{if(x.rep&&x.has_avatar)REP[x.k]=x.rep});const avHtml=x=>`<button class="av" data-entity-kind="performer" data-entity-name="${esc(x.k)}">- <span class="ring"><span class="ini">${esc(x.k.slice(0,1))}</span>${x.id- ? `<img src="/entity-image?kind=performer&id=${x.id}" alt="" loading="lazy"- ${imageFallbackAttrs({fallbacks:x.rep?[`/avatar?id=${x.rep}`]:[]})}>`- : ''}</span>+ <span class="ring"><span class="ini">${esc(x.k.slice(0,1))}</span>${entityFaceImg(+ {id:x.id,hasImage:x.has_image,rep:x.has_avatar?x.rep:null})}</span><span class="nm">${esc(x.k)}</span></button>`;/* 正规厂牌用官网 logo;缺失时只显示首字母,绝不把作品截图冒充厂牌图标。- 没装标识就一个 `<img>` 都不输出。以前这里无条件出图、靠 `/logo` 回 404 再把- 图换成首字母:顶栏一排 30 个厂牌,实测 21 个是 404,而 404 那条响应不可缓存,- 每次重绘再打一整轮。`has_logo` 由 `/api/tops` 下发,判据和取图同一个函数。 */+ 没装标识就一个 `<img>` 都不输出。无条件出图、靠 `/logo` 回 404 换成首字母的+ 代价是:顶栏一排 30 个厂牌里 21 个是 404,而 404 那条响应不可缓存,每次重绘+ 再打一整轮。`has_logo` 由 `/api/tops` 下发,判据和取图同一个函数。 */const bpHtml=x=>{const fallback=`${esc(x.k.slice(0,2))}`;const mark=x.has_logo@@ -5242,21 +5266,19 @@ async function openEntity(kind,name,push=true,requestedTag){document.body.classList.add('entity-open');$('#index').hidden=false;$('#grid').innerHTML='';$('#count').textContent='';$('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;+ /* 大位这条链每一环都先问过再出图:厂牌是标识→实体图,其余是实体图→代表作头像,+ 一环都取不到就一个 `<img>` 都不出,首字母垫底直接露出来。三个标志+ (`has_logo`/`has_image`/`has_avatar`)都由 `/api/entity` 随资料下发。 */const image=d.id?(kind==='studio'- /* 厂牌大位先取标识、取不到才退到实体图。没装标识就直接从实体图起步:那一跳- 必然 404,`has_logo` 已经把答案随资料一起下发了。 */? (d.has_logo? `<img src="/logo?studio=${encodeURIComponent(d.canonical_name)}&variant=logo" alt="${esc(d.canonical_name)}"- ${imageFallbackAttrs({fallbacks:[`/entity-image?kind=studio&id=${d.id}`]})}>`- : `<img src="/entity-image?kind=studio&id=${d.id}" alt="${esc(d.canonical_name)}"- ${imageFallbackAttrs()}>`)- /* 兜底链的最后一环必须真的把 <img> 拿掉(`data-drop="self"`):留着取不到图的- <img> 会让浏览器画出 alt 文本(整个艺人名横在头像圈里),而 `:has(img)`- 仍然匹配,首字母垫底永远回不来。- `data-drop-style` 撤掉人脸取景:换的是另一张照片,脸不在同一个位置。 */- : `<img src="/entity-image?kind=${kind}&id=${d.id}" alt="${esc(d.canonical_name)}"${facePos(d.avatar_focus)}- ${imageFallbackAttrs({dropStyle:true,- fallbacks:d.representative_asset_id?[`/avatar?id=${d.representative_asset_id}`]:[]})}>`):'';+ ${imageFallbackAttrs({fallbacks:d.has_image?[`/entity-image?kind=studio&id=${d.id}`]:[]})}>`+ : entityFaceImg({kind:'studio',id:d.id,hasImage:d.has_image,+ alt:esc(d.canonical_name),lazy:false}))+ : entityFaceImg({kind,id:d.id,hasImage:d.has_image,+ rep:d.has_avatar?d.representative_asset_id:null,+ alt:esc(d.canonical_name),lazy:false,+ style:facePos(d.avatar_focus),dropStyle:true})):'';/* 链接按 beeg 的资料页形态:社媒收成纯图标,官网/事务所保留名字。社媒的 handle 是网址的一部分,写出来只是把 URL 抄一遍——`X @remu19971203` 里@@ -5285,8 +5307,8 @@ async function openEntity(kind,name,push=true,requestedTag){}).join('');const tags=(d.tags||[]).map(x=>`<button class="pill" data-entity-tag="${esc(x.k)}" aria-pressed="${entityTag===x.k}">${esc(tagLabel(x.k))}<small>${x.n.toLocaleString()}</small></button>`).join('');const related=(d.related_performers||[]).map(x=>`<button class="relatedperson" data-related-performer="${esc(x.k)}">- <span class="ring"><span>${esc(x.k.slice(0,1))}</span><img src="/entity-image?kind=performer&id=${x.id}" alt="" loading="lazy"- ${imageFallbackAttrs({fallbacks:x.rep?[`/avatar?id=${x.rep}`]:[]})}></span>+ <span class="ring"><span>${esc(x.k.slice(0,1))}</span>${entityFaceImg(+ {id:x.id,hasImage:x.has_image,rep:x.has_avatar?x.rep:null})}</span><span class="nm">${esc(x.k)}</span></button>`).join('');const photoCount=photos&&!photos.error?(photos.total||0):0;const mediaSelected=entityMediaView.media==='photos';@@ -6106,7 +6128,10 @@ async function openItem(id,push=true,queueContext=null,anchor=null){const CAST_SHOWN=8;const castOverflow=Math.max(0,castList.length-CAST_SHOWN);const idFace=(kind,item)=>kind==='performer'- ? `<span>${esc(item.name.slice(0,1))}</span>${item.id?`<img src="/entity-image?kind=performer&id=${item.id}" alt="" loading="lazy" data-drop="self">`:''}`+ // 和顶栏圆头像同一条判据:没装实体图就不出 `<img>`。这一格没有代表作头像可退,+ // 取不到就是首字母垫底。+ ? `<span>${esc(item.name.slice(0,1))}</span>${entityFaceImg(+ {id:item.id,hasImage:item.has_image})}`: kind==='studio'// 和顶栏小圆片同一条判据:没装标识就不出 `<img>`,不再靠 404 把图摘掉。? `<span>${esc(item.name.slice(0,2))}</span>${item.has_logo?`<img src="/logo?studio=${encodeURIComponent(item.name)}&variant=icon" alt="" loading="lazy" data-drop="self">`:''}`