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

86 lines
6.7 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))
# Self-contained parts keep every state/three sizes together and each upload under 40 MB.
archives=[]
for theme in ['night','day','grade','bluehour']:
theme_rows=[r for r in rows if r['theme']==theme]
b4files=[p for p in (ROOT/'e2e/shots/hel732').glob(f'*-{theme}-*.png') if p.name.startswith(('home-','task-'))]
b4size=sum(p.stat().st_size for p in b4files)
chunks=[];current=[];objects={};weight=b4size
def files_for(group):
return [OUT/'shots'/f"{r['name']}-{theme}-{r['width']}-{suffix}.webp" for r in group for suffix in ['original','mapped','actual','pair']]
for name in dict.fromkeys(r['name'] for r in theme_rows):
group=[r for r in theme_rows if r['name']==name]
candidates={hashlib.sha256(p.read_bytes()).hexdigest():p for p in files_for(group)}
extra=sum(p.stat().st_size for h,p in candidates.items() if h not in objects)
if current and weight+extra>40_000_000:
chunks.append(current);current=[];objects={};weight=0
extra=sum(p.stat().st_size for p in candidates.values())
current+=group;objects.update(candidates);weight+=extra
if current:chunks.append(current)
for part,part_rows in enumerate(chunks,1):
media={};objects={}
for p in files_for(part_rows):
h=hashlib.sha256(p.read_bytes()).hexdigest();media[p.name]='assets/'+h+'.webp';objects[h]=p
doc=['<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+' / '+str(part)+'</h1><p>原图只读;mapped只映射内容。missing-reference 是缺依据;并排左参考、右隔离实图,不代表全页通过。此分包可独立解压阅读。B4 gallery 位于本主题 part1 的 B4-index.html</p>']
for r in part_rows:
stem=f"{r['name']}-{theme}-{r['width']}"
link=lambda suffix:media[stem+'-'+suffix+'.webp']
doc.append('<details><summary>'+html.escape(stem+' · '+r['basis']+' · '+str(r.get('missing','')))+'</summary>'+f'<a href="{link("original")}">未改原图</a> · <a href="{link("mapped")}">内容映射参考</a> · <a href="{link("actual")}">实图</a><img loading="lazy" src="{link("pair")}"></details>')
target=REPORT/f'HEL806-{theme}-part{part}.zip'
with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED,compresslevel=3) as z:
z.writestr('index.html','\n'.join(doc));z.writestr('results.json',json.dumps(part_rows,ensure_ascii=False,indent=2));z.writestr('media-files.json',json.dumps(media,indent=2))
for h,p in objects.items():z.write(p,'assets/'+h+'.webp')
if part==1:
b4doc=['<meta charset="utf-8"><h1>B4 '+theme+'</h1><p>沿用已批准内容/hero映射。原PNG保持不变;不把获批例外扩大解释。</p>']
for p in sorted(b4files):z.write(p,'b4/'+p.name);b4doc.append('<p>'+html.escape(p.name)+'</p><img style="max-width:100%" loading="lazy" src="b4/'+p.name+'">')
z.writestr('B4-index.html','\n'.join(b4doc))
assert target.stat().st_size<45_000_000
archives.append({'name':target.name,'bytes':target.stat().st_size,'groups':len(part_rows)})
(REPORT/'archives.json').write_text(json.dumps(archives,indent=2))
print(json.dumps({'groups':len(rows),'states':len({r['name']for r in rows}),'archives':archives},indent=2))