repair-presentation-check.py

back to table · edit · history · where entries came from · files · download

4758 bytes, as of the version from 2026-11-16 22:11 (current). Recorded here, not run.

"""Render saved authenticated live HTML; no browser credential is required.

Usage: python3 presentation_check.py before|after
Requires shared Playwright runtime (paths configured by the campaign).
"""
import sys,os,json,hashlib,collections,importlib.metadata
from pathlib import Path
from playwright.sync_api import sync_playwright
W=Path(os.environ['TMPDIR']);stage=sys.argv[1]
assert stage in ('before','after','final')
doc=json.loads((W/(stage+'-document.json')).read_text())
with sync_playwright() as p:
 b=p.chromium.launch(headless=True,args=['--no-sandbox','--disable-dev-shm-usage'])
 page=b.new_page(viewport={'width':1500,'height':1000},device_scale_factor=1)
 page_errors=[];page.on('pageerror',lambda e:page_errors.append(str(e)))
 page.route('https://numberdb.org/T728',lambda r:r.fulfill(status=200,content_type='text/html',body=(W/(stage+'-page.html')).read_bytes()))
 page.goto('https://numberdb.org/T728',wait_until='networkidle',timeout=60000)
 page.evaluate('document.fonts.ready')
 page.wait_for_timeout(2000)
 if page.evaluate("typeof MathJax !== 'undefined' && !!MathJax.startup"):
  page.evaluate('MathJax.startup.promise')
 page.evaluate("document.querySelectorAll('details.prose-more').forEach(e=>e.open=true)")
 # Validate the anchor check itself on known-good and deliberately colliding controls.
 controls=page.evaluate('''() => {
 const check = html => {let d=new DOMParser().parseFromString(html,'text/html');return d.querySelectorAll('[id="mpmath"]').length===1 && !!d.getElementById('mpmath')?.querySelector('a[href="https://mpmath.org/doc/current/functions/zeta.html"]')};
 const good='<div id="example"><code>sample</code></div><div id="mpmath"><a href="https://mpmath.org/doc/current/functions/zeta.html">docs</a></div>';
 const bad=good.replace('id="example"','id="mpmath"');
 return {known_answer_control:check(good),duplicate_anchor_negative_control_rejected:!check(bad)};
 }''')
 assert all(controls.values())
 info=page.evaluate('''() => {
 let ids=[...document.querySelectorAll('[id="mpmath"]')];let citation=[...document.querySelectorAll('a.CITE')].find(e=>e.getAttribute('href')==='#mpmath');
 if(!citation)throw new Error('Missing citation');citation.click();
 return {citation_text:citation.textContent,citation_href:citation.getAttribute('href'),matched_count:ids.length,targets:ids.map(e=>({text:e.innerText,contains_code:!!e.querySelector('code'),external_links:[...e.querySelectorAll('a')].map(a=>a.href)}))};
 }''')
 page.wait_for_timeout(1000)
 info.update(page.evaluate('''() => ({fragment:location.hash,target_text:document.querySelector(':target')?.innerText,target_external_links:[...document.querySelector(':target').querySelectorAll('a')].map(a=>a.href),all_ids:[...document.querySelectorAll('[id]')].map(e=>e.id)})'''))
 counts=collections.Counter(info.pop('all_ids'));info['duplicate_ids']={k:v for k,v in counts.items() if v>1}
 expected='https://mpmath.org/doc/current/functions/zeta.html'
 correct=info['matched_count']==1 and expected in info['target_external_links'] and info['fragment']=='#mpmath'
 if stage=='before':assert not correct and info['matched_count']==2
 else:assert correct and not info['duplicate_ids']
 info['documentation_target_correct']=correct
 info['citation_audit']=page.locator('a.CITE').evaluate_all("es=>es.map(e=>({href:e.getAttribute('href'),target_count:[...document.querySelectorAll('[id]')].filter(t=>('#'+t.id)===e.getAttribute('href')).length}))")
 if stage!='before':assert all(e['target_count']==1 for e in info['citation_audit'])
 rows=page.locator('.table-block').evaluate_all('es=>es.map(e=>({id:e.id,text:e.innerText}))')
 rows={e['id']:e['text'].replace('\n','') for e in rows if e['id'] in doc['Numbers']}
 assert len(rows)==105 and all(v in rows[k] for k,v in doc['Numbers'].items())
 program=next(iter(doc['Programs'].values()))['code']
 code=page.locator('pre code').all_text_contents()
 assert program in code
 info.update(controls=controls,entry_count=len(rows),all_stored_rows_rendered=True,code_content_exact=True,page_errors=page_errors,browser_version=b.version,playwright_version=importlib.metadata.version('playwright'),html_sha256=hashlib.sha256((W/(stage+'-page.html')).read_bytes()).hexdigest())
 page.screenshot(path=str(W/(stage+'-citation-target.png')))
 if stage in ('after','final'):
  for title in ['Programs','Data properties','References','Similar tables']:
   page.locator('.table-section-title').filter(has_text=title).first.scroll_into_view_if_needed()
   page.screenshot(path=str(W/(stage+'-'+title.lower().replace(' ','-')+'.png')))
 (W/(stage+'-rendered-page.txt')).write_text(page.inner_text('body'))
 (W/(stage+'-anchor-results.json')).write_text(json.dumps(info,indent=2)+'\n')
 print(json.dumps(info,indent=2));b.close()