Spaces:
Running
Running
Download app.js from Ecodrain-map/web: direct link, hf CLI and curl.
- Browser
- Download file 21 kB
-
https://huggingface.co/spaces/Ecodrain-map/web/resolve/main/app.js
- Command line
-
hf download hf://spaces/Ecodrain-map/web/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Ecodrain-map/web/resolve/main/app.js
21 kB
| /* EcoDrain Map — bản web TĨNH, AI chạy hoàn toàn trong trình duyệt (onnxruntime-web). | |
| Không cần backend. Dữ liệu (camera + báo cáo) lưu trong bộ nhớ trang (mất khi tải lại). */ | |
| // ============ CẤU HÌNH ============ | |
| const CLASSES = ["trash", "drain"]; // model V4: 2 class | |
| const CONF = 0.25; // ngưỡng thấp -> bắt được nhiều rác hơn (app giám sát ưu tiên không bỏ sót) | |
| const MODEL_SIZE = 800; // độ phân giải model V4 (khớp lúc train) | |
| const CLOG_TH = { partial: 20, blocked: 60 }; | |
| const MONITOR_MS = 12000; // camera tự phân tích mỗi 12s | |
| // Ảnh demo nhúng base64 (cùng origin, tránh lỗi canvas tainted do HF redirect CDN) | |
| const DEMO_FRAMES = (window.DEMO_IMAGES && window.DEMO_IMAGES.length) ? window.DEMO_IMAGES : []; | |
| const CLOG_LABEL = { clear:{t:"🟢 Không tắc",c:"clear"}, partial:{t:"🟡 Tắc nhẹ",c:"partial"}, blocked:{t:"🔴 Tắc nặng",c:"blocked"} }; | |
| const RISK_LABEL = { high:{t:"🔴 Nguy cơ ngập CAO",c:"high"}, medium:{t:"🟡 Trung bình",c:"medium"}, low:{t:"🟢 Bình thường",c:"low"} }; | |
| const RISK_COLOR = { high:"#e03131", medium:"#f5b301", low:"#2e9e5b" }; | |
| // ============ TRẠNG THÁI TRONG BỘ NHỚ ============ | |
| let ROLE = "citizen"; | |
| let session = null; | |
| let modelReady = false; | |
| const STATE = { cameras: [], reports: [], camSeq: 0, repSeq: 0 }; | |
| function isManager(){ return ROLE === "manager"; } | |
| // ============ NẠP MODEL ONNX ============ | |
| async function loadModel(){ | |
| const bar = document.getElementById("loadBar"); | |
| const t0 = Date.now(); | |
| const slow = setTimeout(()=>{ bar.textContent = "⏳ Vẫn đang tải model AI (~37MB)… mạng chậm thì hơi lâu, chờ chút nhé."; }, 8000); | |
| try { | |
| ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/"; | |
| ort.env.wasm.numThreads = 1; // ĐƠN LUỒNG: ổn định trên mọi máy (khỏi cần cross-origin isolation -> không treo trên máy tính nhiều nhân) | |
| ort.env.wasm.simd = true; // vẫn dùng SIMD cho nhanh | |
| ort.env.wasm.proxy = false; | |
| session = await ort.InferenceSession.create("best.onnx", { executionProviders: ["wasm"] }); | |
| clearTimeout(slow); | |
| modelReady = true; | |
| bar.className = "loadbar ok"; | |
| bar.textContent = `✅ Model AI sẵn sàng (${((Date.now()-t0)/1000).toFixed(0)}s) — camera bắt đầu giám sát.`; | |
| setTimeout(()=>bar.style.display="none", 4000); | |
| seedDemoCameras(); | |
| startMonitoring(); | |
| } catch (e){ | |
| clearTimeout(slow); | |
| bar.className = "loadbar err"; | |
| bar.textContent = "❌ Không tải được model AI: " + (e && e.message ? e.message : e); | |
| } | |
| } | |
| // ============ SUY LUẬN AI ============ | |
| // vẽ ảnh vào canvas 640x640 -> tensor float32 [1,3,640,640] | |
| function preprocess(source){ | |
| const S = MODEL_SIZE; | |
| const c = document.createElement("canvas"); c.width = S; c.height = S; | |
| const ctx = c.getContext("2d"); ctx.drawImage(source, 0, 0, S, S); | |
| const d = ctx.getImageData(0, 0, S, S).data; // RGBA | |
| const area = S * S; | |
| const f = new Float32Array(3 * area); | |
| for (let i = 0; i < area; i++){ | |
| f[i] = d[i*4] / 255; // R | |
| f[i + area] = d[i*4+1] / 255; // G | |
| f[i + 2*area] = d[i*4+2] / 255; // B | |
| } | |
| return new ort.Tensor("float32", f, [1, 3, S, S]); | |
| } | |
| // trả về list {cls, conf, box=[x1,y1,x2,y2]} theo kích thước gốc origW×origH | |
| async function detect(source, origW, origH){ | |
| const t = preprocess(source); | |
| const res = await session.run({ [session.inputNames[0]]: t }); | |
| const data = res[session.outputNames[0]].data; // [300*6]: x1,y1,x2,y2,score,cls (toạ độ 640) | |
| const sx = origW / MODEL_SIZE, sy = origH / MODEL_SIZE; | |
| const dets = []; | |
| for (let i = 0; i < 300; i++){ | |
| const s = data[i*6+4]; | |
| if (s < CONF) continue; | |
| const cls = Math.round(data[i*6+5]); | |
| dets.push({ cls: CLASSES[cls] || String(cls), conf: s, | |
| box: [data[i*6]*sx, data[i*6+1]*sy, data[i*6+2]*sx, data[i*6+3]*sy] }); | |
| } | |
| return dets; | |
| } | |
| // ============ LOGIC RÁC/CỐNG/NGẬP (port từ backend) ============ | |
| function coverage(drain, trashBoxes){ | |
| const [dx1,dy1,dx2,dy2] = drain; | |
| const da = Math.max(0,dx2-dx1) * Math.max(0,dy2-dy1); | |
| if (da <= 0) return 0; | |
| let inter = 0; | |
| for (const [tx1,ty1,tx2,ty2] of trashBoxes){ | |
| const ix1=Math.max(dx1,tx1), iy1=Math.max(dy1,ty1), ix2=Math.min(dx2,tx2), iy2=Math.min(dy2,ty2); | |
| if (ix2>ix1 && iy2>iy1) inter += (ix2-ix1)*(iy2-iy1); | |
| } | |
| return Math.min(100, 100*inter/da); | |
| } | |
| function clogLevel(pct){ return pct < CLOG_TH.partial ? "clear" : (pct <= CLOG_TH.blocked ? "partial" : "blocked"); } | |
| // Nguy cơ ngập dựa vào: cống bị che nặng HOẶC lượng rác (diện tích) lớn | |
| function floodRisk(clog, trashPct, hasDrain){ | |
| if (hasDrain && clog === "blocked") return "high"; | |
| if (trashPct >= 20) return "high"; // rác chiếm ≥20% khung -> rất nhiều rác | |
| if (clog === "partial" || trashPct >= 6) return "medium"; | |
| return "low"; | |
| } | |
| function analyze(dets, iw, ih){ | |
| // Gộp mọi loại rác thành "rác" (rác nổi + đống rác) cho nhất quán | |
| const trashBoxes = dets.filter(d=>d.cls==="trash").map(d=>d.box); | |
| const nTrash = trashBoxes.length; | |
| const drains = dets.filter(d=>d.cls==="drain"); | |
| const hasDrain = drains.length>0; | |
| let cov = 0, clog = null; | |
| if (hasDrain){ cov = Math.max(...drains.map(dr=>coverage(dr.box, trashBoxes)), 0); clog = clogLevel(cov); } | |
| // LƯỢNG rác = tổng diện tích box rác / diện tích ảnh (%), phản ánh "nhiều/ít rác" theo mắt nhìn | |
| let trashArea = 0; | |
| for (const [x1,y1,x2,y2] of trashBoxes) trashArea += Math.max(0,x2-x1)*Math.max(0,y2-y1); | |
| const trashPct = (iw && ih) ? Math.min(100, Math.round(100*trashArea/(iw*ih))) : 0; | |
| return { nTrash, trashTotal: nTrash, trashPct, hasDrain, coverage: Math.round(cov*10)/10, clog, | |
| flood: floodRisk(clog, trashPct, hasDrain) }; | |
| } | |
| // vẽ box lên ảnh -> dataURL để hiển thị | |
| const BOX_COLOR = { trash:"#ffa500", drain:"#1e90ff" }; | |
| function drawAnnotated(source, dets, w, h){ | |
| const c = document.createElement("canvas"); c.width=w; c.height=h; | |
| const ctx = c.getContext("2d"); ctx.drawImage(source,0,0,w,h); | |
| ctx.lineWidth = Math.max(2, Math.round(w/250)); ctx.font = "16px sans-serif"; | |
| for (const d of dets){ | |
| ctx.strokeStyle = BOX_COLOR[d.cls]||"#0f0"; ctx.fillStyle = ctx.strokeStyle; | |
| ctx.strokeRect(d.box[0], d.box[1], d.box[2]-d.box[0], d.box[3]-d.box[1]); | |
| ctx.fillText(`${d.cls} ${d.conf.toFixed(2)}`, d.box[0]+2, Math.max(12, d.box[1]-4)); | |
| } | |
| return c.toDataURL("image/jpeg", 0.85); | |
| } | |
| // nạp 1 ảnh (URL) -> HTMLImageElement | |
| function loadImage(src, crossOrigin){ | |
| return new Promise((resolve,reject)=>{ | |
| const img = new Image(); | |
| if (crossOrigin) img.crossOrigin = "anonymous"; | |
| img.onload = ()=>resolve(img); | |
| img.onerror = ()=>reject(new Error("Không tải được ảnh")); | |
| img.src = src; | |
| }); | |
| } | |
| // ============ BẢN ĐỒ (Leaflet) ============ | |
| let map, heatLayer, drainLayer, camLayer, mapInited=false; | |
| function initMap(){ | |
| if (mapInited) return; | |
| map = L.map("map").setView([10.7769,106.7009], 12); | |
| L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {attribution:"© OpenStreetMap", maxZoom:19}).addTo(map); | |
| drainLayer = L.layerGroup().addTo(map); | |
| camLayer = L.layerGroup().addTo(map); | |
| heatLayer = L.heatLayer([], {radius:30, blur:20, maxZoom:15}).addTo(map); | |
| mapInited = true; | |
| } | |
| function drainIcon(level){ | |
| const color = level==="blocked"?"#e03131":level==="partial"?"#f5b301":"#2e9e5b"; | |
| return L.divIcon({className:"",html:`<div style="background:${color};width:20px;height:20px;border-radius:50%;border:3px solid #fff;box-shadow:0 0 4px rgba(0,0,0,.5)"></div>`,iconSize:[20,20],iconAnchor:[10,10]}); | |
| } | |
| function camIcon(risk){ | |
| const color = RISK_COLOR[risk]||"#6b7a75"; | |
| return L.divIcon({className:"",html:`<div style="background:${color};width:26px;height:26px;border-radius:6px;border:3px solid #fff;box-shadow:0 0 4px rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;font-size:14px">📹</div>`,iconSize:[26,26],iconAnchor:[13,13]}); | |
| } | |
| function renderMap(){ | |
| if (!mapInited) return; | |
| drainLayer.clearLayers(); camLayer.clearLayers(); | |
| const heatPts = []; | |
| if (document.getElementById("chkDrain").checked){ | |
| for (const r of STATE.reports){ | |
| if (r.hasDrain && r.clog){ | |
| const l = CLOG_LABEL[r.clog]; | |
| L.marker([r.lat,r.lng],{icon:drainIcon(r.clog)}).addTo(drainLayer).bindPopup( | |
| `<b>📍 Báo cáo người dân</b><br>${r.img?`<img src="${r.img}" style="width:200px;border-radius:6px">`:""} | |
| <br>Mức tắc: <span class="badge ${l.c}">${l.t}</span><br>Rác che: ${r.coverage}%<br>${new Date(r.time).toLocaleString("vi-VN")}`); | |
| } | |
| } | |
| } | |
| for (const r of STATE.reports){ if (r.trashTotal>0) heatPts.push([r.lat,r.lng,r.trashTotal]); } | |
| if (document.getElementById("chkCam").checked){ | |
| for (const c of STATE.cameras){ | |
| const rk = RISK_LABEL[c.flood]||{t:"⏳ chưa có dữ liệu",c:"low"}; | |
| const clog = c.clog?CLOG_LABEL[c.clog].t:"không thấy cống"; | |
| L.marker([c.lat,c.lng],{icon:camIcon(c.flood)}).addTo(camLayer).bindPopup( | |
| `<b>📹 ${c.name}</b> <span class="hint">(${c.type})</span><br>${c.img?`<img src="${c.img}" style="width:200px;border-radius:6px">`:""} | |
| <br>Nguy cơ ngập: ${rk.t}<br>Rác: ${c.trashTotal} (chiếm ~${c.trashPct||0}% khung)<br>Cống: ${clog}${c.hasDrain?` · che ${c.coverage}%`:""}<br>Cập nhật: ${c.checked?new Date(c.checked).toLocaleTimeString("vi-VN"):"—"}`); | |
| } | |
| } | |
| for (const c of STATE.cameras){ if (c.trashTotal>0) heatPts.push([c.lat,c.lng,c.trashTotal]); } | |
| heatLayer.setLatLngs(document.getElementById("chkHeat").checked ? heatPts : []); | |
| } | |
| // ============ CAMERA GIÁM SÁT ============ | |
| function seedDemoCameras(){ | |
| if (STATE.cameras.length) return; | |
| const demo = [["Camera Kênh Nhiêu Lộc",10.7908,106.6820],["Camera Cống Bến Nghé",10.7690,106.7040],["Camera Rạch Xuyên Tâm",10.8020,106.7100]]; | |
| for (const [name,lat,lng] of demo){ | |
| STATE.cameras.push({ id:++STATE.camSeq, name, lat, lng, type:"demo", url:null, seq: STATE.camSeq, | |
| trashTotal:0, clog:null, coverage:0, hasDrain:false, flood:null, img:null, checked:null, err:null }); | |
| } | |
| } | |
| async function analyzeCamera(cam){ | |
| if (!modelReady){ cam.err = "Đang chờ model AI tải xong…"; cam.checked=Date.now(); return; } | |
| let img, w, h; | |
| // Bước 1: tải khung hình | |
| try { | |
| if (cam.type==="snapshot" && cam.url){ | |
| img = await loadImage(cam.url + (cam.url.includes("?")?"&":"?") + "t=" + Date.now(), true); | |
| } else { | |
| if (!DEMO_FRAMES.length){ cam.err="Chưa nạp được ảnh demo."; cam.checked=Date.now(); return; } | |
| const src = DEMO_FRAMES[cam.seq % DEMO_FRAMES.length]; cam.seq++; // data-URI, không thêm ?v | |
| img = await loadImage(src, false); | |
| } | |
| } catch(e){ | |
| cam.err = (cam.type==="snapshot") ? "Không tải được ảnh camera (URL sai hoặc bị CORS chặn)." : "Không tải được ảnh demo."; | |
| cam.checked=Date.now(); return; | |
| } | |
| // Bước 2: chạy AI + vẽ | |
| try { | |
| w = img.naturalWidth||640; h = img.naturalHeight||480; | |
| const dets = await detect(img, w, h); | |
| const a = analyze(dets, w, h); | |
| cam.trashTotal=a.trashTotal; cam.trashPct=a.trashPct; cam.clog=a.clog; cam.coverage=a.coverage; | |
| cam.hasDrain=a.hasDrain; cam.flood=a.flood; cam.checked=Date.now(); cam.err=null; | |
| cam.img = drawAnnotated(img, dets, w, h); | |
| } catch(e){ | |
| cam.err = "Lỗi chạy AI: " + (e && e.message ? e.message : e); | |
| cam.checked=Date.now(); | |
| } | |
| } | |
| let monitorTimer=null; | |
| function startMonitoring(){ | |
| const tick = async ()=>{ | |
| for (const cam of STATE.cameras) await analyzeCamera(cam); | |
| if (currentTab==="camera") renderCameras(); | |
| if (currentTab==="map") renderMap(); | |
| }; | |
| tick(); | |
| monitorTimer = setInterval(tick, MONITOR_MS); | |
| } | |
| function renderCameras(){ | |
| const grid = document.getElementById("camGrid"); | |
| grid.innerHTML = STATE.cameras.map(c=>{ | |
| const rk = RISK_LABEL[c.flood]||{t:"⏳ Chưa có dữ liệu",c:"low"}; | |
| const clog = c.clog?CLOG_LABEL[c.clog].t:"không thấy cống"; | |
| const del = isManager()?`<button class="btn gray" style="padding:8px;font-size:14px" onclick="delCamera(${c.id})">🗑️ Xoá</button>`:""; | |
| const err = c.err?`<div class="error" style="font-size:12px">${c.err}</div>`:""; | |
| return `<div class="cam-card"> | |
| ${c.img?`<img src="${c.img}">`:`<div style="height:160px;display:flex;align-items:center;justify-content:center;color:#889">⏳ đang phân tích…</div>`} | |
| <div class="cam-body"><h4>${c.name} <span class="hint">(${c.type})</span></h4> | |
| <span class="risk ${rk.c}">${rk.t}</span> | |
| <div class="cam-meta">🗑️ Rác: <b>${c.trashTotal}</b> (chiếm ~${c.trashPct||0}% khung) · Cống: ${clog}${c.hasDrain?` che ${c.coverage}%`:""}</div> | |
| <div class="cam-meta">⏱️ ${c.checked?new Date(c.checked).toLocaleTimeString("vi-VN"):"—"}</div>${err}${del}</div> | |
| </div>`; | |
| }).join(""); | |
| } | |
| // thêm camera (cán bộ) | |
| let pickMap, pickMarker, picked=null; | |
| function initPickMap(){ | |
| if (pickMap) { setTimeout(()=>pickMap.invalidateSize(),150); return; } | |
| pickMap = L.map("pickMap").setView([10.7769,106.7009], 12); | |
| L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:"© OSM"}).addTo(pickMap); | |
| pickMap.on("click", e=>{ picked=e.latlng; if(pickMarker)pickMarker.setLatLng(e.latlng); else pickMarker=L.marker(e.latlng).addTo(pickMap); }); | |
| setTimeout(()=>pickMap.invalidateSize(),200); | |
| } | |
| function toggleUrlRow(){ document.getElementById("urlRow").classList.toggle("hidden", document.getElementById("cType").value!=="snapshot"); } | |
| async function addCamera(){ | |
| const name=document.getElementById("cName").value.trim(); | |
| const type=document.getElementById("cType").value; | |
| const url=document.getElementById("cUrl").value.trim(); | |
| const msg=document.getElementById("camMsg"); msg.style.color=""; msg.textContent=""; | |
| if(!name){msg.textContent="Nhập tên camera.";return;} | |
| if(!picked){msg.textContent="Bấm lên bản đồ nhỏ để chọn vị trí.";return;} | |
| if(type==="snapshot"&&!url){msg.textContent="Camera snapshot cần link ảnh.";return;} | |
| const cam={id:++STATE.camSeq,name,lat:picked.lat,lng:picked.lng,type,url:type==="snapshot"?url:null,seq:STATE.camSeq,trashTotal:0,clog:null,coverage:0,hasDrain:false,flood:null,img:null,checked:null,err:null}; | |
| STATE.cameras.push(cam); | |
| document.getElementById("cName").value=""; | |
| msg.style.color="green"; msg.textContent="✅ Đã thêm, đang phân tích…"; | |
| await analyzeCamera(cam); renderCameras(); renderMap(); | |
| setTimeout(()=>{msg.textContent="";},2500); | |
| } | |
| function delCamera(id){ if(!confirm("Xoá camera này?"))return; STATE.cameras=STATE.cameras.filter(c=>c.id!==id); renderCameras(); renderMap(); } | |
| // ============ BÁO CÁO BẰNG ẢNH ============ | |
| let repImageEl=null, repCoords=null; | |
| document.getElementById("fileInput").addEventListener("change", async e=>{ | |
| const file=e.target.files[0]; if(!file)return; | |
| const url=URL.createObjectURL(file); | |
| repImageEl=await loadImage(url,false); | |
| const p=document.getElementById("preview"); p.src=url; p.style.display="block"; | |
| refreshSubmit(); | |
| }); | |
| function refreshSubmit(){ document.getElementById("submitBtn").disabled = !(repImageEl && repCoords && modelReady); } | |
| // ---- Chụp ảnh bằng webcam ---- | |
| let camStream=null; | |
| async function startCamera(){ | |
| try{ | |
| camStream = await navigator.mediaDevices.getUserMedia({ video:{ facingMode:"environment" }, audio:false }); | |
| document.getElementById("camVideo").srcObject = camStream; | |
| document.getElementById("camArea").classList.remove("hidden"); | |
| }catch(e){ | |
| document.getElementById("repMsg").textContent = "Không mở được camera: " + e.message + " (cần HTTPS + cấp quyền)."; | |
| } | |
| } | |
| function stopCamera(){ | |
| if(camStream){ camStream.getTracks().forEach(t=>t.stop()); camStream=null; } | |
| document.getElementById("camArea").classList.add("hidden"); | |
| } | |
| async function snapPhoto(){ | |
| const v=document.getElementById("camVideo"); | |
| if(!v.videoWidth){ return; } | |
| const c=document.createElement("canvas"); c.width=v.videoWidth; c.height=v.videoHeight; | |
| c.getContext("2d").drawImage(v,0,0,c.width,c.height); | |
| const dataUrl=c.toDataURL("image/jpeg",0.9); | |
| repImageEl=await loadImage(dataUrl,false); | |
| const p=document.getElementById("preview"); p.src=dataUrl; p.style.display="block"; | |
| stopCamera(); document.getElementById("repMsg").textContent=""; refreshSubmit(); | |
| } | |
| function requestGps(){ | |
| const box=document.getElementById("gpsBox"); | |
| if(!navigator.geolocation){box.innerHTML='<span class="gps-warn">Trình duyệt không hỗ trợ GPS.</span>';showPinMap();return;} | |
| box.textContent="Đang lấy GPS…"; | |
| navigator.geolocation.getCurrentPosition( | |
| pos=>{ repCoords={lat:pos.coords.latitude,lng:pos.coords.longitude}; box.innerHTML=`<span class="gps-ok">✅ ${repCoords.lat.toFixed(6)}, ${repCoords.lng.toFixed(6)}</span>`; refreshSubmit(); }, | |
| err=>{ box.innerHTML=`<span class="gps-warn">⚠️ ${err.code===1?"Bạn từ chối vị trí — ghim tay bên dưới.":"Không lấy được vị trí — ghim tay."}</span>`; showPinMap(); }, | |
| {enableHighAccuracy:true,timeout:10000}); | |
| } | |
| let pinMap,pinMarker; | |
| function showPinMap(){ | |
| const el=document.getElementById("pinMap"); el.classList.remove("hidden"); | |
| if(pinMap){setTimeout(()=>pinMap.invalidateSize(),150);return;} | |
| pinMap=L.map("pinMap").setView([10.7769,106.7009],12); | |
| L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:"© OSM"}).addTo(pinMap); | |
| pinMap.on("click",e=>{ repCoords={lat:e.latlng.lat,lng:e.latlng.lng}; if(pinMarker)pinMarker.setLatLng(e.latlng);else pinMarker=L.marker(e.latlng).addTo(pinMap); | |
| document.getElementById("gpsBox").innerHTML=`<span class="gps-ok">📌 ${repCoords.lat.toFixed(6)}, ${repCoords.lng.toFixed(6)}</span>`; refreshSubmit(); }); | |
| setTimeout(()=>pinMap.invalidateSize(),200); | |
| } | |
| async function submitReport(){ | |
| if(!repImageEl||!repCoords||!modelReady)return; | |
| const btn=document.getElementById("submitBtn"); btn.disabled=true; btn.textContent="⏳ Đang phân tích…"; | |
| try{ | |
| const w=repImageEl.naturalWidth,h=repImageEl.naturalHeight; | |
| const dets=await detect(repImageEl,w,h); const a=analyze(dets, w, h); | |
| const annotated=drawAnnotated(repImageEl,dets,w,h); | |
| STATE.reports.push({ id:++STATE.repSeq, lat:repCoords.lat, lng:repCoords.lng, time:Date.now(), | |
| nFloat:a.nFloat, nPile:a.nPile, trashTotal:a.trashTotal, hasDrain:a.hasDrain, clog:a.clog, coverage:a.coverage, img:annotated }); | |
| // hiện kết quả | |
| document.getElementById("resultCard").classList.remove("hidden"); | |
| document.getElementById("resultImg").src=annotated; | |
| document.getElementById("rTrash").textContent=a.nTrash; | |
| const box=document.getElementById("clogResult"); | |
| const rk=RISK_LABEL[a.flood]||RISK_LABEL.low; | |
| let html=`<p>Nguy cơ ngập: <span class="risk ${rk.c}">${rk.t}</span></p>`; | |
| html+=`<p>Lượng rác: <b>${a.nTrash}</b> vật, chiếm <b>~${a.trashPct}%</b> khung hình.</p>`; | |
| if(a.hasDrain&&a.clog){ const l=CLOG_LABEL[a.clog]; | |
| html+=`<p>Miệng cống: <span class="badge ${l.c}">${l.t}</span> — rác che <b>${a.coverage}%</b>. ${a.clog==="clear"?"":"⚠️ Nên dọn sớm."}</p>`; | |
| } else html+=`<p class="hint">Ảnh không thấy miệng cống — chỉ đánh giá theo lượng rác.</p>`; | |
| box.innerHTML=html; | |
| renderMap(); | |
| document.getElementById("resultCard").scrollIntoView({behavior:"smooth"}); | |
| }catch(e){ document.getElementById("repMsg").textContent="Lỗi phân tích: "+e.message; } | |
| finally{ btn.disabled=false; btn.textContent="📨 Phân tích & gửi lên bản đồ"; } | |
| } | |
| // ============ TAB + VAI TRÒ ============ | |
| let currentTab="map"; | |
| function showTab(t){ | |
| currentTab=t; | |
| for (const p of ["map","camera","report"]) document.getElementById("tab-"+p).classList.toggle("hidden", p!==t); | |
| document.querySelectorAll(".tab").forEach(b=>b.classList.toggle("active", b.dataset.tab===t)); | |
| if(t==="map"){ initMap(); setTimeout(()=>{map.invalidateSize();renderMap();},100); } | |
| if(t==="camera"){ renderCameras(); if(isManager()) initPickMap(); } | |
| } | |
| function setRoleUI(r){ | |
| ROLE=r; | |
| document.getElementById("rCitizen").classList.toggle("active", r==="citizen"); | |
| document.getElementById("rManager").classList.toggle("active", r==="manager"); | |
| document.getElementById("camAddCard").style.display = isManager()?"block":"none"; | |
| document.getElementById("camViewerNote").style.display = isManager()?"none":"block"; | |
| if(currentTab==="camera"){ renderCameras(); if(isManager()) initPickMap(); } | |
| } | |
| // ============ KHỞI ĐỘNG ============ | |
| setRoleUI("citizen"); | |
| initMap(); | |
| showTab("map"); | |
| requestGps(); | |
| loadModel(); | |