File size: 6,071 Bytes
28e3615 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import puppeteer from "puppeteer-core";
import fs from "fs";
const S = "/Users/umer/Documents/hf/tools/browser-tests/out";
const b = await puppeteer.launch({ executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", headless: true, userDataDir: S + "/prof_exam", protocolTimeout: 90000 });
const p = await b.newPage(); await p.setCacheEnabled(false);
const errs = []; p.on("pageerror", (e) => errs.push(e.message));
await p.setRequestInterception(true);
const cors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Methods": "POST, OPTIONS" };
p.on("request", (r) => {
const u = r.url();
if (u.includes("cdn.jsdelivr.net/npm/@huggingface/transformers")) return r.respond({ status: 200, contentType: "application/javascript", headers: cors, body: "export const env={}; export async function pipeline(){ return async()=>[{label:'high_risk',score:.9}]; }" });
if (u.includes("workers.dev") && r.method() === "OPTIONS") return r.respond({ status: 204, headers: cors, body: "" });
if (u.includes("workers.dev")) return r.respond({ status: 200, contentType: "application/json", headers: cors, body: JSON.stringify({ tier: "limited_risk", rationale: "stub" }) });
if (/\.onnx|clarity\.ms/.test(u)) return r.abort();
r.continue();
});
const RIGHT = { "How does an AI model": "It finds patterns", "A system that scores citizens": "Prohibited", "An AI tool that ranks job": "High risk", "A phone voice agent": "Limited risk",
"Your dataset has 600": "200", "What is the test set": "Measuring the final model", "A reworded copy": "The test score looks better", "What does fine-tuning": "Teaches an already",
"100 cases, 5 of them": "Recall on the banned", "Model A scores 82%": "Probably nothing yet", "Your model gets every voice": "Whether the training data", "Which job is best done": "Checking whether training compute" };
const answer = (mode) => p.evaluate((RIGHT, mode) => {
document.querySelectorAll(".exam-q").forEach((fs, n) => {
const q = fs.querySelector("legend").textContent.replace(/^\d+\.\s*/, "");
const key = Object.keys(RIGHT).find((k) => q.startsWith(k));
const opts = [...fs.querySelectorAll(".exam-opt")];
let pick = opts.find((o) => o.textContent.trim().startsWith(RIGHT[key]));
if (mode === "fail" && n < 5) pick = opts.find((o) => o !== pick); // 5 wrong → 7/12, a fail
pick.querySelector("input").click();
});
}, RIGHT, mode);
await p.setViewport({ width: 390, height: 844, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
await p.goto("http://localhost:8766/#learn-14", { waitUntil: "networkidle2" }); await p.click("#consentDecline"); await new Promise((r) => setTimeout(r, 400));
const head = await p.evaluate(() => ({ eyebrow: document.querySelector("#lesson .eyebrow").textContent, title: document.querySelector("#lesson h2").textContent, nav: document.querySelectorAll("#lessonList li").length, next: !!document.getElementById("nextL"),
cert: document.querySelector('[data-widget="certificate"]').innerText.slice(0, 80) }));
console.log("final step:", JSON.stringify(head));
await p.click("#examStart"); await new Promise((r) => setTimeout(r, 200));
const nq = await p.$$eval(".exam-q", (x) => x.length);
await p.click(".exam-q .exam-opt input"); const partial = await p.evaluate(() => ({ disabled: document.getElementById("examSubmit").disabled, left: document.getElementById("examLeft").textContent }));
console.log(`questions shown: ${nq} | after 1 answer: submit disabled=${partial.disabled} ("${partial.left}")`);
await answer("fail"); await p.click("#examSubmit"); await new Promise((r) => setTimeout(r, 400));
const f = await p.evaluate(() => ({ score: document.querySelector(".exam-score").textContent.trim(), reviews: document.querySelectorAll(".exam-review").length, cert: document.querySelector('[data-widget="certificate"]').innerText.slice(0, 60) }));
console.log(`fail attempt: ${f.score} | review items: ${f.reviews} | certificate: "${f.cert}"`);
await p.screenshot({ path: S + "/exam_fail.png" });
await p.click("#examRetry"); await new Promise((r) => setTimeout(r, 200));
const order2 = await p.$$eval(".exam-q legend", (x) => x.map((l) => l.textContent.slice(3, 25)).join("|"));
await answer("pass"); await p.click("#examSubmit"); await new Promise((r) => setTimeout(r, 500));
const ps = await p.evaluate(() => ({ score: document.querySelector(".exam-score").textContent.trim(), certInput: !!document.getElementById("certName"), progress: document.getElementById("progressTxt").textContent, stored: localStorage.getItem("caveat-exam") }));
console.log(`pass attempt: ${ps.score} | certificate unlocked: ${ps.certInput} | progress ${ps.progress} | stored ${ps.stored}`);
console.log("retake reshuffled order (first 2 questions):", order2.split("|").slice(0, 2).join(" / "));
await p.type("#certName", "Dr. Muhammad Umer Wasim"); await p.click("#certMake"); await new Promise((r) => setTimeout(r, 1200));
const data = await p.$eval("#certImg", (e) => e.src); fs.writeFileSync(S + "/certificate.png", Buffer.from(data.split(",")[1], "base64"));
const li = await p.$eval("#certLi", (e) => e.href); console.log("LinkedIn add-to-profile:", decodeURIComponent(li).slice(0, 190));
await p.reload({ waitUntil: "networkidle2" }); await new Promise((r) => setTimeout(r, 400));
console.log("after reload, certificate still unlocked:", await p.evaluate(() => !!document.getElementById("certName")));
// print summary → real PDF
await p.goto("http://localhost:8766/", { waitUntil: "networkidle2" }); await new Promise((r) => setTimeout(r, 400));
await p.click('.chip[data-ex="1"]'); await p.click("#runBtn"); await new Promise((r) => setTimeout(r, 1200));
await p.evaluate(() => { window.print = () => {}; }); await p.click("#printBtn"); await new Promise((r) => setTimeout(r, 300));
await p.pdf({ path: S + "/summary.pdf", format: "A4" });
console.log("summary PDF bytes:", fs.statSync(S + "/summary.pdf").size);
console.log("page errors:", errs.length ? errs.join(" | ") : "none"); await b.close();
|