capstone_testing_folder / screenshots /chrome_gaze_heatmap_runtime.py
Aryaman25's picture
Add complete InsightUX guided testing project and models
517154b verified
Raw History Blame Contribute Delete
13.4 kB
"""Real Google Chrome full-page screenshot + InsightUX gaze heatmap runtime.
This module replaces ONLY the screenshot acquisition part of the working
Microlink runtime. Gaze samples, coordinate mapping, buffering and heatmap
rendering are kept equivalent to the existing runtime.
The screenshot is acquired by a dedicated real Google Chrome process. The
participant-facing pywebview/WebView2 instance is never mutated for capture.
"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
from urllib.parse import urlparse
import cv2
import numpy as np
from PIL import Image
from screenshots.chrome_fullpage_capture import capture_with_real_chrome_async
from screenshots.microlink_gaze_heatmap_runtime import MicrolinkHeatmapSession
from screenshots.microlink_gaze_heatmap_runtime import microlink_api_key
@dataclass(frozen=True)
class ChromeImageGeometry:
screenshot_width: int
screenshot_height: int
@classmethod
def from_png(cls, path: str | Path) -> "ChromeImageGeometry":
with Image.open(path) as im:
return cls(int(im.width), int(im.height))
@dataclass(frozen=True)
class MappedGazePoint:
url: str
timestamp_ms: float
page_x: float
page_y: float
image_x: float
image_y: float
def map_gaze_sample(sample, image_geometry: ChromeImageGeometry) -> MappedGazePoint:
"""Map one real Phase-3 GazeSample into the real-Chrome full-page PNG."""
vw = float(sample.viewport_width)
vh = float(sample.viewport_height)
pw = float(sample.page_width)
ph = float(sample.page_height)
if vw <= 0 or vh <= 0 or pw <= 0 or ph <= 0:
raise ValueError("Invalid gaze/page geometry")
# Existing gaze contract: fx/fy are normalized viewport coordinates.
viewport_x = float(sample.fx) * vw
viewport_y = float(sample.fy) * vh
# Use the scroll captured with this exact gaze sample.
page_x = viewport_x + float(sample.scroll_x)
page_y = viewport_y + float(sample.scroll_y)
# Normalize full-page CSS coordinates into the actual PNG dimensions.
image_x = page_x / pw * image_geometry.screenshot_width
image_y = page_y / ph * image_geometry.screenshot_height
image_x = max(0.0, min(image_x, image_geometry.screenshot_width - 1.0))
image_y = max(0.0, min(image_y, image_geometry.screenshot_height - 1.0))
return MappedGazePoint(
url=str(sample.url),
timestamp_ms=float(sample.timestamp_ms),
page_x=page_x,
page_y=page_y,
image_x=image_x,
image_y=image_y,
)
def map_samples(samples: Iterable, image_geometry: ChromeImageGeometry):
return [map_gaze_sample(s, image_geometry) for s in samples]
class ChromeHeatmapSession:
"""Owns one URL-scoped Chrome screenshot and its gaze heatmap."""
def __init__(self, session_dir: str | Path, url: str, window, capture_guard=None):
self.session_dir = Path(session_dir)
self.url = str(url)
self.window = window
self.capture_guard = capture_guard
self.output_dir = self.session_dir / "chrome_heatmap"
self.output_dir.mkdir(parents=True, exist_ok=True)
safe_host = urlparse(self.url).netloc.replace(":", "_") or "page"
url_hash = hashlib.sha1(self.url.encode("utf-8")).hexdigest()[:12]
stem = f"{safe_host}_{url_hash}"
self.screenshot_path = self.output_dir / f"{stem}_fullpage.png"
self.points_path = self.output_dir / f"{stem}_gaze_points.jsonl"
self.overlay_path = self.output_dir / f"{stem}_heatmap_overlay.png"
self.final_path = self.output_dir / f"{stem}_heatmap_composite.png"
self._lock = threading.RLock()
self._samples = []
self._mapped = []
self._capture_thread = None
self._capture_done = threading.Event()
self._capture_error = None
self._geometry = None
self._rendered = False
self._discarded = False
self._fallback_started = False
self._fallback_thread = None
self._fallback_session = None
@property
def ready(self) -> bool:
with self._lock:
return self._geometry is not None
@property
def capture_error(self):
return self._capture_error
@property
def discarded(self) -> bool:
return self._discarded
def start_capture(self):
if self._capture_thread and self._capture_thread.is_alive():
return
self._capture_thread = threading.Thread(
target=self._capture_worker,
name="chrome-fullpage-screenshot",
daemon=True,
)
self._capture_thread.start()
def _capture_worker(self):
done = threading.Event()
def _finish_success():
self._capture_done.set()
done.set()
def _start_microlink_fallback(reason):
with self._lock:
if self._fallback_started or self._geometry is not None:
return
self._fallback_started = True
print(f"[CHROME-FALLBACK] Chrome failed for {self.url}; trying Microlink: {reason!r}")
def fallback_worker():
try:
# Reuse the original Microlink implementation, including
# its shared cache, usage accounting and API retry logic.
fallback = MicrolinkHeatmapSession(
self.session_dir,
self.url,
api_key=microlink_api_key(),
)
with self._lock:
self._fallback_session = fallback
fallback.start_capture()
fallback.wait_for_capture(None)
if not fallback.ready or not fallback.screenshot_path.exists():
raise RuntimeError(fallback.capture_error or "Microlink fallback did not produce a screenshot")
# The rest of the Chrome heatmap pipeline consumes one
# screenshot path. Put the successful Microlink PNG at that
# exact path, without changing gaze mapping or rendering.
self.screenshot_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(fallback.screenshot_path, self.screenshot_path)
with Image.open(self.screenshot_path) as im:
width, height = int(im.width), int(im.height)
with self._lock:
self._geometry = ChromeImageGeometry(width, height)
self._capture_error = None
print(f"[MICROLINK-FALLBACK] Screenshot ready: {width}x{height} -> {self.screenshot_path}")
self._remap_buffered_samples()
except Exception as exc:
with self._lock:
self._capture_error = repr(exc)
self._discarded = True
print(f"[MICROLINK-FALLBACK] Screenshot capture failed; discarding page {self.url}: {exc!r}")
finally:
_finish_success()
self._fallback_thread = threading.Thread(
target=fallback_worker,
name="microlink-fallback-screenshot",
daemon=True,
)
self._fallback_thread.start()
def on_complete(path):
try:
with Image.open(self.screenshot_path) as im:
width, height = int(im.width), int(im.height)
with self._lock:
self._geometry = ChromeImageGeometry(width, height)
print(f"[CHROME] Screenshot ready: {width}x{height} -> {self.screenshot_path}")
self._remap_buffered_samples()
_finish_success()
except Exception as exc:
_start_microlink_fallback(exc)
def on_error(exc):
_start_microlink_fallback(exc)
try:
# The job is sent to the dedicated real-Google-Chrome worker. Once
# accepted, it is independent of the live WebView2 page. Chrome
# itself performs the initial attempt plus up to two requeues.
capture_with_real_chrome_async(
url=self.url,
output_path=self.screenshot_path,
guard=self.capture_guard,
on_complete=on_complete,
on_error=on_error,
)
# Keep this worker alive until either Chrome succeeds or the
# Microlink fallback finishes.
done.wait()
except Exception as exc:
on_error(exc)
done.wait()
def ingest(self, samples: Iterable):
"""Consume already-created GazeSample objects from the Phase-3 bridge."""
samples = list(samples)
if not samples:
return
with self._lock:
self._samples.extend(samples)
if self._geometry is not None:
for sample in samples:
self._map_one_locked(sample)
def _remap_buffered_samples(self):
with self._lock:
self._mapped.clear()
for sample in self._samples:
self._map_one_locked(sample)
def _map_one_locked(self, sample):
if self._geometry is None:
return
try:
point = map_gaze_sample(sample, self._geometry)
self._mapped.append(point)
except Exception:
return
def wait_for_capture(self, wait_seconds: float | None = None):
"""Wait until real Chrome finishes this accepted request.
None means wait without an artificial report-side timeout. The Chrome
capture service itself has a bounded navigation timeout and converts
network/server failures into the session's capture_error callback.
"""
if wait_seconds is None:
return self._capture_done.wait()
return self._capture_done.wait(max(0.0, float(wait_seconds)))
def finalize(self, wait_seconds: float | None = None):
"""Wait for capture and render once; safe to call from queue/report finalization."""
self.wait_for_capture(wait_seconds)
with self._lock:
if self._geometry is None:
return False
if self._rendered and self.final_path.exists():
return True
points = list(self._mapped)
self._write_points(points)
self._render(points)
with self._lock:
self._rendered = True
return True
def _write_points(self, points):
with self.points_path.open("w", encoding="utf-8") as f:
for p in points:
f.write(json.dumps({
"url": p.url,
"timestamp_ms": p.timestamp_ms,
"page_x": p.page_x,
"page_y": p.page_y,
"image_x": p.image_x,
"image_y": p.image_y,
}, ensure_ascii=False) + "\n")
def _render(self, points):
base = cv2.imread(str(self.screenshot_path), cv2.IMREAD_COLOR)
if base is None:
raise RuntimeError(f"Could not read Chrome PNG: {self.screenshot_path}")
height, width = base.shape[:2]
density = np.zeros((height, width), dtype=np.float32)
for p in points:
x = int(round(p.image_x))
y = int(round(p.image_y))
if 0 <= x < width and 0 <= y < height:
density[y, x] += 1.0
# A real accumulation field: repeated samples increase density instead
# of overwriting previous samples.
density = cv2.GaussianBlur(density, (0, 0), sigmaX=18, sigmaY=18)
if density.max() > 0:
# Percentile normalization prevents one extreme point from making
# the rest of the session visually disappear.
scale = float(np.percentile(density[density > 0], 99.0))
scale = max(scale, 1e-6)
normalized = np.clip(density / scale, 0.0, 1.0)
else:
normalized = density
heat_bgr = cv2.applyColorMap(
(normalized * 255).astype(np.uint8),
cv2.COLORMAP_JET,
)
alpha = (normalized * 0.72).astype(np.float32)[..., None]
alpha[normalized <= 0] = 0.0
composite = (
base.astype(np.float32) * (1.0 - alpha)
+ heat_bgr.astype(np.float32) * alpha
).clip(0, 255).astype(np.uint8)
cv2.imwrite(str(self.overlay_path), heat_bgr)
cv2.imwrite(str(self.final_path), composite)
print(f"[CHROME] Heatmap saved: {self.final_path}")
__all__ = [
"ChromeImageGeometry",
"MappedGazePoint",
"map_gaze_sample",
"map_samples",
"ChromeHeatmapSession",
]