| <!doctype html> |
| <html lang="en"> |
| <head> |
| <meta charset="utf-8" /> |
| <meta name="viewport" content="width=device-width, initial-scale=1" /> |
| <title>RLC Freeform Surface Labeler</title> |
| <style> |
| :root { |
| color-scheme: dark; |
| --bg: #0f1217; |
| --panel: #191f29; |
| --panel-2: #242c39; |
| --line: #394252; |
| --text: #e9eef7; |
| --muted: #aab4c3; |
| --paint: #20e0a2; |
| --erase: #ff6b78; |
| --warn: #ffcc33; |
| --danger: #ff5c6c; |
| } |
| |
| * { box-sizing: border-box; } |
| body { |
| margin: 0; |
| height: 100vh; |
| overflow: hidden; |
| background: var(--bg); |
| color: var(--text); |
| font: 13px/1.35 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; |
| } |
| |
| .app { |
| display: grid; |
| grid-template-columns: 340px 1fr; |
| height: 100vh; |
| min-width: 980px; |
| } |
| |
| aside { |
| overflow: auto; |
| border-right: 1px solid var(--line); |
| background: var(--panel); |
| padding: 14px; |
| } |
| |
| main { |
| position: relative; |
| overflow: hidden; |
| background: #05070a; |
| } |
| |
| h1 { |
| margin: 0 0 12px; |
| font-size: 18px; |
| font-weight: 650; |
| } |
| |
| h2 { |
| margin: 18px 0 8px; |
| color: var(--muted); |
| font-size: 12px; |
| font-weight: 700; |
| text-transform: uppercase; |
| letter-spacing: .05em; |
| } |
| |
| label { |
| display: block; |
| margin: 9px 0 5px; |
| color: var(--muted); |
| font-size: 12px; |
| } |
| |
| input, select, button, textarea { |
| width: 100%; |
| border: 1px solid var(--line); |
| border-radius: 6px; |
| background: #101620; |
| color: var(--text); |
| padding: 8px; |
| font: inherit; |
| } |
| |
| input[type="range"] { padding: 0; } |
| |
| button { |
| background: var(--panel-2); |
| cursor: pointer; |
| min-height: 34px; |
| } |
| |
| button:hover { background: #2d3747; } |
| button.primary { border-color: #2b8cff; background: #174a88; } |
| button.warn { border-color: #8a6a13; background: #493a12; } |
| button.danger { border-color: #8a2430; background: #4b1b22; } |
| button.active { outline: 2px solid #fff; } |
| button:disabled { cursor: not-allowed; opacity: .45; } |
| |
| .row { |
| display: grid; |
| grid-template-columns: 1fr 1fr; |
| gap: 8px; |
| align-items: center; |
| } |
| |
| .row3 { |
| display: grid; |
| grid-template-columns: 1fr 1fr 1fr; |
| gap: 8px; |
| align-items: center; |
| } |
| |
| .sample-list { |
| display: grid; |
| gap: 4px; |
| max-height: 190px; |
| overflow: auto; |
| border: 1px solid var(--line); |
| border-radius: 6px; |
| padding: 6px; |
| background: #101620; |
| } |
| |
| .sample { |
| display: grid; |
| grid-template-columns: 1fr auto; |
| gap: 8px; |
| border-radius: 4px; |
| padding: 5px 6px; |
| color: var(--muted); |
| cursor: pointer; |
| } |
| |
| .sample:hover { background: #202938; } |
| .sample.active { background: #24456a; color: var(--text); } |
| .sample.done::after { content: "done"; color: var(--paint); font-size: 11px; } |
| |
| .stats { |
| display: grid; |
| grid-template-columns: 1fr auto; |
| gap: 4px 8px; |
| color: var(--muted); |
| font-size: 12px; |
| } |
| |
| .status { |
| margin-top: 10px; |
| min-height: 38px; |
| border: 1px solid var(--line); |
| border-radius: 6px; |
| padding: 8px; |
| background: #101620; |
| color: var(--muted); |
| white-space: pre-wrap; |
| } |
| |
| canvas { |
| position: absolute; |
| inset: 0; |
| width: 100%; |
| height: 100%; |
| display: block; |
| cursor: crosshair; |
| } |
| |
| .toolbar { |
| position: absolute; |
| left: 14px; |
| top: 14px; |
| display: flex; |
| gap: 8px; |
| pointer-events: none; |
| } |
| |
| .pill { |
| border: 1px solid rgba(255,255,255,.22); |
| border-radius: 999px; |
| background: rgba(0,0,0,.58); |
| padding: 6px 9px; |
| color: #fff; |
| font-size: 12px; |
| backdrop-filter: blur(8px); |
| pointer-events: none; |
| } |
| |
| .notice { |
| position: absolute; |
| left: 50%; |
| top: 58px; |
| max-width: min(620px, calc(100% - 48px)); |
| transform: translateX(-50%); |
| border: 1px solid rgba(255,255,255,.24); |
| border-radius: 6px; |
| background: rgba(0,0,0,.74); |
| color: #fff; |
| padding: 10px 12px; |
| font-size: 13px; |
| line-height: 1.35; |
| text-align: center; |
| pointer-events: none; |
| opacity: 0; |
| transition: opacity .12s ease; |
| backdrop-filter: blur(8px); |
| } |
| |
| .notice.show { opacity: 1; } |
| .notice.warn { border-color: rgba(255,204,51,.7); color: #ffe08a; } |
| .notice.ok { border-color: rgba(32,224,162,.65); color: #c7ffe9; } |
| |
| .help { |
| color: var(--muted); |
| font-size: 12px; |
| } |
| |
| .kbd { |
| display: inline-block; |
| border: 1px solid var(--line); |
| border-radius: 4px; |
| padding: 1px 5px; |
| color: var(--text); |
| background: #111822; |
| font: 11px ui-monospace, Consolas, monospace; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="app"> |
| <aside> |
| <h1>RLC Freeform Surface Labeler</h1> |
|
|
| <h2>Input</h2> |
| <label>Manifest JSON</label> |
| <input id="manifestFile" type="file" accept="application/json,.json" /> |
| <label>Raw image files (attach after manifest for Fill)</label> |
| <input id="imageFiles" type="file" accept="image/png,image/jpeg,image/webp" multiple /> |
| <div class="row" style="margin-top:8px"> |
| <button id="chooseOut">Choose labels dir</button> |
| <button id="saveAllManifest">Export manifest</button> |
| </div> |
|
|
| <h2>Samples</h2> |
| <div id="sampleList" class="sample-list"></div> |
|
|
| <h2>Mask Brush</h2> |
| <div class="row3"> |
| <button id="toolPaint" class="active">Paint</button> |
| <button id="toolErase">Erase</button> |
| <button id="toolFill">Fill</button> |
| </div> |
| <label>Brush size: <b id="brushSizeText">28</b> px</label> |
| <input id="brushSize" type="range" min="2" max="120" step="1" value="28" /> |
| <label>Fill tolerance: <b id="fillToleranceText">32</b></label> |
| <input id="fillTolerance" type="range" min="0" max="120" step="1" value="32" /> |
| <label>Mask opacity: <b id="maskOpacityText">38</b>%</label> |
| <input id="maskOpacity" type="range" min="5" max="85" step="1" value="38" /> |
| <div class="row" style="margin-top:8px"> |
| <button id="undo">Undo stroke</button> |
| <button id="redo">Redo stroke</button> |
| </div> |
| <div class="row" style="margin-top:8px"> |
| <button id="clearMask" class="danger">Clear mask</button> |
| <button id="fit">Fit</button> |
| </div> |
|
|
| <h2>Save</h2> |
| <div class="row"> |
| <button id="saveSample" class="primary">Save sample</button> |
| <button id="downloadSample">Download</button> |
| </div> |
|
|
| <h2>View</h2> |
| <div class="row3"> |
| <button id="prev">Prev</button> |
| <button id="panTool">Pan</button> |
| <button id="next">Next</button> |
| </div> |
|
|
| <h2>Stats</h2> |
| <div class="stats"> |
| <span>Sample</span><b id="statSample">-</b> |
| <span>Image</span><b id="statImage">-</b> |
| <span>Mask pixels</span><b id="statArea">0</b> |
| <span>Ops</span><b id="statStrokes">0</b> |
| <span>Fill source</span><b id="statFillSource">-</b> |
| <span>Output dir</span><b id="statOut">downloads</b> |
| </div> |
|
|
| <div id="status" class="status">Load a manifest or image files.</div> |
|
|
| <h2>Controls</h2> |
| <p class="help"> |
| <span class="kbd">B</span> paint, <span class="kbd">E</span> erase, <span class="kbd">G</span> fill, |
| <span class="kbd">Z</span> undo, <span class="kbd">Y</span> redo, |
| <span class="kbd">F</span> fit, <span class="kbd">S</span> save, |
| <span class="kbd">[</span>/<span class="kbd">]</span> brush, |
| <span class="kbd">Left</span>/<span class="kbd">Right</span> samples. |
| Middle mouse or <span class="kbd">Space</span>+drag pans. Wheel zooms. In fill mode, <span class="kbd">Shift</span>+click erases. |
| In paint/erase, <span class="kbd">Shift</span>+click sets a line start and the next <span class="kbd">Shift</span>+click draws a straight line. |
| </p> |
| </aside> |
| <main> |
| <canvas id="canvas"></canvas> |
| <div class="toolbar"> |
| <div class="pill" id="pillSample">No sample</div> |
| <div class="pill" id="pillTool">Paint</div> |
| </div> |
| <div id="notice" class="notice"></div> |
| </main> |
| </div> |
|
|
| <script> |
| const canvas = document.getElementById("canvas"); |
| const ctx = canvas.getContext("2d", { alpha: false }); |
| const els = Object.fromEntries([ |
| "manifestFile", "imageFiles", "chooseOut", "saveAllManifest", "sampleList", |
| "toolPaint", "toolErase", "toolFill", "brushSize", "brushSizeText", "fillTolerance", |
| "fillToleranceText", "maskOpacity", |
| "maskOpacityText", "undo", "redo", "clearMask", "fit", "saveSample", |
| "downloadSample", "prev", "panTool", "next", "status", "statSample", |
| "statImage", "statArea", "statStrokes", "statFillSource", "statOut", "pillSample", |
| "pillTool", "notice", |
| ].map(id => [id, document.getElementById(id)])); |
| |
| const maskCanvas = document.createElement("canvas"); |
| const maskCtx = maskCanvas.getContext("2d"); |
| const previewCanvas = document.createElement("canvas"); |
| const previewCtx = previewCanvas.getContext("2d"); |
| const sourceCanvas = document.createElement("canvas"); |
| const sourceCtx = sourceCanvas.getContext("2d", { willReadFrequently: true }); |
| |
| let samples = []; |
| let current = -1; |
| let tool = "paint"; |
| let outDir = null; |
| let view = { scale: 1, x: 0, y: 0 }; |
| let image = null; |
| let imageUrl = null; |
| let sourceReadable = false; |
| let brushSize = 28; |
| let fillTolerance = 32; |
| let maskOpacity = 0.38; |
| let spaceDown = false; |
| let panning = false; |
| let drawing = false; |
| let lastMouse = null; |
| let activeStroke = null; |
| let lineAnchor = null; |
| let cursor = null; |
| let redoStack = []; |
| let cachedMaskArea = 0; |
| let noticeTimer = null; |
| let serverSave = { state: "unknown", labelsDir: "labels", error: "" }; |
| const MAX_FILL_PIXELS = 700000; |
| |
| function setStatus(text) { els.status.textContent = text; } |
| function showNotice(text, mode = "") { |
| clearTimeout(noticeTimer); |
| els.notice.textContent = text; |
| els.notice.className = `notice show ${mode}`.trim(); |
| noticeTimer = setTimeout(() => { |
| els.notice.className = "notice"; |
| }, 2600); |
| } |
| function sample() { return samples[current] || null; } |
| function isBrushTool() { |
| return tool === "paint" || tool === "erase"; |
| } |
| function roundedPoint(p) { |
| return [Number(p[0].toFixed(2)), Number(p[1].toFixed(2))]; |
| } |
| function canUseServerSave() { |
| return location.protocol === "http:" || location.protocol === "https:"; |
| } |
| function basename(path) { |
| return String(path || "").split(/[\\/]/).pop(); |
| } |
| function draftKey(id) { |
| return `rlc.freeform_surface_labeler.v2.${location.pathname}.${id}`; |
| } |
| |
| function loadDraft(id) { |
| try { |
| const raw = localStorage.getItem(draftKey(id)); |
| if (!raw) return null; |
| const draft = JSON.parse(raw); |
| const maskOps = normalizeMaskOps(draft); |
| if (!maskOps.length) return null; |
| const label = { |
| mask_ops: maskOps, |
| saved: !!draft.saved, |
| mask_area_px: Number(draft.mask_area_px || 0), |
| }; |
| syncDerivedLabel(label); |
| return label; |
| } catch { |
| return null; |
| } |
| } |
| |
| function saveDraft(s) { |
| if (!s) return; |
| try { |
| const l = labelFor(s); |
| syncDerivedLabel(l); |
| localStorage.setItem(draftKey(s.id), JSON.stringify({ |
| mask_ops: l.mask_ops, |
| brush_strokes: l.brush_strokes, |
| fill_ops: l.fill_ops, |
| saved: !!l.saved, |
| mask_area_px: Number(l.mask_area_px || 0), |
| updated_at: new Date().toISOString(), |
| })); |
| } catch (error) { |
| console.warn("Failed to save local label draft", error); |
| } |
| } |
| |
| function labelFor(s) { |
| if (!s.label || Array.isArray(s.label)) s.label = {}; |
| if (!Array.isArray(s.label.mask_ops)) s.label.mask_ops = normalizeMaskOps(s.label); |
| if (!Array.isArray(s.label.brush_strokes)) s.label.brush_strokes = []; |
| if (!Array.isArray(s.label.fill_ops)) s.label.fill_ops = []; |
| if (typeof s.label.saved !== "boolean") s.label.saved = false; |
| if (typeof s.label.mask_area_px !== "number") s.label.mask_area_px = 0; |
| syncDerivedLabel(s.label); |
| return s.label; |
| } |
| |
| function normalizeBrushOp(stroke = {}) { |
| return { |
| kind: "brush", |
| tool: stroke.tool === "erase" ? "erase" : "paint", |
| radius: Number(stroke.radius || stroke.brush_radius_px || brushSize), |
| points: Array.isArray(stroke.points) ? stroke.points : [], |
| }; |
| } |
| |
| function normalizeFillOp(fill) { |
| return { |
| kind: "fill", |
| tool: fill.tool === "erase" ? "erase" : "paint", |
| seed: Array.isArray(fill.seed) ? fill.seed : [0, 0], |
| tolerance: Number(fill.tolerance ?? fill.tolerance_rgb ?? fillTolerance), |
| pixel_count: Number(fill.pixel_count || 0), |
| spans: Array.isArray(fill.spans) ? fill.spans : [], |
| limit_hit: !!fill.limit_hit, |
| }; |
| } |
| |
| function normalizeMaskOps(label) { |
| if (!label) return []; |
| if (Array.isArray(label.mask_ops)) { |
| return label.mask_ops |
| .map(op => op?.kind === "fill" ? normalizeFillOp(op) : normalizeBrushOp(op)) |
| .filter(op => op.kind === "fill" || op.points.length); |
| } |
| const ops = []; |
| if (Array.isArray(label.brush_strokes)) { |
| for (const stroke of label.brush_strokes) ops.push(normalizeBrushOp(stroke)); |
| } |
| if (Array.isArray(label.fill_ops)) { |
| for (const fill of label.fill_ops) ops.push(normalizeFillOp(fill)); |
| } |
| return ops; |
| } |
| |
| function syncDerivedLabel(label) { |
| label.mask_ops = normalizeMaskOps(label); |
| label.brush_strokes = label.mask_ops.filter(op => op.kind === "brush").map(op => ({ |
| tool: op.tool, |
| radius: op.radius, |
| points: op.points, |
| })); |
| label.fill_ops = label.mask_ops.filter(op => op.kind === "fill").map(op => ({ |
| tool: op.tool, |
| seed: op.seed, |
| tolerance: op.tolerance, |
| pixel_count: op.pixel_count || 0, |
| spans: op.spans || [], |
| limit_hit: !!op.limit_hit, |
| })); |
| } |
| |
| function resize() { |
| const dpr = window.devicePixelRatio || 1; |
| const rect = canvas.getBoundingClientRect(); |
| canvas.width = Math.max(1, Math.round(rect.width * dpr)); |
| canvas.height = Math.max(1, Math.round(rect.height * dpr)); |
| draw(); |
| } |
| window.addEventListener("resize", resize); |
| |
| function imageToScreen(p) { |
| const dpr = window.devicePixelRatio || 1; |
| return [p[0] * view.scale + view.x / dpr, p[1] * view.scale + view.y / dpr]; |
| } |
| |
| function screenToImage(x, y) { |
| const dpr = window.devicePixelRatio || 1; |
| return [(x - view.x / dpr) / view.scale, (y - view.y / dpr) / view.scale]; |
| } |
| |
| function clampPoint(p) { |
| return [ |
| Math.max(0, Math.min(image.width - 1, p[0])), |
| Math.max(0, Math.min(image.height - 1, p[1])), |
| ]; |
| } |
| |
| function fitImage() { |
| if (!image) return; |
| const rect = canvas.getBoundingClientRect(); |
| const scale = Math.min(rect.width / image.width, rect.height / image.height) * 0.96; |
| view.scale = scale; |
| view.x = (rect.width - image.width * scale) * 0.5 * (window.devicePixelRatio || 1); |
| view.y = (rect.height - image.height * scale) * 0.5 * (window.devicePixelRatio || 1); |
| draw(); |
| } |
| |
| function setupMaskCanvas(width, height) { |
| maskCanvas.width = width; |
| maskCanvas.height = height; |
| previewCanvas.width = width; |
| previewCanvas.height = height; |
| sourceCanvas.width = width; |
| sourceCanvas.height = height; |
| sourceCtx.drawImage(image, 0, 0, width, height); |
| sourceReadable = canReadSourcePixels(); |
| replayMask(); |
| } |
| |
| function canReadSourcePixels() { |
| if (!sourceCanvas.width || !sourceCanvas.height) return false; |
| try { |
| sourceCtx.getImageData(0, 0, 1, 1); |
| return true; |
| } catch { |
| return false; |
| } |
| } |
| |
| function fillNeedsRawFiles() { |
| return !!sample() && !sourceReadable; |
| } |
| |
| function requestRawFilesForFill() { |
| if (location.protocol === "file:") { |
| const text = "Fill is blocked in file:// mode. Open the localhost labeler URL so the browser lets Fill read manifest image pixels."; |
| setStatus(`${text} Raw image attach is only a fallback.`); |
| showNotice(text, "warn"); |
| return; |
| } |
| const text = "Fill cannot read this image yet. Check that the manifest image path resolves from this labeler URL."; |
| setStatus(text); |
| showNotice(text, "warn"); |
| } |
| |
| function fillSourceLabel() { |
| if (!sample() || !image) return "no image"; |
| if (sourceReadable) return "readable"; |
| return location.protocol === "file:" ? "blocked:file" : "blocked"; |
| } |
| |
| function outputLabel() { |
| if (outDir) return outDir.name; |
| if (serverSave.state === "ready") return `server: ${serverSave.labelsDir}`; |
| if (serverSave.state === "unavailable") return "server unavailable"; |
| if (canUseServerSave()) return "server check..."; |
| return "choose labels dir"; |
| } |
| |
| async function probeServerSave() { |
| if (!canUseServerSave()) { |
| serverSave = { state: "unavailable", labelsDir: "labels", error: "not http" }; |
| updateUi(); |
| return; |
| } |
| try { |
| const response = await fetch("/api/labeler/status", { cache: "no-store" }); |
| if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| const doc = await response.json(); |
| if (!doc.save_endpoint) throw new Error("save endpoint missing"); |
| serverSave = { state: "ready", labelsDir: doc.labels_dir || "labels", error: "" }; |
| } catch (error) { |
| serverSave = { state: "unavailable", labelsDir: "labels", error: error.message || String(error) }; |
| } |
| updateUi(); |
| } |
| |
| function replayMask() { |
| maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height); |
| const s = sample(); |
| if (s) { |
| for (const op of labelFor(s).mask_ops) applyMaskOp(op); |
| } |
| rebuildPreviewMask(); |
| cachedMaskArea = computeMaskArea(); |
| if (s) labelFor(s).mask_area_px = cachedMaskArea; |
| } |
| |
| function applyMaskOp(op) { |
| if (op.kind === "fill") { |
| try { |
| return applyFillOp(op); |
| } catch { |
| return 0; |
| } |
| } |
| drawStroke(maskCtx, op); |
| return op.points?.length || 0; |
| } |
| |
| function rebuildPreviewMask() { |
| previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height); |
| previewCtx.save(); |
| previewCtx.fillStyle = "#20e0a2"; |
| previewCtx.fillRect(0, 0, previewCanvas.width, previewCanvas.height); |
| previewCtx.globalCompositeOperation = "destination-in"; |
| previewCtx.drawImage(maskCanvas, 0, 0); |
| previewCtx.restore(); |
| } |
| |
| function drawStroke(context, stroke) { |
| const pts = stroke.points || []; |
| if (!pts.length) return; |
| context.save(); |
| context.lineCap = "round"; |
| context.lineJoin = "round"; |
| context.lineWidth = stroke.radius * 2; |
| if (stroke.tool === "erase") { |
| context.globalCompositeOperation = "destination-out"; |
| context.strokeStyle = "rgba(0,0,0,1)"; |
| context.fillStyle = "rgba(0,0,0,1)"; |
| } else { |
| context.globalCompositeOperation = "source-over"; |
| context.strokeStyle = "#fff"; |
| context.fillStyle = "#fff"; |
| } |
| context.beginPath(); |
| context.arc(pts[0][0], pts[0][1], stroke.radius, 0, Math.PI * 2); |
| context.fill(); |
| if (pts.length > 1) { |
| context.beginPath(); |
| context.moveTo(pts[0][0], pts[0][1]); |
| for (let i = 1; i < pts.length; i++) context.lineTo(pts[i][0], pts[i][1]); |
| context.stroke(); |
| } |
| context.restore(); |
| } |
| |
| function drawStrokeSegment(context, stroke, from, to) { |
| context.save(); |
| context.lineCap = "round"; |
| context.lineJoin = "round"; |
| context.lineWidth = stroke.radius * 2; |
| if (stroke.tool === "erase") { |
| context.globalCompositeOperation = "destination-out"; |
| context.strokeStyle = "rgba(0,0,0,1)"; |
| context.fillStyle = "rgba(0,0,0,1)"; |
| } else { |
| context.globalCompositeOperation = "source-over"; |
| context.strokeStyle = "#fff"; |
| context.fillStyle = "#fff"; |
| } |
| context.beginPath(); |
| context.arc(to[0], to[1], stroke.radius, 0, Math.PI * 2); |
| context.fill(); |
| if (from) { |
| context.beginPath(); |
| context.moveTo(from[0], from[1]); |
| context.lineTo(to[0], to[1]); |
| context.stroke(); |
| } |
| context.restore(); |
| } |
| |
| function computeMaskArea() { |
| if (!maskCanvas.width || !maskCanvas.height) return 0; |
| const data = maskCtx.getImageData(0, 0, maskCanvas.width, maskCanvas.height).data; |
| let count = 0; |
| for (let i = 3; i < data.length; i += 4) { |
| if (data[i] > 0) count++; |
| } |
| return count; |
| } |
| |
| function pixelMatches(src, idx, seed, tolerance) { |
| return Math.max( |
| Math.abs(src[idx] - seed[0]), |
| Math.abs(src[idx + 1] - seed[1]), |
| Math.abs(src[idx + 2] - seed[2]) |
| ) <= tolerance; |
| } |
| |
| function buildSpans(selected, width, height) { |
| const spans = []; |
| for (let y = 0; y < height; y++) { |
| const row = y * width; |
| let x = 0; |
| while (x < width) { |
| while (x < width && !selected[row + x]) x++; |
| if (x >= width) break; |
| const x0 = x; |
| while (x < width && selected[row + x]) x++; |
| spans.push([y, x0, x - 1]); |
| } |
| } |
| return spans; |
| } |
| |
| function applyFillSpans(op) { |
| const width = maskCanvas.width; |
| const height = maskCanvas.height; |
| const mask = maskCtx.getImageData(0, 0, width, height); |
| const dst = mask.data; |
| let count = 0; |
| for (const span of op.spans || []) { |
| const y = Math.max(0, Math.min(height - 1, span[0] | 0)); |
| const x0 = Math.max(0, Math.min(width - 1, span[1] | 0)); |
| const x1 = Math.max(0, Math.min(width - 1, span[2] | 0)); |
| for (let x = x0; x <= x1; x++) { |
| const rgba = (y * width + x) * 4; |
| if (op.tool === "erase") { |
| dst[rgba + 3] = 0; |
| } else { |
| dst[rgba] = 255; |
| dst[rgba + 1] = 255; |
| dst[rgba + 2] = 255; |
| dst[rgba + 3] = 255; |
| } |
| count++; |
| } |
| } |
| maskCtx.putImageData(mask, 0, 0); |
| return count; |
| } |
| |
| function applyFillOp(op) { |
| if (Array.isArray(op.spans) && op.spans.length) { |
| return applyFillSpans(op); |
| } |
| if (!sourceCanvas.width || !sourceCanvas.height) return 0; |
| const width = sourceCanvas.width; |
| const height = sourceCanvas.height; |
| const sx = Math.max(0, Math.min(width - 1, Math.round(op.seed[0]))); |
| const sy = Math.max(0, Math.min(height - 1, Math.round(op.seed[1]))); |
| const tolerance = Math.max(0, Number(op.tolerance || 0)); |
| const src = sourceCtx.getImageData(0, 0, width, height).data; |
| const mask = maskCtx.getImageData(0, 0, width, height); |
| const dst = mask.data; |
| const seedIndex = (sy * width + sx) * 4; |
| const seed = [src[seedIndex], src[seedIndex + 1], src[seedIndex + 2]]; |
| const visited = new Uint8Array(width * height); |
| const selected = new Uint8Array(width * height); |
| const queue = new Int32Array(width * height); |
| let head = 0; |
| let tail = 0; |
| let count = 0; |
| const start = sy * width + sx; |
| queue[tail++] = start; |
| visited[start] = 1; |
| |
| let limitHit = false; |
| while (head < tail) { |
| if (count >= MAX_FILL_PIXELS) { |
| limitHit = true; |
| break; |
| } |
| const p = queue[head++]; |
| const x = p % width; |
| const y = (p / width) | 0; |
| const rgba = p * 4; |
| if (!pixelMatches(src, rgba, seed, tolerance)) continue; |
| selected[p] = 1; |
| if (op.tool === "erase") { |
| dst[rgba + 3] = 0; |
| } else { |
| dst[rgba] = 255; |
| dst[rgba + 1] = 255; |
| dst[rgba + 2] = 255; |
| dst[rgba + 3] = 255; |
| } |
| count++; |
| if (x > 0) { |
| const n = p - 1; |
| if (!visited[n]) { visited[n] = 1; queue[tail++] = n; } |
| } |
| if (x + 1 < width) { |
| const n = p + 1; |
| if (!visited[n]) { visited[n] = 1; queue[tail++] = n; } |
| } |
| if (y > 0) { |
| const n = p - width; |
| if (!visited[n]) { visited[n] = 1; queue[tail++] = n; } |
| } |
| if (y + 1 < height) { |
| const n = p + width; |
| if (!visited[n]) { visited[n] = 1; queue[tail++] = n; } |
| } |
| } |
| |
| maskCtx.putImageData(mask, 0, 0); |
| op.spans = buildSpans(selected, width, height); |
| op.limit_hit = limitHit; |
| return count; |
| } |
| |
| async function loadImageForCurrent() { |
| const s = sample(); |
| if (!s) return; |
| if (imageUrl && imageUrl.startsWith("blob:")) URL.revokeObjectURL(imageUrl); |
| imageUrl = s.file ? URL.createObjectURL(s.file) : s.image; |
| image = new Image(); |
| sourceReadable = false; |
| return new Promise(resolve => { |
| image.onload = () => { |
| setupMaskCanvas(image.width, image.height); |
| fitImage(); |
| updateUi(); |
| resolve(); |
| }; |
| image.onerror = () => { |
| setStatus(`Failed to load image for ${s.id}. If manifest paths do not resolve, load image files directly or open the dataset-local labeler.html.`); |
| resolve(); |
| }; |
| image.src = imageUrl; |
| }); |
| } |
| |
| function draw() { |
| const dpr = window.devicePixelRatio || 1; |
| ctx.setTransform(dpr, 0, 0, dpr, 0, 0); |
| const rect = canvas.getBoundingClientRect(); |
| ctx.fillStyle = "#05070a"; |
| ctx.fillRect(0, 0, rect.width, rect.height); |
| if (!image) return; |
| |
| const x = view.x / dpr; |
| const y = view.y / dpr; |
| const w = image.width * view.scale; |
| const h = image.height * view.scale; |
| ctx.drawImage(image, x, y, w, h); |
| |
| ctx.save(); |
| ctx.globalAlpha = maskOpacity; |
| ctx.drawImage(previewCanvas, x, y, w, h); |
| ctx.restore(); |
| |
| if (lineAnchor && cursor && isBrushTool()) { |
| const [ax, ay] = imageToScreen(lineAnchor.point); |
| const [cx, cy] = imageToScreen(cursor); |
| ctx.save(); |
| ctx.setLineDash([8, 6]); |
| ctx.lineWidth = Math.max(2, brushSize * view.scale * 0.18); |
| ctx.strokeStyle = tool === "erase" ? "#ff6b78" : "#20e0a2"; |
| ctx.beginPath(); |
| ctx.moveTo(ax, ay); |
| ctx.lineTo(cx, cy); |
| ctx.stroke(); |
| ctx.setLineDash([]); |
| ctx.beginPath(); |
| ctx.arc(ax, ay, Math.max(4, brushSize * view.scale * 0.35), 0, Math.PI * 2); |
| ctx.stroke(); |
| ctx.restore(); |
| } |
| |
| if (cursor) { |
| const [cx, cy] = imageToScreen(cursor); |
| ctx.beginPath(); |
| ctx.arc(cx, cy, brushSize * view.scale, 0, Math.PI * 2); |
| ctx.lineWidth = 1.5; |
| ctx.strokeStyle = tool === "erase" ? "#ff6b78" : "#20e0a2"; |
| ctx.stroke(); |
| } |
| } |
| |
| function renderList() { |
| els.sampleList.innerHTML = ""; |
| samples.forEach((s, i) => { |
| const div = document.createElement("div"); |
| div.className = `sample ${i === current ? "active" : ""} ${s.label?.saved ? "done" : ""}`; |
| div.innerHTML = `<span>${s.id}</span>`; |
| div.onclick = () => selectSample(i); |
| els.sampleList.appendChild(div); |
| }); |
| } |
| |
| function updateUi() { |
| const s = sample(); |
| const l = s ? labelFor(s) : { mask_ops: [], brush_strokes: [], mask_area_px: 0 }; |
| els.toolPaint.classList.toggle("active", tool === "paint"); |
| els.toolErase.classList.toggle("active", tool === "erase"); |
| els.toolFill.classList.toggle("active", tool === "fill"); |
| els.toolFill.classList.toggle("warn", tool === "fill" && fillNeedsRawFiles()); |
| els.toolFill.title = fillNeedsRawFiles() |
| ? "Fill needs raw image files attached so the browser allows RGB pixel reads." |
| : "Flood fill by source image color"; |
| els.panTool.classList.toggle("active", tool === "pan"); |
| els.brushSizeText.textContent = String(brushSize); |
| els.fillToleranceText.textContent = String(fillTolerance); |
| els.maskOpacityText.textContent = String(Math.round(maskOpacity * 100)); |
| els.statSample.textContent = s ? s.id : "-"; |
| els.statImage.textContent = image ? `${image.width}x${image.height}` : "-"; |
| els.statArea.textContent = String(l.mask_area_px || cachedMaskArea || 0); |
| els.statStrokes.textContent = String(l.mask_ops.length); |
| els.statFillSource.textContent = fillSourceLabel(); |
| els.statOut.textContent = outputLabel(); |
| els.pillSample.textContent = s ? s.id : "No sample"; |
| els.pillTool.textContent = tool === "erase" |
| ? "Erase" |
| : tool === "fill" |
| ? `Fill: ${sourceReadable ? "ready" : "blocked"}` |
| : tool === "pan" |
| ? "Pan" |
| : "Paint"; |
| renderList(); |
| draw(); |
| } |
| |
| function selectSample(index) { |
| if (index < 0 || index >= samples.length) return; |
| current = index; |
| redoStack = []; |
| lineAnchor = null; |
| loadImageForCurrent().then(() => setStatus(`Loaded ${samples[current].id}`)); |
| } |
| |
| function normalizeSample(item, index) { |
| const id = item.id || item.sample_id || item.name || `sample_${String(index).padStart(4, "0")}`; |
| const label = item.label || {}; |
| const draft = loadDraft(id); |
| const normalized = { |
| mask_ops: normalizeMaskOps(label), |
| saved: !!label.saved, |
| mask_area_px: Number(label.mask_area_px || 0), |
| }; |
| syncDerivedLabel(normalized); |
| return { |
| id, |
| image: item.image || item.raw_rgb || item.path || item.file || "", |
| image_file_name: basename(item.image || item.raw_rgb || item.path || item.file || ""), |
| prompt: item.prompt || "", |
| label: draft || normalized, |
| }; |
| } |
| |
| function applySavedLabelDoc(s, doc) { |
| const maskOps = normalizeMaskOps(doc); |
| if (!maskOps.length) return false; |
| s.label = { |
| mask_ops: maskOps, |
| saved: true, |
| mask_area_px: Number(doc.mask_area_px || 0), |
| }; |
| syncDerivedLabel(s.label); |
| saveDraft(s); |
| return true; |
| } |
| |
| async function loadSavedLabelsFromServer() { |
| if (!canUseServerSave() || !samples.length) return 0; |
| const results = await Promise.all(samples.map(async s => { |
| try { |
| const response = await fetch(`labels/${encodeURIComponent(s.id)}/label.json`, { cache: "no-store" }); |
| if (!response.ok) return false; |
| return applySavedLabelDoc(s, await response.json()); |
| } catch { |
| return false; |
| } |
| })); |
| const loaded = results.filter(Boolean).length; |
| if (sample() && image && maskCanvas.width) replayMask(); |
| updateUi(); |
| return loaded; |
| } |
| |
| async function loadManifestDoc(doc, sourceLabel = "manifest") { |
| samples = (doc.samples || doc.images || []).map(normalizeSample); |
| current = samples.length ? 0 : -1; |
| renderList(); |
| const loadedSaved = await loadSavedLabelsFromServer(); |
| await loadImageForCurrent(); |
| setStatus(fillNeedsRawFiles() |
| ? `Loaded ${sourceLabel} with ${samples.length} samples, but Fill cannot read source pixels from this page mode. Open the dataset through a local HTTP server so manifest images are readable.` |
| : `Loaded ${sourceLabel} with ${samples.length} samples${loadedSaved ? ` and ${loadedSaved} saved labels` : ""}.`); |
| } |
| |
| async function loadManifestUrl(url) { |
| try { |
| const response = await fetch(url); |
| if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| await loadManifestDoc(await response.json(), url); |
| } catch (error) { |
| setStatus(`Failed to load manifest URL ${url}: ${error.message || error}`); |
| } |
| } |
| |
| els.manifestFile.onchange = async (event) => { |
| const file = event.target.files?.[0]; |
| if (!file) return; |
| const doc = JSON.parse(await file.text()); |
| await loadManifestDoc(doc, "manifest"); |
| }; |
| |
| els.imageFiles.onchange = async (event) => { |
| const files = Array.from(event.target.files || []); |
| if (samples.length) { |
| const byName = new Map(files.map(file => [file.name, file])); |
| let attached = 0; |
| for (const s of samples) { |
| const file = byName.get(s.image_file_name || basename(s.image)); |
| if (!file) continue; |
| s.file = file; |
| attached++; |
| } |
| if (attached) { |
| await loadImageForCurrent(); |
| setStatus(sourceReadable |
| ? `Attached ${attached} raw image files to manifest samples. Fill can now read RGB pixels.` |
| : `Attached ${attached} raw image files, but this browser still blocks RGB reads.`); |
| return; |
| } |
| setStatus("No selected raw files matched the manifest image names. Select the PNG files from the dataset raw folder."); |
| return; |
| } |
| samples = files.map((file, i) => ({ |
| id: file.name.replace(/\.[^.]+$/, ""), |
| file, |
| image: file.name, |
| image_file_name: file.name, |
| prompt: "", |
| label: loadDraft(file.name.replace(/\.[^.]+$/, "")) || { brush_strokes: [], saved: false, mask_area_px: 0 }, |
| })); |
| current = samples.length ? 0 : -1; |
| renderList(); |
| await loadImageForCurrent(); |
| setStatus(`Loaded ${samples.length} image files.`); |
| }; |
| |
| function setTool(nextTool) { |
| if (tool !== nextTool) lineAnchor = null; |
| tool = nextTool; |
| updateUi(); |
| } |
| function activateFill() { |
| setTool("fill"); |
| if (fillNeedsRawFiles()) { |
| requestRawFilesForFill(); |
| } else { |
| showNotice("Fill ready. Click the image to flood-fill a contiguous color region.", "ok"); |
| } |
| } |
| els.toolPaint.onclick = () => setTool("paint"); |
| els.toolErase.onclick = () => setTool("erase"); |
| els.toolFill.onclick = activateFill; |
| els.panTool.onclick = () => setTool(tool === "pan" ? "paint" : "pan"); |
| |
| els.brushSize.oninput = () => { |
| brushSize = Number(els.brushSize.value); |
| updateUi(); |
| }; |
| els.fillTolerance.oninput = () => { |
| fillTolerance = Number(els.fillTolerance.value); |
| updateUi(); |
| }; |
| els.maskOpacity.oninput = () => { |
| maskOpacity = Number(els.maskOpacity.value) / 100; |
| updateUi(); |
| }; |
| |
| function eventImagePoint(event) { |
| const rect = canvas.getBoundingClientRect(); |
| return clampPoint(screenToImage(event.clientX - rect.left, event.clientY - rect.top)); |
| } |
| |
| function handleShiftLineClick(event) { |
| const p = roundedPoint(eventImagePoint(event)); |
| if (!lineAnchor) { |
| lineAnchor = { point: p }; |
| const text = `${tool === "erase" ? "Erase" : "Paint"} line start set. Shift+click the line end.`; |
| setStatus(text); |
| showNotice(text, "ok"); |
| draw(); |
| event.preventDefault(); |
| return; |
| } |
| |
| const stroke = { |
| kind: "brush", |
| tool, |
| radius: brushSize, |
| points: [lineAnchor.point, p], |
| }; |
| lineAnchor = null; |
| redoStack = []; |
| drawStroke(maskCtx, stroke); |
| const s = sample(); |
| const l = labelFor(s); |
| l.mask_ops.push(stroke); |
| syncDerivedLabel(l); |
| l.saved = false; |
| cachedMaskArea = computeMaskArea(); |
| l.mask_area_px = cachedMaskArea; |
| rebuildPreviewMask(); |
| saveDraft(s); |
| const text = `${tool === "erase" ? "Erase" : "Paint"} line drawn.`; |
| setStatus(text); |
| showNotice(text, "ok"); |
| updateUi(); |
| event.preventDefault(); |
| } |
| |
| canvas.addEventListener("contextmenu", event => event.preventDefault()); |
| |
| canvas.addEventListener("pointerdown", (event) => { |
| if (!image) return; |
| canvas.setPointerCapture(event.pointerId); |
| const shouldPan = event.button === 1 || spaceDown || tool === "pan"; |
| if (shouldPan) { |
| panning = true; |
| lastMouse = [event.clientX, event.clientY]; |
| return; |
| } |
| if (event.button !== 0) return; |
| if (tool === "fill") { |
| if (fillNeedsRawFiles()) { |
| requestRawFilesForFill(); |
| updateUi(); |
| event.preventDefault(); |
| return; |
| } |
| const p = eventImagePoint(event); |
| const op = { |
| kind: "fill", |
| tool: event.shiftKey ? "erase" : "paint", |
| seed: [Number(p[0].toFixed(2)), Number(p[1].toFixed(2))], |
| tolerance: fillTolerance, |
| pixel_count: 0, |
| }; |
| try { |
| op.pixel_count = applyFillOp(op); |
| } catch (error) { |
| sourceReadable = false; |
| requestRawFilesForFill(); |
| updateUi(); |
| event.preventDefault(); |
| return; |
| } |
| if (op.pixel_count <= 0) { |
| const text = "Fill found no matching pixels. Increase tolerance or click inside the target surface."; |
| setStatus(text); |
| showNotice(text, "warn"); |
| updateUi(); |
| event.preventDefault(); |
| return; |
| } |
| const l = labelFor(sample()); |
| l.mask_ops.push(op); |
| syncDerivedLabel(l); |
| l.saved = false; |
| cachedMaskArea = computeMaskArea(); |
| l.mask_area_px = cachedMaskArea; |
| rebuildPreviewMask(); |
| saveDraft(sample()); |
| const fillText = op.limit_hit |
| ? `Fill painted ${op.pixel_count} px and stopped at the safety cap. Undo or lower tolerance if it spilled.` |
| : op.pixel_count < 512 |
| ? `Fill painted only ${op.pixel_count} px. Increase tolerance if this looks like no change.` |
| : `Fill painted ${op.pixel_count} px.`; |
| setStatus(fillText); |
| showNotice(fillText, op.pixel_count < 512 || op.limit_hit ? "warn" : "ok"); |
| updateUi(); |
| event.preventDefault(); |
| return; |
| } |
| if (event.shiftKey && isBrushTool()) { |
| handleShiftLineClick(event); |
| return; |
| } |
| lineAnchor = null; |
| drawing = true; |
| redoStack = []; |
| const p = eventImagePoint(event); |
| activeStroke = { kind: "brush", tool, radius: brushSize, points: [[Number(p[0].toFixed(2)), Number(p[1].toFixed(2))]] }; |
| drawStrokeSegment(maskCtx, activeStroke, null, p); |
| rebuildPreviewMask(); |
| draw(); |
| event.preventDefault(); |
| }); |
| |
| canvas.addEventListener("pointermove", (event) => { |
| if (image) { |
| const rect = canvas.getBoundingClientRect(); |
| cursor = clampPoint(screenToImage(event.clientX - rect.left, event.clientY - rect.top)); |
| } |
| if (panning && lastMouse) { |
| const dpr = window.devicePixelRatio || 1; |
| view.x += (event.clientX - lastMouse[0]) * dpr; |
| view.y += (event.clientY - lastMouse[1]) * dpr; |
| lastMouse = [event.clientX, event.clientY]; |
| draw(); |
| return; |
| } |
| if (!drawing || !activeStroke) { |
| draw(); |
| return; |
| } |
| const events = typeof event.getCoalescedEvents === "function" ? event.getCoalescedEvents() : [event]; |
| const moveEvents = events.length ? events : [event]; |
| for (const moveEvent of moveEvents) appendBrushPoint(moveEvent); |
| rebuildPreviewMask(); |
| draw(); |
| }); |
| |
| function appendBrushPoint(event) { |
| const p = eventImagePoint(event); |
| const rounded = [Number(p[0].toFixed(2)), Number(p[1].toFixed(2))]; |
| const prev = activeStroke.points[activeStroke.points.length - 1]; |
| const dx = rounded[0] - prev[0]; |
| const dy = rounded[1] - prev[1]; |
| if (Math.hypot(dx, dy) < Math.max(0.35, brushSize * 0.045)) return; |
| activeStroke.points.push(rounded); |
| drawStrokeSegment(maskCtx, activeStroke, prev, rounded); |
| } |
| |
| function finishStroke(event) { |
| if (event?.pointerId != null && canvas.hasPointerCapture(event.pointerId)) { |
| canvas.releasePointerCapture(event.pointerId); |
| } |
| panning = false; |
| lastMouse = null; |
| if (!drawing || !activeStroke) return; |
| const s = sample(); |
| const l = labelFor(s); |
| l.mask_ops.push(activeStroke); |
| syncDerivedLabel(l); |
| l.saved = false; |
| activeStroke = null; |
| drawing = false; |
| cachedMaskArea = computeMaskArea(); |
| l.mask_area_px = cachedMaskArea; |
| saveDraft(s); |
| updateUi(); |
| } |
| canvas.addEventListener("pointerup", finishStroke); |
| canvas.addEventListener("pointercancel", finishStroke); |
| canvas.addEventListener("pointerleave", () => { cursor = null; draw(); }); |
| |
| canvas.addEventListener("wheel", (event) => { |
| if (!image) return; |
| event.preventDefault(); |
| const rect = canvas.getBoundingClientRect(); |
| const mx = event.clientX - rect.left; |
| const my = event.clientY - rect.top; |
| const before = screenToImage(mx, my); |
| const factor = Math.exp(-event.deltaY * 0.0012); |
| view.scale = Math.max(0.05, Math.min(20, view.scale * factor)); |
| const after = screenToImage(mx, my); |
| const dpr = window.devicePixelRatio || 1; |
| view.x += (after[0] - before[0]) * view.scale * dpr; |
| view.y += (after[1] - before[1]) * view.scale * dpr; |
| draw(); |
| }, { passive: false }); |
| |
| function undo() { |
| const s = sample(); |
| if (!s) return; |
| const l = labelFor(s); |
| const op = l.mask_ops.pop(); |
| if (!op) return; |
| redoStack.push(op); |
| syncDerivedLabel(l); |
| l.saved = false; |
| replayMask(); |
| saveDraft(s); |
| updateUi(); |
| } |
| els.undo.onclick = undo; |
| |
| function redo() { |
| const s = sample(); |
| if (!s) return; |
| const stroke = redoStack.pop(); |
| if (!stroke) return; |
| const l = labelFor(s); |
| l.mask_ops.push(stroke); |
| syncDerivedLabel(l); |
| l.saved = false; |
| replayMask(); |
| saveDraft(s); |
| updateUi(); |
| } |
| els.redo.onclick = redo; |
| |
| els.clearMask.onclick = () => { |
| const s = sample(); |
| if (!s) return; |
| const l = labelFor(s); |
| if (!l.mask_ops.length) return; |
| redoStack = []; |
| lineAnchor = null; |
| l.mask_ops = []; |
| l.brush_strokes = []; |
| l.fill_ops = []; |
| l.mask_area_px = 0; |
| l.saved = false; |
| replayMask(); |
| saveDraft(s); |
| updateUi(); |
| }; |
| els.fit.onclick = fitImage; |
| els.prev.onclick = () => selectSample(Math.max(0, current - 1)); |
| els.next.onclick = () => selectSample(Math.min(samples.length - 1, current + 1)); |
| |
| window.addEventListener("keydown", (event) => { |
| if (event.target && ["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)) return; |
| if (event.code === "Space") spaceDown = true; |
| if (event.key === "Escape" && lineAnchor) { |
| lineAnchor = null; |
| setStatus("Line start cancelled."); |
| updateUi(); |
| return; |
| } |
| if (event.key.toLowerCase() === "b") setTool("paint"); |
| if (event.key.toLowerCase() === "e") setTool("erase"); |
| if (event.key.toLowerCase() === "g") activateFill(); |
| if (event.key.toLowerCase() === "z") undo(); |
| if (event.key.toLowerCase() === "y") redo(); |
| if (event.key.toLowerCase() === "f") fitImage(); |
| if (event.key.toLowerCase() === "s") saveSample(); |
| if (event.key === "[") { |
| brushSize = Math.max(2, brushSize - 2); |
| els.brushSize.value = String(brushSize); |
| updateUi(); |
| } |
| if (event.key === "]") { |
| brushSize = Math.min(120, brushSize + 2); |
| els.brushSize.value = String(brushSize); |
| updateUi(); |
| } |
| if (event.key === "ArrowLeft") selectSample(Math.max(0, current - 1)); |
| if (event.key === "ArrowRight") selectSample(Math.min(samples.length - 1, current + 1)); |
| }); |
| window.addEventListener("keyup", (event) => { |
| if (event.code === "Space") spaceDown = false; |
| }); |
| |
| async function readLabelFromDir(dir, sampleId) { |
| const sampleDir = await dir.getDirectoryHandle(sampleId); |
| const labelHandle = await sampleDir.getFileHandle("label.json"); |
| const file = await labelHandle.getFile(); |
| return JSON.parse(await file.text()); |
| } |
| |
| async function loadSavedLabelsFromDir(dir) { |
| let loaded = 0; |
| for (const s of samples) { |
| try { |
| const doc = await readLabelFromDir(dir, s.id); |
| if (applySavedLabelDoc(s, doc)) loaded++; |
| } catch { |
| |
| } |
| } |
| if (sample()) replayMask(); |
| updateUi(); |
| return loaded; |
| } |
| |
| async function chooseOut() { |
| if (!window.showDirectoryPicker) { |
| setStatus("Directory write is not supported in this browser. Use Download."); |
| return; |
| } |
| outDir = await window.showDirectoryPicker({ mode: "readwrite" }); |
| els.statOut.textContent = outDir.name; |
| const loaded = await loadSavedLabelsFromDir(outDir); |
| setStatus(`Output directory selected: ${outDir.name}. Loaded ${loaded} saved labels.`); |
| } |
| els.chooseOut.onclick = chooseOut; |
| |
| function labelDoc(s) { |
| const l = labelFor(s); |
| return { |
| schema_version: "rlc.freeform_surface_label.v3", |
| label_type: "raster_mask", |
| sample_id: s.id, |
| image: s.image, |
| prompt: s.prompt || "", |
| image_width_px: image.width, |
| image_height_px: image.height, |
| coordinate_order: "xy", |
| source_of_truth: "target_track_mask.png", |
| target_mask: "target_track_mask.png", |
| overlay: "overlay.png", |
| mask_area_px: l.mask_area_px || cachedMaskArea || 0, |
| mask_ops: l.mask_ops, |
| brush_strokes: l.brush_strokes, |
| fill_ops: l.fill_ops, |
| contour_status: "derive_from_target_track_mask_downstream", |
| }; |
| } |
| |
| function targetMaskCanvas() { |
| const c = document.createElement("canvas"); |
| c.width = image.width; |
| c.height = image.height; |
| const m = c.getContext("2d"); |
| m.fillStyle = "#000"; |
| m.fillRect(0, 0, c.width, c.height); |
| m.drawImage(maskCanvas, 0, 0); |
| return c; |
| } |
| |
| function overlayCanvas() { |
| const c = document.createElement("canvas"); |
| c.width = image.width; |
| c.height = image.height; |
| const o = c.getContext("2d"); |
| o.drawImage(image, 0, 0); |
| o.save(); |
| o.globalAlpha = 0.42; |
| o.drawImage(previewCanvas, 0, 0); |
| o.restore(); |
| return c; |
| } |
| |
| async function canvasBlob(c) { |
| return await new Promise((resolve, reject) => { |
| try { |
| c.toBlob(blob => blob ? resolve(blob) : reject(new Error("Canvas export returned no blob.")), "image/png"); |
| } catch (error) { |
| reject(error); |
| } |
| }); |
| } |
| |
| function downloadBlob(blob, filename) { |
| const a = document.createElement("a"); |
| a.href = URL.createObjectURL(blob); |
| a.download = filename; |
| document.body.appendChild(a); |
| a.click(); |
| a.remove(); |
| setTimeout(() => URL.revokeObjectURL(a.href), 1000); |
| } |
| |
| async function writeFile(dir, pathParts, blobOrText) { |
| let handle = dir; |
| for (let i = 0; i < pathParts.length - 1; i++) { |
| handle = await handle.getDirectoryHandle(pathParts[i], { create: true }); |
| } |
| const fh = await handle.getFileHandle(pathParts[pathParts.length - 1], { create: true }); |
| const w = await fh.createWritable(); |
| await w.write(blobOrText); |
| await w.close(); |
| } |
| |
| async function saveSampleToServer(s, doc, mask, overlay) { |
| if (!canUseServerSave()) return { ok: false, error: "not running over http" }; |
| const form = new FormData(); |
| form.append("sample_id", s.id); |
| form.append("label_json", new Blob([doc], { type: "application/json" }), "label.json"); |
| form.append("target_track_mask", mask, "target_track_mask.png"); |
| if (overlay) form.append("overlay_png", overlay, "overlay.png"); |
| try { |
| const response = await fetch("/api/labeler/save-sample", { method: "POST", body: form }); |
| const text = await response.text(); |
| let result = {}; |
| try { |
| result = text ? JSON.parse(text) : {}; |
| } catch { |
| result = { error: text }; |
| } |
| if (!response.ok || result.ok === false) { |
| throw new Error(result.error || `HTTP ${response.status}`); |
| } |
| serverSave.state = "ready"; |
| return { ok: true, ...result }; |
| } catch (error) { |
| serverSave = { state: "unavailable", labelsDir: "labels", error: error.message || String(error) }; |
| return { ok: false, error: serverSave.error }; |
| } |
| } |
| |
| async function saveSample(downloadOnly = false) { |
| const s = sample(); |
| if (!s || !image) return; |
| const l = labelFor(s); |
| l.mask_area_px = computeMaskArea(); |
| cachedMaskArea = l.mask_area_px; |
| if (l.mask_area_px <= 0) { |
| setStatus("Mask is empty. Paint the track surface first."); |
| updateUi(); |
| return; |
| } |
| const doc = JSON.stringify(labelDoc(s), null, 2); |
| const mask = await canvasBlob(targetMaskCanvas()); |
| let overlay = null; |
| let overlayWarning = ""; |
| try { |
| overlay = await canvasBlob(overlayCanvas()); |
| } catch { |
| overlayWarning = " Overlay export was skipped because the source image is browser-protected; target_track_mask.png was still saved."; |
| } |
| if (downloadOnly) { |
| downloadBlob(new Blob([doc], { type: "application/json" }), `${s.id}_label.json`); |
| downloadBlob(mask, `${s.id}_target_track_mask.png`); |
| if (overlay) downloadBlob(overlay, `${s.id}_overlay.png`); |
| saveDraft(s); |
| setStatus(`Downloaded ${s.id} label artifacts. Local draft is kept for reload; choose labels dir or use the local labeler server for dataset writes.${overlayWarning}`); |
| } else { |
| const serverResult = await saveSampleToServer(s, doc, mask, overlay); |
| if (serverResult.ok) { |
| l.saved = true; |
| saveDraft(s); |
| const where = serverResult.sample_dir || `${serverSave.labelsDir}/${s.id}`; |
| setStatus(`Saved ${s.id}/label.json + target_track_mask.png${overlay ? " + overlay.png" : ""} to ${where}.${overlayWarning}`); |
| } else if (outDir) { |
| await writeFile(outDir, [s.id, "label.json"], doc); |
| await writeFile(outDir, [s.id, "target_track_mask.png"], mask); |
| if (overlay) await writeFile(outDir, [s.id, "overlay.png"], overlay); |
| l.saved = true; |
| saveDraft(s); |
| setStatus(`Saved ${s.id}/label.json + target_track_mask.png${overlay ? " + overlay.png" : ""}.${overlayWarning}`); |
| } else { |
| const text = `Automatic dataset save is unavailable (${serverResult.error || "no local labeler server"}). Start the local labeler server or use Choose labels dir once. Use Download only for manual exports.`; |
| setStatus(text); |
| showNotice(text, "warn"); |
| updateUi(); |
| return; |
| } |
| } |
| updateUi(); |
| } |
| els.saveSample.onclick = () => saveSample(false); |
| els.downloadSample.onclick = () => saveSample(true); |
| |
| els.saveAllManifest.onclick = () => { |
| const doc = { |
| schema_version: "rlc.freeform_surface_manifest.v3", |
| label_type: "raster_mask", |
| samples: samples.map(s => ({ |
| id: s.id, |
| image: s.image, |
| prompt: s.prompt || "", |
| labeled: !!s.label?.saved, |
| mask_area_px: s.label?.mask_area_px || 0, |
| })), |
| }; |
| downloadBlob(new Blob([JSON.stringify(doc, null, 2)], { type: "application/json" }), "freeform_labeling_manifest.json"); |
| }; |
| |
| resize(); |
| probeServerSave(); |
| const manifestUrl = new URLSearchParams(location.search).get("manifest"); |
| if (manifestUrl) loadManifestUrl(manifestUrl); |
| </script> |
| </body> |
| </html> |
|
|