Files
WoW-Hybrid-gateway/ops/content_db_reference.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

225 lines
15 KiB
Python

#!/usr/bin/env python3
"""Cache public content references; never install definitions or execute page scripts.
Octo is the preferred web reference; Capy is a separately labelled fallback.
Displayed values and links are evidence, not raw DBC fields or engine mappings.
"""
import argparse,datetime,hashlib,json,re
from dataclasses import dataclass,field
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import urljoin,urlsplit,parse_qs
from urllib.request import Request,urlopen
from urllib.error import HTTPError,URLError
ROOT=Path(__file__).resolve().parents[1]
HOSTS={'octo':'octowow.st','capy':'db.capycraft.org'}
KINDS=('item','spell','quest','npc','object','faction','itemset')
OCTO_TITLES={'item':'Items','spell':'Spells','quest':'Quests','npc':'NPCs',
'object':'Objects','faction':'Factions','itemset':'Item Sets'}
LIMIT=2*1024*1024
def url(site,kind,ident):
if site not in HOSTS or kind not in KINDS or type(ident)is not int or not 0<ident<2**31:raise ValueError('Explicit public database and source identity required')
return f'https://octowow.st/db/?{kind}={ident}'if site=='octo'else f'https://db.capycraft.org/{kind}/{ident}'
@dataclass
class Node:
tag:str
attrs:dict=field(default_factory=dict)
children:list=field(default_factory=list)
def nodes(self,tag=None):
for child in self.children:
if isinstance(child,Node):
if tag is None or child.tag==tag:yield child
yield from child.nodes(tag)
def text(self):
if self.tag in ('script','style'):return ''
return ' '.join(' '.join(c.text()if isinstance(c,Node)else c for c in self.children).split())
class Document(HTMLParser):
def __init__(self):super().__init__(convert_charrefs=True);self.root=Node('root');self.stack=[self.root];self.count=0
def handle_starttag(self,tag,attrs):
self.count+=1
if self.count>100000 or len(self.stack)>128:raise ValueError('Public page structure bound')
node=Node(tag,dict(attrs));self.stack[-1].children.append(node)
if tag not in ('area','base','br','col','embed','hr','img','input','link','meta','param','source','track','wbr'):self.stack.append(node)
def handle_endtag(self,tag):
for i in range(len(self.stack)-1,0,-1):
if self.stack[i].tag==tag:self.stack=self.stack[:i];break
def handle_data(self,data):self.stack[-1].children.append(data)
def linked_identity(href,base):
if not isinstance(href,str)or not href:return None
target=urlsplit(urljoin(base,href))
if target.scheme!='https'or target.hostname not in HOSTS.values():return None
match=re.fullmatch(r'/(item|spell|itemset|npc|quest|object|faction)/([1-9][0-9]{0,9})',target.path)
if match and int(match[2])<2**31:return dict(kind=match[1],id=int(match[2]),url=target.geturl())
query=parse_qs(target.query)
if target.hostname=='octowow.st'and target.path in('/db','/db/')and len(query)==1:
kind,values=next(iter(query.items()))
if kind in KINDS and len(values)==1 and re.fullmatch('[1-9][0-9]{0,9}',values[0])and int(values[0])<2**31:return dict(kind=kind,id=int(values[0]),url=target.geturl())
return None
def parse(site,kind,ident,raw):
address=url(site,kind,ident)
if not isinstance(raw,bytes)or not 0<len(raw)<=LIMIT:raise ValueError('Bounded public HTML bytes required')
text=raw.decode('utf-8',errors='replace');doc=Document();doc.feed(text)
result=dict(site=site,kind=kind,id=ident,url=address,body_sha256=hashlib.sha256(raw).hexdigest(),usable_as_content=False,engine_mapping_verified=False)
visible=doc.root.text().lower()
if 'verifying your browser'in visible or 'ddos protection by'in visible or 'just a moment'in visible:
return dict(result,status='browser-verification-required')
identities=[n for n in doc.root.nodes('div')if 'detail-identity'in n.attrs.get('class','').split()and n.attrs.get('data-entity-key')==f'{kind}:{ident}']
identity=len(identities)==1 and any(n.text()for n in identities[0].nodes('h1'))
if site=='octo':
title=' '.join(n.text()for n in doc.root.nodes('title'))
# Some AoWoW record types have no tooltip block. A heading alone is
# insufficient: retain the existing positive identity gate until a
# captured type-specific page establishes its real identity marker.
identity=any(n.attrs.get('id')in(f'tooltip{ident}',f'tooltip{ident}-generic')for n in doc.root.nodes())and (' - '+OCTO_TITLES[kind]+' - ')in title
if not identity:return dict(result,status='record-identity-not-proven')
titles=[n.text()for n in (identities[0].nodes('h1')if site=='capy'else doc.root.nodes('h1'))];result['name']=titles[0]if titles else None
if site=='capy':
icons=[n.attrs.get('src')for n in identities[0].nodes('img')if n.attrs.get('src')]
if len(icons)==1:result['displayed_icon_url']=urljoin(address,icons[0])
# Use the rich detail tables. Capy's convenience sidebar can disagree with
# its original table; never silently promote those shifted summary fields.
facts={};effects=[];relations=[]
for table in doc.root.nodes('table'):
if 'grid'not in table.attrs.get('class','').split():continue
for row in table.nodes('tr'):
cells=[n for n in row.children if isinstance(n,Node)and n.tag in('th','td')]
if len(cells)!=2 or cells[0].tag!='th':continue
key,value=cells[0].text(),cells[1].text()
if not key or not value:continue
facts.setdefault(key,set()).add(value)
effect=re.fullmatch(r'Effect #([1-9][0-9]*)',key)
if effect:
entry=dict(index=int(effect[1]),display_text=value,links=[])
effect_type=re.match(r'\(([0-9]+)\)',value)
if effect_type:entry['displayed_effect_type']=int(effect_type[1])
aura=re.search(r'Apply Aura #([0-9]+)',value)
if aura:entry['displayed_aura_type']=int(aura[1])
for anchor in cells[1].nodes('a'):
link=linked_identity(anchor.attrs.get('href',''),address)
if link:entry['links'].append(dict(link,label=anchor.text()))
if entry not in effects:effects.append(entry)
for section in doc.root.nodes('section'):
headings=[n.text()for n in section.nodes('h2')]
# Preserve the site's relation label. "Related", quest rewards,
# objectives, vendor stock and loot are not interchangeable with a
# trigger-spell edge. Do not lose them or infer execution semantics.
if not headings:continue
for anchor in section.nodes('a'):
link=linked_identity(anchor.attrs.get('href',''),address)
if link:
relation=dict(section=headings[0],target=link,label=anchor.text())
if relation not in relations:relations.append(relation)
result.update(status='parsed-reference',usable_as_content=True,fields={k:next(iter(v))for k,v in sorted(facts.items())if len(v)==1},field_conflicts={k:sorted(v)for k,v in sorted(facts.items())if len(v)>1},effects=effects,relations=relations)
return result
def correlate(references):
"""Typed cross-category reference graph, never executable engine definitions.
Preserve relationship labels and cross-source disagreements. An incoming
loot/reward/See Also link is not a trigger, and equal IDs of different record
types are different nodes. Repeated links and legitimate cycles are finite.
"""
if not isinstance(references,list)or len(references)>250000:raise ValueError('Bounded public reference inventory required')
grouped={};edges={}
def key(kind,ident):
url('capy',kind,ident)
return kind+':'+str(ident)
for r in references:
site=r.get('site');node=key(r.get('kind'),r.get('id'))
if site not in HOSTS:raise ValueError('Known public source required')
if r.get('url')!=url(site,r['kind'],r['id']):raise ValueError('Reference URL and typed identity differ')
if not r.get('usable_as_content'):continue
if not re.fullmatch('[0-9a-f]{64}',r.get('body_sha256','')):raise ValueError('Captured content hash required')
versions=grouped.setdefault(node,[])
if not any(v['site']==site and v['body_sha256']==r['body_sha256']for v in versions):versions.append(r)
relations=[(x['section'],x['target'],x.get('label',''))for x in r.get('relations',[])]
for effect in r.get('effects',[]):
relations.extend(('Effect #'+str(effect['index']),link,link.get('label',''))for link in effect.get('links',[]))
for relation,target,label in relations:
other=key(target['kind'],target['id']);edge=(node,relation,other)
evidence=dict(site=site,body_sha256=r['body_sha256'],label=label)
known=edges.setdefault(edge,[])
if evidence not in known:known.append(evidence)
nodes=[]
for node,versions in sorted(grouped.items()):
preferred=[v for v in versions if v['site']=='octo']or[v for v in versions if v['site']=='capy']
conflicts={}
fields=sorted({f for r in versions for f in r.get('fields',{})})
for f in fields:
values=sorted({r['fields'][f]for r in versions if f in r.get('fields',{})})
if len(values)>1:conflicts[f]=values
nodes.append(dict(key=node,kind=versions[0]['kind'],id=versions[0]['id'],
preferred_site=preferred[0]['site'],preferred_record=preferred[0]if len(preferred)==1 else None,
ambiguous_preferred_capture=len(preferred)>1,field_disagreements=conflicts,
sources=[dict(site=v['site'],body_sha256=v['body_sha256'],url=v['url'])for v in versions]))
known=set(grouped);targets={e[2]for e in edges}
return dict(kind='public-content-reference-graph',schema_version=1,
categories=list(KINDS),nodes=nodes,
edges=[dict(source=a,relation=b,target=c,evidence=sorted(e,key=lambda v:(v['site'],v['body_sha256'],v['label'])))for(a,b,c),e in sorted(edges.items())],
unresolved_targets=sorted(targets-known),records_by_category={k:sum(n['kind']==k for n in nodes)for k in KINDS},
captures_considered=len(references),installed=False,engine_mapping_verified=False,
limits=['Reference labels are retained, not inferred gameplay execution semantics.',
'Preferred public source is Octo; Capy-only findings remain separately identified.',
'Missing references and contradictory sources require source-data/engine validation before conversion.'])
def captured_references(directories):
"""Reparse hash-pinned public captures with the current shared parser."""
records=[];seen=set()
for directory in directories:
directory=Path(directory).resolve()
if not directory.is_relative_to(ROOT/'runtime')or not directory.is_dir():raise ValueError('Owned public capture directory required')
for path in sorted(directory.glob('*.json')):
if path.is_symlink()or path.stat().st_size>LIMIT:raise ValueError('Regular bounded reference metadata required')
r=json.loads(path.read_text())
if not isinstance(r,dict)or r.get('site')not in HOSTS or r.get('kind')not in KINDS:continue
url(r['site'],r['kind'],r.get('id')) # Validate before forming a capture filename.
capture=path.with_name(r['site']+'-'+r['kind']+'-'+str(r['id'])+'.html')
if not capture.is_file():
if r.get('usable_as_content'):raise ValueError('Usable reference lacks its retained public body')
continue
if capture.is_symlink()or capture.stat().st_size>LIMIT:raise ValueError('Regular bounded public capture required')
raw=capture.read_bytes();digest=hashlib.sha256(raw).hexdigest()
if digest!=r.get('body_sha256'):raise ValueError('Public capture body hash differs')
identity=(r['site'],r['kind'],r['id'],digest)
if identity in seen:continue
seen.add(identity);records.append(parse(r['site'],r['kind'],r['id'],raw))
if len(records)>250000:raise ValueError('Public capture inventory bound')
return records
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--site',choices=HOSTS);p.add_argument('--kind',choices=KINDS);p.add_argument('--id',type=int);p.add_argument('--output',type=Path,required=True);p.add_argument('--html',type=Path,help='Parse a retained public capture without any request');p.add_argument('--captures',type=Path,nargs='+',help='Correlate all retained public record types offline; no HTTP or client changes');a=p.parse_args()
output=a.output.resolve()
if not output.is_relative_to(ROOT/'runtime')or output.exists():p.error('Fresh owned runtime output required')
output.parent.mkdir(parents=True,exist_ok=True)
if a.captures:
if any(v is not None for v in(a.site,a.kind,a.id,a.html)):p.error('Capture graph mode takes no individual record arguments')
result=correlate(captured_references(a.captures));output.write_text(json.dumps(result,indent=2,sort_keys=True)+'\n')
print('Correlated',len(result['nodes']),'public records and',len(result['edges']),'typed relationships; no definitions installed.')
return 0
if a.site is None or a.kind is None or a.id is None:p.error('Individual lookup requires site, kind and ID')
address=url(a.site,a.kind,a.id)
result=dict(site=a.site,kind=a.kind,id=a.id,url=address,processed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),usable_as_content=False,engine_mapping_verified=False)
raw=None
if a.html:raw=a.html.read_bytes();result['capture_path']=str(a.html);result['offline_capture']=True
else:
result['retrieved_at']=datetime.datetime.now(datetime.timezone.utc).isoformat()
try:
with urlopen(Request(address,headers={'User-Agent':'WoW-Hybrid-local-compatibility-reference/1.0'}),timeout=15)as response:
raw=response.read(LIMIT+1);result.update(http_status=response.status,final_url=response.url)
except HTTPError as error:result.update(http_status=error.code,status='not-indexed-or-unavailable'if error.code==404 else'http-error')
except(URLError,TimeoutError)as error:result.update(status='fetch-error',error=str(error)[:1000])
if raw is not None:
result.update(parse(a.site,a.kind,a.id,raw))
if not a.html:
capture=output.with_suffix('.html');capture.write_bytes(raw);result['capture_path']=str(capture)
output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps(result,indent=2,sort_keys=True)+'\n');print(result['status'],address,'->',output)
return 0 if result['usable_as_content']else 2
if __name__=='__main__':raise SystemExit(main())