Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(entity): observed 只属于代码判据

longmeidaofcbdf2275b02
diff --git a/docs/adr/0095-entity-classification.md b/docs/adr/0095-entity-classification.md
index df559c5e0..faf8296d1 100644
--- a/docs/adr/0095-entity-classification.md
+++ b/docs/adr/0095-entity-classification.md
@@ -4,7 +4,7 @@
`performer` 表示出演者,`creator` 表示发布账号,`studio` 表示发行机构。作品关系不直接断言职业、国籍或性别。日本 AV 与西方成人发行是可并存的发行市场,不是互斥的人物身份。
-身份事实使用独立的多值来源断言:身份类型、职业、发行市场、账号角色。每条记录保留来源 URL、证据、置信度、核验时间与状态。目录推断和搜索命中保持 candidate;公开来源的确定事实使用 observed;用户复核才能 approved。
+身份事实使用独立的多值来源断言:身份类型、职业、发行市场、账号角色。每条记录保留来源 URL、证据、置信度、核验时间与状态。状态按 ADR-0052 决策一划分:observed 只属于代码判据,即抓取器从来源页解析出的 `source:` 事实与 FC2 作品页快照解析出的卖家;目录推断、搜索命中与人或智能体读页面写成的研究清单都是 candidate;用户复核才能 approved。`write_claim` 拒绝其他来源写 observed,查询侧的可信口径(`trusted_sql`)与它一致。
浏览分类是查询时生成的显示投影:艺人页为女优、素人、西方,允许同一个人同时命中多类。女优复用 `entry_links.JAV_DIRECTORIES` 的已绑定 performer id 或可信日本 AV 市场断言;素人按有效 FC2 出演作品或作品的素人标签分类;西方采用可信市场断言或作品发行地区。素人表示作品类型,不断言职业经历。MinnanoAV 的 production id、Stash 本机 id、Babepedia 的普通收录与候选不单独证明 JAV 身份。发布账号分为网黄博主、卖家、动画作者,后两类分别需要可信 seller、animator 断言。待核验是来源状态,不作为浏览分类。分类计数按搜索和有效作品计算,每类独立计数,筛选条隐藏空分类。
diff --git a/scripts/repair_identity_claims.py b/scripts/repair_identity_claims.py
new file mode 100644
index 000000000..5a37e3d1b
--- /dev/null
+++ b/scripts/repair_identity_claims.py
@@ -0,0 +1,103 @@
+"""存量身份数据的两项修正,默认只列计划。
+
+- `--downgrade`:标成 observed 却不出自代码判据(`source:`、`script:fc2-seller@`)的分类断言与
+ 身份关联降为 candidate,等用户复核(ADR-0052 决策一)。来源、证据与检查时间不变。
+- `--directories`:某账号在一个目录子树里的每件有效作品都已被逐个否定时,补一条目录级否定,
+ 以后进入该目录的新文件不再归给这个账号。只留最上层目录,不顺带否定任何未被否定的作品。
+
+两项都不给时两项都列。`--report` 把完整计划写成 JSON;`--apply` 必须同时给 `--backup`,
+在一个事务里写完并做完整性与外键自检。
+
+ repair_identity_claims.py --report build/identity-claims.json
+ repair_identity_claims.py --downgrade --apply --backup <备份路径>
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
+
+from peach.entities import apply_directory_rejections, derived_directory_rejections # noqa: E402
+from peach.entity_classification import downgrade_untrusted_observed, untrusted_observed # noqa: E402
+from peach.field_owners import script_owner # noqa: E402
+from peach.fsutil import atomic_write_text # noqa: E402
+from peach.scripting import add_ledger_write_args, counts_of, open_for_write, verify_after_write # noqa: E402
+
+REVIEWER = script_owner('repair_identity_claims')
+EXTRA_COUNTS = {
+ 'observed_claims': "SELECT count(*) FROM entity_classification WHERE status='observed'",
+ 'candidate_claims': "SELECT count(*) FROM entity_classification WHERE status='candidate'",
+ 'attribution_rejections': "SELECT count(*) FROM review_decision WHERE category='creator-attribution' AND status='rejected'",
+}
+
+
+def build_plan(connection, *, downgrade: bool, directories: bool) -> dict:
+ plan = {}
+ if downgrade:
+ plan['downgrade'] = untrusted_observed(connection)
+ if directories:
+ plan['directories'] = derived_directory_rejections(connection)
+ return plan
+
+
+def summary(plan: dict) -> dict:
+ result = {}
+ if 'downgrade' in plan:
+ result['downgrade'] = {table: _by_source(rows) for table, rows in plan['downgrade'].items()}
+ if 'directories' in plan:
+ result['directories'] = [{key: row[key] for key in ('name', 'directory', 'subtree_assets', 'name_rejections')}
+ for row in plan['directories']]
+ return result
+
+
+def _by_source(rows) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for row in rows:
+ counts[row['source']] = counts.get(row['source'], 0) + 1
+ return counts
+
+
+def main(argv=None) -> int:
+ parser = add_ledger_write_args(argparse.ArgumentParser(description='存量身份断言降级与目录级否定'))
+ parser.add_argument('--downgrade', action='store_true', help='只处理非代码判据的 observed 降级')
+ parser.add_argument('--directories', action='store_true', help='只处理由作品级否定派生的目录级否定')
+ parser.add_argument('--report', type=Path, help='完整计划写成 JSON')
+ args = parser.parse_args(argv)
+ both = not (args.downgrade or args.directories)
+ selected = {'downgrade': args.downgrade or both, 'directories': args.directories or both}
+ connection = open_for_write(args)
+ try:
+ plan = build_plan(connection, **selected)
+ if args.report:
+ atomic_write_text(args.report, json.dumps(plan, ensure_ascii=False, indent=2))
+ output = {'plan': summary(plan)}
+ if args.apply:
+ connection.execute('BEGIN IMMEDIATE')
+ output['before'] = counts_of(connection, EXTRA_COUNTS)
+ _, known_violations = verify_after_write(connection)
+ if selected['downgrade']:
+ output['downgraded'] = downgrade_untrusted_observed(connection)
+ if selected['directories']:
+ output['directory_rejections'] = apply_directory_rejections(
+ connection, plan['directories'], reviewer=REVIEWER)
+ integrity, violations = verify_after_write(connection)
+ if integrity != 'ok' or violations > known_violations:
+ connection.rollback()
+ print(json.dumps({'error': '完整性或外键自检未通过', 'integrity': integrity,
+ 'foreign_key_violations': violations}, ensure_ascii=False), file=sys.stderr)
+ return 1
+ connection.commit()
+ output['after'] = counts_of(connection, EXTRA_COUNTS)
+ else:
+ output['dry_run'] = '未写 ledger;加 --apply --backup <路径> 才写入'
+ print(json.dumps(output, ensure_ascii=False, indent=2))
+ finally:
+ connection.close()
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/src/peach/entities.py b/src/peach/entities.py
index 2004cf5dc..d18c6d03b 100644
--- a/src/peach/entities.py
+++ b/src/peach/entities.py
@@ -537,11 +537,12 @@ def _creator_ingest_identity(connection, name, asset_id):
and _creator_attribution_rejected(connection, (original, base, name), asset_id, asset[0] if asset else '')):
return ''
if connection.execute("SELECT 1 FROM sqlite_schema WHERE name='entity_classification'").fetchone():
+ from .entity_classification import trusted_sql
normalized = normalize_entity_name(name)
normalized_base = normalize_entity_name(base)
if connection.execute("SELECT 1 FROM entity e JOIN entity_classification ec ON ec.entity_id=e.id "
"WHERE e.kind IN ('creator','studio') AND ec.facet='account_role' "
- "AND ec.value='studio' AND ec.status IN ('observed','approved') "
+ "AND ec.value='studio' AND " + trusted_sql('ec') + " "
"AND (e.normalized_name IN (?,?) OR EXISTS (SELECT 1 FROM entity_alias al "
"WHERE al.entity_id=e.id AND al.normalized_alias IN (?,?)))",
(normalized, normalized_base, normalized, normalized_base)).fetchone():
diff --git a/src/peach/entity_classification.py b/src/peach/entity_classification.py
index 1e83dd8a1..d17164014 100644
--- a/src/peach/entity_classification.py
+++ b/src/peach/entity_classification.py
@@ -16,12 +16,44 @@ VALUES = {
}
CATEGORIES = {'japanese_av': '女优', 'amateur': '素人', 'western': '西方',
'blogger': '网黄博主', 'seller': '卖家', 'animation': '动画作者'}
-TRUSTED = "status IN ('observed','approved')"
+#: observed 只属于代码判据(ADR-0052 决策一):`source:` 是抓取器从来源页解析出的事实,
+#: `script:fc2-seller@` 由 FC2 作品页快照的卖家字段解析。研究与检索结论只写 candidate。
+CODE_SOURCES = ('source:', 'script:fc2-seller@')
+
+
+def _code_source_sql(column: str) -> str:
+ return '(' + ' OR '.join(f"{column}source LIKE '{prefix}%'" for prefix in CODE_SOURCES) + ')'
+
+
+def trusted_sql(alias: str = '') -> str:
+ """可信断言:用户复核,或代码判据来源的 observed。"""
+ column = f'{alias}.' if alias else ''
+ return f"({column}status='approved' OR ({column}status='observed' AND {_code_source_sql(column)}))"
+
+
+_UNTRUSTED_OBSERVED = "status='observed' AND NOT " + _code_source_sql('')
+_CLAIM_TABLES = ('entity_classification', 'entity_identity_link')
+
+
+def untrusted_observed(connection) -> dict[str, list[dict]]:
+ """标成 observed 却不出自代码判据的断言与身份关联,即存量降级计划。"""
+ plan = {}
+ for table in _CLAIM_TABLES:
+ cursor = connection.execute(f'SELECT * FROM {table} WHERE {_UNTRUSTED_OBSERVED} ORDER BY rowid')
+ columns = [column[0] for column in cursor.description]
+ plan[table] = [dict(zip(columns, row)) for row in cursor]
+ return plan
+
+
+def downgrade_untrusted_observed(connection) -> dict[str, int]:
+ """这些行降为 candidate 等用户复核;来源、证据、置信度与检查时间原样保留。"""
+ return {table: connection.execute(f"UPDATE {table} SET status='candidate' WHERE {_UNTRUSTED_OBSERVED}").rowcount
+ for table in _CLAIM_TABLES}
def write_claim(connection, *, entity_id, facet, value, source, evidence,
source_url='', status='candidate', confidence=0.5, checked_at=None):
- """目录与检索推断保持 candidate,公开来源事实使用 observed,用户复核使用 approved。"""
+ """目录、检索与研究推断保持 candidate,代码判据事实使用 observed,用户复核使用 approved。"""
if facet not in VALUES or value not in VALUES[facet]:
raise ValueError('未知身份分类')
if status not in {'candidate','observed','approved','rejected'}:
@@ -32,8 +64,8 @@ def write_claim(connection, *, entity_id, facet, value, source, evidence,
raise ValueError('approved 只属于用户复核')
if status == 'observed' and urlsplit(source_url).scheme != 'https':
raise ValueError('公开事实需要 HTTPS 来源')
- if status == 'observed' and not source.startswith(('source:', 'script:')):
- raise ValueError('公开事实需要明确来源命名空间')
+ if status == 'observed' and not source.startswith(CODE_SOURCES):
+ raise ValueError('observed 只属于代码判据来源')
# 脚本不覆盖同来源上的用户复核。
old = connection.execute('SELECT status FROM entity_classification WHERE entity_id=? AND facet=? AND value=? AND source=?',
(entity_id,facet,value,source)).fetchone()
@@ -74,7 +106,7 @@ def category_predicates(column='e.id', kind_column='e.kind', connection=None):
if not has_claims:
return '0'
return (f"EXISTS (SELECT 1 FROM entity_classification ec WHERE ec.entity_id={column} "
- f"AND ec.facet='{facet}' AND ec.value='{value}' AND {TRUSTED})")
+ f"AND ec.facet='{facet}' AND ec.value='{value}' AND {trusted_sql('ec')})")
def work(condition):
return (f"EXISTS (SELECT 1 FROM asset_entity ca JOIN asset av ON av.id=ca.asset_id "
f"WHERE ca.entity_id={column} AND ca.role='performer' AND av.medium='video' "
@@ -126,10 +158,10 @@ def work_portrait_predicate(connection, column='e.id', kind_column='e.kind'):
if not connection.execute("SELECT 1 FROM sqlite_schema WHERE name='entity_classification'").fetchone():
return f"{kind_column}<>'creator'"
return (f"({kind_column}<>'creator' OR EXISTS (SELECT 1 FROM entity_classification ec "
- f"WHERE ec.entity_id={column} AND ec.{TRUSTED} "
+ f"WHERE ec.entity_id={column} AND {trusted_sql('ec')} "
"AND ((ec.facet='identity' AND ec.value='person') "
"OR (ec.facet='occupation' AND ec.value IN ('adult_performer','model','actor')))) "
- f"AND NOT EXISTS (SELECT 1 FROM entity_classification ec WHERE ec.entity_id={column} AND ec.{TRUSTED} "
+ f"AND NOT EXISTS (SELECT 1 FROM entity_classification ec WHERE ec.entity_id={column} AND {trusted_sql('ec')} "
"AND ((ec.facet='occupation' AND ec.value='animator') "
"OR (ec.facet='account_role' AND ec.value IN ('seller','studio')) "
"OR (ec.facet='identity' AND ec.value IN ('organization','platform','collection','release')))))")
@@ -144,7 +176,7 @@ def index_scope(connection, kind: str) -> str:
return ("(e.kind='performer' OR (e.kind='creator' AND (NOT (" + predicates['seller'] + ") "
"OR (" + predicates['blogger'] + ") OR (" + predicates['animation'] + ")) "
"AND NOT EXISTS (SELECT 1 FROM entity_classification ec WHERE ec.entity_id=e.id "
- "AND ec.status IN ('observed','approved') AND ((ec.facet='account_role' AND ec.value='studio') "
+ "AND " + trusted_sql('ec') + " AND ((ec.facet='account_role' AND ec.value='studio') "
"OR (ec.facet='identity' AND ec.value IN ('organization','platform','collection','release'))))))")
if kind == 'creator':
return '(' + predicates['seller'] + ')'
@@ -171,7 +203,7 @@ def related_identities(connection, entity_id):
return []
cursor = connection.execute("SELECT e.id,e.kind,e.canonical_name,l.relation,l.source_url,l.evidence "
"FROM entity_identity_link l JOIN entity e ON e.id=CASE WHEN l.left_id=? THEN l.right_id ELSE l.left_id END "
- "WHERE (l.left_id=? OR l.right_id=?) AND l.status IN ('observed','approved') ORDER BY e.kind,e.canonical_name",
+ "WHERE (l.left_id=? OR l.right_id=?) AND " + trusted_sql('l') + " ORDER BY e.kind,e.canonical_name",
(entity_id,entity_id,entity_id))
columns = [column[0] for column in cursor.description]
return [dict(zip(columns,raw)) for raw in cursor]
diff --git a/src/peach/entity_identity_research.py b/src/peach/entity_identity_research.py
index 9c028f2a4..d84ca7fe9 100644
--- a/src/peach/entity_identity_research.py
+++ b/src/peach/entity_identity_research.py
@@ -1,4 +1,8 @@
-"""公开身份来源与馆藏署名的衔接;冻结计划和逐行回执保持可撤回。"""
+"""公开身份来源与馆藏署名的衔接;冻结计划和逐行回执保持可撤回。
+
+研究清单由人或智能体读页面后写成,不是代码判据:分类断言与身份关联一律落 candidate,
+等用户复核后才 approved(ADR-0052 决策一)。
+"""
from __future__ import annotations
import re
@@ -74,7 +78,7 @@ def apply(connection, frozen):
'params':[entity_id,performer_id,SOURCE], 'before':_rows(connection,'entity_identity_link','left_id=? AND right_id=? AND source=?',(entity_id,performer_id,SOURCE))})
connection.execute('INSERT OR IGNORE INTO entity_identity_link VALUES(?,?,?,?,?,?,?,?)',
(entity_id,performer_id,'same_person',SOURCE,finding['cast_source_url'],
- '发行文件完整署名与公开出演者身份一致','observed',stamp))
+ '发行文件完整署名与公开出演者身份一致','candidate',stamp))
for cast in row['cast']:
asset_id = cast['asset']['id']
receipt['changes'].append({'table':'asset_entity','clause':"asset_id=? AND (entity_id=? OR (entity_id=? AND source=?))",
@@ -96,7 +100,8 @@ def apply(connection, frozen):
receipt['changes'].append({'table':'entity_classification','clause':'entity_id=? AND source=?','params':[target,SOURCE],
'before':_rows(connection,'entity_classification','entity_id=? AND source=?',(target,SOURCE))})
for claim in finding['claims']:
- write_claim(connection, entity_id=target, source=SOURCE, **claim)
+ status = 'rejected' if claim.get('status') == 'rejected' else 'candidate'
+ write_claim(connection, entity_id=target, source=SOURCE, **{**claim, 'status': status})
for change in receipt['changes']:
change['after'] = _rows(connection,change['table'],change['clause'],change['params'])
return receipt
diff --git a/src/peach/fc2_sellers.py b/src/peach/fc2_sellers.py
index fec2f18da..17dcbaa29 100644
--- a/src/peach/fc2_sellers.py
+++ b/src/peach/fc2_sellers.py
@@ -12,7 +12,7 @@ from urllib.parse import urlsplit
from .catalog_rules import normalise_code_key
from .classification import creator_collection_base
from .entities import canonicalize_entity_name, normalize_entity_name, upsert_asset_entity
-from .entity_classification import write_claim
+from .entity_classification import trusted_sql, write_claim
SOURCE = 'script:fc2-seller'
PROVIDERS = {'fc2ppvdb': 'fc2ppv-db.com', 'fc2cmadb': 'fc2cmadb.com',
@@ -138,7 +138,7 @@ def _link(connection, entity_id, record, batch):
def _claim(connection, entity_id, record, owner):
if connection.execute("SELECT 1 FROM entity_classification WHERE entity_id=? AND facet='account_role' "
- "AND value='seller' AND status IN ('observed','approved')", (entity_id,)).fetchone():
+ "AND value='seller' AND " + trusted_sql(), (entity_id,)).fetchone():
return
write_claim(connection, entity_id=entity_id, facet='account_role', value='seller', source=owner,
source_url=record['source_url'], evidence=f"作品 {record['code']} 的販売者:{record['name']};账号 {record['account_url']}",
diff --git a/src/peach/metadata_creator_attributions.py b/src/peach/metadata_creator_attributions.py
index b6aa3145d..043585742 100644
--- a/src/peach/metadata_creator_attributions.py
+++ b/src/peach/metadata_creator_attributions.py
@@ -10,6 +10,7 @@ from collections import defaultdict
from .catalog_rules import compact_label, western_release_identity
from .classification import is_structural_creator, is_repost_creator, creator_collection_base, creator_release_identifier
from .entities import normalize_entity_name, upsert_asset_entity
+from .entity_classification import trusted_sql
from .field_owners import is_protected, owner_of, write_owned_fields
from .studio_sites import is_platform, normalise
@@ -126,7 +127,7 @@ def collect(connection: sqlite3.Connection) -> list[dict]:
issuers = {}
if connection.execute("SELECT 1 FROM sqlite_schema WHERE name='entity_classification'").fetchone():
issuers = dict(connection.execute("SELECT entity_id,min(source_url) FROM entity_classification "
- "WHERE facet='account_role' AND value='studio' AND status IN ('observed','approved') "
+ "WHERE facet='account_role' AND value='studio' AND " + trusted_sql() + " "
"AND source_url LIKE 'https://%' GROUP BY entity_id"))
creators = {row[1]: row[2] for row in connection.execute(
"SELECT id,normalized_name,canonical_name FROM entity WHERE kind='creator'") if row[0] not in issuers}
diff --git a/tests/test_entity_classification.py b/tests/test_entity_classification.py
index f4ac174a7..238b8b5cc 100644
--- a/tests/test_entity_classification.py
+++ b/tests/test_entity_classification.py
@@ -243,6 +243,41 @@ class EntityClassificationTests(unittest.TestCase):
classification.write_claim(self.connection,entity_id=entity_id,facet='identity',value='person',source='script:lookup',evidence='推断',**patch)
with self.assertRaises(ValueError):
self.claim(entity_id,'occupation','unknown_profession')
+ with self.assertRaisesRegex(ValueError,'代码判据'):
+ classification.write_claim(self.connection,entity_id=entity_id,facet='identity',value='person',
+ source='script:identity-research',source_url='https://publisher.test/profile',
+ evidence='研究清单判断',status='observed',confidence=1)
+
+ def test_only_code_sources_make_observed_claims_trusted(self):
+ _,research=self.entity('Research Person',kind='performer')
+ _,parsed=self.entity('Parsed Person',kind='performer')
+ self.connection.execute("INSERT INTO entity_classification VALUES(?,'market','japanese_av',"
+ "'script:identity-research','https://publisher.test/a','研究清单判断','observed',1,'t')",(research,))
+ self.claim(parsed,'market','japanese_av')
+ self.connection.commit()
+ page=q_index(WebContract(self.db),'performers',category='japanese_av')
+ self.assertEqual([row['entity_id'] for row in page['items']],[parsed])
+ self.assertEqual(page['categories'],{'japanese_av':1})
+
+ def test_research_observations_downgrade_to_candidates_and_code_facts_stay(self):
+ _,research=self.entity('Research Person',kind='performer')
+ _,parsed=self.entity('Parsed Person',kind='performer')
+ self.connection.execute("INSERT INTO entity_classification VALUES(?,'market','japanese_av',"
+ "'script:identity-research','https://publisher.test/a','研究清单判断','observed',0.8,'t')",(research,))
+ self.connection.execute("INSERT INTO entity_identity_link VALUES(?,?,'same_person',"
+ "'script:identity-research','https://publisher.test/a','研究清单判断','observed','t')",(research,parsed))
+ self.claim(parsed,'market','japanese_av')
+ plan=classification.untrusted_observed(self.connection)
+ self.assertEqual([(row['entity_id'],row['source']) for row in plan['entity_classification']],
+ [(research,'script:identity-research')])
+ self.assertEqual(len(plan['entity_identity_link']),1)
+ self.assertEqual(classification.downgrade_untrusted_observed(self.connection),
+ {'entity_classification':1,'entity_identity_link':1})
+ rows=self.connection.execute('SELECT entity_id,status,confidence,evidence FROM entity_classification ORDER BY entity_id').fetchall()
+ self.assertEqual([tuple(row) for row in rows],
+ [(research,'candidate',0.8,'研究清单判断'),(parsed,'observed',1.0,'发行方资料')])
+ self.assertEqual(classification.untrusted_observed(self.connection),
+ {'entity_classification':[],'entity_identity_link':[]})
def test_cast_role_repair_and_restore_preserve_all_business_fields(self):
asset_id,entity_id=self.entity('Known Person')
@@ -253,7 +288,9 @@ class EntityClassificationTests(unittest.TestCase):
with self.connection:
receipt=research.apply(self.connection,frozen)
self.assertEqual(self.connection.execute('SELECT role FROM asset_entity WHERE asset_id=?',(asset_id,)).fetchone()[0],'performer')
- self.assertEqual(len(classification.related_identities(self.connection,entity_id)),1)
+ self.assertEqual(self.connection.execute('SELECT group_concat(DISTINCT status) FROM entity_classification').fetchone()[0],'candidate')
+ self.assertEqual(self.connection.execute('SELECT group_concat(status) FROM entity_identity_link').fetchone()[0],'candidate')
+ self.assertEqual(classification.related_identities(self.connection,entity_id),[])
with self.connection:
research.restore(self.connection,receipt)
after=dict(self.connection.execute('SELECT * FROM asset WHERE id=?',(asset_id,)).fetchone())