Peach: Local-first video metadata scraper and media manager.
fix(web): 统一艺人与真人账号资料并补全公开档案
longmeidao8cd26022ec9d
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex a537732f1..33038d52e 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -8,6 +8,8 @@ Babepedia 主图库和 Vixen 网络公开 GraphQL 的字段核对 [Stash Communi## 实体身份与职业+Babepedia 资料采集复用 `babepedia_page` 的主名与别名交叉核对、`performer_profiles` 的整行来源保护和 `performer_alias_followup.land` 的占用检查。英文艺名只在明确允许的来源中登记,JAV 后继保留自己的名字策略。真人账号与出演者共用资料表、别名分组与头像候选;保留账号角色及旧地址。主图可以补空头像,本人档案图库仅作候选,推荐人物排除,单图失败继续其余有限候选。`harvest_western_profiles.py` 每轮至多 16 位,计划、备份、回执与批次撤回齐备;既有资料和头像保留。真实只读复核取得 Ria Kurumi 等 16 份匹配档案,无新增依赖。+身份分类复用 `entity`、来源关系、`field_owners`、SQLite 迁移与版本触发器。职业与账号角色使用独立多值断言,跨角色身份使用可撤回关系;[Schema.org Person](https://schema.org/Person) 的 `hasOccupation`、`sameAs` 与 [Role](https://schema.org/Role) 提供语义参照,2026-10-06 已核对官方文档。实现不复制外部解析器或新增依赖。目录推断和搜索命中只存候选,公开来源事实与用户复核分别保留状态。`entity_identity_research` 与 `apply_entity_identity_research.py` 复用规范实体写入、字段归属保护、只读预览、SQLite 备份及冻结计划。逐行撤回回执核对后续修改,新增实体有额外引用时拒绝删除;观看历史和人工判断不被回滚覆盖。diff --git a/frontend/src/react/entity-hero/entity-hero-page.tsx b/frontend/src/react/entity-hero/entity-hero-page.tsxindex 4a4ef8e96..b621d39f5 100644--- a/frontend/src/react/entity-hero/entity-hero-page.tsx+++ b/frontend/src/react/entity-hero/entity-hero-page.tsx@@ -35,7 +35,7 @@ function costarImg(person: HeroCostar): string {export function EntityHeroPage({ kind, name, entity, feedNew, feedHost, actions, helpers }: EntityHeroProps) {const people = isPeople(kind);const company = isCompany(kind);- const facts = kind === 'performer' ? factRows(entity.profile) : [];+ const facts = people ? factRows(entity.profile) : [];const links = heroLinks(entity, kind);const marks = entryMarks(entity);const costars = kind === 'agency' ? [] : (entity.related_performers || []);@@ -130,9 +130,7 @@ function Portrait({ kind, name, helpers, people, company }: {);}-/** 名字下面那一行。女优页各项带图标:分类、视频数、事务所、别名(读音在最前);其余种类- * 仍是一行字:别名 · 视频数 · 归属。事务所是身份信息,不是链接的标签;账本里有这家的实体时- * 给去处,只有采到的原文时只写名字。 */+/** 身份资料各项带图标;别名独立排列,归属有实体时提供站内入口。 */function AliasLine({ kind, entity, actions }: { kind: string; entity: EntityHeroData; actions: EntityHeroActions }) {const agency = agencyOf(entity);const go = (target: string, to: string) => (event: MouseEvent) => {@@ -143,7 +141,7 @@ function AliasLine({ kind, entity, actions }: { kind: string; entity: EntityHero? <a href={entityPath('agency', agency.name)} data-agency={agency.name} onClick={go('agency', agency.name)}>{agency.name}</a>: agency.name) : null;const count = <><b>{entity.asset_count.toLocaleString()}</b> 个视频</>;- if (kind === 'performer') {+ if (kind === 'performer' || kind === 'creator') {const line = nameLine(entity.name_groups);return (<div data-entity-alias="meta">@@ -176,27 +174,22 @@ function AliasLine({ kind, entity, actions }: { kind: string; entity: EntityHero: (entity.labels || []).length ? <> · <b>{entity.labels!.length.toLocaleString()}</b> 个厂牌</> : null;const maker = entity.maker;return (- <div data-entity-alias={kind === 'creator' ? 'meta' : ''}>+ <div data-entity-alias="meta">{kind === 'creator' ? <IdentityMeta entity={entity} /> : null}- <span>{aliases.length ? `${aliases.join(' / ')} · ` : ''}{count}{members}- {agencyNode ? <> · {agencyNode}</> : null}- {maker ? <> · <a href={entityPath('studio', maker.name)} data-studio-link={maker.name}- onClick={go('studio', maker.name)}>{maker.name}</a></> : null}</span>+ <span data-meta-item="" title="视频"><Glyph name="film" /><span>{count}{members}</span></span>+ {agencyNode ? <span data-meta-item="" title="事务所"><Glyph name="briefcase" /><span>{agencyNode}</span></span> : null}+ {maker ? <span data-meta-item="" title="片商"><Glyph name="clapperboard" /><a href={entityPath('studio', maker.name)} data-studio-link={maker.name}+ onClick={go('studio', maker.name)}>{maker.name}</a></span> : null}+ {aliases.length ? <div data-meta-item="names" data-company-names={kind === 'studio' || kind === 'agency' ? '' : undefined}><Glyph name="id-card" /><span data-alias-names="" title="别名">{aliases.map((name, at) => <span key={at}>{name}</span>)}</span></div> : null}</div>);}-/** 分类是身份行的第一项;来源证据随资料下发并作为补充提示。 */+/** 分类位于身份行的第一项。 */function IdentityMeta({ entity }: { entity: EntityHeroData }) {if (!entity.identity_labels?.length) return null;- const sources = [- ...(entity.external_refs || []).map((ref) => ref.provider),- ...(entity.classifications || []).filter((claim) => claim.status === 'observed' || claim.status === 'approved')- .map((claim) => claim.evidence),- ];return (- <span data-meta-item="classification" data-identity-classification=""- title={sources.length ? [...new Set(sources)].join(' · ') : '分类'}>+ <span data-meta-item="classification" data-identity-classification=""><Glyph name="user-round" /><span>{entity.identity_labels.join(' · ')}</span></span>);@@ -266,7 +259,7 @@ function HeroLinkView({ link }: { link: LinkView }) {);case 'private':return (- <span data-link="private" title="私人馆藏来源记录,不直接打开下载页">+ <span data-link="private" title={link.label}><LinkIcon mark={{ globe: true }} /><span data-link-label="">来源 · {link.label}</span></span>);diff --git a/frontend/src/react/entity-hero/entity-hero.css b/frontend/src/react/entity-hero/entity-hero.cssindex 0d4d9bb56..6a070dfa8 100644--- a/frontend/src/react/entity-hero/entity-hero.css+++ b/frontend/src/react/entity-hero/entity-hero.css@@ -179,6 +179,7 @@.peach-react [data-meta-item] { display: inline-flex; align-items: center; gap: 6px; min-width: 0; }.peach-react [data-meta-item="classification"] { white-space: nowrap; flex: none; }.peach-react [data-meta-item="names"] { flex-wrap: wrap; }+.peach-react [data-company-names] { flex-basis: 100%; }.peach-react [data-meta-item] > svg,.peach-react [data-entity-facts] dt svg {width: 16px;diff --git a/frontend/src/react/entity-hero/entity-hero.ts b/frontend/src/react/entity-hero/entity-hero.tsindex f8cf4e37c..242c3a6a7 100644--- a/frontend/src/react/entity-hero/entity-hero.ts+++ b/frontend/src/react/entity-hero/entity-hero.ts@@ -139,8 +139,8 @@ export const isCompany = (kind: string) => kind === 'studio' || kind === 'agencyexport const isPeople = (kind: string) => kind === 'performer' || kind === 'creator';export const entityFeedTip = (on: boolean) => on- ? '已订阅新作:库里还没有的新片排在资料卡下面。再点一下取消订阅。'- : '订阅新作:定时去 JavDB 查这位有没有出新片,库里还没有的排在资料卡下面。';+ ? '已订阅新作,点击取消订阅'+ : '订阅新作';/** 这条实体名下已有的写法,统称排第一。 */export function nameChoices(entity: EntityHeroData): string[] {@@ -190,7 +190,7 @@ export function heroLinks(entity: EntityHeroData, kind: string): LinkView[] {}const url = x.url || '';if (!(x.clickable && /^https?:\/\//i.test(url))) return { type: 'private', label: x.label || x.hostname || '已记录' };- if (kind === 'performer' && x.link_kind !== 'social') {+ if (isPeople(kind) && x.link_kind !== 'social') {return { type: 'icon', url, title: performerLinkName(x, agency), mark: siteMark(x) };}if (x.link_kind === 'social') {diff --git a/frontend/src/react/index/index-data.ts b/frontend/src/react/index/index-data.tsindex bce288ddf..47458246f 100644--- a/frontend/src/react/index/index-data.ts+++ b/frontend/src/react/index/index-data.ts@@ -24,7 +24,7 @@ export const INDEX_URL = '/api/index';/** 页头标题与名册口径。 */export const INDEX_TITLES: Record<IndexKind, string> = {- performers: '艺人', creators: '创作者', studios: '厂牌', agencies: '事务所', tags: '标签',+ performers: '艺人', creators: '卖家与动画作者', studios: '厂牌', agencies: '事务所', tags: '标签',};/** 索引格对应的实体类型,资料页与取图链都按它分。 */@@ -45,8 +45,8 @@ export const ONLINE_TAG_CATEGORIES: readonly (readonly [string, string])[] = [['copyright', '作品'], ['metadata', '元数据'],];export const IDENTITY_CATEGORIES: Record<'performers' | 'creators', readonly (readonly [string, string])[]> = {- performers: [['all', '全部'], ['japanese_av', '女优'], ['amateur', '素人'], ['western', '西方']],- creators: [['all', '全部'], ['blogger', '网黄博主'], ['seller', '卖家'], ['animation', '动画作者']],+ performers: [['all', '全部'], ['japanese_av', '女优'], ['amateur', '素人'], ['western', '西方'], ['blogger', '网黄博主']],+ creators: [['all', '全部'], ['seller', '卖家'], ['animation', '动画作者']],};/** 每页条数:一屏头像 120 格,标签 180 枚。 */@@ -57,6 +57,7 @@ export const isCompany = (kind: IndexKind) => kind === 'studios' || kind === 'ag/** 本地名册的一格。字段以 `q_index` 为准;公司另有标识,事务所另有成员数。 */export interface IndexPerson {+ entity_kind?: string;identity_labels?: string[];entity_id?: number;id?: number;diff --git a/frontend/src/react/index/index-page.tsx b/frontend/src/react/index/index-page.tsxindex 6b3325f95..24fb5cfa5 100644--- a/frontend/src/react/index/index-page.tsx+++ b/frontend/src/react/index/index-page.tsx@@ -42,6 +42,10 @@ const SCOPE_TABS: BoardTab<IndexScope>[] = [{ value: 'local', label: '本地', symbol: 'hard-drive' },{ value: 'online', label: '在线', symbol: 'rss' },];+const PEOPLE_TABS: BoardTab<'performers' | 'creators'>[] = [+ { value: 'performers', label: '艺人', symbol: 'user-round' },+ { value: 'creators', label: '卖家与动画作者', symbol: 'user-round' },+];/* 公司那一格摆的是标识而不是脸,沿用艺人那套词就是提示说着「竖幅头像」、屏幕上摆着方标识。档位仍是同一个设置值,分开的只有说法。 */@@ -219,6 +223,10 @@ export function IndexPage(props: IndexProps) {<span aria-hidden className="hidden h-0 basis-full max-board-narrow:order-2 max-board-narrow:block" /><IndexSearch label={`过滤${title}`} value={q} onQuery={(next) => { if (next !== q) go({ q: next }, !!next) }} /></div>+ {kind === 'performers' || kind === 'creators' ? (+ <BoardTabs tabs={PEOPLE_TABS} value={kind} label="人物名册"+ onChange={(next) => go({ kind: next, scope: 'local', category: 'all' })} />+ ) : null}{tabs}{(kind === 'creators' || kind === 'performers') && scope === 'local' ? (<div aria-label="身份分类" className="mb-4 flex flex-wrap gap-2">@@ -259,7 +267,7 @@ export function IndexPage(props: IndexProps) {}const LABELS: Record<IndexKind, string> = {- tags: '标签', performers: '艺人', creators: '创作者', studios: '厂牌', agencies: '事务所',+ tags: '标签', performers: '艺人', creators: '卖家与动画作者', studios: '厂牌', agencies: '事务所',};/** 空馆藏、筛选无结果与在线来源还没有内容分别给出可执行的去处。文案同目录页的空态diff --git a/frontend/src/react/index/index-people.tsx b/frontend/src/react/index/index-people.tsxindex 0bce69b0c..9c91f08fb 100644--- a/frontend/src/react/index/index-people.tsx+++ b/frontend/src/react/index/index-people.tsx@@ -57,16 +57,16 @@ export function PeopleGrid(props: Pick<IndexProps, 'personAvatar' | 'openEntity'>;},) {- const entityKind = ENTITY_KINDS[kind];const company = isCompany(kind);const big = layout === 'big';return (<div data-index-grid="" data-layout={layout} data-cells={company ? 'company' : 'people'}className={`${company ? 'index-grid-company' : 'index-grid-person'} gap-3`}>{items.map((item) => {+ const entityKind = item.entity_kind || ENTITY_KINDS[kind];const avatar = props.personAvatar(item, entityKind, big);return (- <Cell key={item.k} data-k={item.k} data-kind={entityKind} name={item.k} readout={`${personReadout(kind, item)}${item.identity_labels?.length ? ' · ' + item.identity_labels.join(' / ') : ''}`}+ <Cell key={`${entityKind}:${item.entity_id || item.k}`} data-k={item.k} data-kind={entityKind} name={item.k} readout={`${personReadout(kind, item)}${item.identity_labels?.length ? ' · ' + item.identity_labels.join(' / ') : ''}`}big={big} onPress={() => props.openEntity(entityKind, item.k)}><Ring html={avatar.html} face={avatar.face} company={company} big={big} /></Cell>diff --git a/frontend/test/react/entity-hero.test.tsx b/frontend/test/react/entity-hero.test.tsxindex 17ad13bbf..e2984410a 100644--- a/frontend/test/react/entity-hero.test.tsx+++ b/frontend/test/react/entity-hero.test.tsx@@ -53,6 +53,24 @@ async function open(initial: EntityHeroProps) {}describe('排版用的纯函数', () => {+ it('真人账号与女优共用资料、别名和图标行', async () => {+ const host = await open(props({ kind: 'creator', name: 'RiaKurumi', entity: performer({+ canonical_name: 'RiaKurumi', identity_labels: ['女优','网黄博主'],+ profile: { height: 149 }, name_groups: { shown: ['Ria Kurumi', '百田くるみ'], total: 2 },+ }) }));+ expect(host.querySelector('[data-entity-facts]')?.textContent).toContain('T149');+ expect(host.querySelector('[data-alias-names]')?.textContent).toContain('百田くるみ');+ expect(host.querySelector('[data-meta-item][title="视频"] use')?.getAttribute('href')).toBe('#i-film');+ });+ it('厂牌视频数与别名各自带图标,资料不填人物字段', async () => {+ const host = await open(props({ kind: 'studio', name: 'MOODYZ', entity: performer({+ canonical_name: 'MOODYZ', display_aliases: ['ムーディーズ'], agency: undefined,+ }) }));+ expect(host.querySelector('[data-meta-item][title="视频"] use')?.getAttribute('href')).toBe('#i-film');+ expect(host.querySelector('[data-company-names] use')?.getAttribute('href')).toBe('#i-id-card');+ expect(host.querySelector('[data-company-names]')?.textContent).toBe('ムーディーズ');+ expect(host.querySelector('[data-entity-facts]')).toBeNull();+ });it('分类带图标位于身份行最左侧,资料保留来源与跨角色身份入口', async () => {const given = props({ entity: performer({identity_labels: ['女优','西方'],@@ -63,7 +81,8 @@ describe('排版用的纯函数', () => {const classification = host.querySelector('[data-identity-classification]')!;expect(classification.textContent).toBe('女优 · 西方');expect(classification.querySelector('use')?.getAttribute('href')).toBe('#i-user-round');- expect(classification.getAttribute('title')).toContain('发行方演员名单');+ expect(classification.hasAttribute('title')).toBe(false);+ expect(host.textContent).not.toContain('发行方演员名单');expect(host.querySelector('[data-entity-alias]')?.firstElementChild).toBe(classification);expect(host.textContent).not.toContain('成人出演者');await click(host.querySelector('[data-entity-identity] button.underline'));diff --git a/frontend/test/react/index-page.test.tsx b/frontend/test/react/index-page.test.tsxindex 5747aa2b1..ba9aed9f4 100644--- a/frontend/test/react/index-page.test.tsx+++ b/frontend/test/react/index-page.test.tsx@@ -85,12 +85,12 @@ describe('地址栏上的类型', () => {describe('名册', () => {it('浏览分类写回地址并隔离分页缓存,筛选只显示有内容的分类', async () => {- seed(indexKey('creators', ''), [person('真人账号', { identity_labels: ['网黄博主'] })], false, { blogger:1, seller:1 });- const fetcher = serve(() => ({ items: [person('卖家账号', { identity_labels: ['卖家'] })], categories:{ blogger:1, seller:1 }, has_more: false }));+ seed(indexKey('creators', ''), [person('动画作者', { identity_labels: ['动画作者'] })], false, { animation:1, seller:1 });+ const fetcher = serve(() => ({ items: [person('卖家账号', { identity_labels: ['卖家'] })], categories:{ animation:1, seller:1 }, has_more: false }));const given = props({ kind: 'creators' });const host = await open(given);- expect(cells(host)[0]?.textContent).toContain('网黄博主');- expect(host.querySelector('[aria-label="身份分类"]')?.textContent).toBe('全部网黄博主卖家');+ expect(cells(host)[0]?.textContent).toContain('动画作者');+ expect(host.querySelector('[aria-label="身份分类"]')?.textContent).toBe('全部卖家动画作者');await click(buttonNamed('卖家', host));await settle();expect(given.route).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'seller' }), { replace: false });@@ -98,12 +98,21 @@ describe('名册', () => {expect(cells(host)[0]?.textContent).toContain('卖家');expect(indexRoute({ kind: 'performers', q: '', scope: 'online', view: 'alphabet', category: 'artist' }).category).toBe('all');});- it('艺人分类不显示空分类或账号分类,创作者地址不接受女优筛选', async () => {+ it('艺人分类显示有内容的分类,卖家与动画作者地址不接受女优筛选', async () => {seed(indexKey('performers', ''), [person('女优', { identity_labels:['女优','西方'] })], false, { japanese_av:1, western:1 });const host = await open(props());expect(host.querySelector('[aria-label="身份分类"]')?.textContent).toBe('全部女优西方');expect(indexRoute({ kind:'creators', q:'', scope:'local', view:'alphabet', category:'japanese_av' }).category).toBe('all');});+ it('艺人名册的真人账号保留账号头像及资料页入口', async () => {+ seed(indexKey('performers',''),[person('真人账号',{entity_kind:'creator',identity_labels:['网黄博主']})],false,{blogger:1});+ const given = props();+ const host = await open(given);+ expect(given.personAvatar).toHaveBeenCalledWith(expect.objectContaining({k:'真人账号'}),'creator',true);+ await click(cells(host)[0]);+ expect(given.openEntity).toHaveBeenCalledWith('creator','真人账号');+ expect(host.querySelector('[aria-label="身份分类"]')?.textContent).toBe('全部网黄博主');+ });it('首屏读缓存,读数带加号,大图版式按大格取头像', async () => {seed(indexKey('performers', ''), [person('甲'), person('乙')], true);const given = props();diff --git a/scripts/harvest_western_artwork.py b/scripts/harvest_western_artwork.pyindex 8def0c7af..24e6800f7 100644--- a/scripts/harvest_western_artwork.py+++ b/scripts/harvest_western_artwork.py@@ -57,25 +57,32 @@ def run(args) -> dict:try:portraits = babepedia_portraits(http, name, aliases, profile_url=profiles.get(entity_id, ''))for origin in portraits:- cache = AvatarCandidateCache(providers / 'babepedia')- body = cache.lookup(origin['upstream_url'])- if body is None:- if not avatar_picker.allowed_source(origin['upstream_url']):- raise ValueError('头像来源不是公网 HTTPS')- body = avatar_picker.fetch_image(http, origin['upstream_url'])- inspected = avatar_picker.accept_image(body)- item['portraits'].append({**origin, 'sha256': inspected.sha256,- 'width': inspected.width, 'height': inspected.height})- if args.apply:- avatar_picker.keep(providers, entity_id, body, origin)- destination = avatar_root / f'{kind}-{entity_id}.img'- if not destination.exists() and acceptable_avatar(inspected, MIN_LONG_SIDE, MIN_SHORT_SIDE):- install_entity_avatar(avatar_root, kind, entity_id, body, inspected.mime_type,- {**origin, 'source_url': origin['upstream_url']})- item['installed'] = inspected.sha256- time.sleep(args.delay)+ try:+ cache = AvatarCandidateCache(providers / 'babepedia')+ body = cache.lookup(origin['upstream_url'])+ if body is None:+ if not avatar_picker.allowed_source(origin['upstream_url']):+ raise ValueError('头像来源不是公网 HTTPS')+ body = avatar_picker.fetch_image(http, origin['upstream_url'])+ inspected = avatar_picker.accept_image(body)+ item['portraits'].append({**origin, 'sha256': inspected.sha256,+ 'width': inspected.width, 'height': inspected.height})+ if args.apply:+ avatar_picker.keep(providers, entity_id, body, origin)+ destination = avatar_root / f'{kind}-{entity_id}.img'+ if (origin.get('automatic_install', True) and not destination.exists()+ and acceptable_avatar(inspected, MIN_LONG_SIDE, MIN_SHORT_SIDE)):+ install_entity_avatar(avatar_root, kind, entity_id, body, inspected.mime_type,+ {**origin, 'source_url': origin['upstream_url']})+ item['installed'] = inspected.sha256+ except Exception as error:+ item['issues'].append({'source_url': origin['upstream_url'], 'error': str(error)})+ finally:+ time.sleep(args.delay)except Exception as error:item['issues'].append(str(error))+ if args.portraits_only:+ continueworks = connection.execute('SELECT a.id,a.name,a.code,a.studio,a.release_date FROM asset a ''JOIN asset_entity ae ON ae.asset_id=a.id WHERE ae.entity_id=? '"AND a.medium='video' AND a.disposal IS NULL ORDER BY a.id LIMIT 30", (entity_id,)).fetchall()@@ -129,6 +136,7 @@ def build_parser():parser.add_argument('--entity', type=int, action='append', required=True)parser.add_argument('--delay', type=float, default=3)parser.add_argument('--apply', action='store_true')+ parser.add_argument('--portraits-only', action='store_true')return parserdiff --git a/scripts/harvest_western_profiles.py b/scripts/harvest_western_profiles.pynew file mode 100644index 000000000..cb1544f40--- /dev/null+++ b/scripts/harvest_western_profiles.py@@ -0,0 +1,71 @@+"""读取指定艺人与真人账号的 Babepedia 资料,生成计划或备份后补空落库。"""+from __future__ import annotations++import argparse+import json+import sys+import time+from pathlib import Path+from datetime import datetime, timezone++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))++from peach.config import REVIEW_DIR+from peach.http import HttpxTransport+from peach.scripting import add_ledger_write_args, open_for_write, open_readonly, counts_of, verify_after_write+from peach.western_profiles import profile, land+++def run(args):+ if args.apply:+ if not args.plan:+ raise ValueError('执行需要已生成的 --plan')+ records = json.loads(args.plan.read_text(encoding='utf8'))+ connection = open_for_write(args)+ before = counts_of(connection)+ baseline = {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')}+ result = {'before':before,'entities':[],'batch':'auto:babepedia-profile@'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}+ try:+ with connection:+ for record in records:+ result['entities'].append(land(connection, record['entity_id'], record['name'], record, batch=result['batch']))+ integrity, violations = verify_after_write(connection)+ if integrity != 'ok' or {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')} != baseline:+ raise ValueError('资料写入产生完整性或外键变化')+ result.update(after=counts_of(connection),integrity=integrity,foreign_keys=violations)+ finally:+ connection.close()+ args.out.parent.mkdir(parents=True,exist_ok=True)+ args.out.write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')+ return result+ if not args.entity or len(set(args.entity)) > 16 or args.delay < 1:+ raise ValueError('每轮 1–16 位艺人,请求间隔至少 1 秒')+ http = HttpxTransport()+ connection = open_readonly(args.db)+ records = []+ try:+ for entity_id in sorted(set(args.entity)):+ row = connection.execute("SELECT canonical_name FROM entity WHERE id=? AND kind IN ('performer','creator')",(entity_id,)).fetchone()+ if not row:+ raise ValueError(f'艺人 {entity_id} 不存在')+ aliases = [r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?',(entity_id,))]+ url = dict(args.profile_url or []).get(str(entity_id), '')+ records.append({'entity_id':entity_id, 'name':row[0], **profile(http,row[0],aliases,profile_url=url)})+ time.sleep(args.delay)+ finally:+ connection.close()+ http.close()+ destination = args.plan or args.out+ destination.parent.mkdir(parents=True,exist_ok=True)+ destination.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf8')+ return {'profiles':len(records),'plan':str(destination)}+++if __name__ == '__main__':+ parser = add_ledger_write_args(argparse.ArgumentParser(description=__doc__))+ parser.add_argument('--entity',type=int,action='append')+ parser.add_argument('--profile-url',nargs=2,action='append',metavar=('ENTITY_ID','URL'))+ parser.add_argument('--plan',type=Path)+ parser.add_argument('--out',type=Path,default=REVIEW_DIR/'western-profiles-receipt.json')+ parser.add_argument('--delay',type=float,default=1)+ print(json.dumps(run(parser.parse_args()),ensure_ascii=False))diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 231396b6e..239e2221b 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -75,6 +75,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_community_catalog.py","test_babepedia_match.py","test_western_artwork.py",+ "test_western_profiles.py","test_jav*.py", "test_code_creators.py", "test_tag_renames.py","test_reproject_snapshot_tags.py","test_stale_candidates.py", "test_logo_provider.py",diff --git a/src/peach/classification.py b/src/peach/classification.pyindex 3af628994..67723a020 100644--- a/src/peach/classification.py+++ b/src/peach/classification.py@@ -74,6 +74,13 @@ def creator_release_identifier(creator: str, *, path: str, filename: str, code:return 'release_identifier', f'目录与媒体文件同为站点作品号 {site};官网目录 {SITE_RELEASES[site.split("-")[0]]}'versionless = re.sub(r'[-_](?:[468]k|hd)(?:[-_](?:c|ch))?$', '', creator, flags=re.I)identity = release_code_from_text(versionless)+ if (versionless != creator and identity and is_jav_code(identity)+ and normalise_code_key(versionless) == normalise_code_key(identity)+ and creator.casefold() in [part.casefold() for part in re.split(r'[\\/]', path)]):+ return 'release_identifier', f'目录名是发行标识 {identity} 与画质版本后缀;不作为账号,也不推断目录内文件的番号'+ ppv = re.fullmatch(r'gachincoppv[-_](\d{3,6})[-_](?:hd|fhd|[468]k)', creator, re.I)+ if ppv and re.fullmatch(re.escape(creator) + r'(?:[-_]?\d+)?\.[a-z0-9]+', filename, re.I):+ return 'release_identifier', '目录与分段文件使用 Gachinco PPV 作品号及画质后缀;不作为账号'if identity and is_jav_code(identity) and re.search(r'(?<![a-z0-9])' + re.escape(versionless) + r'(?:[-_](?:[468]k|hd)\d?(?:[-_]c)?)?\.[a-z0-9]+$',filename,re.I):return 'release_identifier', f'目录与媒体文件的发行标识 {identity} 一致;画质与版本后缀不作为账号'diff --git a/src/peach/entity_classification.py b/src/peach/entity_classification.pyindex ebcfec384..c33ca889a 100644--- a/src/peach/entity_classification.py+++ b/src/peach/entity_classification.py@@ -93,7 +93,7 @@ def category_predicates(column='e.id', kind_column='e.kind', connection=None):f"WHERE ca.entity_id={column} AND ca.role='creator' AND av.medium='video' ""AND COALESCE(av.disposal,'')<>'vanished')")return {- 'japanese_av': f"{kind_column}='performer' AND ({jav})",+ 'japanese_av': f"{kind_column} IN ('performer','creator') AND ({jav})",'amateur': f"{kind_column}='performer' AND ({amateur})",'western': f"{kind_column}='performer' AND ({western})",'blogger': f"{kind_column}='creator' AND ({creator_video}) AND NOT ({seller}) AND NOT ({animation}) AND NOT ({claim('account_role','studio')})",@@ -118,14 +118,24 @@ def summaries(connection, entity_ids):return result+def index_scope(connection, kind: str) -> str:+ """艺人名册包含真人账号;卖家与动画作者使用独立名册。"""+ predicates = category_predicates(connection=connection)+ if kind == 'performer':+ return "(e.kind='performer' OR (" + predicates['blogger'] + '))'+ if kind == 'creator':+ return '(' + predicates['seller'] + ' OR ' + predicates['animation'] + ')'+ return "e.kind='" + kind + "'"++def counts(connection, kind, query, visible_clause):"""对搜索范围中的有效实体独立计数,不受所选分类及分页限制。"""predicates = category_predicates(connection=connection)sql = ('SELECT ' + ','.join(f'COALESCE(SUM(({value})),0)' for value in predicates.values()) + ' '- 'FROM entity e WHERE e.kind=? AND EXISTS ('+ 'FROM entity e WHERE ' + index_scope(connection, kind) + ' AND EXISTS (''SELECT 1 FROM asset_entity ae CROSS JOIN asset a ON a.id=ae.asset_id ''WHERE ae.entity_id=e.id AND ' + visible_clause + ') ')- params = [kind]+ params = []if query:sql += 'AND e.canonical_name LIKE ? 'params.append(f'%{query}%')diff --git a/src/peach/performer_alias_followup.py b/src/peach/performer_alias_followup.pyindex 453252b86..baf92ba77 100644--- a/src/peach/performer_alias_followup.py+++ b/src/peach/performer_alias_followup.py@@ -170,9 +170,10 @@ def parse_key(key: str) -> int:return int(raw)-def _names(connection: sqlite3.Connection, entity_id: int, *, own: bool = True):+def _names(connection: sqlite3.Connection, entity_id: int, *, own: bool = True, allow_creator: bool = False):"""(规范名, [别名]);实体不在或不是女优返回 None。`own=False` 时不算这条后继自己写的。"""- row = connection.execute("SELECT canonical_name FROM entity WHERE id=? AND kind='performer'",+ kinds = "('performer','creator')" if allow_creator else "('performer')"+ row = connection.execute("SELECT canonical_name FROM entity WHERE id=? AND kind IN " + kinds,(int(entity_id),)).fetchone()if row is None:return None@@ -657,24 +658,26 @@ def fc2cmadb_page(pages: Fc2cmadbPages, codes: list[str], mine: set[str]) -> tup# -- 落库 ---------------------------------------------------------------------def _owners(connection: sqlite3.Connection) -> dict[str, set[int]]:+def _owners(connection: sqlite3.Connection, *, allow_creator: bool = False) -> dict[str, set[int]]:"""折叠键 → 用着这个写法的女优实体。"""owners: dict[str, set[int]] = {}+ kinds = "('performer','creator')" if allow_creator else "('performer')"for entity_id, written in connection.execute(- "SELECT id,canonical_name FROM entity WHERE kind='performer'"+ "SELECT id,canonical_name FROM entity WHERE kind IN " + kinds +" UNION SELECT a.entity_id,a.alias FROM entity_alias a"- " JOIN entity e ON e.id=a.entity_id WHERE e.kind='performer'"):+ " JOIN entity e ON e.id=a.entity_id WHERE e.kind IN " + kinds):if written:owners.setdefault(match_key(str(written)), set()).add(int(entity_id))return ownersdef land(connection: sqlite3.Connection, entity_id: int, expected_name: str, site: str,- url: str, names: list[str], batch: str) -> list[dict]:+ url: str, names: list[str], batch: str, *, allow_latin: bool = False,+ allow_creator: bool = False) -> list[dict]:"""把一页上的写法逐个判完,该写的写进 `entity_alias`。返回每个写法一行判词。"""base = {"entity_id": entity_id, "canonical_name": expected_name, "site": site,"page": url, "batch": ""}- current = _names(connection, entity_id)+ current = _names(connection, entity_id, allow_creator=allow_creator)if current is None:return [{**base, "alias": name, "action": GONE, "detail": "实体不在或不是女优"}for name in names]@@ -682,9 +685,11 @@ def land(connection: sqlite3.Connection, entity_id: int, expected_name: str, sitreturn [{**base, "alias": name, "action": STALE,"detail": f"账本里这条实体现在叫 {current[0]}"} for name in names]have = {normalize_entity_name(name) for name in [current[0], *current[1]]}- owners, rows = _owners(connection), []+ owners, rows = _owners(connection, allow_creator=allow_creator), []for name in dict.fromkeys(names):reason = rejection(name)+ if allow_latin and reason == '罗马字写法':+ reason = '' if len(match_key(name)) >= 4 else '短单名,会命中别人'others = sorted(owners.get(match_key(name), set()) - {entity_id})if reason:rows.append({**base, "alias": name, "action": SKIP, "detail": reason})diff --git a/src/peach/performer_header.py b/src/peach/performer_header.pyindex aa13f1e8a..9038820c7 100644--- a/src/peach/performer_header.py+++ b/src/peach/performer_header.py@@ -203,7 +203,7 @@ def profiled(connection: sqlite3.Connection) -> set[int]:return set()return {int(row[0]) for row in connection.execute(f"SELECT p.entity_id FROM {TABLE} p JOIN entity e ON e.id=p.entity_id"- " AND e.kind='performer'")}+ " AND e.kind IN ('performer','creator')")}def header(connection: sqlite3.Connection, entity_id: int, canonical: str,diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex 52b212ca7..cba01c7d5 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -199,10 +199,10 @@ def q_entity(contract: WebContract, args):"ORDER BY provider,external_kind,external_id",(d["id"],),)]- d.update(_performer_entries(contract, c, d, alias_rows) if kind == "performer"+ d.update(_performer_entries(contract, c, d, alias_rows) if kind == "performer" or 'japanese_av' in d['identity_categories']else {"entry_links": []})- # 页头的五项资料与按名义分组的别名(ADR-0069):只有女优有。- if kind == "performer":+ # 人物资料与按名义分组的别名。+ if kind in {"performer", "creator"}:d.update(performer_header.header(c, d["id"], d["canonical_name"]))scope = scope_predicate(kind, "ae.entity_id")count, rep = c.execute(@@ -566,16 +566,16 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")rows = rows[:limit]elif kind in INDEX_ENTITY_KINDS:entity_kind = INDEX_ENTITY_KINDS[kind]- sql = ("SELECT e.id entity_id,e.canonical_name k,count(DISTINCT " + video_work_key(contract) + ") n,"+ sql = ("SELECT e.id entity_id,e.kind entity_kind,e.canonical_name k,count(DISTINCT " + video_work_key(contract) + ") n,""(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "" WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL " +- (" AND " + solo_performer_clause("a2.id", "e.id") if entity_kind == "performer" else "") ++ (" AND (e.kind='creator' OR (" + solo_performer_clause("a2.id", "e.id") + '))' if entity_kind == "performer" else "") +" ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"" COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep ""FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id ""JOIN asset a ON a.id=ae.asset_id "- "WHERE " + COUNTED_VIDEO + " AND e.kind=? ")- par = [entity_kind]+ "WHERE " + COUNTED_VIDEO + " AND " + entity_classification.index_scope(c,entity_kind) + ' ')+ par = []if q: sql += "AND e.canonical_name LIKE ? "; par.append(f"%{q}%")clause, values = entity_classification.filter_sql(category,connection=c)sql += clause@@ -614,13 +614,14 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")# `/performers` 桌面视口滚三屏实测 77 个取图请求里 5 个是这样的 404。# 判定在库连接之外做,它读的是目录索引而不是账本。for row in rows:- row["has_image"] = contract.has_entity_image(entity_kind, row.get("entity_id"))- row["image_version"] = contract.entity_image_version(entity_kind, row.get("entity_id"))+ row_kind = row.get('entity_kind',entity_kind)+ row["has_image"] = contract.has_entity_image(row_kind, row.get("entity_id"))+ row["image_version"] = contract.entity_image_version(row_kind, row.get("entity_id"))attach_avatar_availability(contract, rows)#: 索引页的大图版式把头像裁成竖幅,几何居中会切掉脸。取景与资料页大图同一份#: sidecar、同一个换算,只是这里按行取;读的是文件,所以放在连接之外。for row in rows:- row["avatar_focus"] = contract.avatar_focus(entity_kind, row["entity_id"])+ row["avatar_focus"] = contract.avatar_focus(row.get('entity_kind',entity_kind), row["entity_id"])#: 公司的门面是它的标识,和资料页大位同一条链:`/logo` 优先,取不到才退回实体图。#: 索引页一屏几十格,缺了这个标志就只能格格出 `<img>` 等 404。if entity_kind in ("studio", "agency"):diff --git a/src/peach/western_artwork.py b/src/peach/western_artwork.pyindex a6599971f..cc9c56193 100644--- a/src/peach/western_artwork.py+++ b/src/peach/western_artwork.py@@ -46,8 +46,8 @@ def _name(name: str) -> str:return re.sub(r'[\W_]+', '', str(name).casefold())-def babepedia_portraits(http: HttpTransport, name: str, aliases=(), *, profile_url: str = '') -> list[dict]:- """只取名字栏与已知身份一致的主图库,推荐与用户上传不参与。"""+def babepedia_page(http: HttpTransport, name: str, aliases=(), *, profile_url: str = '') -> tuple:+ """读取与名字栏或别名明确相符的档案。"""url = profile_url or 'https://www.babepedia.com/babe/' + quote(name.replace(' ', '_'))parsed_profile = urlsplit(url)if (not public_https_url(url) or parsed_profile.hostname not in ('www.babepedia.com', 'babepedia.com')@@ -64,27 +64,40 @@ def babepedia_portraits(http: HttpTransport, name: str, aliases=(), *, profile_uif aka:for label in aka.select('small, #aliasinfobtn'):label.decompose()- listed = {_name(n) for n in aka.get_text(' ', strip=True).split(' - ')} if aka else set()+ alias_names = [n.strip() for n in aka.get_text(' ', strip=True).split(' - ') if n.strip()] if aka else []+ listed = {_name(n) for n in alias_names}if not found or not (known & {_name(found), *listed}):raise ValueError('Babepedia 未取得:档案身份不一致')final = response.url or urlif urlsplit(final).hostname not in ('www.babepedia.com', 'babepedia.com'):raise ValueError('Babepedia 未取得:来源域名不一致')+ return soup, final, found, alias_names+++def babepedia_portraits(http: HttpTransport, name: str, aliases=(), *, profile_url: str = '') -> list[dict]:+ """主图与本人档案图库作为候选;推荐人物不参与。"""+ soup, final, found, _ = babepedia_page(http, name, aliases, profile_url=profile_url)portraits = []seen = set()- for link in soup.select('#profbox2 a.img[href]'):+ for link in soup.select('#profbox2 a.img[href], .useruploads2 a.img[href]'):image = urljoin(final, str(link['href']))parsed = urlsplit(image)+ primary = parsed.path.startswith('/pics/') and link.find_parent(id='profbox2') is not None+ thumbnail = link.find('img')+ gallery = (parsed.path.startswith('/user-uploads/') and thumbnail is not None+ and _name(thumbnail.get('alt', '')) == _name(found)+ and link.find_parent(class_='useruploads2') is not None)if (parsed.hostname not in ('www.babepedia.com', 'babepedia.com')- or not parsed.path.startswith('/pics/') or not public_https_url(image)+ or not (primary or gallery) or not public_https_url(image)or image in seen):continueseen.add(image)portraits.append({'provider': 'babepedia', 'source_kind': 'external_media_library','upstream_url': image, 'profile_url': final,'external_id': f'babepedia:{found}', 'matched_name': found,- 'name_source': 'babepedia-profile', 'identity_verified': True})- if len(portraits) == 4:+ 'name_source': 'babepedia-profile', 'identity_verified': True,+ 'automatic_install': primary})+ if len(portraits) == 48:breakreturn portraitsdiff --git a/src/peach/western_profiles.py b/src/peach/western_profiles.pynew file mode 100644index 000000000..9c6e0fffa--- /dev/null+++ b/src/peach/western_profiles.py@@ -0,0 +1,96 @@+"""Babepedia 档案资料、别名和本人链接;保留原始页面字段。"""+from __future__ import annotations++import re+import json+from datetime import date+from datetime import datetime, timezone+from urllib.parse import urljoin, urlsplit++from .http import public_https_url+from .western_artwork import babepedia_page+from .performer_profiles import read_profile, write_profile+from .performer_alias_followup import land as land_aliases++MONTHS = {name: i for i, name in enumerate(('January', 'February', 'March', 'April', 'May',+ 'June', 'July', 'August', 'September', 'October', 'November', 'December'), 1)}+LINK_NAMES = {'www': '官网', 'instagram': 'Instagram', 'x': 'X', 'tiktok': 'TikTok',+ 'onlyfans': 'OnlyFans', 'onlyfansfree': 'OnlyFans', 'twitch': 'Twitch',+ 'imdb': 'IMDb', 'iafd': 'IAFD', 'facebook': 'Facebook', 'youtube': 'YouTube'}+++def profile(http, name: str, aliases=(), *, profile_url='') -> dict:+ """明确名字匹配后解析资料;缺失与无法解析的值保持空。"""+ soup, url, found, names = babepedia_page(http, name, aliases, profile_url=profile_url)+ fields = {}+ for item in soup.select('#personal-info-block .info-item'):+ label, value = item.select_one('.label'), item.select_one('.value')+ if label is not None and value is not None:+ key = label.get_text(' ', strip=True).rstrip(':')+ fields[key] = value.get_text(' ', strip=True)+ result = {'raw': {**fields, '名前': found, '別名': names}, 'tags': []}+ born = re.search(r'(\d{1,2})(?:st|nd|rd|th) of ([A-Za-z]+) (\d{4})', fields.get('Born', ''))+ if born and born[2] in MONTHS:+ try:+ result['birth_date'] = date(int(born[3]), MONTHS[born[2]], int(born[1])).isoformat()+ except ValueError:+ pass+ height = re.search(r'(\d{2,3})\s*cm\b', fields.get('Height', ''))+ if height:+ result['height_cm'] = int(height[1])+ sizes = re.match(r'(\d+(?:\.\d+)?)\s*[–-]\s*(\d+(?:\.\d+)?)\s*[–-]\s*(\d+(?:\.\d+)?)\s*(in|cm)\b', fields.get('Measurements', ''))+ if sizes:+ for key, number in zip(('bust_cm', 'waist_cm', 'hip_cm'), sizes.groups()[:3]):+ result[key] = round(float(number) * (2.54 if sizes[4] == 'in' else 1))+ # 采用页面明示的日本尺码,避免把英美罩杯当成日本罩杯。+ cup = re.search(r'\bJP:\s*\d+([A-Z]+)', fields.get('Bra/cup size', ''))+ if cup:+ result['cup'] = cup[1]+ years = re.match(r'(\d{4})\s*[-–]\s*(present|\d{4})\b', fields.get('Years active', ''))+ if years:+ result['debut_year'] = int(years[1])+ if years[2] != 'present':+ result['active_until'] = int(years[2])+ birthplace = fields.get('Birthplace', '')+ if birthplace:+ result['birthplace'] = re.sub(r'\s*\(#\d+\)', '', birthplace).strip()+ links = []+ for anchor in soup.select('#socialicons a[href]'):+ target = urljoin(url, str(anchor['href']))+ icon = next((key for key in anchor.get('class', []) if key in LINK_NAMES), '')+ if not icon or not public_https_url(target):+ continue+ links.append({'url': target, 'label': LINK_NAMES[icon],+ 'link_kind': 'official' if icon == 'www' else+ ('catalog' if icon in {'iafd', 'imdb'} else 'social')})+ if icon == 'www':+ result.setdefault('site_url', target)+ return {'matched_name': found, 'aliases': names, 'profile_url': url,+ 'profile': result, 'links': links}+++def land(connection, entity_id: int, expected_name: str, record: dict, *, batch: str) -> dict:+ """仅补空资料,别名走同名占用判据,现有链接保留。调用方持有事务。"""+ current = connection.execute('SELECT kind,canonical_name FROM entity WHERE id=?', (entity_id,)).fetchone()+ if not current or current[0] not in ('performer', 'creator') or current[1] != expected_name:+ raise ValueError('艺人身份已变化,请重新预览')+ held = read_profile(connection, entity_id)+ written = False+ if held is None:+ written = write_profile(connection, entity_id, record['profile'], source=batch,+ source_url=record['profile_url'])+ aliases = land_aliases(connection, entity_id, expected_name, 'Babepedia', record['profile_url'],+ [record['matched_name'], *record['aliases']], batch, allow_latin=True,+ allow_creator=True)+ added = []+ stamp = datetime.now(timezone.utc).isoformat()+ for link in record['links']:+ url = link['url']+ if connection.execute('SELECT 1 FROM entity_link WHERE entity_id=? AND url=?', (entity_id,url)).fetchone():+ continue+ metadata = json.dumps({'source':batch, 'source_url':record['profile_url']}, ensure_ascii=False)+ cursor = connection.execute('INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,metadata_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)',+ (entity_id, link['link_kind'], link['label'], url, urlsplit(url).hostname, metadata,stamp,stamp))+ added.append(cursor.lastrowid)+ return {'entity_id':entity_id,'name':expected_name,'profile_written':written,+ 'preserved_profile':held is not None,'aliases':aliases,'added_links':added,'source':batch}diff --git a/tests/test_entity_classification.py b/tests/test_entity_classification.pyindex 3560448b2..5bcc80d11 100644--- a/tests/test_entity_classification.py+++ b/tests/test_entity_classification.py@@ -52,11 +52,11 @@ class EntityClassificationTests(unittest.TestCase):self.claim(known,'account_role','seller')classification.write_claim(self.connection,entity_id=unknown,facet='account_role',value='seller',source='script:lookup',evidence='同名搜索命中')self.connection.commit()- data=q_index(WebContract(self.db),'creators',limit=1,category='blogger')+ data=q_index(WebContract(self.db),'performers',limit=1,category='blogger')self.assertEqual([row['entity_id'] for row in data['items']],[unknown])self.assertFalse(data['has_more'])self.assertEqual(data['items'][0]['identity_labels'],['网黄博主'])- self.assertEqual(data['categories'],{'blogger':1,'seller':1})+ self.assertEqual(data['categories'],{'blogger':1})self.assertEqual(q_index(WebContract(self.db),'creators',category='seller')['items'][0]['entity_id'],known)self.assertEqual(q_index(WebContract(self.db),'creators',category="person' OR 1=1")['items'],[])@@ -103,7 +103,7 @@ class EntityClassificationTests(unittest.TestCase):self.connection.execute("UPDATE asset SET disposal='vanished' WHERE id=?",(asset_id,))self.connection.commit()data = q_index(WebContract(self.db),'creators',q='Match',limit=1,category='seller')- self.assertEqual(data['categories'],{'blogger':1,'seller':1})+ self.assertEqual(data['categories'],{'seller':1})self.assertEqual([row['entity_id'] for row in data['items']],[seller])def test_fc2_cast_and_western_release_filters_allow_multiple_memberships(self):@@ -128,7 +128,21 @@ class EntityClassificationTests(unittest.TestCase):self.connection.commit()page = q_index(WebContract(self.db),'creators',category='animation')self.assertEqual([row['entity_id'] for row in page['items']],[animator])- self.assertEqual(page['categories'],{'blogger':1,'animation':1})+ self.assertEqual(page['categories'],{'animation':1})++ def test_real_accounts_share_artist_directory_and_keep_avatars_and_profile_routes(self):+ _, actor = self.entity('Actor', kind='performer')+ _, blogger = self.entity('Blogger')+ _, seller = self.entity('Seller')+ _, animator = self.entity('Animator')+ self.claim(seller,'account_role','seller')+ self.claim(animator,'occupation','animator')+ self.connection.commit()+ artists = q_index(WebContract(self.db),'performers')+ self.assertCountEqual([row['entity_id'] for row in artists['items']],[actor,blogger])+ self.assertEqual({row['entity_id']:row['entity_kind'] for row in artists['items']},{actor:'performer',blogger:'creator'})+ separate = q_index(WebContract(self.db),'creators')+ self.assertCountEqual([row['entity_id'] for row in separate['items']],[seller,animator])def test_western_cast_occupation_does_not_assert_a_japanese_av_career(self):_, entity_id = self.entity('Western Performer',kind='performer')diff --git a/tests/test_metadata_creator_attributions.py b/tests/test_metadata_creator_attributions.pyindex 1f07ed3df..7c95c6be2 100644--- a/tests/test_metadata_creator_attributions.py+++ b/tests/test_metadata_creator_attributions.py@@ -71,7 +71,7 @@ class CreatorAttributionTests(unittest.TestCase):self.assertEqual(len(self.plan()),3)self.assertEqual(self.connection.execute('PRAGMA foreign_key_check').fetchall(),[])- def test_versioned_release_and_publisher_numbers_require_matching_files(self):+ def test_versioned_release_directories_and_publisher_numbers_are_excluded(self):samples = {'WAAA-415_6K-C':r'B:\云下载\WAAA-415_6K-C\@[email protected]_WAAA-415_6K-C.mp4','wavr00178pl':r'B:\云下载\wavr00178pl\wavr00178.part1.mp4',@@ -86,6 +86,28 @@ class CreatorAttributionTests(unittest.TestCase):self.asset('ABW-987',path=r'B:\创作者\ABW-987\another title.mp4')self.assertCountEqual([row['current_creator'] for row in self.plan()],samples)+ def test_release_directory_does_not_assign_its_code_to_unrelated_files(self):+ examples = [('WAAA-415_6K-C', 'HMN-597.mp4'),+ ('WAAA-415_6K-C', 'daily life.mp4'),+ ('gachincoppv-1009-HD', 'gachincoppv-1009-HD1.wmv'),+ ('gachincoppv-1009-HD', 'gachincoppv-1009-HD3.wmv')]+ ids = []+ for name, filename in examples:+ asset_id, _ = self.asset(name, path=f'B:\\云下载\\{name}\\{filename}')+ ids.append(asset_id)+ self.assertIsNone(upsert_asset_entity(self.connection,kind='creator',name=name,+ asset_id=asset_id,role='creator',source='scan:directory'))+ self.asset('banbi_555', path=r'B:\创作者\banbi_555\holiday.mp4')+ frozen = self.plan()+ self.assertCountEqual([row['asset_id'] for row in frozen], ids)+ with self.connection:+ receipt = apply_plan(self.connection, frozen)+ self.assertEqual(self.connection.execute('SELECT count(*) FROM asset WHERE creator IS NULL AND code IS NULL').fetchone()[0], 4)+ self.assertEqual(self.connection.execute('SELECT count(*) FROM asset').fetchone()[0], 5)+ with self.connection:+ restore(self.connection, receipt)+ self.assertCountEqual([row['asset_id'] for row in self.plan()], ids)+def test_tokyo_publisher_requires_registered_studio_and_matching_release_file(self):asset_id,_ = self.asset('Tokyo',studio='东京热',code='n1042',path=r'B:\云下载\TokyoHot-n1042.mp4')studio_id = upsert_asset_entity(self.connection,kind='studio',name='东京热',diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex ab4e19419..459f73b1d 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -559,7 +559,8 @@ class WebDataTests(unittest.TestCase):"""def flags(kind):return [(row["k"], row["has_image"], row["has_avatar"])- for row in rm_web.q_index(self.contract, kind, limit=10)["items"]]+ for row in rm_web.q_index(self.contract, 'performers', limit=10)["items"]+ if row['entity_kind'] == {'performers':'performer','creators':'creator'}[kind]]self.assertEqual(flags("performers"), [("Canonical Alice", False, False)])self.assertEqual(flags("creators"), [("Canonical Creator", False, False)])diff --git a/tests/test_western_profiles.py b/tests/test_western_profiles.pynew file mode 100644index 000000000..57eb1906c--- /dev/null+++ b/tests/test_western_profiles.py@@ -0,0 +1,91 @@+"""西方档案身份、单位转换、别名及链接边界。"""+import unittest+import sqlite3+import tempfile+from pathlib import Path+from contextlib import closing++from peach.http import HttpResponse+from peach.western_profiles import profile, land+from peach.western_artwork import babepedia_portraits+from peach.performer_header import header, profiled+from tests.support.ledger import fresh_ledger+++class WesternProfileTests(unittest.TestCase):+ def page(self, extra='', name='Christy White'):+ return f'<h1 id="babename">{name}</h1><h2 id="aka"><small>Also known as:</small>Christine White - Christina Andreadou<img id="aliasinfobtn"></h2><div id="personal-info-block">{extra}</div>'.encode()++ def cell(self, label, value):+ return f'<div class="info-item"><span class="label">{label}:</span><span class="value">{value}</span></div>'++ def test_units_dates_aliases_and_profile_links(self):+ body = self.page(''.join(self.cell(label,value) for label,value in (+ ('Born','Monday 17th of September 2001'), ('Height', '5\'6" (or 167 cm)'),+ ('Measurements','34–26–34 in (B–W–H)'), ('Bra/cup size','32B - JP: 70C'),+ ('Years active','2021-present'), ('Birthplace','Thessaloniki, Greece (#20)'))))+ body += b'<div id="socialicons"><a class="proficon x" href="https://x.com/Christy_whitee">X</a><a class="proficon www" href="https://linktr.ee/christywhite_">Web</a><a class="proficon x" href="https://localhost/">bad</a></div>'+ got = profile(lambda *a: HttpResponse(200,{},body),'Christy White')+ facts = got['profile']+ self.assertEqual(facts['birth_date'],'2001-09-17')+ self.assertEqual([facts[k] for k in ('height_cm','bust_cm','waist_cm','hip_cm')],[167,86,66,86])+ self.assertEqual(facts['cup'],'C')+ self.assertEqual(facts['debut_year'],2021)+ self.assertNotIn('active_until',facts)+ self.assertEqual(facts['birthplace'],'Thessaloniki, Greece')+ self.assertEqual(got['aliases'],['Christine White','Christina Andreadou'])+ self.assertEqual(len(got['links']),2)+ self.assertIn('Born',facts['raw'])++ def test_invalid_dates_and_unspecified_units_are_not_invented(self):+ body = self.page(self.cell('Born','31st of February 2000') + self.cell('Measurements','34-26-34')+ + self.cell('Bra/cup size','32B') + self.cell('Years active','2015-2025'))+ facts = profile(lambda *a:HttpResponse(200,{},body),'Christy White')['profile']+ for key in ('birth_date','bust_cm','cup'):+ self.assertNotIn(key,facts)+ self.assertEqual(facts['active_until'],2025)++ def test_babepedia_alias_identity_is_required_for_all_profile_fields(self):+ with self.assertRaisesRegex(ValueError,'身份不一致'):+ profile(lambda *a:HttpResponse(200,{},self.page()),'Someone Else')++ def test_creator_profile_and_aliases_share_the_person_header(self):+ with tempfile.TemporaryDirectory() as directory, closing(sqlite3.connect(fresh_ledger(Path(directory).resolve()))) as connection:+ entity_id = connection.execute("INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) VALUES('creator','RiaKurumi','riakurumi','t','t')").lastrowid+ body = b'<h1 id="babename">Ria Kurumi</h1><h2 id="aka"><small>Also known as:</small>Kurumi Momota - Momo Ichinose - \xe7\x99\xbe\xe7\x94\xb0\xe3\x81\x8f\xe3\x82\x8b\xe3\x81\xbf</h2>'+ body += ('<div id="personal-info-block">' + self.cell('Height','149 cm') + '</div>').encode()+ record = profile(lambda *a:HttpResponse(200,{},body),'RiaKurumi')+ with connection:+ result = land(connection,entity_id,'RiaKurumi',record,batch='auto:babepedia-profile@creator')+ self.assertTrue(result['profile_written'])+ self.assertIn(entity_id,profiled(connection))+ facts = header(connection,entity_id,'RiaKurumi')+ self.assertEqual(facts['profile']['height'],149)+ self.assertIn('Kurumi Momota',[r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?',(entity_id,))])+ self.assertGreater(facts['name_groups']['total'],1)++ def test_named_person_gallery_adds_candidates_and_excludes_other_people(self):+ body = self.page() + b'<div id="profbox2"><a class="img" href="/pics/Christy.jpg"></a></div><div class="useruploads2"><a class="img" href="/user-uploads/Christy.jpg"><img alt="Christy White"></a><a class="img" href="/user-uploads/Other.jpg"><img alt="Someone Else"></a></div><a class="img" href="/pics/related.jpg"><img alt="Christy White"></a>'+ found = babepedia_portraits(lambda *a:HttpResponse(200,{},body),'Christy White')+ self.assertEqual(len(found),2)+ self.assertEqual([p['automatic_install'] for p in found],[True,False])++ def test_profile_landing_preserves_existing_profile_and_links_and_alias_owners(self):+ with tempfile.TemporaryDirectory() as directory, closing(sqlite3.connect(fresh_ledger(Path(directory).resolve()))) as connection:+ entity_id = connection.execute("INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) VALUES('performer','Christy White','christy white','t','t')").lastrowid+ connection.execute("INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) VALUES('performer','Christine White','christine white','t','t')")+ record = profile(lambda *a: HttpResponse(200,{},self.page(self.cell('Height','167 cm'))+ + b'<div id="socialicons"><a class="proficon x" href="https://x.com/christy">X</a></div>'),'Christy White')+ with connection:+ first = land(connection,entity_id,'Christy White',record,batch='auto:babepedia-profile@test')+ self.assertTrue(first['profile_written'])+ self.assertEqual(len(first['added_links']),1)+ self.assertEqual(connection.execute('SELECT count(*) FROM entity_alias WHERE entity_id=? AND normalized_alias=?',(entity_id,'christine white')).fetchone()[0],0)+ self.assertEqual(connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?',(entity_id,)).fetchall(),[('Christina Andreadou',)])+ record['profile']['height_cm'] = 170+ with connection:+ second = land(connection,entity_id,'Christy White',record,batch='auto:babepedia-profile@test2')+ self.assertTrue(second['preserved_profile'])+ self.assertEqual(second['added_links'],[])+ self.assertEqual(connection.execute('SELECT height_cm FROM performer_profile WHERE entity_id=?',(entity_id,)).fetchone()[0],167)+ self.assertEqual(connection.execute('PRAGMA foreign_key_check').fetchall(),[])