// ==UserScript== // @name 比邻云行人助手 // @namespace https://label.bilinyun.net // @version 2.9 // @description 比邻云行人(2DPedestrian)质检助手:① 进题包全量预加载全部帧,消除首次切帧的灰屏转圈等待 ② 切帧去黑屏遮罩 ③ 帧级标注缓存 + 缺帧自动补请求 ④ 面板实时显示本帧框数与整包统计 ⑤ 整包框尺寸检查(宽≥20 高≥40,错误帧点击跳转)⑥ 同一帧内 person_id 主ID 查重,重复即报红 ⑦ 格式校验:person_id 必须 5 位数字、appearance_id 必须 2 位数字,不合规报红 ⑧ 主框/其他框标了「忽略」的报黄提醒 ⑨ 一键复制「包号 + 有效帧数 + 框数」⑩ 一键复制错误信息(TSV,可直接粘 Excel)⑪ 选中行人主框后进网格模式,自动按 person_id 筛选并调 240px(可开关)⑫ 网格筛选后只显示命中帧,空隙自动紧凑排列 ⑬ 属性选 person_id 时,值改为下拉,只列本包出现过的 person_id ⑭ 亮底框标签自动改黑字(默认开启)⑮ 选中行人主框可批量改 person_id / appearance_id(按主ID匹配全包,并发扫描+并发写入)⑯ 提交前检查批注:还有「待修复」就拦截并弹框 // @author CC // @match https://label.bilinyun.net/* // @match http://118.196.122.17/* // @grant none // @run-at document-start // @license CC // ==/UserScript== (function () { 'use strict'; /* ==================== 常量 ==================== */ const API_MARK = '/api/mark/image'; const API_STATIC = '/api/mark/contents/static'; const WARMUP_KEY = '_blyped_warmup'; const GRID_AUTO_KEY = '_blyped_grid_auto'; // ---- 框尺寸规则(来自 BB 平台「行人验收框大小」脚本,单位:图像像素)---- // 不分主/非主行人,统一按此标准;标了「忽略」的框跳过检查 const MIN_W = 20; const MIN_H = 40; let WARMUP_ON = true; try { WARMUP_ON = localStorage.getItem(WARMUP_KEY) !== '0'; } catch (e) { } // 网格模式自动筛选开关:选中行人主框后点「网格模式」→ 自动按 person_id 筛选 + 240px let GRID_AUTO_ON = true; try { GRID_AUTO_ON = localStorage.getItem(GRID_AUTO_KEY) !== '0'; } catch (e) { } /* ==================== 全局状态 ==================== */ let CMAP = null; // 类目映射(从 projectClass 动态构建) let IMG_SIZE = null; // 图像宽高缓存 let AUTH_HDRS = null; // 页面真实请求里的鉴权头(用于兜底补请求) let FRAME_IDS = []; // 帧序号(1-based) → frameId const FRAME_CACHE = {}; // frameId → shapeList let PROJECT_INFO = {}; // taskNo / projectName 等 let lastFrameNo = null; let lastRenderKey = null; let PACK_STAT = null; // 整包统计结果 let WARMUP_RUNNING = false; let WARMUP_DONE = false; let warmupTried = false; let staticTried = false; /* ==================== 工具 ==================== */ function num(v) { const n = parseFloat(v); return isNaN(n) ? null : n; } function parseJson(s) { try { return JSON.parse(s) || {}; } catch (e) { return {}; } } function esc(s) { return String(s === null || s === undefined ? '' : s) .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } function fmt1(n) { if (n === null || n === undefined || isNaN(n)) return '?'; return (Math.round(n * 10) / 10).toFixed(1); } function taskIdFromUrl() { const m = /[?&]recordId=([^&]+)/.exec(location.search || ''); return m ? m[1] : null; } function frameIdFromUrl(u) { const m = /frame_id=([^&]+)/.exec(u || ''); return m ? m[1] : null; } function currentFrameNo() { const el = document.querySelector('.frame-counter-clickable'); if (!el) return null; const m = /(\d+)\s*\/\s*(\d+)/.exec(el.innerText || ''); return m ? parseInt(m[1], 10) : null; } /* ==================== 类目映射(自适应 projectClass) ==================== */ // 行人项目实测两个类目: // full_bbox → 行人主框(含 是否忽略 / 遮挡 / 截断) // Other pedestrian boxes → 其他行人框(含 忽略 / 遮挡 / 截断) function buildClassMap(pcStr) { let pc; if (!pcStr) return null; try { pc = (typeof pcStr === 'string') ? JSON.parse(pcStr) : pcStr; } catch (e) { return null; } if (!pc || !pc.id || !pc.id.length) return null; const ids = pc.id || []; const exps = pc.exportName || []; const names = pc.name || []; const attrs = pc.attributes || []; const m = { mainId: null, // 行人主框类目 id otherId: null, // 其他行人框类目 id idName: {}, // 类目 id → 名称 ignoreAttr: {}, // 类目 id → { attrId, values:Set(忽略值id) } personAttr: {}, // 类目 id → person_id 属性 id(仅行人主框有) appearAttr: {}, // 类目 id → appearance_id 属性 id(仅行人主框有) occAttr: {}, // 类目 id → { attrId, values:{} } truncAttr: {}, // 类目 id → { attrId, values:{} } allIds: ids.slice() }; ids.forEach(function (id, i) { const ex = String(exps[i] || ''); const nm = String(names[i] || ''); m.idName[id] = nm || ex || id; if (/other/i.test(ex) || nm.indexOf('其他') !== -1) m.otherId = id; else if (!m.mainId) m.mainId = id; const collect = function (a, target) { const vals = {}; (a.attributes || []).forEach(function (v) { vals[v.id] = String(v.name || v.exportName || ''); }); target[id] = { attrId: a.id, values: vals }; }; (attrs[i] || []).forEach(function (a) { const ax = String(a.exportName || ''); const an = String(a.name || ''); // 是否忽略:主框是「Ignore / 0=是 1=否」,其他框是「ignore / 0=有效 1=忽略」 if (/ignore/i.test(ax) || an.indexOf('忽略') !== -1) { const set = {}; (a.attributes || []).forEach(function (v) { const vn = String(v.name || '').trim(); const ve = String(v.exportName || '').trim(); if (vn === '忽略' || ve === '忽略' || vn === '是' || ve === '是') set[v.id] = true; }); m.ignoreAttr[id] = { attrId: a.id, values: set }; } // 主ID:行人主框上的 person_id(自由文本属性,无枚举值) if (/^person_?id$/i.test(ax) || /^person_?id$/i.test(an) || /^主\s*id$/i.test(an) || ax === 'main_id') { m.personAttr[id] = a.id; } // 变装ID:行人主框上的 appearance_id if (/^appearance_?id$/i.test(ax) || /^appearance_?id$/i.test(an) || /^变装\s*id$/i.test(an)) { m.appearAttr[id] = a.id; } if (/occlusion/i.test(ax) || an.indexOf('遮挡') !== -1) collect(a, m.occAttr); if (/truncation/i.test(ax) || an.indexOf('截断') !== -1) collect(a, m.truncAttr); }); }); if (!m.mainId) m.mainId = m.otherId; return m; } function getMap() { return CMAP; } function isIgnored(box) { const M = getMap(); if (!M || !M.ignoreAttr) return false; const conf = M.ignoreAttr[box.typeId]; if (!conf) return false; const v = box.attrs ? box.attrs[conf.attrId] : null; return !!(v && conf.values[v]); } /* ==================== 标注归一化 ==================== */ // 比邻云 shapeList 元素:{ labelId, imageId, shapeJson, attrJson }(后两者是字符串化 JSON) function boxOf(s) { if (!s || s.labelId === undefined) return null; const sh = parseJson(s.shapeJson); const at = parseJson(s.attrJson); const g = sh.shape || {}; let lx = num(g.lx), ly = num(g.ly), rx = num(g.rx), ry = num(g.ry); // 平台有两种坐标格式: // 老格式 { lx, ly, rx, ry } // 新格式 { x, y, width, height, rotation } + geometryVersion:2(AI 预标注/旋转框) // 统一折算成 lx/ly/rx/ry,否则新格式会算不出宽高、误报「无有效尺寸数据」 if (lx === null || rx === null) { const gx = num(g.x), gw = num(g.width); if (gx !== null && gw !== null) { lx = gx; rx = gx + gw; } } if (ly === null || ry === null) { const gy = num(g.y), gh = num(g.height); if (gy !== null && gh !== null) { ly = gy; ry = gy + gh; } } const M = getMap(); const pidAttr = (M && M.personAttr) ? M.personAttr[at.type_id] : null; const aidAttr = (M && M.appearAttr) ? M.appearAttr[at.type_id] : null; const rawPid = (pidAttr && at.attributes) ? at.attributes[pidAttr] : null; const rawAid = (aidAttr && at.attributes) ? at.attributes[aidAttr] : null; const pid = (rawPid === null || rawPid === undefined) ? '' : String(rawPid).trim(); const aid = (rawAid === null || rawAid === undefined) ? '' : String(rawAid).trim(); return { labelId: s.labelId, typeId: at.type_id, attrs: at.attributes || {}, isRect: String(sh.shapeType) === '0', personId: pid || null, appearId: aid || null, pidTracked: !!pidAttr, // 该类目是否有 person_id 属性 aidTracked: !!aidAttr, // 该类目是否有 appearance_id 属性 lx: lx, ly: ly, rx: rx, ry: ry, w: (lx !== null && rx !== null) ? Math.abs(rx - lx) : null, h: (ly !== null && ry !== null) ? Math.abs(ry - ly) : null, clsName: (getMap() && getMap().idName[s.attrJson ? at.type_id : '']) || '' }; } /* ==================== 图像真实尺寸 ==================== */ // 页面 里有 logo,不能直接用;优先从 Konva 舞台的 Image 节点取 function getImageSize() { let w = 0, h = 0; try { if (typeof Konva !== 'undefined' && Konva.stages && Konva.stages.length) { const nodes = Konva.stages[0].find('Image'); for (let i = 0; i < nodes.length; i++) { const im = nodes[i].image && nodes[i].image(); if (im && im.naturalWidth > 200 && im.naturalHeight > 200) { w = im.naturalWidth; h = im.naturalHeight; break; } } } } catch (e) { } if (!w) { const imgs = document.querySelectorAll('img'); for (let i = 0; i < imgs.length; i++) { const iw = imgs[i].naturalWidth, ih = imgs[i].naturalHeight; if (iw > 1000 && ih > 1000) { w = iw; h = ih; break; } } } if (!w) { IMG_SIZE = null; return null; } if (!IMG_SIZE || IMG_SIZE.w !== w || IMG_SIZE.h !== h) IMG_SIZE = { w: w, h: h }; return IMG_SIZE; } /* ==================== 本帧分析 ==================== */ let lastBoxes = null; function analyzeShapes(shapeList, size) { const boxes = []; (shapeList || []).forEach(function (s) { const b = boxOf(s); if (b && b.isRect) boxes.push(b); }); const ignored = boxes.filter(function (b) { return isIgnored(b); }); const st = statOfBoxes(boxes); lastBoxes = { boxes: boxes, valid: boxes.length - ignored.length, ignored: ignored.length, fmtErrs: st.fmtErrs, sizeErrs: st.sizeErrs, dupErrs: st.dupErrs, ignoredList: st.ignoredBoxes }; const rk = boxes.map(function (b) { return b.labelId + '|' + b.lx + ',' + b.ly + ',' + b.rx + ',' + b.ry + '|' + JSON.stringify(b.attrs); }).join(';') + '|' + currentFrameNo() + '|' + (size ? size.w + 'x' + size.h : '-'); if (rk === lastRenderKey) return; // 数据未变不重渲染,避免面板闪烁 lastRenderKey = rk; renderPanel(); } function showWaiting(no) { if (WARMUP_RUNNING) return; lastBoxes = null; lastRenderKey = null; renderPanel(no); } /* ==================== 面板 UI ==================== */ let panelContainer = null, panelBody = null, panelContent = null; let isMinimized = false, isDragging = false, dragOffsetX = 0, dragOffsetY = 0; let panelX = null, panelY = 60; function createPanel() { if (panelContainer && document.body && document.body.contains(panelContainer)) return; const exist = document.getElementById('_blyped_panel'); if (exist) { panelContainer = exist; panelBody = exist.querySelector('#_blyped_body'); panelContent = exist.querySelector('#_blyped_content'); return; } panelContainer = document.createElement('div'); panelContainer.id = '_blyped_panel'; if (panelX === null) panelX = Math.max(20, window.innerWidth - 372); panelContainer.style.cssText = 'position:fixed;z-index:999999;width:352px;background:#ffffff;' + 'border:1px solid #d1d5db;border-radius:10px;box-shadow:0 4px 20px rgba(0,0,0,0.15);' + 'font-family:"Microsoft YaHei","PingFang SC",Arial,sans-serif;font-size:13px;color:#1f2937;' + 'overflow:hidden;left:' + panelX + 'px;top:' + panelY + 'px;user-select:none;'; const titleBar = document.createElement('div'); titleBar.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:8px 12px;' + 'background:#f3f4f6;cursor:move;border-bottom:1px solid #d1d5db;'; titleBar.innerHTML = '🚶 比邻云行人助手'; titleBar.addEventListener('mousedown', startDrag); const btns = document.createElement('div'); btns.style.cssText = 'display:flex;gap:6px;'; btns.appendChild(createBtn('—', '#e5e7eb', '#d1d5db', function (e) { e.stopPropagation(); toggleMinimize(); })); btns.appendChild(createBtn('✕', '#fca5a5', '#f87171', function (e) { e.stopPropagation(); closePanel(); })); titleBar.appendChild(btns); panelContainer.appendChild(titleBar); panelBody = document.createElement('div'); panelBody.id = '_blyped_body'; panelBody.style.cssText = 'max-height:520px;overflow-y:auto;'; panelContent = document.createElement('div'); panelContent.id = '_blyped_content'; panelContent.style.cssText = 'padding:11px;background:#ffffff;'; panelBody.appendChild(panelContent); panelContainer.appendChild(panelBody); document.body.appendChild(panelContainer); } function createBtn(text, color, hover, onClick) { const b = document.createElement('span'); b.textContent = text; b.style.cssText = 'width:26px;height:26px;display:flex;align-items:center;justify-content:center;' + 'border-radius:6px;cursor:pointer;font-size:14px;font-weight:bold;color:#374151;background:' + color + ';'; b.addEventListener('mouseenter', function () { b.style.background = hover; }); b.addEventListener('mouseleave', function () { b.style.background = color; }); b.addEventListener('click', onClick); return b; } function toggleMinimize() { isMinimized = !isMinimized; if (panelBody) panelBody.style.maxHeight = isMinimized ? '0' : '520px'; } function closePanel() { if (panelContainer) { panelContainer.remove(); panelContainer = null; } } function startDrag(e) { if (e.button !== 0 || !panelContainer) return; isDragging = true; const r = panelContainer.getBoundingClientRect(); dragOffsetX = e.clientX - r.left; dragOffsetY = e.clientY - r.top; document.addEventListener('mousemove', onDrag); document.addEventListener('mouseup', stopDrag); e.preventDefault(); } function onDrag(e) { if (!isDragging || !panelContainer) return; panelX = Math.max(0, e.clientX - dragOffsetX); panelY = Math.max(0, e.clientY - dragOffsetY); panelContainer.style.left = panelX + 'px'; panelContainer.style.top = panelY + 'px'; } function stopDrag() { isDragging = false; document.removeEventListener('mousemove', onDrag); document.removeEventListener('mouseup', stopDrag); } function row(label, value) { return '
' + '' + label + '' + '' + value + '
'; } function renderPanel(waitingNo) { createPanel(); if (!panelContent) return; const no = currentFrameNo(); const total = FRAME_IDS.length || (function () { const el = document.querySelector('.frame-counter-clickable'); const m = el ? /(\d+)\s*\/\s*(\d+)/.exec(el.innerText || '') : null; return m ? parseInt(m[2], 10) : 0; })(); let h = ''; // 顶部信息 h += '
'; if (PROJECT_INFO.projectName) h += row('项目', esc(PROJECT_INFO.projectName)); if (PROJECT_INFO.taskNo) h += row('包号', esc(PROJECT_INFO.taskNo)); h += row('当前帧', (no || '-') + ' / ' + (total || '-')); h += '
'; // 本帧状态 if (waitingNo) { h += '
' + '⏳' + '
' + '
第 ' + waitingNo + ' 帧加载中…
' + '正在获取该帧标注数据
'; } else if (lastBoxes) { const fmt = lastBoxes.fmtErrs || []; const dup = lastBoxes.dupErrs || []; const ign = lastBoxes.ignoredList || []; const hasErr = fmt.length > 0 || dup.length > 0; const hasIgn = ign.length > 0; const bg = hasErr ? '#fef2f2' : (hasIgn ? '#fffbeb' : '#ecfdf5'); const bd = hasErr ? '#fca5a5' : (hasIgn ? '#fcd34d' : '#6ee7b7'); const ic = hasErr ? '⛔' : (hasIgn ? '⚠️' : '✅'); h += '
' + '' + ic + '' + '
' + '
本帧 ' + lastBoxes.boxes.length + ' 个框' + (hasIgn ? '(忽略 ' + ign.length + ')' : '') + '
' + '参与统计 ' + lastBoxes.valid + ' 个'; fmt.slice(0, 8).forEach(function (d) { h += '
• [' + esc(d.cls) + ' #' + d.labelId + '] ' + esc(d.msg) + '
'; }); if (fmt.length > 8) { h += '
… 还有 ' + (fmt.length - 8) + ' 条格式问题
'; } dup.forEach(function (d) { h += '
' + esc(d.msg) + '
'; }); // 忽略框:黄色提醒,不阻断 ign.forEach(function (d, i) { if (i >= 8) return; h += '
• [' + esc(d.cls) + ' #' + d.labelId + '] 已标「忽略」,请确认是否应该忽略
'; }); if (ign.length > 8) { h += '
… 还有 ' + (ign.length - 8) + ' 个忽略框
'; } h += '
'; } else { h += '
本帧暂无标注数据
'; } // 整包统计 h += '
'; h += '
'; const st = PACK_STAT; h += cell('总帧', st ? st.frameTotal : (total || '-')); h += cell('有框帧数', st ? st.frameWithBox : '-'); h += cell('总框数', st ? st.boxTotal : '-'); h += '
'; // 整包错误列表(点击跳帧):格式 → 主ID 重复 → 尺寸 const fmtList = (st && st.fmtErrors) ? st.fmtErrors : []; const dupList = (st && st.dupErrors) ? st.dupErrors : []; const sizeList = (st && st.sizeErrors) ? st.sizeErrors : []; const ignList = (st && st.ignoreWarns) ? st.ignoreWarns : []; if (fmtList.length) { h += '
'; h += '
⛔ 主ID / 变装ID 格式不合规(点击跳帧):
'; fmtList.forEach(function (ef) { h += '
'; h += '
' + '第 ' + ef.frameNo + ' 帧' + ef.items.length + ' 处 →
'; ef.items.forEach(function (it) { h += '
• [' + esc(it.cls) + ' #' + it.labelId + '] ' + esc(it.msg) + '
'; }); h += '
'; }); h += '
'; } if (dupList.length) { h += '
'; h += '
⛔ 主ID 重复(点击跳帧):
'; dupList.forEach(function (ef) { h += '
'; h += '
' + '第 ' + ef.frameNo + ' 帧' + ef.items.length + ' 处 →
'; ef.items.forEach(function (it) { h += '
• ' + esc(it.msg) + '
'; }); h += '
'; }); h += '
'; } // 尺寸异常列表(点击跳帧) if (sizeList.length) { h += '
'; h += '
⚠ 尺寸不达标(点击跳帧):
'; sizeList.forEach(function (ef) { h += '
'; h += '
' + '第 ' + ef.frameNo + ' 帧' + ef.items.length + ' 个 →
'; ef.items.forEach(function (it) { h += '
• [' + esc(it.cls) + ' #' + it.labelId + '] ' + esc(it.msg) + '
'; }); h += '
'; }); h += '
'; } // 忽略框黄色提醒(非错误) if (ignList.length) { h += '
'; h += '
⚠ 存在「忽略」框(点击跳帧):
'; ignList.forEach(function (ef) { h += '
'; h += '
' + '第 ' + ef.frameNo + ' 帧' + ef.items.length + ' 个 →
'; ef.items.forEach(function (it) { h += '
• [' + esc(it.cls) + ' #' + it.labelId + '] 已标忽略,请确认
'; }); h += '
'; }); h += '
'; } if (st && !fmtList.length && !dupList.length && !sizeList.length && !ignList.length) { h += '
✓ 未发现异常(主ID 5位 / 变装ID 2位;主ID 无重复;宽≥' + MIN_W + ' 高≥' + MIN_H + ';忽略框已跳过)
'; } // 功能区 h += '
'; h += ''; h += ''; h += '
' + COPY_LABEL + '
'; h += '
🔍 整包检查(框尺寸 + 主ID 重复)
'; h += '
' + COPY_ERR_LABEL + '
'; // 批量改属性(仅选中行人主框时出现) const selMain = currentSelectedMainBox(); if (selMain) { const inputStyle = 'width:100%;box-sizing:border-box;height:26px;border:1px solid #d1d5db;' + 'border-radius:5px;padding:0 6px;font-size:12px;margin-bottom:5px;color:#1f2937;background:#fff;'; h += '
'; h += '
🔁 批量改属性' + (selMain.personId ? '(主ID ' + esc(selMain.personId) + ')' : '(未读到主ID)') + '
'; h += '
按主ID匹配全包;留空=不修改;会自动切到标注模式
'; h += ''; h += ''; h += '
执行批量修改
'; h += '
'; } h += '
'; h += '
'; panelContent.innerHTML = h; const cb = document.getElementById('_blyped_warm'); if (cb) cb.addEventListener('change', function () { WARMUP_ON = cb.checked; try { localStorage.setItem(WARMUP_KEY, WARMUP_ON ? '1' : '0'); } catch (e) { } if (WARMUP_ON && !WARMUP_DONE) warmupAllFrames(); }); const gacb = document.getElementById('_blyped_gridauto'); if (gacb) gacb.addEventListener('change', function () { GRID_AUTO_ON = gacb.checked; try { localStorage.setItem(GRID_AUTO_KEY, GRID_AUTO_ON ? '1' : '0'); } catch (e) { } // 立刻生效:关掉就撤掉下拉和隐藏,打开就补上 syncPersonIdPicker(); compactGrid(); }); const cpb = document.getElementById('_blyped_copy'); if (cpb) cpb.addEventListener('click', function () { copyPackInfo(); }); const sb = document.getElementById('_blyped_stat'); if (sb) sb.addEventListener('click', function () { runPackCheck(); }); const ceb = document.getElementById('_blyped_copyerr'); if (ceb) ceb.addEventListener('click', function () { copyErrorInfo(); }); const np = document.getElementById('_blyped_newpid'); if (np) np.addEventListener('input', function () { BATCH_PID = np.value; }); const na = document.getElementById('_blyped_newaid'); if (na) na.addEventListener('input', function () { BATCH_AID = na.value; }); const bb = document.getElementById('_blyped_batchbtn'); if (bb) bb.addEventListener('click', function () { runBatchAttrChange(); }); panelContent.querySelectorAll('[data-blyped-frame]').forEach(function (el) { el.addEventListener('click', function () { goToFrame(el.getAttribute('data-blyped-frame')); }); }); // 只在帧号变化时回到顶部,避免统计结果被滚走 const key = 'f' + no; if (panelBody && key !== lastPanelFrame) { panelBody.scrollTop = 0; lastPanelFrame = key; } } let lastPanelFrame = null; function cell(label, value) { return '
' + '
' + label + '
' + '
' + esc(value) + '
'; } function setMsg(s) { const el = document.getElementById('_blyped_msg'); if (el) el.innerHTML = s; } /* ==================== 帧缓存与补请求 ==================== */ function requestFrame(no) { const fid = FRAME_IDS[no - 1]; if (!fid || !AUTH_HDRS) { showWaiting(no); return; } fetch(API_MARK + '?frame_id=' + fid, { headers: AUTH_HDRS }) .then(function (r) { return r.json(); }) .then(function (j) { if (j && (j.code === 200 || j.code === 0) && j.data && j.data.shapeList) { FRAME_CACHE[fid] = j.data.shapeList; analyzeShapes(j.data.shapeList, getImageSize()); } else { showWaiting(no); } }) .catch(function () { showWaiting(no); }); } let staticFetching = false; function fetchStatic() { const tid = taskIdFromUrl(); if (!tid || !AUTH_HDRS || staticFetching) return; staticFetching = true; fetch(API_STATIC + '?task_id=' + tid, { headers: AUTH_HDRS }) .then(function (r) { return r.json(); }) .then(function (j) { handleStaticResponse(j); }) .catch(function () { }) .then(function () { staticFetching = false; }); } function handleMarkResponse(url, json) { if (!json || (json.code !== 200 && json.code !== 0)) return; const d = json.data; if (!d || !d.shapeList) return; const fid = frameIdFromUrl(url); if (fid) FRAME_CACHE[fid] = d.shapeList; analyzeShapes(d.shapeList, getImageSize()); } function handleStaticResponse(json) { if (!json || (json.code !== 200 && json.code !== 0)) return; const d = json.data || {}; const list = d.image2dList || []; if (list.length) FRAME_IDS = list.map(function (f) { return f.frameId; }); const pi = d.projectInfo || {}; PROJECT_INFO = { taskNo: pi.taskNo ? String(pi.taskNo) : '', projectName: pi.projectName ? String(pi.projectName) : '' }; const m = buildClassMap(pi.projectClass); if (m) { CMAP = m; lastRenderKey = null; if (lastBoxes) renderPanel(); if (!warmupTried && WARMUP_ON && FRAME_IDS.length) { warmupTried = true; setTimeout(function () { warmupAllFrames(); }, 2500); } } } function routeResponse(url, json) { if (!url) return; if (url.indexOf(API_MARK) !== -1) handleMarkResponse(url, json); else if (url.indexOf(API_STATIC) !== -1) handleStaticResponse(json); } /* ==================== 整包检查(统计 + 框尺寸) ==================== */ function clsLabel(b) { const M = getMap(); return (M && M.idName && M.idName[b.typeId]) || '行人框'; } function sizeProblem(b) { if (b.w === null || b.h === null) return '无有效尺寸数据'; if (b.w < MIN_W || b.h < MIN_H) { return '宽 ' + fmt1(b.w) + 'px(需≥' + MIN_W + ') 高 ' + fmt1(b.h) + 'px(需≥' + MIN_H + ')'; } return null; } // 格式规则:主ID 5 位数字;变装ID 2 位数字(如 01、02) const PID_RE = /^\d{5}$/; const AID_RE = /^\d{2}$/; function statOfBoxes(boxes) { let total = 0, valid = 0; const sizeErrs = [], dupErrs = [], fmtErrs = [], ignoredBoxes = []; const byPid = {}; (boxes || []).forEach(function (b) { total++; if (isIgnored(b)) { // 忽略框:计入总数、不参与硬性校验,但单独收集用于黄色提醒 ignoredBoxes.push({ labelId: b.labelId, cls: clsLabel(b) }); return; } valid++; const cls = clsLabel(b); // ---- 格式校验(只校验该类目确实配了这个属性的框)---- if (b.pidTracked) { if (!b.personId) { fmtErrs.push({ kind: 'fmt', labelId: b.labelId, cls: cls, msg: '主ID 缺失(person_id 为空)' }); } else if (!PID_RE.test(b.personId)) { fmtErrs.push({ kind: 'fmt', labelId: b.labelId, cls: cls, msg: '主ID 格式不合规:「' + b.personId + '」(需 5 位数字)' }); } } if (b.aidTracked) { if (!b.appearId) { fmtErrs.push({ kind: 'fmt', labelId: b.labelId, cls: cls, msg: '变装ID 缺失(appearance_id 为空)' }); } else if (!AID_RE.test(b.appearId)) { fmtErrs.push({ kind: 'fmt', labelId: b.labelId, cls: cls, msg: '变装ID 格式不合规:「' + b.appearId + '」(需 2 位数字,01–99)' }); } } const msg = sizeProblem(b); if (msg) sizeErrs.push({ kind: 'size', labelId: b.labelId, cls: cls, w: b.w, h: b.h, msg: msg }); if (b.personId) { if (!byPid[b.personId]) byPid[b.personId] = []; byPid[b.personId].push(b); } }); // 同一帧内 person_id 不允许重复 Object.keys(byPid).forEach(function (pid) { const arr = byPid[pid]; if (arr.length < 2) return; const ids = arr.map(function (b) { return b.labelId; }); dupErrs.push({ kind: 'dup', personId: pid, cls: '行人主框', labelIds: ids, msg: '主ID 重复:person_id=' + pid + '(' + arr.length + ' 个框:#' + ids.join('、#') + ')' }); }); return { total: total, valid: valid, fmtErrs: fmtErrs, sizeErrs: sizeErrs, dupErrs: dupErrs, ignoredBoxes: ignoredBoxes, errs: fmtErrs.concat(dupErrs, sizeErrs) }; } function frameStat(shapeList) { const boxes = []; (shapeList || []).forEach(function (s) { const b = boxOf(s); if (b && b.isRect) boxes.push(b); }); return statOfBoxes(boxes); } async function getFrameList(fid) { let list = FRAME_CACHE[fid]; if (list) return list; if (!AUTH_HDRS) return []; try { const j = await (await fetch(API_MARK + '?frame_id=' + fid, { headers: AUTH_HDRS })).json(); list = (j && j.data && j.data.shapeList) || []; } catch (e) { list = []; } FRAME_CACHE[fid] = list; return list; } let CHECK_RUNNING = false; async function runPackCheck() { if (CHECK_RUNNING) return; if (!FRAME_IDS.length) { setMsg('⚠ 帧列表未就绪,请刷新页面'); return; } if (!AUTH_HDRS) { setMsg('⚠ 请先在工作台切一次帧'); return; } CHECK_RUNNING = true; setMsg('⏳ 整包检查中…'); let frameWithBox = 0, boxTotal = 0, boxValid = 0; const sizeErrors = [], dupErrors = [], fmtErrors = [], ignoreWarns = []; for (let i = 0; i < FRAME_IDS.length; i++) { const list = await getFrameList(FRAME_IDS[i]); const s = frameStat(list); boxTotal += s.total; boxValid += s.valid; if (s.total > 0) frameWithBox++; if (s.fmtErrs.length) fmtErrors.push({ frameNo: i + 1, items: s.fmtErrs }); if (s.sizeErrs.length) sizeErrors.push({ frameNo: i + 1, items: s.sizeErrs }); if (s.dupErrs.length) dupErrors.push({ frameNo: i + 1, items: s.dupErrs }); if (s.ignoredBoxes.length) ignoreWarns.push({ frameNo: i + 1, items: s.ignoredBoxes }); } const badFrames = {}; fmtErrors.forEach(function (f) { badFrames[f.frameNo] = 1; }); sizeErrors.forEach(function (f) { badFrames[f.frameNo] = 1; }); dupErrors.forEach(function (f) { badFrames[f.frameNo] = 1; }); PACK_STAT = { frameTotal: FRAME_IDS.length, frameWithBox: frameWithBox, boxTotal: boxTotal, boxValid: boxValid, boxIgnored: boxTotal - boxValid, fmtErrors: fmtErrors, sizeErrors: sizeErrors, dupErrors: dupErrors, ignoreWarns: ignoreWarns, badFrameCount: Object.keys(badFrames).length, badBoxCount: fmtErrors.concat(sizeErrors, dupErrors).reduce(function (a, f) { return a + f.items.length; }, 0) }; lastRenderKey = null; renderPanel(); const cnt = function (arr) { return arr.reduce(function (a, f) { return a + f.items.length; }, 0); }; const fmtN = cnt(fmtErrors), dupN = cnt(dupErrors), sizeN = cnt(sizeErrors), ignN = cnt(ignoreWarns); if (fmtN || dupN || sizeN) { const parts = []; if (fmtN) parts.push(fmtN + ' 处ID格式不合规'); if (dupN) parts.push(dupN + ' 处主ID重复'); if (sizeN) parts.push(sizeN + ' 个框尺寸不达标'); if (ignN) parts.push('另有 ' + ignN + ' 个忽略框'); setMsg('⚠ ' + parts.join(',') + '(分布 ' + PACK_STAT.badFrameCount + ' 帧),见上方列表'); } else if (ignN) { setMsg('✓ 无硬性错误;另有 ' + ignN + ' 个忽略框(' + ignoreWarns.length + ' 帧),请确认是否应该忽略'); } else { setMsg('✓ 全部通过(主ID 5位 / 变装ID 2位,主ID无重复,宽≥' + MIN_W + ' 高≥' + MIN_H + ',忽略框已跳过)'); } CHECK_RUNNING = false; } /* ==================== 复制「包号 + 帧数 + 框数」 ==================== */ function copyText(text) { if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text); return new Promise(function (resolve, reject) { try { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;left:-9999px;top:0;'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); resolve(); } catch (e) { reject(e); } }); } const COPY_LABEL = '📋 复制「包号 + 有效帧数 + 框数」'; function setCopyBtn(t) { const b = document.getElementById('_blyped_copy'); if (b) b.innerText = t; } async function copyPackInfo() { if (!FRAME_IDS.length) { setMsg('⚠ 帧列表未就绪,请刷新页面'); return; } if (!AUTH_HDRS) { setMsg('⚠ 请先在工作台切一次帧'); return; } setCopyBtn('⏳ 统计中…'); if (!PACK_STAT) await runPackCheck(); const stat = PACK_STAT || { frameWithBox: 0, boxTotal: 0 }; const no = PROJECT_INFO.taskNo || '未知包号'; // 包号 → 空一列 → 有效帧数(有框的帧)→ 框数 try { await copyText(no + '\t\t' + stat.frameWithBox + '\t' + stat.boxTotal); setCopyBtn('✓ 已复制:' + no + ' · ' + stat.frameWithBox + ' 有效帧 · ' + stat.boxTotal + ' 框'); } catch (e) { setCopyBtn('⚠ 复制失败:' + (e && e.message ? e.message : e)); } setTimeout(function () { setCopyBtn(COPY_LABEL); }, 2500); } /* ==================== 复制错误信息(TSV,可直接粘进 Excel) ==================== */ const COPY_ERR_LABEL = '📋 复制错误信息(可粘 Excel)'; function setErrBtn(t) { const b = document.getElementById('_blyped_copyerr'); if (b) b.innerText = t; } // 按帧号归并四类问题 function collectIssues() { const map = {}; const add = function (frameNo, kind, it) { (map[frameNo] = map[frameNo] || []).push({ kind: kind, it: it }); }; const st = PACK_STAT || {}; (st.fmtErrors || []).forEach(function (ef) { ef.items.forEach(function (it) { let kind = '格式'; if (/^主ID/.test(it.msg)) kind = '主ID格式'; else if (/^变装ID/.test(it.msg)) kind = '变装ID格式'; add(ef.frameNo, kind, it); }); }); (st.dupErrors || []).forEach(function (ef) { ef.items.forEach(function (it) { add(ef.frameNo, '主ID重复', it); }); }); (st.sizeErrors || []).forEach(function (ef) { ef.items.forEach(function (it) { add(ef.frameNo, '尺寸', it); }); }); (st.ignoreWarns || []).forEach(function (ef) { ef.items.forEach(function (it) { add(ef.frameNo, '忽略', it); }); }); return map; } async function copyErrorInfo() { if (!FRAME_IDS.length) { setMsg('⚠ 帧列表未就绪,请刷新页面'); return; } if (!AUTH_HDRS) { setMsg('⚠ 请先在工作台切一次帧'); return; } setErrBtn('⏳ 检查中…'); if (!PACK_STAT) await runPackCheck(); const no = PROJECT_INFO.taskNo || '未知包号'; const map = collectIssues(); const frameNos = Object.keys(map).map(Number).sort(function (a, b) { return a - b; }); const lines = ['包号\t帧号\t框ID\t类目\t问题类型\t问题描述']; let n = 0; frameNos.forEach(function (f) { map[f].forEach(function (e) { const it = e.it; const boxIds = it.labelIds ? it.labelIds.join('、') : (it.labelId === undefined || it.labelId === null ? '' : String(it.labelId)); let desc = it.msg || ''; if (e.kind === '忽略' && !desc) desc = '已标忽略,请确认'; desc = desc.replace(/[\t\r\n]+/g, ' '); lines.push([no, f, boxIds, it.cls || '', e.kind, desc].join('\t')); n++; }); }); if (!n) { setErrBtn('✓ 无错误可复制'); setMsg('当前包没有格式 / 重复 / 尺寸错误,也没有忽略框'); setTimeout(function () { setErrBtn(COPY_ERR_LABEL); }, 2500); return; } try { await copyText(lines.join('\n')); setErrBtn('✓ 已复制 ' + n + ' 条(' + frameNos.length + ' 帧)'); setMsg('已复制错误信息:' + n + ' 条,合计 ' + frameNos.length + ' 帧'); } catch (e) { setErrBtn('⚠ 复制失败:' + (e && e.message ? e.message : e)); } setTimeout(function () { setErrBtn(COPY_ERR_LABEL); }, 2500); } /* ==================== 体验优化:去黑屏 ==================== */ // 平台切帧会弹全屏遮罩(.block-mask) + 转圈(.pc-loading),实测约 400ms function installMaskCss() { if (document.getElementById('_blyped_mask_style')) return; const st = document.createElement('style'); st.id = '_blyped_mask_style'; st.textContent = '.block-mask{background-color:transparent !important;}' + '.pc-loading{display:none !important;}' + '._blyped_row:hover{background:#eef2ff !important;}' + '._blyped_row:active{background:#e0e7ff !important;}'; (document.head || document.documentElement).appendChild(st); } /* ==================== 进题包全量预热 ==================== */ // 平台切帧流程 loadAnnotatesDate() 第一步就 clearResource() 清空画布(灰屏来源), // 随后若 dataManager.getFrameObject(frameId) 命中则直接 return(秒开)。 // 所以这里进题包后主动把每一帧过一遍,把 dataManager 填满 —— 之后切帧就顺滑了。 function goToFrame(n) { const items = document.querySelectorAll('.frame-navigation .page-item'); for (let i = 0; i < items.length; i++) { if ((items[i].innerText || '').trim() === String(n)) { items[i].click(); return true; } } return false; } function frameDataReady(fid) { try { const dm = window.editor && window.editor.dataManager; if (!dm || typeof dm.getFrameObject !== 'function') return false; return !!dm.getFrameObject(fid); } catch (e) { return false; } } function waitFrameReady(fid, timeout) { return new Promise(function (resolve) { const t0 = Date.now(); const timer = setInterval(function () { if (frameDataReady(fid)) { clearInterval(timer); resolve(true); return; } if (Date.now() - t0 > (timeout || 4000)) { clearInterval(timer); resolve(false); } }, 80); }); } function warmupOverlay(show, cur, total) { let el = document.getElementById('_blyped_warm'); if (!show) { if (el) el.remove(); return; } if (!el) { el = document.createElement('div'); el.id = '_blyped_warm'; el.style.cssText = 'position:fixed;z-index:999997;left:50%;top:50%;transform:translate(-50%,-50%);' + 'background:rgba(17,24,39,0.92);color:#fff;padding:14px 22px;border-radius:9px;text-align:center;' + 'font-family:"Microsoft YaHei","PingFang SC",Arial,sans-serif;font-size:13px;box-shadow:0 8px 28px rgba(0,0,0,.35);'; document.body.appendChild(el); } el.innerHTML = '
📦 正在预加载全部帧…
' + '
' + (cur || 0) + ' / ' + (total || 0) + ' 完成后切帧不再等待
'; } async function warmupAllFrames() { if (WARMUP_RUNNING || WARMUP_DONE) return; if (!WARMUP_ON || !FRAME_IDS.length || !AUTH_HDRS) return; WARMUP_RUNNING = true; const startNo = currentFrameNo() || 1; const total = FRAME_IDS.length; warmupOverlay(true, 0, total); let done = 0; for (let n = 1; n <= total; n++) { const fid = FRAME_IDS[n - 1]; if (!frameDataReady(fid)) { goToFrame(n); await waitFrameReady(fid, 4000); } const cached = FRAME_CACHE[fid]; if (!cached && AUTH_HDRS) { try { const j = await (await fetch(API_MARK + '?frame_id=' + fid, { headers: AUTH_HDRS })).json(); if (j && j.data && j.data.shapeList) FRAME_CACHE[fid] = j.data.shapeList; } catch (e) { } } done++; warmupOverlay(true, done, total); } goToFrame(startNo); await waitFrameReady(FRAME_IDS[startNo - 1], 3000); warmupOverlay(false); WARMUP_DONE = true; WARMUP_RUNNING = false; lastRenderKey = null; renderPanel(); // 全部帧已在缓存里,顺手把整包检查(统计 + 尺寸)跑出来 runPackCheck(); } /* ==================== 鉴权头捕获 ==================== */ try { const origSetHeader = XMLHttpRequest.prototype.setRequestHeader; XMLHttpRequest.prototype.setRequestHeader = function (k, v) { if (!AUTH_HDRS && /^blade-auth$/i.test(k)) { AUTH_HDRS = { 'Blade-Auth': v, 'Tenant-Id': localStorage.getItem('tenantId') || '' }; } return origSetHeader.apply(this, arguments); }; } catch (e) { } /* ==================== XHR / fetch 拦截 ==================== */ try { const origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function (method, url) { this._blypedUrl = url; return origOpen.apply(this, arguments); }; const origSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function () { const u = this._blypedUrl || ''; if (u.indexOf(API_MARK) !== -1 || u.indexOf(API_STATIC) !== -1) { this.addEventListener('load', function () { let j = null; try { j = JSON.parse(this.responseText); } catch (e) { return; } routeResponse(u, j); }); } return origSend.apply(this, arguments); }; } catch (e) { } try { const origFetch = window.fetch; if (origFetch) { window.fetch = function (input, init) { const url = (typeof input === 'string') ? input : ((input instanceof Request) ? input.url : ''); const hit = (url.indexOf(API_MARK) !== -1 || url.indexOf(API_STATIC) !== -1); if (!hit) return origFetch.apply(this, arguments); return origFetch.apply(this, arguments).then(function (response) { try { response.clone().json().then(function (data) { routeResponse(url, data); }).catch(function () { }); } catch (e) { } return response; }); }; } } catch (e) { } /* ==================== 帧切换监听 ==================== */ function handleFrameSwitch(no) { lastFrameNo = no; const fid = FRAME_IDS[no - 1]; const cached = (fid && FRAME_CACHE[fid]) ? FRAME_CACHE[fid] : null; if (cached) { analyzeShapes(cached, getImageSize()); } else { showWaiting(no); requestFrame(no); } } // 用 MutationObserver 即时感知帧切换,定时器只做兜底 function setupFrameWatcher() { const nav = document.querySelector('.frame-navigation'); if (!nav || nav.__blypedMo) return; nav.__blypedMo = new MutationObserver(function () { const n = currentFrameNo(); if (n !== null && n !== lastFrameNo) handleFrameSwitch(n); }); nav.__blypedMo.observe(nav, { childList: true, subtree: true, attributes: true, characterData: true }); } setInterval(function () { if (!staticTried && AUTH_HDRS && FRAME_IDS.length === 0) { staticTried = true; fetchStatic(); } setupFrameWatcher(); // 网格模式:只留命中帧,紧密排列 if (document.querySelector('.grid-toolbar')) { ensureGridObserver(); ensureToolbarObserver(); syncPersonIdPicker(); compactGrid(); } fixBoxLabelColor(); // 选中框变化 → 重绘面板(批量改属性区随选中出现/消失) const selNow = currentSelectedMainBox(); const selKey = selNow ? (selNow.classId + '|' + selNow.personId + '|' + selNow.labelId) : ''; if (selKey !== lastSelKey) { lastSelKey = selKey; renderPanel(); } const no = currentFrameNo(); if (no !== null && no !== lastFrameNo) { handleFrameSwitch(no); return; } // 兜底:数据未变时 analyzeShapes 内部会因指纹相同直接 return,不会重建面板 if (lastBoxes) analyzeShapesFromCache(); }, 900); function analyzeShapesFromCache() { const no = currentFrameNo(); const fid = no ? FRAME_IDS[no - 1] : null; const list = fid ? FRAME_CACHE[fid] : null; if (list) analyzeShapes(list, getImageSize()); } /* ==================== 网格模式自动筛选 ==================== */ // 平台网格筛选是原生 HTML 控件: // select[aria-label=筛选标签] / [筛选属性] / input[筛选属性值] / input[网格大小] // 直接改 value 再派发 input/change 即可驱动筛选(已实测)。 let GRID_PENDING = null; let GRID_FORCED = false; // 本次进网格是为了绕过平台「必须先选中」的限制 function sleepMs(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } function fireNative(el, evtName, val) { if (!el) return false; if (val !== undefined) el.value = val; el.dispatchEvent(new Event(evtName, { bubbles: true })); return true; } // Konva 选中节点的几何 → 与 shapeList 对齐用 function konvaGeometry(n) { const a = (n && n.attrs) || {}; const x = num(a.x), y = num(a.y), w = num(a.width), h = num(a.height); if (x === null || y === null || w === null || h === null) return null; return { classId: n.userData ? n.userData.classId : null, lx: x, ly: y, rx: x + w, ry: y + h }; } function matchBoxByGeometry(boxes, kb) { for (let i = 0; i < boxes.length; i++) { const b = boxes[i]; if (!b || b.typeId !== kb.classId || b.lx === null || b.ly === null) continue; if (Math.abs(b.lx - kb.lx) < 1 && Math.abs(b.ly - kb.ly) < 1 && Math.abs(b.rx - kb.rx) < 1 && Math.abs(b.ry - kb.ry) < 1) return b; } return null; } // 读取当前选中的「行人主框」及其 person_id async function getSelectedMainTarget() { const ed = window.editor; const M = getMap(); if (!ed || !ed.selection || !ed.selection.length || !M) return null; // 注意:以下循环必须同步跑完,模式切换后 selection 会被清空 const nodes = []; ed.selection.forEach(function (s) { let n = s; if (typeof s === 'string') { try { n = JSON.parse(s); } catch (e) { return; } } if (!n || !n.userData || !n.userData.classId) return; if (!M.personAttr || !M.personAttr[n.userData.classId]) return; // 该类目没有 person_id if (M.mainId && n.userData.classId !== M.mainId) return; // 只认行人主框 nodes.push(n); }); if (!nodes.length) return null; const no = currentFrameNo(); const fid = no ? FRAME_IDS[no - 1] : null; // 先用本帧已解析的框兜底 let boxes = (lastBoxes && lastBoxes.boxes) ? lastBoxes.boxes : []; // 再拉一次最新数据(属性可能刚改过,缓存不可靠) if (fid && AUTH_HDRS) { try { const j = await (await fetch(API_MARK + '?frame_id=' + fid, { headers: AUTH_HDRS })).json(); const list = (j && j.data && j.data.shapeList) || null; if (list) { const fresh = []; list.forEach(function (s) { const b = boxOf(s); if (b && b.isRect) fresh.push(b); }); if (fresh.length) boxes = fresh; } } catch (e) { } } if (!boxes.length) return null; for (let i = 0; i < nodes.length; i++) { const kb = konvaGeometry(nodes[i]); if (!kb) continue; const b = matchBoxByGeometry(boxes, kb); if (b && b.personId) return { personId: b.personId, classId: kb.classId }; } return null; } async function applyGridFilter(target, attempt) { attempt = attempt || 0; const tb = document.querySelector('.grid-toolbar'); if (!tb) return false; // 1) 标签(行人主框) const tagSel = tb.querySelector('select[aria-label="筛选标签"]'); if (tagSel && target.classId && tagSel.value !== target.classId) { fireNative(tagSel, 'change', target.classId); await sleepMs(200); } // 2) 属性 = person_id(选中后「值」输入框才会渲染出来) const M = getMap(); const pidAttr = M && M.personAttr ? M.personAttr[target.classId] : null; const attrSel = document.querySelector('.grid-toolbar select[aria-label="筛选属性"]'); if (pidAttr && attrSel && attrSel.value !== pidAttr) { fireNative(attrSel, 'change', pidAttr); await sleepMs(300); } // 3) 值 = person_id const valInp = document.querySelector('.grid-toolbar input[aria-label="筛选属性值"]'); if (valInp && valInp.value !== target.personId) { valInp.value = target.personId; valInp.dispatchEvent(new Event('input', { bubbles: true })); valInp.dispatchEvent(new Event('change', { bubbles: true })); await sleepMs(300); } // 4) 网格大小 = 240px const range = document.querySelector('.grid-toolbar input[aria-label="网格大小"]'); if (range && range.value !== '240') { fireNative(range, 'input', '240'); range.dispatchEvent(new Event('change', { bubbles: true })); } // 校验是否真的落上了;没落上重试 await sleepMs(400); const v2 = document.querySelector('.grid-toolbar input[aria-label="筛选属性值"]'); if (attempt < 2 && (!v2 || v2.value !== target.personId)) { return applyGridFilter(target, attempt + 1); } scheduleCompact(); // 筛完立即紧凑排列 return true; } function waitToolbarThenApply(target) { let tries = 0; const timer = setInterval(function () { const tb = document.querySelector('.grid-toolbar'); if (tb && tb.querySelector('select[aria-label="筛选属性"]')) { clearInterval(timer); applyGridFilter(target); } else if (++tries > 50) { clearInterval(timer); } }, 100); } function installGridAutoFilter() { document.addEventListener('click', function (ev) { if (!GRID_AUTO_ON) return; const btn = ev.target && ev.target.closest ? ev.target.closest('.mode-switch') : null; if (!btn) return; if ((btn.innerText || '').trim() !== '网格模式') return; if (document.querySelector('.grid-toolbar')) return; // 已经在网格模式 // 强制放行后的第二次点击:不再自动筛选,改为清掉平台按锚点预填的条件 if (GRID_FORCED) { GRID_FORCED = false; resetGridAfterForced(); return; } const ed = window.editor; const hasSel = !!(ed && ed.selection && ed.selection.length); // 平台守卫:必须已有 1 个选中对象,否则「请先选中一个点或框」 // 没选中就自动选本帧第一个框来放行,进入后再把条件清掉 if (!hasSel) { ev.stopImmediatePropagation(); ev.preventDefault(); if (!selectFirstShape()) return; // 选不到就交给平台弹原提示 GRID_FORCED = true; setTimeout(function () { btn.click(); }, 120); return; } GRID_PENDING = 'pending'; getSelectedMainTarget().then(function (t) { GRID_PENDING = t; if (!t) return; // 没选中行人主框 → 不自动筛 waitToolbarThenApply(t); }); }, true); } // 在画布上选中本帧第一个框(合成鼠标事件,与真实点击等价) function selectFirstShape() { try { if (typeof Konva === 'undefined' || !Konva.stages || !Konva.stages.length) return false; const st = Konva.stages[0]; const cands = st.find('Shape').filter(function (n) { return n.userData && n.userData.classId; }); if (!cands.length) return false; let node = cands[0]; for (let i = 0; i < cands.length; i++) { if (cands[i].className === 'rect') { node = cands[i]; break; } } const b = node.getClientRect(); const c = st.container().getBoundingClientRect(); if (!b || !b.width || !b.height) return false; const x = c.left + b.x + b.width / 2; const y = c.top + b.y + b.height / 2; const el = document.elementFromPoint(x, y); if (!el) return false; ['mousedown', 'mouseup', 'click'].forEach(function (t) { el.dispatchEvent(new MouseEvent(t, { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y, button: 0 })); }); return true; } catch (e) { return false; } } // 清掉平台按「锚点框」预填的筛选条件,并恢复无选中状态 function resetGridAfterForced(tries) { tries = tries || 0; const tb = document.querySelector('.grid-toolbar'); if (!tb) { if (tries < 40) setTimeout(function () { resetGridAfterForced(tries + 1); }, 100); return; } const clearBtn = tb.querySelector('.clear-filter'); if (clearBtn) clearBtn.click(); try { if (window.editor && window.editor.selection) window.editor.selection.length = 0; } catch (e) { } // 平台可能在渲染完成后再回填一次,700ms 后补一刀 setTimeout(function () { const b2 = document.querySelector('.grid-toolbar .clear-filter'); if (b2) b2.click(); try { if (window.editor && window.editor.selection) window.editor.selection.length = 0; } catch (e) { } scheduleCompact(); }, 700); } /* ==================== 网格筛选后只留命中帧(紧密排列) ==================== */ // 平台筛选后仍会把所有帧渲染成格子(未命中的是空壳),这里把空壳 display:none, // CSS grid 的 auto-fill 会自动重排,剩余格子自然紧贴。 let compactTimer = null; function gridFilterActive() { const tb = document.querySelector('.grid-toolbar'); if (!tb) return false; const attr = tb.querySelector('select[aria-label="筛选属性"]'); const val = tb.querySelector('input[aria-label="筛选属性值"]'); return !!(attr && attr.value && val && String(val.value).trim()); } function gridCellHasBox(cell) { // 有框的格子:「定位」按钮可用,且标题里带「· N 个框 ·」 const btns = cell.querySelectorAll('.viewport-actions button'); const last = btns.length ? btns[btns.length - 1] : null; if (last && !last.disabled) return true; const head = cell.querySelector('.cell-header'); return !!(head && /个框/.test(head.innerText || '')); } function compactGrid() { if (!document.querySelector('.grid-toolbar')) return; const cells = document.querySelectorAll('.image-grid-view .image-grid-cell'); // 开关关闭:所有格子恢复原样,不做任何隐藏 if (!GRID_AUTO_ON) { for (let i = 0; i < cells.length; i++) { if (cells[i].style.display === 'none') cells[i].style.display = ''; } return; } const active = gridFilterActive(); for (let i = 0; i < cells.length; i++) { const c = cells[i]; const want = active ? (gridCellHasBox(c) ? '' : 'none') : ''; if (c.style.display !== want) c.style.display = want; } } function scheduleCompact() { if (compactTimer) return; compactTimer = setTimeout(function () { compactTimer = null; compactGrid(); }, 100); } function ensureGridObserver() { const holder = document.querySelector('.image-grid-view .grid-cells'); if (!holder || holder.__blypedCompactMo) return; holder.__blypedCompactMo = new MutationObserver(scheduleCompact); holder.__blypedCompactMo.observe(holder, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['disabled', 'class'] }); } // 工具栏本身变化(切属性后输入框重建)→ 立即同步下拉 function ensureToolbarObserver() { const tb = document.querySelector('.grid-toolbar'); if (!tb || tb.__blypedToolbarMo) return; tb.__blypedToolbarMo = new MutationObserver(function () { syncPersonIdPicker(); }); tb.__blypedToolbarMo.observe(tb, { childList: true, subtree: true }); } /* ==================== 网格筛选:person_id 改成下拉框 ==================== */ // 属性选 person_id 时,把「值」输入框换成下拉,只列出当前包出现过的 person_id。 // 原 input 保留(隐藏),选中后写回 value 并派发事件,兼容平台的绑定。 let PID_LIST_CACHE = null; let PID_LIST_KEY = ''; let PID_LIST_LOADING = false; function pidAttrId() { const M = getMap(); return (M && M.mainId && M.personAttr) ? M.personAttr[M.mainId] : null; } async function getPersonIdList() { const key = (PROJECT_INFO.taskNo || '') + '|' + FRAME_IDS.length + '|' + (FRAME_IDS[0] || ''); if (PID_LIST_CACHE && PID_LIST_KEY === key) return PID_LIST_CACHE; if (PID_LIST_LOADING) return PID_LIST_CACHE; PID_LIST_LOADING = true; const set = {}; for (let i = 0; i < FRAME_IDS.length; i++) { const list = await getFrameList(FRAME_IDS[i]); (list || []).forEach(function (s) { const b = boxOf(s); if (b && b.isRect && b.personId) set[b.personId] = 1; }); if (i % 10 === 0) await sleepMs(0); // 别把主线程堵死 } PID_LIST_CACHE = Object.keys(set).sort(function (a, b) { const na = parseInt(a, 10), nb = parseInt(b, 10); if (!isNaN(na) && !isNaN(nb) && na !== nb) return na - nb; return a < b ? -1 : (a > b ? 1 : 0); }); PID_LIST_KEY = key; PID_LIST_LOADING = false; return PID_LIST_CACHE; } async function syncPersonIdPicker() { const tb = document.querySelector('.grid-toolbar'); if (!tb) return; const attrSel = tb.querySelector('select[aria-label="筛选属性"]'); const input = tb.querySelector('input[aria-label="筛选属性值"]'); if (!attrSel || !input) return; const pidAttr = pidAttrId(); const isPid = !!(pidAttr && attrSel.value === pidAttr); let sel = tb.querySelector('select[data-blyped-pid]'); // 开关关闭 / 不是 person_id:还原原生输入框 if (!GRID_AUTO_ON || !isPid) { if (sel) sel.remove(); if (input.style.display === 'none') input.style.display = ''; return; } // 平台重绘换掉了 input → 旧下拉作废 if (sel && sel.__forInput !== input) { sel.remove(); sel = null; } if (!sel) { sel = document.createElement('select'); sel.setAttribute('data-blyped-pid', '1'); sel.setAttribute('aria-label', 'person_id 选择'); sel.style.cssText = 'height:26px;border:1px solid #d9d9d9;border-radius:4px;padding:0 6px;' + 'font-size:12px;color:#1f2937;background:#fff;max-width:170px;margin-left:6px;'; sel.innerHTML = ''; sel.__forInput = input; input.style.display = 'none'; // 插到