Peach: Local-first video metadata scraper and media manager.
fix(web): 头像候选按整条名字链取并集
longmeidao9d582e3fdc9b
diff --git a/frontend/src/avatar-picker.tsx b/frontend/src/avatar-picker.tsxindex 5ca5170cd..68a9124af 100644--- a/frontend/src/avatar-picker.tsx+++ b/frontend/src/avatar-picker.tsx@@ -24,6 +24,8 @@ export interface AvatarChoice {width: number;height: number;detail: string;+ /** 这一格是按哪个名字从图库里找到的。只有一个名字命中时是空串。 */+ found_by: string;current: boolean;}@@ -31,7 +33,8 @@ export interface AvatarChoices {kind: string;entity_id: number;names: string[];- matched_name: string;+ /** 名字链里在图库中真有图的那几个,按链上的先后。 */+ matched_names: string[];choices: AvatarChoice[];index_age_hours: number | null;index_stale: boolean;@@ -110,9 +113,10 @@ function Picker({ kind, id, name, onPicked }: PickerProps) {const choices = data?.choices || [];/* 说明只留一句:这一屏已经用图说清了在选什么,多一行字就是多一行要读的东西。按哪个名字找到的要说——找错人是这里唯一会出的大错,而名字是唯一的线索。 */+ const elsewhere = (data?.matched_names || []).filter(one => one !== name);const note = !data ? '正在找可用的图…'- : data.matched_name && data.matched_name !== name- ? `${name}:图库里按「${data.matched_name}」找到的。`+ : elsewhere.length+ ? `${name}:图库里按「${elsewhere.join('」「')}」找到的。`: choices.length ? `${name}:换上的那张留在本机,随时能换回来。`: `${name}:图库里没有这个名字,用下面两种方式换。`;const stale = !!data && data.index_stale@@ -154,7 +158,8 @@ function Picker({ kind, id, name, onPicked }: PickerProps) {aria-selected={choice.current} disabled={!!busy}class={`avatarpick-cell${choice.current ? ' current' : ''}`}title={`${SOURCE_LABELS[choice.source] || choice.source} · ${choice.label}`- + (choice.width ? ` · ${choice.width}×${choice.height}` : '')}+ + (choice.width ? ` · ${choice.width}×${choice.height}` : '')+ + (choice.found_by ? ` · 按「${choice.found_by}」找到` : '')}onClick={() => pick(choice)}><img loading="lazy" alt=""src={`/avatar-choice?kind=${kind}&id=${id}&ref=${encodeURIComponent(choice.ref)}`} />diff --git a/frontend/test/avatar-picker.test.tsx b/frontend/test/avatar-picker.test.tsxindex 09b6a8545..f1ccd15cd 100644--- a/frontend/test/avatar-picker.test.tsx+++ b/frontend/test/avatar-picker.test.tsx@@ -14,13 +14,14 @@ const choice = (overrides: Partial<AvatarChoice> = {}): AvatarChoice => ({width: 0,height: 0,detail: '葵つかさ.jpg',+ found_by: '',current: false,...overrides,});const listing = (choices: AvatarChoice[], extra: Record<string, unknown> = {}) => ({kind: 'performer', entity_id: 7792, names: ['葵司', '葵つかさ'],- matched_name: '葵つかさ', choices, index_age_hours: 2, index_stale: false, ...extra,+ matched_names: ['葵つかさ'], choices, index_age_hours: 2, index_stale: false, ...extra,});type Call = [string, RequestInit];@@ -81,6 +82,20 @@ it('图库里的名字与页面上的不同名时说清按谁找到的', async (expect(root.textContent).toContain('图库里按「葵つかさ」找到的');});+it('好几个名字各带回一批图时,每一格说清自己是按哪个名字找到的', async () => {+ // 找错人是这一屏唯一会出的大错,而名字是唯一的线索:整屏只报一句「图库里找到的」,+ // 一张同名不同人的图就没有任何能让人起疑的地方。+ server(listing(+ [choice({ found_by: '葵つかさ' }),+ choice({ ref: 'gfriends:3-Prestige/葵ツカサ.jpg', label: '3-Prestige', found_by: '葵ツカサ' })],+ { matched_names: ['葵つかさ', '葵ツカサ'] }));+ await openPicker();+ expect(root.textContent).toContain('图库里按「葵つかさ」「葵ツカサ」找到的');+ const cells = [...root.querySelectorAll('.avatarpick-cell')];+ expect(cells[0]!.getAttribute('title')).toContain('按「葵つかさ」找到');+ expect(cells[1]!.getAttribute('title')).toContain('按「葵ツカサ」找到');+});+it('点一张就提交,换完关掉弹层并让宿主重画', async () => {const calls = server(listing([choice()]));const { picked, popup } = await openPicker();@@ -134,7 +149,7 @@ it('换不成时弹层留在原地,原因写在里面', async () => {});it('图库索引还没取过时只剩手填那两条路', async () => {- server(listing([], { matched_name: '', index_age_hours: null, index_stale: true }));+ server(listing([], { matched_names: [], index_age_hours: null, index_stale: true }));await openPicker();expect(root.querySelectorAll('.avatarpick-cell')).toHaveLength(0);expect(root.textContent).toContain('图库索引还没取过');diff --git a/src/peach/avatar_picker.py b/src/peach/avatar_picker.pyindex 8b85e4931..32d373c4b 100644--- a/src/peach/avatar_picker.py+++ b/src/peach/avatar_picker.py@@ -67,12 +67,15 @@ class Choice:width: int = 0height: int = 0detail: str = ""+ #: 这一格是按哪个名字从图库里找到的。只有一个名字命中时留空。+ found_by: str = ""current: bool = Falsedef as_dict(self) -> dict:return {"ref": self.ref, "source": self.source, "label": self.label,"width": self.width, "height": self.height,- "detail": self.detail, "current": self.current}+ "detail": self.detail, "found_by": self.found_by,+ "current": self.current}def name_chain(connection: sqlite3.Connection, entity_id: int) -> list[str]:@@ -157,7 +160,7 @@ def choices(connection: sqlite3.Connection, providers_root: Path,index_dir = providers_root / GFRIENDS_CACHEnames = name_chain(connection, entity_id)index = gfriends.load_index(index_dir)- matched, found = gfriends.candidates(index, names)+ match = gfriends.candidates(index, names)current = installed_digest(avatar_root, kind, entity_id)cache = AvatarCandidateCache(index_dir)#: 图库候选里已经取过的那些,按内容哈希记下来。取过的图会同时以「图库某个分类」@@ -165,7 +168,11 @@ def choices(connection: sqlite3.Connection, providers_root: Path,#: 一边:`S1`、`GRAPHIS` 说得出是谁家的图,「图库」只说得出它从哪个路子来。taken: set[str] = set()items: list[Choice] = []- for category, filename in found:+ # 好几个名字都命中时,每一格得说得出自己是按哪个名字找来的:找错人是这一屏唯一+ # 会出的大错,而一屏里混着两个人的图时,名字是唯一能看出来的线索。只有一个名字+ # 命中就不必说——那句话对每一格都一样,等于没说。+ tell_finder = len(match.names) > 1+ for category, filename in match.items:shot = cache.describe(gfriends.image_url(category, filename)) or {}digest = str(shot.get("sha256") or "")if digest:@@ -173,6 +180,7 @@ def choices(connection: sqlite3.Connection, providers_root: Path,items.append(Choice(ref=f"gfriends:{category}/{filename}", source="gfriends",label=gfriends.category_label(category), detail=filename,+ found_by=match.finder.get((category, filename), "") if tell_finder else "",width=int(shot.get("width") or 0), height=int(shot.get("height") or 0),current=bool(digest) and digest == current))for choice in _history(providers_root, entity_id, current):@@ -184,7 +192,7 @@ def choices(connection: sqlite3.Connection, providers_root: Path,age = gfriends.index_age(index_dir)return {"kind": kind, "entity_id": int(entity_id),- "names": names, "matched_name": matched,+ "names": names, "matched_names": list(match.names),"choices": [choice.as_dict() for choice in items[:MAX_CHOICES]],"index_age_hours": round(age / 3600, 1) if age is not None else None,"index_stale": age is None or age > gfriends.INDEX_MAX_AGE_SECONDS,@@ -269,9 +277,11 @@ def resolve(ref: str, connection: sqlite3.Connection, providers_root: Path,raise PickerError("认不出这个候选")category, _, filename = ref.split(":", 1)[1].partition("/")index = gfriends.load_index(providers_root / GFRIENDS_CACHE)- matched, found = gfriends.candidates(index, name_chain(connection, entity_id))- if (category, filename) not in found:+ match = gfriends.candidates(index, name_chain(connection, entity_id))+ if (category, filename) not in match.finder:raise PickerError("这个候选不在当前索引里")+ # 证据里记的是找到这一张的那个名字,不是整条链:事后要答的是「这张图凭什么算他」。+ matched = match.finder[(category, filename)]url = gfriends.image_url(category, filename)cache = AvatarCandidateCache(providers_root / GFRIENDS_CACHE)body = cache.lookup(url)diff --git a/src/peach/gfriends.py b/src/peach/gfriends.pyindex 678c1b79f..32a581434 100644--- a/src/peach/gfriends.py+++ b/src/peach/gfriends.py@@ -18,6 +18,7 @@ import jsonimport reimport timeimport urllib.parse+from dataclasses import dataclass, fieldfrom pathlib import Path#: 图库的 raw 根。索引和图片都挂在它下面。@@ -93,16 +94,50 @@ def load_index(cache_dir: Path) -> dict[str, list[tuple[str, str]]]:return {}-def candidates(index: dict[str, list[tuple[str, str]]],- names: list[str]) -> tuple[str, list[tuple[str, str]]]:- """按名字链依次查索引,返回 (命中的名字, 候选)。一个都不命中就是 ("", [])。+@dataclass(frozen=True)+class Match:+ """名字链在图库里的全部落点。++ `names` 是命中的那几个名字,按名字链的先后;`items` 是去重后的候选;+ `finder` 答的是「这一张是被哪个名字找到的」——装图时要把它写进证据,+ 一张图的来路不能记成整条名字链。+ """++ names: tuple[str, ...] = ()+ items: tuple[tuple[str, str], ...] = ()+ finder: dict[tuple[str, str], str] = field(default_factory=dict)++ def __bool__(self) -> bool:+ return bool(self.items)+++def candidates(index: dict[str, list[tuple[str, str]]], names: list[str]) -> Match:+ """按名字链查索引,命中的全部并起来。- 次序即匹配次序:先 canonical、再别名、最后本地化写法,第一个命中的就定下来。大陆简体与日文字体是两个不同的键(`横宫七海` 与 `横宮七海`),所以名字链必须带上别名——只拿规范名去查,汉字简化过的那些人一个也找不到。++ 并起来而不是命中即停:同一个人在图库里常按好几种写法各存一批,停在第一个命中的+ 名字上,排在它后面那几个名下的图整批出不来。实测 `新有菜` 那条链,`新ありな`+ 命中 1 张、`橋本ありな` 命中 11 张,而前者排在前面——停下来就只剩一张可选,+ 那 11 张一次也没机会露面。++ 同一个文件可能被两个名字同时指到(键不同、落到同一条记录),按 (来源目录, 文件名)+ 去重,先指到它的那个名字算它的来路。并完之后整体重排一次:挑图看的是哪张该先试,+ 不是它由链上第几个名字找到的。"""+ found: list[tuple[str, str]] = []+ hit_names: list[str] = []+ finder: dict[tuple[str, str], str] = {}for name in names:- found = index.get(normalized(name))- if found:- return name, list(found)- return "", []+ rows = index.get(normalized(name))+ if not rows:+ continue+ hit_names.append(name)+ for pair in rows:+ if pair in finder:+ continue+ finder[pair] = name+ found.append(pair)+ found.sort(key=lambda pair: quality_key(*pair))+ return Match(tuple(hit_names), tuple(found), finder)diff --git a/tests/test_avatar_picker.py b/tests/test_avatar_picker.pyindex d83ead72b..f6bfa8110 100644--- a/tests/test_avatar_picker.py+++ b/tests/test_avatar_picker.py@@ -28,6 +28,8 @@ FILETREE = {"7-S1": {"葵つかさ.jpg": "葵つかさ.jpg?t=2"},"y-Minnano": {"葵つかさ.jpg": "AI-Fix-葵つかさ.jpg?t=3"},"8-GRAPHIS": {"別人.jpg": "別人.jpg?t=4"},+ # 同一个人按另一种写法另存的一批。图库里这是常态,而它跟上面三张一个键也不共用。+ "3-Prestige": {"葵ツカサ.jpg": "葵ツカサ.jpg?t=5"},}}LIBRARY_REF = "gfriends:7-S1/葵つかさ.jpg"@@ -107,12 +109,31 @@ class IndexTests(unittest.TestCase):self.assertEqual(gfriends.load_index(Path(folder)), {})self.assertIsNone(gfriends.index_age(Path(folder)))- def test_the_first_name_that_hits_decides_the_candidates(self):+ def test_every_name_on_the_chain_brings_its_own_pictures(self):+ """并起来,不是停在第一个命中的名字上。++ 同一个人在图库里常按好几种写法各存一批,停下来就只剩其中一批——实测「新有菜」+ 那条链,先命中的那个名下 1 张、后面那个名下 11 张。+ """index = gfriends.parse_filetree(json.dumps(FILETREE).encode("utf-8"))- matched, found = gfriends.candidates(index, ["葵司", "葵つかさ"])- self.assertEqual(matched, "葵つかさ")- self.assertEqual(len(found), 3)- self.assertEqual(gfriends.candidates(index, ["谁都不是"]), ("", []))+ match = gfriends.candidates(index, ["葵司", "葵つかさ", "葵ツカサ"])+ self.assertEqual(match.names, ("葵つかさ", "葵ツカサ"))+ # 并完之后整体重排:挑图看的是哪张该先试,不是它由链上第几个名字找到的。+ self.assertEqual([category for category, _ in match.items],+ ["0-Hand-Storage", "3-Prestige", "7-S1", "y-Minnano"])+ # 一张图的来路记的是找到它的那个名字,不能记成整条链。+ self.assertEqual(match.finder[("3-Prestige", "葵ツカサ.jpg")], "葵ツカサ")++ def test_a_picture_two_names_both_point_at_is_listed_once(self):+ index = {"甲": [("7-S1", "a.jpg")], "乙": [("7-S1", "a.jpg")]}+ match = gfriends.candidates(index, ["甲", "乙"])+ self.assertEqual(match.items, (("7-S1", "a.jpg"),))+ # 先指到它的那个名字算它的来路。+ self.assertEqual(match.finder[("7-S1", "a.jpg")], "甲")++ def test_a_chain_that_hits_nothing_is_falsy(self):+ index = gfriends.parse_filetree(json.dumps(FILETREE).encode("utf-8"))+ self.assertFalse(gfriends.candidates(index, ["谁都不是"]))class SourceBoundaryTests(unittest.TestCase):@@ -197,12 +218,30 @@ class ChoiceTests(PickerFixture):"""规范名是简体,图库里只有日文写法;不查别名一张也列不出来。"""out = self.listed()self.assertEqual(out["names"], ["葵司", "葵つかさ"])- self.assertEqual(out["matched_name"], "葵つかさ")+ self.assertEqual(out["matched_names"], ["葵つかさ"])self.assertEqual([one["ref"] for one in out["choices"]], ["gfriends:0-Hand-Storage/葵つかさ.jpg",LIBRARY_REF,"gfriends:y-Minnano/AI-Fix-葵つかさ.jpg",])+ # 只有一个名字找得到时不必说是哪一个:那一屏上写着的就是她。+ self.assertEqual({one["found_by"] for one in out["choices"]}, {""})++ def test_a_second_writing_of_her_name_brings_its_own_pictures(self):+ """两种写法在图库里是两批图,而屏幕上要说清哪一张是按哪个名字找到的。++ 找错人是这里唯一会出的大错,名字是唯一的线索:只报「图库里找到的」,一张+ 同名不同人的图就没有任何能让人起疑的地方。+ """+ with self.connection:+ self.connection.execute(+ "INSERT INTO entity_alias(entity_id,alias,normalized_alias,source,"+ "confidence) VALUES(7792,'葵ツカサ','葵ツカサ','user:alias',1.0)")+ out = self.listed()+ self.assertEqual(out["matched_names"], ["葵つかさ", "葵ツカサ"])+ found = {one["ref"]: one["found_by"] for one in out["choices"]}+ self.assertEqual(found["gfriends:3-Prestige/葵ツカサ.jpg"], "葵ツカサ")+ self.assertEqual(found[LIBRARY_REF], "葵つかさ")def test_pictures_taken_before_show_up_as_their_own_group(self):"""换回去不该再下一次:取过的图按内容哈希躺在候选缓存里。"""@@ -408,7 +447,7 @@ class AvatarPickerRouteTests(unittest.TestCase):def test_the_choices_endpoint_lists_the_library_candidates(self):out = self.client.get("/api/avatar-choices?kind=performer&id=7792&t=secret").json()- self.assertEqual(out["matched_name"], "葵つかさ")+ self.assertEqual(out["matched_names"], ["葵つかさ"])self.assertIn(LIBRARY_REF, [one["ref"] for one in out["choices"]])def test_a_preview_serves_the_picture_and_a_bad_reference_404s(self):diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsindex dc49eddfc..d9f1adcb1 100644--- a/web/dist/peach-ui.js+++ b/web/dist/peach-ui.js@@ -4637,7 +4637,7 @@ function Vi({ kind: e, id: t, name: n, onPicked: r }) {let e = await r.json().catch(() => null);throw Error(e?.error || `请求失败(${r.status})`);}- }, "file"), w = s?.choices || [], T = s ? s.matched_name && s.matched_name !== n ? `${n}:图库里按「${s.matched_name}」找到的。` : w.length ? `${n}:换上的那张留在本机,随时能换回来。` : `${n}:图库里没有这个名字,用下面两种方式换。` : "正在找可用的图…", E = !!s && s.index_stale && !w.some((e) => e.source === "gfriends");+ }, "file"), w = s?.choices || [], T = (s?.matched_names || []).filter((e) => e !== n), E = s ? T.length ? `${n}:图库里按「${T.join("」「")}」找到的。` : w.length ? `${n}:换上的那张留在本机,随时能换回来。` : `${n}:图库里没有这个名字,用下面两种方式换。` : "正在找可用的图…", D = !!s && s.index_stale && !w.some((e) => e.source === "gfriends");return /* @__PURE__ */ q("div", {class: "avatarpick",children: [/* @__PURE__ */ q("button", {@@ -4681,8 +4681,8 @@ function Vi({ kind: e, id: t, name: n, onPicked: r }) {children: [w.length, " 张可选"]})]}),- /* @__PURE__ */ q("p", { children: T }),- E && /* @__PURE__ */ q("p", {+ /* @__PURE__ */ q("p", { children: E }),+ D && /* @__PURE__ */ q("p", {class: "avatarpick-note",children: "图库索引还没取过,只能从用过的图里选。"}),@@ -4720,7 +4720,7 @@ function Vi({ kind: e, id: t, name: n, onPicked: r }) {"aria-selected": n.current,disabled: !!f,class: `avatarpick-cell${n.current ? " current" : ""}`,- title: `${Bi[n.source] || n.source} · ${n.label}` + (n.width ? ` · ${n.width}×${n.height}` : ""),+ title: `${Bi[n.source] || n.source} · ${n.label}` + (n.width ? ` · ${n.width}×${n.height}` : "") + (n.found_by ? ` · 按「${n.found_by}」找到` : ""),onClick: () => x(n),children: [/* @__PURE__ */ q("img", {