capstone_testing_folder / screenshots /analysis_microlink.py
Aryaman25's picture
Add complete InsightUX guided testing project and models
517154b verified
Raw History Blame Contribute Delete
15.4 kB
"""InsightUX report adapter for Microlink multi-page gaze heatmaps."""
from __future__ import annotations
import base64
import os
import re
import shutil
from pathlib import Path
from core import analysis as _legacy_analysis
load_session = _legacy_analysis.load_session
session_summary = _legacy_analysis.session_summary
summarize_mouse = _legacy_analysis.summarize_mouse
def _generate_without_legacy_screenshots(session_dir: str | os.PathLike) -> str:
session = Path(session_dir)
screenshots = session / "screenshots"
hidden = session / ".microlink_legacy_screenshots_hidden"
moved = False
try:
if screenshots.exists():
if hidden.exists():
shutil.rmtree(hidden, ignore_errors=True)
screenshots.rename(hidden)
moved = True
return _legacy_analysis.generate_report(str(session))
finally:
if moved and hidden.exists():
if screenshots.exists():
shutil.rmtree(screenshots, ignore_errors=True)
hidden.rename(screenshots)
def _gallery_html(heatmaps: list[dict]) -> str:
"""Create one gallery with one exact PNG per visited URL."""
images = []
for i, item in enumerate(heatmaps, 1):
path = Path(item["composite_path"])
encoded = base64.b64encode(path.read_bytes()).decode("ascii")
images.append(
f'<img class="iux-gallery-image" alt="Webpage {i}" '
f'src="data:image/png;base64,{encoded}">'
)
n = len(images)
return f'''<style>
.iux-heatmap-gallery{{width:100%}}
.iux-gallery-head{{display:flex;justify-content:space-between;align-items:center;margin:0 0 12px}}
.iux-gallery-head h3{{margin:0;font-size:15px}}
.iux-gallery-count{{font-size:12px;color:var(--iux-text-dim,#666)}}
.iux-gallery-stage{{position:relative;width:100%;height:min(72vh,760px);min-height:360px;overflow-y:auto;overflow-x:hidden;border-radius:12px;background:#111;display:block;scroll-behavior:smooth}}
.iux-gallery-image{{display:none;width:100%;height:auto;max-width:100%;object-fit:contain;object-position:top center;cursor:zoom-in;margin:0 auto}}
.iux-gallery-image.active{{display:block}}
.iux-gallery-nav,.iux-gallery-fullscreen{{position:absolute;z-index:3;border:0;color:#fff;background:rgba(0,0,0,.58);cursor:pointer}}
.iux-gallery-nav{{top:50%;transform:translateY(-50%);width:44px;height:44px;border-radius:50%;font-size:28px}}
.iux-gallery-prev{{left:14px}} .iux-gallery-next{{right:14px}}
.iux-gallery-fullscreen{{right:14px;top:14px;width:40px;height:40px;border-radius:8px;font-size:19px}}
.iux-gallery-thumbs{{display:flex;gap:9px;overflow-x:auto;padding:12px 2px 4px}}
.iux-gallery-thumb{{flex:0 0 112px;height:72px;padding:2px;border:2px solid transparent;border-radius:8px;background:transparent;cursor:pointer;overflow:hidden}}
.iux-gallery-thumb.selected{{border-color:currentColor}}
.iux-gallery-thumb canvas{{width:100%;height:100%;display:block;border-radius:5px;background:#eee}}
.iux-gallery-thumb span{{display:block;font-size:10px;text-align:center;margin-top:2px}}
.iux-lightbox{{position:fixed;inset:0;z-index:99999;display:none;background:rgba(0,0,0,.95);align-items:flex-start;justify-content:center;overflow:hidden}}
.iux-lightbox.open{{display:flex}}
.iux-lightbox img{{width:96vw;max-width:none;height:auto;object-fit:contain;object-position:top center;transform-origin:top center;margin:4vh auto 8vh;cursor:grab}}
.iux-lightbox img:active{{cursor:grabbing}}
.iux-lightbox-scroll{{position:absolute;inset:0;overflow:auto;display:flex;justify-content:center;align-items:flex-start}}
.iux-lb-btn{{position:absolute;z-index:2;min-width:42px;height:42px;border:0;border-radius:8px;background:rgba(255,255,255,.14);color:#fff;cursor:pointer;font-size:22px}}
.iux-lb-close{{right:18px;top:18px;font-size:25px}} .iux-lb-prev{{left:18px;top:50%;transform:translateY(-50%)}} .iux-lb-next{{right:18px;top:50%;transform:translateY(-50%)}}
.iux-lb-out{{left:calc(50% - 110px);bottom:20px}} .iux-lb-reset{{left:calc(50% - 42px);bottom:20px}} .iux-lb-in{{right:calc(50% - 110px);bottom:20px}}
.iux-lb-count{{position:absolute;top:20px;left:50%;transform:translateX(-50%);color:#fff;font-size:13px}}
</style>
<section class="microlink-report-heatmap iux-heatmap-gallery">
<div class="iux-gallery-head"><h3 id="iuxGalleryTitle">Webpage 1</h3><span class="iux-gallery-count" id="iuxGalleryCount">1 / {n}</span></div>
<div class="iux-gallery-stage">
{''.join(images)}
<button class="iux-gallery-nav iux-gallery-prev" id="iuxGalleryPrev" type="button">&#8249;</button>
<button class="iux-gallery-nav iux-gallery-next" id="iuxGalleryNext" type="button">&#8250;</button>
<button class="iux-gallery-fullscreen" id="iuxGalleryFullscreen" type="button" title="View full screen">&#x26F6;</button>
</div>
<div class="iux-gallery-thumbs" id="iuxGalleryThumbs"></div>
</section>
<div class="iux-lightbox" id="iuxLightbox">
<div class="iux-lightbox-scroll"><img id="iuxLightboxImage" alt=""></div>
<button class="iux-lb-btn iux-lb-close" id="iuxLbClose" type="button">&times;</button>
<button class="iux-lb-btn iux-lb-prev" id="iuxLbPrev" type="button">&#8249;</button>
<button class="iux-lb-btn iux-lb-next" id="iuxLbNext" type="button">&#8250;</button>
<button class="iux-lb-btn iux-lb-out" id="iuxLbOut" type="button">&minus;</button>
<button class="iux-lb-btn iux-lb-reset" id="iuxLbReset" type="button">100%</button>
<button class="iux-lb-btn iux-lb-in" id="iuxLbIn" type="button">+</button>
<div class="iux-lb-count" id="iuxLbCount">1 / {n}</div>
</div>
<script>
(function(){{
if(window.__iuxGalleryInstalled)return;window.__iuxGalleryInstalled=true;
const imgs=[...document.querySelectorAll('.iux-gallery-image')];if(!imgs.length)return;
const thumbs=document.getElementById('iuxGalleryThumbs'),title=document.getElementById('iuxGalleryTitle'),count=document.getElementById('iuxGalleryCount');
const lb=document.getElementById('iuxLightbox'),lbImg=document.getElementById('iuxLightboxImage'),lbCount=document.getElementById('iuxLbCount');
let cur=0,zoom=1;
function show(i){{cur=(i+imgs.length)%imgs.length;imgs.forEach((x,j)=>x.classList.toggle('active',j===cur));title.textContent='Webpage '+(cur+1);count.textContent=(cur+1)+' / '+imgs.length;[...thumbs.children].forEach((x,j)=>x.classList.toggle('selected',j===cur));if(lb.classList.contains('open'))sync();}}
function sync(){{lbImg.src=imgs[cur].src;lbImg.alt='Webpage '+(cur+1);lbCount.textContent=(cur+1)+' / '+imgs.length;lbImg.style.transform='scale('+zoom+')';}}
function openLb(){{zoom=1;lb.classList.add('open');document.body.style.overflow='hidden';sync();}}
function closeLb(){{lb.classList.remove('open');document.body.style.overflow='';}}
imgs.forEach((img,i)=>{{img.onclick=openLb;const b=document.createElement('button');b.type='button';b.className='iux-gallery-thumb';const c=document.createElement('canvas');c.width=224;c.height=144;const ctx=c.getContext('2d');function draw(){{try{{const s=Math.min(c.width/img.naturalWidth,c.height/img.naturalHeight);const w=img.naturalWidth*s,h=img.naturalHeight*s;ctx.clearRect(0,0,c.width,c.height);ctx.drawImage(img,(c.width-w)/2,(c.height-h)/2,w,h);}}catch(e){{}}}}if(img.complete)draw();else img.addEventListener('load',draw,{{once:true}});b.appendChild(c);const l=document.createElement('span');l.textContent='Webpage '+(i+1);b.appendChild(l);b.onclick=()=>show(i);thumbs.appendChild(b);}});
document.getElementById('iuxGalleryPrev').onclick=()=>show(cur-1);document.getElementById('iuxGalleryNext').onclick=()=>show(cur+1);document.getElementById('iuxGalleryFullscreen').onclick=openLb;
document.getElementById('iuxLbClose').onclick=closeLb;document.getElementById('iuxLbPrev').onclick=()=>show(cur-1);document.getElementById('iuxLbNext').onclick=()=>show(cur+1);
document.getElementById('iuxLbIn').onclick=()=>{{zoom=Math.min(4,zoom+.25);sync();}};document.getElementById('iuxLbOut').onclick=()=>{{zoom=Math.max(.25,zoom-.25);sync();}};document.getElementById('iuxLbReset').onclick=()=>{{zoom=1;sync();}};
lb.onclick=e=>{{if(e.target===lb)closeLb();}};document.addEventListener('keydown',e=>{{if(!lb.classList.contains('open'))return;if(e.key==='Escape')closeLb();else if(e.key==='ArrowLeft')show(cur-1);else if(e.key==='ArrowRight')show(cur+1);}});
show(0);
}})();
</script>'''
def _inject_export_override(html: str) -> str:
"""Replace the old exported heatmap with the same Microlink gallery images."""
script = r'''<script>
(function(){
if(window.__iuxMicrolinkExportInstalled)return;window.__iuxMicrolinkExportInstalled=true;
const oldReady=window.__insightuxPrintReady||Promise.resolve();
function rebuild(){
const root=document.getElementById('printReport'),gallery=document.querySelector('.iux-heatmap-gallery');if(!root||!gallery)return;
const imgs=[...gallery.querySelectorAll('.iux-gallery-image')];if(!imgs.length)return;
const heading=[...root.querySelectorAll('.pp-section-title')].find(x=>x.textContent.trim()==='Attention Heatmaps');if(!heading)return;
const oldPage=heading.closest('.print-page'),parent=oldPage&&oldPage.parentNode;if(!parent)return;
const pages=[];
imgs.forEach(function(img,i){
const page=oldPage.cloneNode(true),body=page.querySelector('.pp-body');if(!body)return;body.innerHTML='';
const h=document.createElement('div');h.className='pp-section-title';h.style.cssText='font-size:15px;margin-bottom:10px';h.textContent='Webpage '+(i+1);body.appendChild(h);
const card=document.createElement('div');card.className='pp-card';card.style.cssText='display:flex;justify-content:center';
const image=document.createElement('img');image.src=img.src;image.alt='Webpage '+(i+1);image.style.cssText='display:block;width:auto;height:auto;max-width:100%;max-height:940px;object-fit:contain';card.appendChild(image);body.appendChild(card);pages.push(page);
});
pages.forEach(p=>parent.insertBefore(p,oldPage));parent.removeChild(oldPage);
const all=[...root.querySelectorAll('.print-page')],total=all.length;all.forEach((p,i)=>{const n=p.querySelector('.pp-f-page');if(n)n.textContent='Page '+(i+1)+' of '+total;});
}
window.__insightuxPrintReady=Promise.resolve(oldReady).then(rebuild);
})();
</script>'''
pos=html.lower().rfind('</body>')
return html[:pos]+script+html[pos:] if pos>=0 else html+script
def attach_microlink_heatmaps_to_report(report_path: str | os.PathLike, heatmaps: list[dict]) -> bool:
"""Embed all URL-scoped Microlink composites as one interactive gallery."""
report=Path(report_path)
if not report.exists() or not heatmaps:
return False
try:
for item in heatmaps:
if not Path(item.get("composite_path", "")).exists():
print(f"[MICROLINK] ERROR: missing composite for {item.get('url','')}")
return False
html=report.read_text(encoding="utf-8")
start=html.find("// ---------- Attention Heatmaps panel:")
end=html.find("// ---------- Element Attention Analysis:",start+1)
if start>=0 and end>start:
html=html[:start]+"// ---------- Microlink interactive gallery ----------\n"+html[end:]
html=re.sub(r'<section class="microlink-report-heatmap iux-heatmap-gallery".*?</section>\s*','',html,flags=re.DOTALL)
html=re.sub(r'<div class="microlink-report-heatmap".*?</div>\s*','',html,flags=re.DOTALL)
pattern=re.compile(r'<div\s+id=["\']heatmapArea["\']\s*>\s*</div>',re.I|re.S)
replacement='<div id="heatmapArea">'+_gallery_html(heatmaps)+'</div>'
html,count=pattern.subn(replacement,html,count=1)
if count==0:
print('[MICROLINK] ERROR: heatmapArea container was not found in generated report.')
return False
html=_inject_export_override(html)
report.write_text(html,encoding='utf-8')
final=report.read_text(encoding='utf-8')
expected=len(heatmaps);actual=final.count('class="iux-gallery-image"')
if actual!=expected:
print(f'[MICROLINK] ERROR: expected {expected} gallery images, found {actual}.')
return False
print(f'[MICROLINK] Verified: {actual} webpage image(s) in gallery; export uses the same images')
return True
except Exception as exc:
print(f'[MICROLINK] Multi-page report gallery attachment failed: {exc!r}')
return False
def attach_microlink_heatmap_to_report(report_path: str | os.PathLike, composite_path: str | os.PathLike, url: str = "") -> bool:
return attach_microlink_heatmaps_to_report(report_path,[{"url":url,"composite_path":str(composite_path)}])
def generate_report(session_dir):
return _generate_without_legacy_screenshots(session_dir)
_GALLERY_IMG_RE = re.compile(
r'<img class="iux-gallery-image"[^>]*?src="data:image/png;base64,([^"]+)"', re.S
)
def refresh_report_if_stale(report_path: str | os.PathLike) -> bool:
"""Rebuild a report written before the current template existed.
A report is a static HTML file written when its session ended, so template fixes
(for example the slanted chart labels) never reach older sessions. This rebuilds
the report once from the session's raw logs and puts the already-captured heatmap
images back, then leaves a marker so it is never repeated. The original is kept as
analysis_report.backup.html and restored if anything fails. Returns True if the
report was rebuilt."""
report = Path(report_path)
if not report.exists():
return False
session = report.parent
sentinel = session / ".report_refreshed"
backup = session / "analysis_report.backup.html"
tmp = session / ".refresh_tmp"
try:
old_html = report.read_text(encoding="utf-8")
if sentinel.exists() or "LABEL_ANGLE" in old_html:
return False # already built with the current template
shutil.copyfile(report, backup)
composites = []
tmp.mkdir(exist_ok=True)
for i, m in enumerate(_GALLERY_IMG_RE.finditer(old_html)):
png = tmp / f"page_{i}.png"
png.write_bytes(base64.b64decode(m.group(1)))
composites.append({"url": "", "composite_path": str(png)})
_generate_without_legacy_screenshots(str(session))
if composites and not attach_microlink_heatmaps_to_report(report, composites):
raise RuntimeError("could not re-attach heatmap images")
sentinel.write_text("1", encoding="utf-8")
return True
except Exception as exc:
print(f"[MICROLINK] report refresh failed, keeping the original: {exc!r}")
try:
if backup.exists():
shutil.copyfile(backup, report)
sentinel.write_text("1", encoding="utf-8") # don't retry on every open
except Exception:
pass
return False
finally:
shutil.rmtree(tmp, ignore_errors=True)
__all__=[
'generate_report','refresh_report_if_stale','load_session','session_summary','summarize_mouse',
'attach_microlink_heatmap_to_report','attach_microlink_heatmaps_to_report','_legacy_analysis'
]