Peach: Local-first video metadata scraper and media manager.
fix(company): 公司资料只认能按缓存页重放的通用判据
longmeidao3f49f6e1673b
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex a71c1bd50..746534195 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -14,7 +14,7 @@ Babepedia 主图库和 Vixen 网络公开 GraphQL 的字段核对 [Stash Communi## 实体身份与职业-公司资料复用 `entity.metadata_json`、HTTPX、官网公司概要表和定义列表、实体链接安装器与标识采集器。`company_profiles` 按字段保存公开出处、原文和批次,只填空;集团公司表按实体限定范围,公司成立与品牌启动分列,运营主体、发行商和集团不互相推导。目录页面不作独立公司官网。`harvest_company_profiles.py` 默认产复核 JSON,`--input --apply --backup --batch` 才落库,候选不落库,来源冲突留在产物;别名碰撞不写。`revert_auto_landing.py` 可撤回同批公司字段、链接、别名及标识,无新增依赖。+公司资料复用 `entity.metadata_json`、HTTPX、官网公司概要表和定义列表与标识采集器。`company_profiles` 只有通用判据(概要标签、服务条款订立方原句),按字段保存出处、原文和批次,只填空;一页多张公司表时按法人名对实体名与别名选表,公司成立与品牌启动分列,集团与分工关系不由代码推导,只作候选。`harvest_company_profiles.py` 默认产复核 JSON,`--input --apply --backup --batch auto:company-profile@…` 按缓存页重放判据后落库,清单里的别名、链接与第三方页面不写。`revert_auto_landing.py` 可撤回同批公司字段及标识,无新增依赖。Babepedia 资料采集复用 `babepedia_page` 的主名与别名交叉核对、`performer_profiles` 的整行来源保护和 `performer_alias_followup.land` 的占用检查。英文艺名只在明确允许的来源中登记,JAV 后继保留自己的名字策略。真人账号与出演者共用资料表、别名分组与头像候选;保留账号角色及旧地址。主图可以补空头像,本人档案图库仅作候选,推荐人物排除,单图失败继续其余有限候选。`harvest_western_profiles.py` 每轮至多 16 位,计划、备份、回执与批次撤回齐备;既有资料和头像保留。真实只读复核取得 Ria Kurumi 等 16 份匹配档案,无新增依赖。diff --git a/scripts/harvest_company_profiles.py b/scripts/harvest_company_profiles.pyindex 90230cb9e..4b446a86f 100644--- a/scripts/harvest_company_profiles.py+++ b/scripts/harvest_company_profiles.py@@ -1,4 +1,9 @@-"""逐家采集公开公司资料;默认只生成可复核的 JSON,不写账本。"""+"""逐家采集公开公司资料;默认只生成可复核的 JSON,不写账本。++`--input` 落库时按清单里记的原始页面缓存重放判据,只写重放得出的事实:页面要是采集器+取回的 HTTP 200 页面、落在这家已登记官网的主机上。清单里的 `aliases`、`links`、另添的+第三方页面与手填的结论都不写。+"""from __future__ import annotationsimport argparse@@ -9,14 +14,26 @@ from pathlib import Pathfrom urllib.parse import urlsplitsys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))+sys.path.insert(0, str(Path(__file__).resolve().parent))-from peach.company_profiles import extract_for_entity, brand_facts, fill, fill_aliases # noqa: E402+from peach.company_profiles import (entity_names, fill, merge_page, official_hosts, page_facts, # noqa: E402+ replay, settle)from peach.http import HttpRequest, HttpxTransport, body_text # noqa: E402from peach.scripting import (USER_AGENT, HostLimiter, add_ledger_write_args, counts_of,open_for_write, open_readonly, verify_after_write) # noqa: E402from peach.studio_sites import parked_reason, page_title # noqa: E402from find_studio_socials import affirmative_link # noqa: E402-from install_entity_links import plan, check_links, install # noqa: E402++SOURCE = 'auto:company-profile'+#: 限流与拒绝访问只说明那一刻没取到,续跑时要重试。+RETRY_STATUSES = {403, 429}+++def settled(item: dict) -> bool:+ """续跑时可以跳过的结论:已核查,或没有官网这种与时机无关的结论。"""+ if any(page.get('http_status') in RETRY_STATUSES for page in item.get('pages', [])):+ return False+ return item.get('status') == '已核查' or bool(item.get('reason'))def scan(entity: dict, root: Path, limiter: HostLimiter) -> dict:@@ -59,15 +76,8 @@ def scan(entity: dict, root: Path, limiter: HostLimiter) -> dict:file = root / f"{entity['id']}-{len(visited)}.html"file.write_text(html, encoding='utf-8')item['cache'] = str(file)- parsed = extract_for_entity(html, final, entity['canonical_name'])- parsed['facts'].update(brand_facts(html, final, entity['canonical_name']))- for key, fact in parsed['facts'].items():- held = result['facts'].get(key)- if held and held['value'] != fact['value']:- result['conflicts'].append({'field': key, 'values': [held, fact]})- else:- result['facts'][key] = fact- result['conflicts'].extend(parsed['conflicts'])+ parsed = page_facts(html, final, [entity['canonical_name'], *entity.get('aliases', [])])+ merge_page(result, parsed)result['socials'].extend(parsed['socials'])for target in parsed['company_pages']:if target not in visited and target not in urls:@@ -78,47 +88,44 @@ def scan(entity: dict, root: Path, limiter: HostLimiter) -> dict:result['status'] = '已核查'except Exception as error:result['pages'].append({'url': url, 'reason': f'{type(error).__name__}: {str(error)[:150]}'})- for conflict in result['conflicts']:- result['facts'].pop(conflict['field'], None)+ settle(result)finally:http.close()return resultdef land(args: argparse.Namespace) -> int:- """写入已观测的填空清单,保存计数、出处与回执。"""+ """按采集保存的原始页面重放判据,只写重放得出的事实;清单自带的结论不作数。"""rows = json.loads(args.input.read_text(encoding='utf-8'))['entities']connection = open_for_write(args)try:before = counts_of(connection)before_fk = connection.execute('PRAGMA foreign_key_check').fetchall()changes = []- link_rows = [link for row in rows if row.get('status') != 'candidate'- for link in row.get('links', []) if link.get('status') == 'observed']- links = plan(connection, link_rows)- check_links(links)- for link in links:- if link['action'] == 'relabel':- link.update(action='skip', reason='保留既有链接标签')for row in rows:- if row.get('status') == 'candidate':- changes.append({'entity_id': row['entity_id'], 'skipped': '候选尚未复核'})+ names = entity_names(connection, row['entity_id'])+ if names is None:+ changes.append({'entity_id': row['entity_id'], 'skipped': '实体不在或不是厂牌、事务所'})continue- facts = {key: fact for key, fact in row.get('facts', {}).items()- if fact.get('status') == 'observed'}+ facts = replay(row.get('pages', []), names, official_hosts(connection, row['entity_id']))['facts']+ change = {'entity_id': row['entity_id']}+ unproven = sorted(set(row.get('facts', {})) - set(facts))+ if unproven:+ change['not_replayed'] = unproven+ ignored = {key: len(row[key]) for key in ('aliases', 'links') if row.get(key)}+ if ignored:+ change['ignored'] = ignoredif args.apply:- changes.append({'entity_id': row['entity_id'], **fill(connection, row['entity_id'], facts, source='auto:company-profile', batch=args.batch),- 'aliases_written': fill_aliases(connection, row['entity_id'], row.get('aliases', []), batch=args.batch)})+ change.update(fill(connection, row['entity_id'], facts, source=SOURCE, batch=args.batch))else:- changes.append({'entity_id': row['entity_id'], 'planned': list(facts)})+ change['planned'] = list(facts)+ changes.append(change)if args.apply:- links_written = install(connection, links, 'auto:company-profile', batch=args.batch)connection.commit()after = counts_of(connection)integrity, foreign_keys = verify_after_write(connection)receipt = {'apply': args.apply, 'before': before, 'after': after, 'integrity': integrity,- 'foreign_keys_before': len(before_fk), 'foreign_keys_after': foreign_keys, 'changes': changes,- 'links': links, 'links_written': links_written if args.apply else 0}+ 'foreign_keys_before': len(before_fk), 'foreign_keys_after': foreign_keys, 'changes': changes}args.output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2), encoding='utf-8')print(json.dumps({'entities_changed': sum(bool(row.get('written')) for row in changes), 'fields_written': sum(len(row.get('written', [])) for row in changes), 'integrity': integrity, 'foreign_keys': foreign_keys}))return 0 if integrity == 'ok' and foreign_keys == len(before_fk) else 1@@ -137,8 +144,8 @@ def main() -> int:parser.add_argument('--batch', default='')args = parser.parse_args()if args.input:- if args.apply and not args.batch:- parser.error('--apply 需要 --batch 记录可撤回的批次')+ if args.apply and not args.batch.startswith(SOURCE + '@'):+ parser.error(f'--apply 需要 {SOURCE}@ 开头的 --batch,撤回按这个前缀认')return land(args)if args.inventory:entities = json.loads(args.inventory.read_text(encoding='utf-8'))['entities']@@ -148,13 +155,13 @@ def main() -> int:for row in connection.execute("SELECT id,kind,canonical_name FROM entity WHERE kind IN ('studio','agency') ORDER BY id"):item = dict(row)item['links'] = [dict(link) for link in connection.execute("SELECT link_kind,url FROM entity_link WHERE entity_id=?", (item['id'],))]+ item['aliases'] = [alias for (alias,) in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?', (item['id'],))]entities.append(item)if args.cache is None:parser.error('采集需要 --cache 保存原始页面')args.cache.mkdir(parents=True, exist_ok=True)results = json.loads(args.output.read_text(encoding='utf-8'))['entities'] if args.resume and args.output.exists() else []- done = {item['entity_id'] for item in results if item['status'] == '已核查'- or item.get('reason') or any(page.get('http_status') in {403, 429} for page in item['pages'])}+ done = {item['entity_id'] for item in results if settled(item)}results = [item for item in results if item['entity_id'] in done]limiter = HostLimiter({}, default_interval=1.5)with ThreadPoolExecutor(max_workers=3) as workers:diff --git a/scripts/repair_company_profile_landing.py b/scripts/repair_company_profile_landing.pynew file mode 100644index 000000000..384b6703c--- /dev/null+++ b/scripts/repair_company_profile_landing.py@@ -0,0 +1,146 @@+"""存量修正:公司资料批次里没有代码判据的结论(ADR-0052 第一条)。++公司资料落库只认 `company_profiles` 的通用判据。这里按采集清单记下的原始页面缓存重放一遍+判据,把指定批次写下的内容改到判据下的样子:++- 公司资料格:重放得出同一个值的保持 observed,原文换成重放得出的那一句;得不出的降为+ `candidate`,记下原因,不进入显示契约,等人复核。+- 别名与链接:采集器不产出公司别名和链接,这一批写下的全部删掉,原值记进回执。++默认只列计划(只读打开账本);`--apply` 必须同时给 `--backup`。++ repair_company_profile_landing.py --batch auto:company-profile@20261007-company \+ --plan <复核目录>/company-profile-observed-plan.json --output <回执.json>+"""+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 import company_profiles # noqa: E402+from peach.config import REVIEW_DIR # noqa: E402+from peach.scripting import ( # noqa: E402+ add_ledger_write_args, counts_of, open_for_write, verify_after_write)++SOURCE = "auto:company-profile"+REASON = "采集清单的原始页面按通用判据重放得不出这个值"+++def plan(connection, pages_by_entity: dict[int, list[dict]], batch: str) -> dict:+ """逐格判定保留、改原文还是降为候选;别名与链接整批列出。"""+ fields = []+ for entity_id, name, raw in connection.execute(+ "SELECT id,canonical_name,metadata_json FROM entity WHERE kind IN ('studio','agency') ORDER BY id"):+ profile = json.loads(raw or "{}").get(company_profiles.KEY)+ if not isinstance(profile, dict):+ continue+ ours = {key: fact for key, fact in profile.items() if isinstance(fact, dict)+ and fact.get("source") == SOURCE and fact.get("batch") == batch+ and fact.get("status") != "candidate"}+ if not ours:+ continue+ names = company_profiles.entity_names(connection, entity_id) or [name]+ hosts = company_profiles.official_hosts(connection, entity_id, skip_batch=batch)+ replayed = company_profiles.replay(pages_by_entity.get(entity_id, []), names, hosts)["facts"]+ for key, fact in sorted(ours.items()):+ again = replayed.get(key)+ if again and again["value"] == fact.get("value"):+ action = "keep" if again["evidence"] == fact.get("evidence") else "evidence"+ fields.append({"entity_id": entity_id, "entity": name, "field": key, "action": action,+ "value": fact.get("value"), "evidence": again["evidence"],+ "source_url": again["source_url"]})+ else:+ fields.append({"entity_id": entity_id, "entity": name, "field": key, "action": "candidate",+ "value": fact.get("value"), "evidence": fact.get("evidence")})+ aliases = [dict(zip(("entity_id", "entity", "alias"), row)) for row in connection.execute(+ "SELECT a.entity_id,e.canonical_name,a.alias FROM entity_alias a JOIN entity e ON e.id=a.entity_id"+ " WHERE a.source=? ORDER BY a.entity_id,a.alias", (batch,))]+ links = []+ for link_id, entity_id, name, url, raw in connection.execute(+ "SELECT l.id,l.entity_id,e.canonical_name,l.url,l.metadata_json FROM entity_link l"+ " JOIN entity e ON e.id=l.entity_id WHERE l.metadata_json LIKE ? ORDER BY l.id", (f"%{batch}%",)):+ metadata = json.loads(raw or "{}")+ if metadata.get("source") == SOURCE and metadata.get("batch") == batch:+ links.append({"id": link_id, "entity_id": entity_id, "entity": name, "url": url})+ return {"fields": fields, "aliases": aliases, "links": links}+++def apply(connection, planned: dict) -> dict:+ """按计划改写;调用方负责事务。"""+ by_entity: dict[int, list[dict]] = {}+ for item in planned["fields"]:+ by_entity.setdefault(item["entity_id"], []).append(item)+ for entity_id, items in by_entity.items():+ metadata = json.loads(connection.execute("SELECT metadata_json FROM entity WHERE id=?",+ (entity_id,)).fetchone()[0] or "{}")+ profile = metadata[company_profiles.KEY]+ for item in items:+ fact = profile[item["field"]]+ if item["action"] == "candidate":+ fact.update(status="candidate", candidate_reason=REASON)+ elif item["action"] == "evidence":+ fact.update(evidence=item["evidence"], source_url=item["source_url"])+ connection.execute("UPDATE entity SET metadata_json=? WHERE id=?",+ (json.dumps(metadata, ensure_ascii=False), entity_id))+ for alias in planned["aliases"]:+ connection.execute("DELETE FROM entity_alias WHERE entity_id=? AND alias=?",+ (alias["entity_id"], alias["alias"]))+ for link in planned["links"]:+ connection.execute("DELETE FROM entity_link WHERE id=?", (link["id"],))+ return {action: sum(item["action"] == action for item in planned["fields"])+ for action in ("keep", "evidence", "candidate")} | {+ "aliases": len(planned["aliases"]), "links": len(planned["links"])}+++def build_parser() -> argparse.ArgumentParser:+ parser = add_ledger_write_args(argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter))+ parser.add_argument("--batch", required=True)+ parser.add_argument("--plan", type=Path, default=REVIEW_DIR / "company-profile-observed-plan.json")+ parser.add_argument("--output", type=Path, required=True)+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ if not args.batch.startswith(SOURCE + "@"):+ raise SystemExit(f"--batch 必须以 {SOURCE}@ 开头")+ rows = json.loads(args.plan.read_text(encoding="utf-8"))["entities"]+ pages = {int(row["entity_id"]): row.get("pages", []) for row in rows}+ connection = open_for_write(args)+ try:+ before = counts_of(connection)+ planned = plan(connection, pages, args.batch)+ summary = {action: sum(item["action"] == action for item in planned["fields"])+ for action in ("keep", "evidence", "candidate")} | {+ "aliases": len(planned["aliases"]), "links": len(planned["links"])}+ receipt = {"apply": args.apply, "batch": args.batch, "before": before, "plan": planned}+ if args.apply:+ summary = apply(connection, planned)+ connection.commit()+ integrity, violations = verify_after_write(connection)+ receipt.update(after=counts_of(connection), integrity=integrity, foreign_keys=violations)+ receipt["summary"] = summary+ args.output.parent.mkdir(parents=True, exist_ok=True)+ args.output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2), encoding="utf-8")+ for item in planned["fields"]:+ if item["action"] != "keep":+ print(f" - {item['action']:<9} {item['entity']} {item['field']} = {item['value']}")+ for alias in planned["aliases"]:+ print(f" - 删别名 {alias['entity']} {alias['alias']}")+ for link in planned["links"]:+ print(f" - 删链接 {link['entity']} {link['url']}")+ print(json.dumps(summary, ensure_ascii=False))+ if args.apply:+ return 0 if receipt["integrity"] == "ok" else 1+ return 0+ finally:+ connection.close()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/company_profiles.py b/src/peach/company_profiles.pyindex 9adc83037..778a8506a 100644--- a/src/peach/company_profiles.py+++ b/src/peach/company_profiles.py@@ -2,6 +2,10 @@厂牌与事务所资料保存在 entity.metadata_json.company_profile;不参与身份归并。成立日期、品牌启动与运营公司各有字段。每格保存来源 URL、原文和批次,自动结果只填空。++观测结果只来自本模块的通用判据:概要表、定义列表与成对区块里的标签,以及服务条款里的+订立方原句。落库时按采集保存的原始页面重跑一遍(`replay`),重跑得不出的格不写;+页面上读不出、只能由人判断的集团归属与分工关系留作 `candidate`,不进入显示契约。"""from __future__ import annotations@@ -9,12 +13,14 @@ import jsonimport reimport sqlite3from datetime import datetime, timezone+from pathlib import Pathfrom urllib.parse import urljoin, urlsplitfrom bs4 import BeautifulSoupfrom .http import public_https_url-from .entities import normalize_entity_name+from .kanji import fold_glyphs+from .social_links import name_keyKEY = 'company_profile'FIELDS = ('legal_name', 'founded', 'launched', 'country', 'location', 'operator', 'parent', 'group', 'distributor')@@ -30,6 +36,11 @@ LABELS = {'親会社': 'parent', 'parentcompany': 'parent','国': 'country', 'country': 'country',}+#: 法人名里的公司形态词:比名字时剥掉,`SODクリエイト株式会社` 与别名 `SODクリエイト` 同键。+CORPORATE_FORM = re.compile(r'株式会社|有限会社|合同会社|合資会社|合名会社|[((]\s*[株有]\s*[))]'+ r'|\b(?:inc|llc|ltd|corp|co|kft|gmbh)\b\.?', re.I)+#: 英文服务条款开头订立方那一句:运营主体是括号或句号前的那一段。+TERMS_OPERATOR = re.compile(r'These terms of (?:service|use) are entered into between you and ([^.()]+?)\s*(?:\(|\.)', re.I)COMPANY_LINK = re.compile(r'会社概要|企業情報|会社案内|特定商取引|about\s*(?:us)?|company\s*(?:profile)?|terms\s*(?:of|and|&)?\s*(?:service|use|conditions)|privacy\s*policy', re.I)SOCIAL_HOSTS = {'x.com', 'twitter.com', 'instagram.com', 'youtube.com', 'tiktok.com', 'facebook.com', 'threads.net', 'threads.com'}@@ -115,96 +126,124 @@ def extract(html: str, source_url: str) -> dict:return {'facts': facts, 'conflicts': conflicts, 'company_pages': pages, 'socials': socials}-def _vmg_facts(text: str, source_url: str, name: str) -> dict:- """VMG 的站点条款、品牌启动与官方品牌名录。"""- host = (urlsplit(source_url).hostname or '').removeprefix('www.')- facts = {}-- def keep(key: str, value: str, evidence: str) -> None:- facts[key] = {'value': value, 'source_url': source_url, 'evidence': evidence, 'status': 'observed'}-- if host in {'vixen.com', 'tushy.com', 'blacked.com'} and urlsplit(source_url).path == '/terms':- match = re.search(r'These terms of service are entered into between you and ([^.]+?)(?:\s*\(|\.)', text, re.I)- if match and name.casefold() == host.split('.')[0]:- keep('operator', match[1].strip(), match[0])- if host == 'vixengroup.com':- if urlsplit(source_url).path.rstrip('/') == '/vixen10' and name == 'Vixen':- match = re.search(r'\bSince (20\d{2})\.', text)- if match:- keep('launched', match[1], match[0])- listing = re.search(r'OUR BRANDS .*?Explore ([^.]+), all available on Vixen Plus', text)- if listing and name in {'Vixen', 'Tushy', 'Blacked'} and 'Vixen Media Group' in text:- names = [part.strip().removeprefix('and ') for part in listing[1].split(',')]- if name in names:- keep('group', 'Vixen Media Group', listing[0])- return facts---def _corporate_events(soup: BeautifulSoup, text: str, source_url: str, name: str) -> dict:- """公司招聘页、法人沿革与分工陈述。"""- host = (urlsplit(source_url).hostname or '').removeprefix('www.')- facts = {}-- def keep(key: str, value: str, evidence: str) -> None:- facts[key] = {'value': value, 'source_url': source_url, 'evidence': evidence, 'status': 'observed'}-- if host == 'arwrk.net' and urlsplit(source_url).path == '/recruit/prestige-av/' and name == 'Prestige':- heading = soup.select_one('h1')- if heading and '有限会社プレステージ' in heading.get_text():- keep('legal_name', '有限会社プレステージ', heading.get_text(' ', strip=True))- if host == 'corporate.sod.co.jp' and name == 'SOD Create':- if '/business/softondemand' in source_url and 'SODクリエイト株式会社を設立。ソフト・オン・デマンドが販売・物流業務などを担う' in text:- keep('distributor', 'ソフト・オン・デマンド株式会社', 'SODクリエイト株式会社を設立。ソフト・オン・デマンドが販売・物流業務などを担う形になりました。')- if 'SODグループ' in text and 'SODクリエイト株式会社' in text:- keep('group', 'SODグループ', 'SODグループ:SODクリエイト株式会社')- if host == 't-powers.co.jp' and '/company' in source_url:- # 法人成立与2001年的集团创立是两件事,读取时间线里的法人事件。- for row in soup.select('dl, .p-company__history-list-item'):- year = row.select_one('dt, .p-company__history-list-year-text')- detail = row.select_one('dd, .p-company__history-list-desc')- if year and detail:- detail_text = _clean(detail.get_text(' ', strip=True))- if 'ティーパワーズ株式会社を設立' in detail_text:- date = date_text(year.get_text(strip=True))- if date:- keep('founded', date, f'{year.get_text(strip=True)} {detail_text}')- keep('legal_name', 'ティーパワーズ株式会社', detail_text)- return facts---def brand_facts(html: str, source_url: str, name: str) -> dict:- """官方品牌页明确陈述的事实;运营主体与集团名录分别读取。"""+def company_key(name: str) -> str:+ """比法人名与实体名的键:剥掉公司形态词,再按全半角、空白、大小写与字形折叠。"""+ return fold_glyphs(name_key(CORPORATE_FORM.sub(' ', str(name or ''))))+++def _table_legal_names(table) -> list[str]:+ return [_clean(value) for label, value in _labelled_pairs(table)+ if LABELS.get(re.sub(r'[\s::]', '', label).casefold()) == 'legal_name']+++def extract_for_entity(html: str, source_url: str, names: list[str]) -> dict:+ """一页列着几家公司的概要表时,只读法人名对得上这个实体名字的那一张。++ 法人名剥掉公司形态词后要与实体的规范名或别名相等;恰好一张对上才读,对不上或+ 对上多张时整页不出事实,避免把集团里另一家公司的成立日期记到这里。+ """+ soup = BeautifulSoup(html, 'html.parser')+ tables = [table for table in soup.select('table') if _table_legal_names(table)]+ if len(tables) < 2:+ return extract(html, source_url)+ keys = {company_key(name) for name in names} - {''}+ own = [table for table in tables if any(company_key(value) in keys for value in _table_legal_names(table))]+ if len(own) == 1:+ parsed = extract(str(own[0]), source_url)+ parsed['company_pages'], parsed['socials'] = _page_links(soup, source_url)+ return parsed+ pages, socials = _page_links(soup, source_url)+ return {'facts': {}, 'conflicts': [], 'company_pages': pages, 'socials': socials}+++def terms_facts(html: str, source_url: str) -> dict:+ """服务条款页里「与你订立本条款的是某公司」那一句:运营主体取自原句。"""+ if 'terms' not in urlsplit(source_url).path.casefold():+ return {}soup = BeautifulSoup(html, 'html.parser')for node in soup(['script', 'style']):node.decompose()- text = _clean(soup.get_text(' ', strip=True))- host = (urlsplit(source_url).hostname or '').removeprefix('www.')- facts = _vmg_facts(text, source_url, name)- facts.update(_corporate_events(soup, text, source_url, name))- if host == 'falenogroup.com' and name == '素人CLOVER' and '/makers' in source_url:- if 'メーカー一覧' in text and 'FALENO GROUP' in text and re.search(r'\b素人CLOVER\s+PROFILE', text):- facts['group'] = {'value': 'FALENO GROUP', 'source_url': source_url,- 'evidence': 'メーカー一覧:素人CLOVER PROFILE', 'status': 'observed'}- if host == 'dorcel.com' and name == 'DorcelClub' and '/confidentialitedonnees' in source_url:- # 隐私页的法文句子按字符倒序存放;只读该站域名与明确运营陈述的完整句子。- for node in soup.find_all(string=lambda value: value and 'TFK secivreS ycnegAbeW' in value):- statement = _clean(str(node)[::-1])- if statement.startswith('WebAgency Services KFT') and 'exploite les Sites internet dorcelclub.com' in statement:- facts['operator'] = {'value': 'WebAgency Services KFT', 'source_url': source_url,- 'evidence': statement, 'status': 'observed'}- return facts---def extract_for_entity(html: str, source_url: str, name: str) -> dict:- """集团页面只读该实体的公司表,不合并其他子公司的成立日期。"""- if (urlsplit(source_url).hostname or '') == 'corporate.sod.co.jp' and name == 'SOD Create':- soup = BeautifulSoup(html, 'html.parser')- tables = [table for table in soup.select('table')- if any(cell.get_text(strip=True) == 'SODクリエイト株式会社' for cell in table.select('td'))]- if len(tables) == 1:- return extract(str(tables[0]), source_url)- return {'facts': {}, 'conflicts': [], 'company_pages': [], 'socials': []}- return extract(html, source_url)+ match = TERMS_OPERATOR.search(_clean(soup.get_text(' ', strip=True)))+ if not match or not match[1].strip():+ return {}+ return {'operator': {'value': match[1].strip(), 'source_url': source_url,+ 'evidence': match[0], 'status': 'observed'}}+++def page_facts(html: str, source_url: str, names: list[str]) -> dict:+ """一张官网页面上由代码判据读出的全部事实、歧义与后续页面。"""+ parsed = extract_for_entity(html, source_url, names)+ for key, fact in terms_facts(html, source_url).items():+ held = parsed['facts'].get(key)+ if held and held['value'] != fact['value']:+ parsed['conflicts'].append({'field': key, 'values': [parsed['facts'].pop(key), fact]})+ elif not any(item['field'] == key for item in parsed['conflicts']):+ parsed['facts'][key] = fact+ return parsed+++def merge_page(result: dict, parsed: dict) -> None:+ """把一页的结论并进这一家:同一字段在两页上说法不同就记成歧义。"""+ for key, fact in parsed['facts'].items():+ held = result['facts'].get(key)+ if held and held['value'] != fact['value']:+ result['conflicts'].append({'field': key, 'values': [held, fact]})+ else:+ result['facts'][key] = fact+ result['conflicts'].extend(parsed['conflicts'])+++def settle(result: dict) -> None:+ """有歧义的字段整格不出。"""+ for conflict in result['conflicts']:+ result['facts'].pop(conflict['field'], None)+++def site_host(url: str) -> str:+ return (urlsplit(url).hostname or '').casefold().removeprefix('www.')+++def replay(pages: list[dict], names: list[str], hosts: set[str]) -> dict:+ """按采集时保存的原始页面重跑判据;只有这里得出的事实才算观测结果。++ 只读采集器自己取回的页面:HTTP 200、落在这家已登记官网的主机上。清单里另外+ 添进来的第三方页面(工商登记、新闻稿站)不算。+ """+ result = {'facts': {}, 'conflicts': []}+ for page in pages:+ cache, final = page.get('cache'), page.get('final_url') or page.get('url')+ if not cache or not final or page.get('http_status') != 200 or site_host(final) not in hosts:+ continue+ try:+ html = Path(cache).read_text(encoding='utf-8')+ except OSError:+ continue+ merge_page(result, page_facts(html, final, names))+ settle(result)+ return result+++def entity_names(connection: sqlite3.Connection, entity_id: int) -> list[str] | None:+ """公司实体的规范名与别名;实体不在或不是厂牌、事务所时返回 None。"""+ row = connection.execute('SELECT kind,canonical_name FROM entity WHERE id=?', (entity_id,)).fetchone()+ if not row or row[0] not in {'studio', 'agency'}:+ return None+ return [str(row[1]), *(str(alias) for (alias,) in connection.execute(+ 'SELECT alias FROM entity_alias WHERE entity_id=? ORDER BY alias', (entity_id,)))]+++def official_hosts(connection: sqlite3.Connection, entity_id: int, *, skip_batch: str = '') -> set[str]:+ """这家已登记官网的主机(去掉 `www.`);存档地址与 `skip_batch` 这一批写下的不算。"""+ hosts = set()+ for url, raw in connection.execute(+ "SELECT url,metadata_json FROM entity_link WHERE entity_id=? AND link_kind='official'", (entity_id,)):+ try:+ batch = json.loads(raw or '{}').get('batch')+ except ValueError:+ batch = None+ if 'web.archive.org' not in url and not (skip_batch and batch == skip_batch):+ hosts.add(site_host(url))+ return hosts - {''}def public_profile(metadata: dict) -> dict:@@ -218,32 +257,8 @@ def public_profile(metadata: dict) -> dict:and value['value'].strip() and public_https_url(str(value.get('source_url', '')))}-def fill_aliases(connection: sqlite3.Connection, entity_id: int, aliases: list[dict], *, batch: str) -> list[str]:- """只补带官方出处的观测别名;与其他同类实体冲突时留在复核文件。"""- row = connection.execute('SELECT kind,canonical_name FROM entity WHERE id=?', (entity_id,)).fetchone()- if not row or row[0] not in {'studio', 'agency'}:- return []- written = []- for alias in aliases:- name = str(alias.get('value', '')).strip()- if alias.get('status') != 'observed' or not name or name == row[1] or not public_https_url(alias.get('source_url', '')):- continue- normalized = normalize_entity_name(name)- conflict = connection.execute(- 'SELECT e.id FROM entity e LEFT JOIN entity_alias a ON a.entity_id=e.id '- 'WHERE e.kind=? AND e.id!=? AND (e.normalized_name=? OR a.normalized_alias=?) LIMIT 1',- (row[0], entity_id, normalized, normalized)).fetchone()- if conflict:- continue- connection.execute('INSERT OR IGNORE INTO entity_alias(entity_id,alias,normalized_alias,source,confidence) VALUES(?,?,?,?,1)',- (entity_id, name, normalized, batch))- if connection.execute('SELECT changes()').fetchone()[0]:- written.append(name)- return written--def fill(connection: sqlite3.Connection, entity_id: int, facts: dict, *, source: str, batch: str) -> dict:- """给公司资料填空,保留其他元信息和既有字段。调用方负责事务。"""+ """给公司资料填空,保留其他元信息和既有字段;候选格可由观测结果接替。调用方负责事务。"""row = connection.execute('SELECT kind,metadata_json FROM entity WHERE id=?', (entity_id,)).fetchone()if row is None or row[0] not in {'studio', 'agency'}:return {'written': [], 'conflicts': []}@@ -254,7 +269,7 @@ def fill(connection: sqlite3.Connection, entity_id: int, facts: dict, *, source:written, conflicts = [], []now = datetime.now(timezone.utc).isoformat()for key, fact in public_profile({KEY: facts}).items():- if key in held:+ if key in held and not (isinstance(held[key], dict) and held[key].get('status') == 'candidate'):if held[key] != fact and (not isinstance(held[key], dict) or held[key].get('value') != fact['value']):conflicts.append(key)continue@@ -268,12 +283,13 @@ def fill(connection: sqlite3.Connection, entity_id: int, facts: dict, *, source:def planned_revert(connection: sqlite3.Connection, source: str, batch: str) -> list[dict]:- """只列这批拥有的公司资料格,其他元信息不受影响。"""+ """只列这批拥有的公司资料格(含已降为候选的格),其他元信息不受影响。"""found = []for row in connection.execute("SELECT id,canonical_name,metadata_json FROM entity WHERE kind IN ('studio','agency')"):- metadata = json.loads(row[2] or '{}')- fields = [key for key, fact in public_profile(metadata).items()- if fact.get('source') == source and (not batch or fact.get('batch') == batch)]+ profile = json.loads(row[2] or '{}').get(KEY)+ fields = [key for key, fact in (profile.items() if isinstance(profile, dict) else ())+ if isinstance(fact, dict) and fact.get('source') == source+ and (not batch or fact.get('batch') == batch)]if fields:found.append({'entity_id': row[0], 'entity': row[1], 'fields': fields})return founddiff --git a/tests/test_company_profiles.py b/tests/test_company_profiles.pyindex e8a0312c9..b7810485e 100644--- a/tests/test_company_profiles.py+++ b/tests/test_company_profiles.py@@ -3,7 +3,9 @@ import jsonimport sqlite3import tempfileimport unittest+from contextlib import closingfrom pathlib import Path+from types import SimpleNamespacefrom peach import company_profilesfrom peach.entities import upsert_asset_entity@@ -45,33 +47,145 @@ class CompanyProfileTests(unittest.TestCase):self.assertEqual(company_profiles.revert(connection, rows), 1)self.assertEqual(json.loads(connection.execute('SELECT metadata_json FROM entity').fetchone()[0]), {'provider': 'catalog'})- def test_group_company_tables_are_scoped_to_the_named_company(self):+ def test_group_company_tables_are_scoped_by_the_entity_names(self):html = '<table><tr><th>社名</th><td>ソフト・オン・デマンド株式会社</td></tr><tr><th>設立</th><td>1995年11月</td></tr></table><table><tr><th>社名</th><td>SODクリエイト株式会社</td></tr><tr><th>設立</th><td>1999年3月</td></tr></table>'- result = company_profiles.extract_for_entity(html, 'https://corporate.sod.co.jp/about_us/info/', 'SOD Create')+ result = company_profiles.extract_for_entity(html, 'https://group.example/about_us/info/', ['SOD Create', 'SODクリエイト'])self.assertEqual(result['facts']['founded']['value'], '1999-03')self.assertEqual(result['facts']['legal_name']['value'], 'SODクリエイト株式会社')+ unnamed = company_profiles.extract_for_entity(html, 'https://group.example/about_us/info/', ['SOD Create'])+ self.assertEqual(unnamed['facts'], {})- def test_brand_listing_is_not_a_company_foundation_date(self):+ def test_terms_operator_comes_from_the_page_sentence_and_listings_give_no_group(self):html = '<h1>Vixen Media Group</h1><p>OUR BRANDS Each studio is a world. Explore Vixen, Blacked, Blacked Raw, Tushy, and Deeper, all available on Vixen Plus</p>'- facts = company_profiles.brand_facts(html, 'https://www.vixengroup.com/', 'Tushy')- self.assertEqual(facts['group']['value'], 'Vixen Media Group')- self.assertNotIn('founded', facts)+ self.assertEqual(company_profiles.page_facts(html, 'https://www.vixengroup.com/', ['Tushy'])['facts'], {})terms = '<p>These terms of service are entered into between you and General Media Systems, LLC (the Company).</p>'- facts = company_profiles.brand_facts(terms, 'https://www.tushy.com/terms', 'Tushy')+ facts = company_profiles.page_facts(terms, 'https://www.anybrand.example/terms', ['Any'])['facts']self.assertEqual(facts['operator']['value'], 'General Media Systems, LLC')+ self.assertEqual(facts['operator']['evidence'], 'These terms of service are entered into between you and General Media Systems, LLC (')+ self.assertEqual(company_profiles.page_facts(terms, 'https://www.anybrand.example/news', ['Any'])['facts'], {})- def test_aliases_are_observed_and_do_not_collide_with_another_company(self):+ def test_group_statements_without_labels_are_not_observed(self):+ cases = [+ ('<p>SODグループ</p><p>SODクリエイト株式会社</p>', 'https://corporate.sod.co.jp/business/softondemand/', ['SOD Create']),+ ('<h2>メーカー一覧</h2><p>FALENO GROUP</p><p>素人CLOVER PROFILE</p>', 'https://falenogroup.com/makers/', ['素人CLOVER']),+ ('<dl><dt>2006</dt><dd>組織拡大の為、ティーパワーズ株式会社を設立</dd></dl>', 'https://www.t-powers.co.jp/company/', ['T-POWERS']),+ ]+ for html, url, names in cases:+ with self.subTest(url=url):+ self.assertEqual(company_profiles.page_facts(html, url, names)['facts'], {})++ def test_replay_reads_saved_pages_and_drops_cross_page_conflicts(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ root = Path(temporary.name)+ (root / 'a.html').write_text('<table><tr><th>設立</th><td>2002年5月</td></tr><tr><th>所在地</th><td>東京都</td></tr></table>', encoding='utf-8')+ (root / 'b.html').write_text('<dl><dt>設立</dt><dd>2001年</dd></dl>', encoding='utf-8')+ (root / 'c.html').write_text('<dl><dt>商号</dt><dd>株式会社ブランド</dd></dl>', encoding='utf-8')+ pages = [{'url': 'https://brand.example/', 'final_url': 'https://www.brand.example/company', 'http_status': 200, 'cache': str(root / 'a.html')},+ {'url': 'https://brand.example/about', 'http_status': 404},+ {'url': 'https://brand.example/x', 'final_url': 'https://brand.example/x', 'http_status': 200, 'cache': str(root / 'b.html')},+ {'url': 'https://registry.example/brand', 'final_url': 'https://registry.example/brand', 'http_status': 200, 'cache': str(root / 'c.html')},+ {'url': 'https://brand.example/y', 'final_url': 'https://brand.example/y', 'cache': str(root / 'c.html')}]+ result = company_profiles.replay(pages, ['Brand'], {'brand.example'})+ self.assertEqual(list(result['facts']), ['location'])+ self.assertEqual(result['facts']['location']['source_url'], 'https://www.brand.example/company')++ def test_observed_fact_replaces_a_candidate_and_revert_lists_candidates(self):temporary = tempfile.TemporaryDirectory()self.addCleanup(temporary.cleanup)connection = sqlite3.connect(fresh_ledger(Path(temporary.name).resolve()))self.addCleanup(connection.close)- connection.executemany("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) VALUES(?,?,?,?,'2026-10-07','2026-10-07')",- [(1,'studio','Brand','brand'),(2,'studio','Other','other')])- aliases = [{'value': value, 'source_url': 'https://brand.example/', 'status': status}- for value,status in [('Brand JP','observed'),('Unverified','candidate'),('Other','observed')]]- self.assertEqual(company_profiles.fill_aliases(connection,1,aliases,batch='auto:company-profile@1'), ['Brand JP'])- self.assertEqual(connection.execute('SELECT alias,source FROM entity_alias WHERE entity_id=1').fetchall(),- [('Brand JP','auto:company-profile@1')])+ held = {'company_profile': {+ 'group': {'value': 'Group', 'source_url': 'https://brand.example/', 'status': 'candidate', 'source': 'auto:company-profile', 'batch': 'old'},+ 'location': {'value': '東京都', 'source_url': 'https://brand.example/', 'status': 'candidate', 'source': 'auto:company-profile', 'batch': 'old'}}}+ connection.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,metadata_json,created_at,updated_at) VALUES(1,'studio','Brand','brand',?,'2026-10-07','2026-10-07')",+ (json.dumps(held),))+ self.assertEqual(company_profiles.planned_revert(connection, 'auto:company-profile', 'old'),+ [{'entity_id': 1, 'entity': 'Brand', 'fields': ['group', 'location']}])+ fact = {'value': '大阪府', 'source_url': 'https://brand.example/company', 'evidence': '所在地:大阪府', 'status': 'observed'}+ self.assertEqual(company_profiles.fill(connection, 1, {'location': fact}, source='auto:company-profile', batch='new')['written'], ['location'])+ profile = json.loads(connection.execute('SELECT metadata_json FROM entity').fetchone()[0])['company_profile']+ self.assertEqual(profile['location']['value'], '大阪府')+ self.assertEqual(list(company_profiles.public_profile({'company_profile': profile})), ['location'])++ def test_landing_writes_only_replayed_facts_and_ignores_listed_aliases_and_links(self):+ from scripts import harvest_company_profiles as harvest++ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ root = Path(temporary.name).resolve()+ path = fresh_ledger(root)+ with sqlite3.connect(path) as connection:+ connection.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) VALUES(1,'studio','Brand','brand','2026-10-07','2026-10-07')")+ connection.execute("INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,created_at,updated_at) VALUES(1,'official','Brand','https://brand.example/','brand.example','2026-10-07','2026-10-07')")+ connection.close()+ (root / 'page.html').write_text('<table><tr><th>設立</th><td>2002年5月</td></tr></table>', encoding='utf-8')+ listed = {'value': 'Brand Group', 'source_url': 'https://brand.example/', 'evidence': 'Brand Group', 'status': 'observed'}+ plan = {'entities': [{'entity_id': 1, 'name': 'Brand', 'status': '已核查',+ 'facts': {'founded': {**listed, 'value': '2002-05'}, 'group': listed},+ 'pages': [{'url': 'https://brand.example/company', 'final_url': 'https://brand.example/company', 'http_status': 200, 'cache': str(root / 'page.html')}],+ 'aliases': [{'value': 'ブランド', 'source_url': 'https://brand.example/', 'status': 'observed'}],+ 'links': [{'entity_id': 1, 'link_kind': 'catalog', 'label': 'Brand', 'url': 'https://catalog.example/brand', 'status': 'observed'}]}]}+ (root / 'plan.json').write_text(json.dumps(plan, ensure_ascii=False), encoding='utf-8')+ args = SimpleNamespace(input=root / 'plan.json', db=path, apply=True, backup=root / 'backup.db',+ batch='auto:company-profile@test', output=root / 'receipt.json')+ self.assertEqual(harvest.land(args), 0)+ with closing(sqlite3.connect(path)) as connection:+ profile = json.loads(connection.execute('SELECT metadata_json FROM entity WHERE id=1').fetchone()[0])['company_profile']+ self.assertEqual(list(profile), ['founded'])+ self.assertEqual(profile['founded']['evidence'], '設立:2002年5月')+ self.assertEqual(connection.execute('SELECT count(*) FROM entity_alias').fetchone()[0], 0)+ self.assertEqual(connection.execute('SELECT url FROM entity_link').fetchall(), [('https://brand.example/',)])+ change = json.loads((root / 'receipt.json').read_text(encoding='utf-8'))['changes'][0]+ self.assertEqual(change['not_replayed'], ['group'])+ self.assertEqual(change['ignored'], {'aliases': 1, 'links': 1})++ def test_repair_demotes_unreplayable_fields_and_drops_batch_aliases_and_links(self):+ from scripts import repair_company_profile_landing as repair++ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ root = Path(temporary.name).resolve()+ path = fresh_ledger(root)+ batch = 'auto:company-profile@old'+ stamp = {'source': 'auto:company-profile', 'batch': batch, 'status': 'observed', 'source_url': 'https://brand.example/company'}+ profile = {'founded': {**stamp, 'value': '2002-05', 'evidence': '設立:2002年5月'},+ 'group': {**stamp, 'value': 'Brand Group', 'evidence': 'Brand Group:Brand'},+ 'location': {'source': 'auto:company-profile', 'batch': 'other', 'status': 'observed', 'value': '東京都',+ 'source_url': 'https://brand.example/company'}}+ with closing(sqlite3.connect(path)) as connection, connection:+ connection.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,metadata_json,created_at,updated_at) VALUES(1,'studio','Brand','brand',?,'2026-10-07','2026-10-07')",+ (json.dumps({'company_profile': profile}, ensure_ascii=False),))+ connection.execute("INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,created_at,updated_at) VALUES(1,'official','Brand','https://brand.example/','brand.example','2026-10-07','2026-10-07')")+ connection.execute("INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,metadata_json,created_at,updated_at) VALUES(1,'catalog','Brand','https://catalog.example/brand','catalog.example',?,'2026-10-07','2026-10-07')",+ (json.dumps({'source': 'auto:company-profile', 'batch': batch}),))+ connection.execute("INSERT INTO entity_alias(entity_id,alias,normalized_alias,source) VALUES(1,'ブランド','ブランド',?)", (batch,))+ (root / 'page.html').write_text('<table><tr><th>設立</th><td>2002年5月</td></tr></table>', encoding='utf-8')+ plan = {'entities': [{'entity_id': 1, 'pages': [{'url': 'https://brand.example/company', 'final_url': 'https://brand.example/company',+ 'http_status': 200, 'cache': str(root / 'page.html')}]}]}+ (root / 'plan.json').write_text(json.dumps(plan), encoding='utf-8')+ common = ['--db', str(path), '--batch', batch, '--plan', str(root / 'plan.json'), '--output', str(root / 'receipt.json')]+ self.assertEqual(repair.main(common), 0)+ with closing(sqlite3.connect(path)) as connection:+ self.assertEqual(connection.execute('SELECT count(*) FROM entity_alias').fetchone()[0], 1)+ self.assertEqual(repair.main([*common, '--apply', '--backup', str(root / 'backup.db')]), 0)+ with closing(sqlite3.connect(path)) as connection:+ held = json.loads(connection.execute('SELECT metadata_json FROM entity').fetchone()[0])['company_profile']+ self.assertEqual({key: fact['status'] for key, fact in held.items()},+ {'founded': 'observed', 'group': 'candidate', 'location': 'observed'})+ self.assertEqual(connection.execute('SELECT count(*) FROM entity_alias').fetchone()[0], 0)+ self.assertEqual(connection.execute('SELECT url FROM entity_link').fetchall(), [('https://brand.example/',)])+ self.assertEqual(json.loads((root / 'receipt.json').read_text(encoding='utf-8'))['summary'],+ {'keep': 1, 'evidence': 0, 'candidate': 1, 'aliases': 1, 'links': 1})++ def test_resume_retries_rate_limited_entities(self):+ from scripts import harvest_company_profiles as harvest++ self.assertTrue(harvest.settled({'status': '已核查', 'pages': [{'http_status': 200}]}))+ self.assertTrue(harvest.settled({'status': '未取得', 'reason': '没有可访问的已确认官网', 'pages': []}))+ self.assertFalse(harvest.settled({'status': '已核查', 'pages': [{'http_status': 200}, {'http_status': 429}]}))+ self.assertFalse(harvest.settled({'status': '未取得', 'pages': [{'http_status': 403}]}))+ self.assertFalse(harvest.settled({'status': '未取得', 'pages': [{'reason': 'ConnectTimeout'}]}))def test_public_profile_requires_public_source_and_known_nonempty_values(self):facts = {key: {'value': value, 'source_url': url} for key, value, url in [('country','日本','https://brand.example/company'), ('operator','secret','https://localhost/admin'), ('founded','','https://brand.example/'), ('telephone','123','https://brand.example/')]}