Spaces:
Running

web / app.js
ThanhNhan2006's picture
Deploy EcoLens (YOLO26n ONNX)
dd6f9a1 verified
Raw History Blame Contribute Delete
10.7 kB
/* ============================================================
EcoLens — chạy AI (YOLO26n ONNX) TRỰC TIẾP trong trình duyệt
Không cần server: ảnh không rời khỏi máy, tải model 1 lần rồi cache.
============================================================ */
const MODEL_URL = "best.onnx";
const IMGSZ = 640;
const CONF = 0.4; // ngưỡng tin cậy
const ORT_CDN = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/";
const $ = (id) => document.getElementById(id);
const screens = ["screen-home", "screen-camera", "screen-loading", "screen-result", "screen-empty"];
const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
function show(id) {
screens.forEach((s) => ($(s).hidden = s !== id));
window.scrollTo({ top: 0, behavior: "instant" });
}
// ---------- Khởi tạo onnxruntime-web + nạp model (chạy nền ngay khi mở trang) ----------
ort.env.wasm.numThreads = 1; // không cần cross-origin isolation -> chạy mọi nơi
ort.env.wasm.simd = true;
ort.env.wasm.wasmPaths = ORT_CDN;
const sessionPromise = ort.InferenceSession
.create(MODEL_URL, { executionProviders: ["wasm"] })
.then((s) => {
const el = $("ai-status");
el.textContent = "✅ AI đã sẵn sàng!";
el.classList.add("ok");
setTimeout(() => (el.hidden = true), 2200);
return s;
})
.catch((e) => {
$("ai-status").textContent = "⚠️ Không tải được AI. Kiểm tra mạng rồi tải lại trang.";
throw e;
});
// ---------- Sự kiện ----------
$("btn-camera").addEventListener("click", startCapture);
$("btn-again").addEventListener("click", startCapture);
$("btn-retry").addEventListener("click", startCapture);
$("btn-shutter").addEventListener("click", snapPhoto);
$("btn-cam-close").addEventListener("click", () => { closeCamera(); resetHome(); });
$("camera-input").addEventListener("change", onPick);
$("gallery-input").addEventListener("change", onPick);
function resetHome() {
$("camera-input").value = "";
$("gallery-input").value = "";
show("screen-home");
}
// ---------- Camera thật trong trang ----------
let camStream = null;
async function startCapture() {
$("camera-input").value = "";
$("gallery-input").value = "";
closeCamera();
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia && window.isSecureContext) {
try {
camStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
audio: false,
});
const video = $("cam-video");
video.srcObject = camStream;
await video.play().catch(() => {});
show("screen-camera");
return;
} catch (e) { /* từ chối quyền / không có camera */ }
}
$("camera-input").click();
}
function closeCamera() {
if (camStream) { camStream.getTracks().forEach((t) => t.stop()); camStream = null; }
$("cam-video").srcObject = null;
}
async function snapPhoto() {
const video = $("cam-video");
if (!video.videoWidth) return;
const canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0, 0);
closeCamera();
const blob = await new Promise((res) => canvas.toBlob(res, "image/jpeg", 0.9));
if (blob) analyze(blob);
}
function onPick(e) {
closeCamera();
const file = e.target.files && e.target.files[0];
if (file) analyze(file);
}
// ---------- Luồng chính: ảnh -> tiền xử lý -> chạy model -> hiển thị ----------
async function analyze(fileOrBlob) {
const url = URL.createObjectURL(fileOrBlob);
$("preview-img").src = url;
$("loading-text").textContent = "AI đang phân tích ảnh…";
const slow = setTimeout(() => {
$("loading-text").textContent = "Máy đang xử lý 🐢 — đợi chút nhé…";
}, 6000);
show("screen-loading");
try {
const bitmap = await createImageBitmap(fileOrBlob);
const { dets, ms } = await runModel(bitmap);
logStats(dets);
if (!dets.length) {
bitmap.close && bitmap.close();
show("screen-empty");
return;
}
const resultUrl = drawResult(bitmap, dets);
bitmap.close && bitmap.close();
render(dets, resultUrl, ms);
} catch (err) {
showError(err);
} finally {
clearTimeout(slow);
URL.revokeObjectURL(url);
}
}
// ---------- Tiền xử lý: letterbox về 640x640, dựng tensor ----------
function preprocess(bitmap) {
const w = bitmap.width, h = bitmap.height;
const scale = Math.min(IMGSZ / w, IMGSZ / h);
const nw = Math.round(w * scale), nh = Math.round(h * scale);
const padx = Math.floor((IMGSZ - nw) / 2), pady = Math.floor((IMGSZ - nh) / 2);
const c = document.createElement("canvas");
c.width = IMGSZ; c.height = IMGSZ;
const ctx = c.getContext("2d");
ctx.fillStyle = "rgb(114,114,114)"; // màu đệm giống lúc train
ctx.fillRect(0, 0, IMGSZ, IMGSZ);
ctx.drawImage(bitmap, padx, pady, nw, nh);
const px = ctx.getImageData(0, 0, IMGSZ, IMGSZ).data; // RGBA
const plane = IMGSZ * IMGSZ;
const arr = new Float32Array(3 * plane);
for (let i = 0; i < plane; i++) {
arr[i] = px[i * 4] / 255; // R
arr[i + plane] = px[i * 4 + 1] / 255; // G
arr[i + 2*plane] = px[i * 4 + 2] / 255; // B
}
return { tensor: new ort.Tensor("float32", arr, [1, 3, IMGSZ, IMGSZ]), scale, padx, pady, w, h };
}
// ---------- Chạy model + giải mã kết quả (output (1,300,6) đã gồm NMS) ----------
async function runModel(bitmap) {
const session = await sessionPromise;
const { tensor, scale, padx, pady, w, h } = preprocess(bitmap);
const t0 = performance.now();
const out = await session.run({ [session.inputNames[0]]: tensor });
const data = out[session.outputNames[0]].data; // Float32Array độ dài 300*6
const ms = Math.round(performance.now() - t0);
const dets = [];
for (let i = 0; i < 300; i++) {
const score = data[i * 6 + 4];
if (score < CONF) continue;
const cls = Math.round(data[i * 6 + 5]);
const info = EL_CLASSES[cls];
if (!info) continue;
// Gỡ letterbox -> toạ độ ảnh gốc
const x1 = clamp((data[i * 6] - padx) / scale, 0, w);
const y1 = clamp((data[i * 6 + 1] - pady) / scale, 0, h);
const x2 = clamp((data[i * 6 + 2] - padx) / scale, 0, w);
const y2 = clamp((data[i * 6 + 3] - pady) / scale, 0, h);
if (x2 <= x1 || y2 <= y1) continue;
dets.push(enrich(info, score, [x1, y1, x2, y2]));
}
dets.sort((a, b) => b.confidence - a.confidence);
return { dets, ms };
}
function enrich(info, confidence, bbox) {
const b = EL_BINS[info.bin];
return {
class_name: info.class_name, name_vi: info.name_vi,
confidence: confidence, bbox: bbox,
bin: b.label, bin_emoji: b.emoji, bin_color: b.color,
pollution_score: info.pollution_score, guide: info.guide, fact: info.fact,
};
}
// ---------- Vẽ khung + nhãn lên ảnh gốc, trả về dataURL ----------
function drawResult(bitmap, dets) {
const long = Math.max(bitmap.width, bitmap.height);
const s = Math.min(1, 720 / long); // thu nhỏ cho nhẹ khi hiển thị
const W = Math.round(bitmap.width * s), H = Math.round(bitmap.height * s);
const c = document.createElement("canvas");
c.width = W; c.height = H;
const ctx = c.getContext("2d");
ctx.drawImage(bitmap, 0, 0, W, H);
const lw = Math.max(2, Math.round(Math.min(W, H) * 0.006));
const fs = Math.max(13, Math.round(Math.min(W, H) * 0.035));
ctx.lineWidth = lw;
ctx.font = `bold ${fs}px sans-serif`;
ctx.textBaseline = "top";
for (const d of dets) {
const [x1, y1, x2, y2] = d.bbox.map((v) => v * s);
ctx.strokeStyle = d.bin_color;
ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
const label = `${d.name_vi} ${Math.round(d.confidence * 100)}%`;
const tw = ctx.measureText(label).width;
const ty = Math.max(0, y1 - fs - 6);
ctx.fillStyle = d.bin_color;
ctx.fillRect(x1, ty, tw + 10, fs + 6);
ctx.fillStyle = "#fff";
ctx.fillText(label, x1 + 5, ty + 3);
}
return c.toDataURL("image/jpeg", 0.85);
}
// ---------- Hiển thị kết quả ----------
function render(dets, resultUrl, ms) {
$("result-img").src = resultUrl;
$("result-time").textContent = `⚡ Phân tích trong ${(ms / 1000).toFixed(1)} giây (ngay trên máy bạn)`;
const wrap = $("result-cards");
wrap.innerHTML = "";
dets.forEach((d) => wrap.appendChild(card(d)));
show("screen-result");
}
function card(d) {
const el = document.createElement("div");
el.className = "det-card";
el.style.setProperty("--bin", d.bin_color);
const segs = [1, 2, 3, 4, 5]
.map((i) => `<div class="score-seg ${i <= d.pollution_score ? "on-" + d.pollution_score : ""}"></div>`)
.join("");
const words = ["", "Rất thấp", "Thấp", "Trung bình", "Cao", "Rất cao"];
el.innerHTML = `
<div class="det-head">
<div class="det-obj">${esc(d.name_vi)}</div>
<div class="det-title">→ Thùng ${esc(d.bin)} ${d.bin_emoji}</div>
<span class="det-conf">Độ chắc chắn ${Math.round(d.confidence * 100)}%</span>
</div>
<div class="det-body">
<div class="det-guide">👉 ${esc(d.guide)}</div>
<div class="score-wrap">
<div class="score-label"><span>Điểm ô nhiễm</span>
<span class="score-text">${d.pollution_score}/5 · ${words[d.pollution_score]}</span></div>
<div class="score-bar">${segs}</div>
</div>
<div class="det-fact">💡 ${esc(d.fact)}</div>
</div>`;
return el;
}
// ---------- Thống kê lưu trên máy (localStorage) ----------
function logStats(dets) {
const key = "ecolens_stats";
const s = JSON.parse(localStorage.getItem(key) || '{"total":0,"none":0,"byClass":{},"byDay":{}}');
s.total += 1;
const day = new Date().toISOString().slice(0, 10);
s.byDay[day] = (s.byDay[day] || 0) + 1;
if (!dets.length) s.none += 1;
for (const d of dets) s.byClass[d.class_name] = (s.byClass[d.class_name] || 0) + 1;
localStorage.setItem(key, JSON.stringify(s));
}
// ---------- Lỗi thân thiện ----------
function showError(err) {
console.error(err);
$("empty-title").textContent = "Có lỗi xảy ra 😢";
$("empty-text").innerHTML = "Thử chụp lại nhé! Nếu máy quá cũ, AI có thể không chạy được — " +
"khi đó bạn tự chọn thùng theo gợi ý bên dưới.";
show("screen-empty");
}
function esc(s) {
return String(s ?? "").replace(/[&<>"']/g, (c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}