Automated Accessibility Regression Pipeline Using Computer Vision
As Sherlock, I'll engineer a robust, end-to-end accessibility (a11y) regression pipeline leveraging computer vision (CV) for screenshot diffing, heuristic validation for rule-based checks, human review loops for edge cases, and backlog integration for actionable triage. This pipeline detects visual a11y regressions (e.g., contrast loss, focus indicator disappearance, layout shifts affecting readability) triggered by UI changes in CI/CD.
The design prioritizes:
Automation-first : 80-90% pass rate via CV/heursitics.
False-positive minimization : Thresholds + ML-assisted diffs.
Scalability : Cloud-native, containerized.
Zero-downtime : Runs on staging/PR branches.
High-Level Architecture
mermaid Copy code
graph TD
A[Code Change / PR] --> B[CI/CD Trigger<br/>(GitHub Actions / Jenkins)]
B --> C[Deploy to Staging]
C --> D[Capture New Screenshots<br/>(Playwright)]
D --> E[Screenshot Diffing<br/>(pixelmatch + resemble.js)]
E --> F[CV Heuristic Validation<br/>(OpenCV + Tesseract)]
F --> G[Pass? / Diff < Threshold?]
G -->|Yes| H[Update Golden Baselines<br/>(Auto-merge PR)]
G -->|No| I[Generate Annotated Diffs<br/>(CV Highlights: Red=Contrast Fail)]
I --> J[Human Review Loop<br/>(Slack/Jira Notification + Dashboard)]
J --> K[Human Approve/Reject<br/>(API Callback)]
K -->|Reject| L[Backlog Integration<br/>(Create/Update Jira/GitHub Issue)]
K -->|Approve| H
L --> M[Block Merge / Notify Team]
Key Components & Implementation
1. Tools Stack
Component Tool/Library Rationale Screenshots Playwright Cross-browser, viewport/state-aware captures. Diffing pixelmatch + resemble.js Pixel-perfect + perceptual diffs (ignores minor anti-aliasing). CV Heuristics OpenCV (Python) + Tesseract OCR Detect text regions, sample colors, compute WCAG contrast (min 4.5:1). Human Review Slack + Retool/Streamlit Dashboard Interactive diffs with zoom/annotate. Backlog Jira API / GitHub Issues Auto-create tickets with attachments. Orchestration GitHub Actions (YAML) Serverless, integrates with PRs. Storage S3/GCS + Golden Repo Baselines versioned in Git. ML Boost Optional: Applitools Eyes SDK AI visual validation (free tier available).
2. Pipeline Steps (Detailed)
Step 1: Baseline Generation (One-time / On-Demand)
Run manually on main branch to capture "golden" screenshots.
Viewports: Mobile (375x667), Tablet (768x1024), Desktop (1920x1080).
States: Logged out/in, hover/focus, dark mode.
Store: Git repo (golden-screenshots/) + S3.
Playwright Script Snippet (capture-baseline.js):
javascript Copy code
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://staging.app.com');
await page.setViewportSize({ width: 1920, height: 1080 });
await page.locator('#focusable-btn').focus(); // Simulate focus
await page.screenshot({ path: 'golden-desktop-focus.png', fullPage: true });
await browser.close();
})();
Step 2: Trigger & Screenshot Capture (CI Job)
On PR push/merge: Deploy to ephemeral staging (e.g., Vercel/Netlify preview).
Replay exact same script as baseline, capture new screenshots.
Artifact: ZIP of new PNGs.
Step 3: Screenshot Diffing
Compare new vs. golden pixel-by-pixel.
Threshold: <5% diff = pass (configurable).
Output: Diff PNG (red=changed pixels).
Node.js Diff Script (diff-screenshots.js):
javascript Copy code
const pixelmatch = require('pixelmatch');
const { PNG } = require('pngjs');
const fs = require('fs');
const resemble = require('node-resemble-js');
async function diffImages baseline, current, output {
const img1 = PNG.sync.read(fs.readFileSync(baseline));
const img2 = PNG.sync.read(fs.readFileSync(current));
const { width, height } = img1;
const diff = new PNG({ width, height });
const numDiffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold: 0.1 });
fs.writeFileSync(output, PNG.sync.write(diff));
const percent = (numDiffPixels / (width * height)) * 100;
return percent < 5 ? 'PASS' : 'FAIL';
}
// Perceptual diff fallback
const data = await resemble(baseline).compareTo(current);
console.log(`MisMatch Score: ${data.misMatchPercentage}`);
Step 4: CV Heuristic Validation
Heuristics (WCAG-inspired):
Heuristic CV Implementation Contrast OCR text regions → Sample fg/bg colors → WCAG ratio ≥4.5:1 Focus Indicators Detect outlines (Canny edge) on focused elements; min 2px/3:1 contrast. Text Size OCR → Font height ≥16px (or 14px bold). Layout Shift Diff + homography to detect >10% shift in key elements. Image Alt Proxy Detect <img>-like regions (aspect ratio) without overlaid text.
Python CV Script (heuristic-check.py):
python Copy code
import cv2
import pytesseract
import numpy as np
from colorsys import rgb_to_hsv # For contrast calc
def check_contrast(image_path):
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
text_data = pytesseract.image_to_data(gray, output_type=pytesseract.Output.DICT)
fails = []
for i, conf in enumerate(text_data['conf']):
if conf > 60: # Reliable text
x, y, w, h = text_data['left'][i], text_data['top'][i], text_data['width'][i], text_data['height'][i]
text_roi = img[y:y+h, x:x+w]
fg = np.mean(text_roi) # Avg text color
bg = np.mean(img[y-10:y, x:x+w]) if y>10 else 255 # Sample bg
ratio = (max(fg, bg) + 0.05) / (min(fg, bg) + 0.05) # Simplified WCAG
if ratio < 4.5:
fails.append((x, y, w, h, ratio))
# Annotate fails in red
annotated = img.copy()
for box in fails:
cv2.rectangle(annotated, (box[0], box[1]), (box[0]+box[2], box[1]+box[3]), (0,0,255), 3)
cv2.imwrite('annotated-fail.png', annotated)
return len(fails) == 0
# Run: check_contrast('new-screenshot.png')
Integrate: Node calls Python via child_process.
Step 5: Human Review Loop
On fail: Upload diffs/annotated PNGs to S3.
Notify Slack: "🚨 A11y Regression: [PR Link] [Diff Image]".
Dashboard (Retool/Streamlit): Side-by-side viewer + "Approve" / "Reject + Comment" buttons.
API Callback: Updates GitHub check/status.
Step 6: Backlog Integration
On reject: Use Jira API / GitHub GraphQL.
javascript Copy code
// GitHub Issue Creation
const issue = await octokit.rest.issues.create({
owner: 'repo',
repo: 'app',
title: 'A11y Regression: Low Contrast in Header',
body: 'Detected via CV pipeline. Diff: ',
labels: ['a11y', 'regression'],
});
Link to PR, assign to a11y squad.
GitHub Actions Workflow (Full YAML)
yaml Copy code
name: A11y Regression Pipeline
on: [pull_request]
jobs:
a11y-regression:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy Staging # Custom action
run: vercel --prod=false
- name: Capture Screenshots
run: npx playwright test capture.js
- name: Diff & Heuristics
run: node diff-screenshots.js && python heuristic-check.py
- name: Human Review & Backlog
if: failure()
uses: actions/github-script@v6
with:
script: | # Slack notify + Jira ticket
// Implementation as above
Metrics & Monitoring
KPIs : False positive rate (<10%), MTTR (<1 day), Coverage (100% key flows).
Alerts : Datadog/Prometheus on fail rates.
Cost : ~$0.10/run (GitHub minutes + S3).
Benefits & Limitations
Benefits :
Catches visual regressions DOM tools (axe) miss (e.g., CSS contrast breaks).
Scalable to 1000s of screenshots.
Human-in-loop prevents alert fatigue.
Limitations :
Screenshot-only: Misses semantic a11y (ARIA); pair with axe-core DOM checks.
OCR inaccuracies: Tune with custom-trained Tesseract.
Extend: Add ML (YOLO for element detection).
Deploy this in <1 day. Need code repo or tweaks? Let me know! 🕵️♂️