Files
aigc-home/scripts/report-hel806.py
T

62 lines
5.1 KiB
Python

"""Package lossless original/content-mapped/actual captures; never infer visual approval."""
from pathlib import Path
import concurrent.futures, hashlib, html, json, zipfile, csv
from PIL import Image, ImageDraw, ImageFont
ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT.parent/'evidence/hel806-final'
REPORT=ROOT.parent/'evidence/hel806/report'
REPORT.mkdir(parents=True,exist_ok=True)
data=json.loads((OUT/'results.json').read_text())
rows=[r for r in data['rows'] if r['name']!='toast']
assert len(rows)==408, f'Expected 34 states x 12, got {len(rows)}'
assert len(rows)==len({(r['name'],r['theme'],r['width']) for r in rows})
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',14)
manifest=[]
def convert(p):
im=Image.open(p).convert('RGB');q=p.with_suffix('.webp')
if not q.exists() or Image.open(q).convert('RGB').tobytes()!=im.tobytes():im.save(q,lossless=True,method=3)
assert Image.open(q).convert('RGB').tobytes()==im.tobytes()
return {'source':p.name,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'delivered':q.name,'sha256_webp':hashlib.sha256(q.read_bytes()).hexdigest(),'pixels_identical':True}
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
manifest=list(pool.map(convert, sorted((OUT/'shots').glob('*.png'))))
for r in rows:
stem=f"{r['name']}-{r['theme']}-{r['width']}"
pair_path=OUT/'shots'/(stem+'-pair.webp')
if pair_path.exists() and pair_path.stat().st_mtime>=max((OUT/'shots'/(stem+'-actual.webp')).stat().st_mtime,(OUT/'shots'/(stem+'-mapped.webp')).stat().st_mtime):continue
a=Image.open(OUT/'shots'/(stem+'-actual.webp')).convert('RGB');s=Image.open(OUT/'shots'/(stem+'-mapped.webp')).convert('RGB')
pair=Image.new('RGB',(a.width*2,a.height+32),'#181818');d=ImageDraw.Draw(pair)
d.text((10,8),'REFERENCE CONTENT MAPPED / '+r['basis'],font=font,fill='white');d.text((a.width+10,8),'ACTUAL ISOLATED API / '+stem,font=font,fill='white');pair.paste(s,(0,32));pair.paste(a,(a.width,32));pair.save(OUT/'shots'/(stem+'-pair.webp'),lossless=True,method=3)
# Twelve actual viewports per state, for layout inspection; native pairs remain available.
contacts=REPORT/'contacts';contacts.mkdir(exist_ok=True)
for name in sorted({r['name'] for r in rows}):
sheet=Image.new('RGB',(1920,3*302),'#202020');d=ImageDraw.Draw(sheet)
for r in [r for r in rows if r['name']==name]:
col=['night','day','grade','bluehour'].index(r['theme']);line=[1440,1366,1280].index(r['width'])
im=Image.open(OUT/'shots'/f"{name}-{r['theme']}-{r['width']}-actual.webp").convert('RGB');im.thumbnail((480,270));sheet.paste(im,(col*480,line*302+28));d.text((col*480+6,line*302+6),f"{name} / {r['theme']} / {r['width']}",font=font,fill='white')
sheet.save(contacts/(name+'.webp'),lossless=True)
# Source values, with no tolerance-based pass flag. A hidden region is not comparable.
with (REPORT/'key-values.csv').open('w') as f:
w=csv.writer(f);w.writerow(['state','theme','viewport','region','actual_xywh','reference_xywh','delta_xywh','basis'])
for r in rows:
for key,a in r['actual'].items():
b=r['sample'].get(key)
if not a or not b or a['width']<=0 or b['width']<=0:continue
values=lambda o:[round(o[k],4) for k in ['x','y','width','height']]
av,bv=values(a),values(b);w.writerow([r['name'],r['theme'],f"{r['width']}x{r['height']}",key,av,bv,[round(x-y,4)for x,y in zip(av,bv)],r['basis']])
(REPORT/'capture-manifest.json').write_text(json.dumps({'source_png_to_lossless_webp':manifest,'states':len({r['name']for r in rows}),'groups':len(rows),'errors':data['errors'],'blocked_external_origins':sorted(set(data['blocked']))},indent=2))
# A theme archive is self-contained and opens without a running server.
for theme in ['night','day','grade','bluehour']:
theme_rows=[r for r in rows if r['theme']==theme]
intro='<meta charset="utf-8"><title>HEL806 '+theme+'</title><style>body{font:15px system-ui;background:#181818;color:#eee}img{max-width:100%}a{color:#8ed3ff}details{margin:20px 0}</style><h1>HEL806 '+theme+'</h1><p>原图只读。mapped只映射内容;missing-reference 表示原件缺此状态。并排图左为映射参考,右为隔离实图,不代表全页通过。原始数值在results.json。</p>'
chunks=[intro]
for r in theme_rows:
stem=f"{r['name']}-{theme}-{r['width']}"
chunks.append('<details><summary>'+html.escape(stem+' · '+r['basis']+' · '+str(r.get('missing','')))+'</summary>'+f'<a href="shots/{stem}-original.webp">未改原图</a> · <a href="shots/{stem}-mapped.webp">内容映射参考</a> · <a href="shots/{stem}-actual.webp">实图</a><img loading="lazy" src="shots/{stem}-pair.webp"></details>')
with zipfile.ZipFile(REPORT/f'HEL806-{theme}.zip','w',zipfile.ZIP_DEFLATED,compresslevel=3) as z:
z.writestr('index.html','\n'.join(chunks));z.writestr('results.json',json.dumps(theme_rows,ensure_ascii=False,indent=2))
for r in theme_rows:
stem=f"{r['name']}-{theme}-{r['width']}"
for suffix in ['original','mapped','actual','pair']:
p=OUT/'shots'/f'{stem}-{suffix}.webp';z.write(p,'shots/'+p.name)
print(json.dumps({'groups':len(rows),'states':len({r['name']for r in rows}),'archives':{p.name:p.stat().st_size for p in REPORT.glob('*.zip')}},indent=2))