feat: initial project setup

This commit is contained in:
2026-10-08 09:46:47 +08:00
commit 5833a303bc
65 changed files with 11628 additions and 0 deletions
+1127
View File
File diff suppressed because it is too large Load Diff
+267
View File
@@ -0,0 +1,267 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BiRefNet WebUI · 智能抠图</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%234f8cff'/%3E%3Cpath d='M9 21c4-1 5-10 14-10-4 1-5 10-14 10z' fill='white'/%3E%3C/svg%3E">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="logo" aria-hidden="true">
<svg viewBox="0 0 32 32" width="26" height="26"><rect width="32" height="32" rx="8" fill="var(--accent)"/><path d="M9 21c4-1 5-10 14-10-4 1-5 10-14 10z" fill="#fff"/></svg>
</span>
<h1>BiRefNet <em>WebUI</em></h1>
</div>
<dl class="meta" id="meta">
<div><dt>设备</dt><dd id="meta-device">检测中…</dd></div>
<div><dt>模型</dt><dd id="meta-models">—</dd></div>
<div><dt>模型代码</dt><dd id="meta-node" class="path" title="">—</dd></div>
</dl>
<div class="topbar-actions">
<button class="btn ghost sm" id="btn-reload-models" type="button">重新扫描模型</button>
<button class="btn ghost sm" id="btn-unload" type="button">卸载显存</button>
</div>
</header>
<main class="layout">
<!-- ============================= 参数面板 ============================= -->
<aside class="sidebar">
<section class="block">
<header class="block-head"><h2>1 · 图片</h2><span class="hint" id="file-count">未选择</span></header>
<div class="dropzone compact" id="dropzone" tabindex="0" role="button" aria-label="选择或拖入图片">
<p>拖入图片 / 点击选择 / <kbd>Ctrl</kbd>+<kbd>V</kbd> 粘贴</p>
<p class="sub">支持 PNG · JPG · WebP · BMP · TIFF · 一次一张,新图会替换上一张</p>
<input type="file" id="file-input" accept="image/*" hidden>
</div>
<ul class="thumbs" id="thumbs"></ul>
<p class="pending-note" id="pending-note"></p>
</section>
<section class="block">
<header class="block-head"><h2>2 · 模型</h2><span class="hint" id="model-hint"></span></header>
<label class="field">
<span>权重文件</span>
<select id="opt-model"></select>
</label>
<div class="field-row">
<label class="field">
<span>设备</span>
<select id="opt-device">
<option value="auto">自动 (GPU)</option>
<option value="cpu">CPU</option>
</select>
</label>
<label class="field">
<span>精度</span>
<select id="opt-dtype">
<option value="auto">自动 (fp16 加速)</option>
<option value="float32">float32 · 最稳</option>
<option value="float16">float16 · 最省显存</option>
<option value="bfloat16">bfloat16</option>
</select>
</label>
</div>
<label class="field">
<span>架构</span>
<select id="opt-arch">
<option value="auto">自动识别</option>
<option value="v1">v1(新版,safetensors)</option>
<option value="old">old(旧版 .pth)</option>
</select>
</label>
</section>
<section class="block">
<header class="block-head"><h2>3 · 参数</h2><span class="hint">按需调整</span></header>
<label class="field">
<span>预处理尺寸</span>
<select id="opt-resolution-mode">
<option value="square">固定 1024×1024(推荐)</option>
<option value="longest">长边自适应(保宽高比)</option>
<option value="custom">自定义宽高</option>
</select>
</label>
<div class="field-row" id="row-longest">
<label class="field">
<span>长边像素</span>
<input type="number" id="opt-longest-side" value="1024" min="32" max="4096" step="32">
</label>
</div>
<div class="field-row hidden" id="row-wh">
<label class="field">
<span>宽</span>
<input type="number" id="opt-width" value="1024" min="32" max="4096" step="32">
</label>
<label class="field">
<span>高</span>
<input type="number" id="opt-height" value="1024" min="32" max="4096" step="32">
</label>
</div>
<div class="field-row">
<label class="field">
<span>插值方式</span>
<select id="opt-upscale">
<option value="bilinear">bilinear</option>
<option value="bicubic">bicubic</option>
<option value="nearest">nearest</option>
<option value="nearest-exact">nearest-exact</option>
</select>
</label>
<label class="field">
<span>遮罩阈值</span>
<input type="number" id="opt-threshold" value="0" min="0" max="1" step="0.004">
</label>
</div>
<label class="field">
<span>背景</span>
<select id="opt-background">
<option value="transparent">透明(PNG Alpha)</option>
<option value="color">纯色背景</option>
</select>
</label>
<div class="field-row hidden" id="row-bgcolor">
<label class="field">
<span>背景色</span>
<input type="color" id="opt-bgcolor" value="#ffffff">
</label>
<div class="swatches" id="swatches">
<button type="button" data-color="#ffffff" style="--c:#ffffff" title="白"></button>
<button type="button" data-color="#000000" style="--c:#000000" title="黑"></button>
<button type="button" data-color="#00ff00" style="--c:#00ff00" title="绿幕"></button>
<button type="button" data-color="#4f8cff" style="--c:#4f8cff" title="蓝"></button>
</div>
</div>
<label class="check">
<input type="checkbox" id="opt-refine" checked>
<span>前景精修(去除边缘残留背景色)</span>
</label>
<div class="field-row" id="row-blur">
<label class="field">
<span>大核 r1</span>
<input type="number" id="opt-blur1" value="90" min="1" max="255">
</label>
<label class="field">
<span>小核 r2</span>
<input type="number" id="opt-blur2" value="6" min="1" max="255">
</label>
</div>
<label class="check">
<input type="checkbox" id="opt-mask">
<span>同时输出遮罩(灰度 PNG)</span>
</label>
<label class="field">
<span>最终尺寸 · 最长边(0 = 保持原图尺寸)</span>
<input type="number" id="opt-final-side" value="0" min="0" max="32768" step="16">
</label>
<p class="field-tip">非 0 时按原图比例等比缩放,使结果最长边等于该值。例:2000×3000 填 1440 → 960×1440</p>
</section>
<section class="block actions">
<button class="btn primary" id="btn-run" type="button" disabled>开始抠图</button>
<div class="progress" id="progress" hidden>
<div class="bar"><i id="progress-bar"></i></div>
<div class="progress-meta">
<span id="progress-stage">等待中</span>
<button class="btn link" id="btn-cancel" type="button">取消</button>
</div>
</div>
<p class="error-text" id="error-text" hidden></p>
</section>
<section class="block">
<header class="block-head"><h2>4 · 批量处理</h2><span class="hint">按目录批量抠图</span></header>
<label class="field">
<span>图片目录(模板路径)</span>
<input type="text" id="batch-input-dir" placeholder="例:F:\photos\待抠图" spellcheck="false" autocomplete="off">
</label>
<label class="field">
<span>输出目录</span>
<input type="text" id="batch-output-dir" placeholder="默认:项目 outputs 目录" spellcheck="false" autocomplete="off">
</label>
<label class="check">
<input type="checkbox" id="batch-recursive">
<span>包含子目录</span>
</label>
<button class="btn" id="btn-batch" type="button">开始批量抠图</button>
<div class="progress" id="batch-progress" hidden>
<div class="bar"><i id="batch-progress-bar"></i></div>
<div class="progress-meta">
<span id="batch-progress-stage">准备中…</span>
<button class="btn link" id="btn-batch-cancel" type="button">取消</button>
</div>
</div>
<p class="error-text" id="batch-error" hidden></p>
<p class="batch-note">
两个目录都必须<strong>已存在</strong>(本工具不会自动创建,路径不对会直接报错)。结果写入输出目录,命名
<code>RMBG_原名_时间戳.后缀</code>,原名超 20 字符截断;抠图参数沿用左侧当前设置。
</p>
</section>
</aside>
<!-- ============================= 结果区 ============================= -->
<section class="stage">
<header class="stage-head">
<h2>结果 <span class="count" id="result-count">0</span></h2>
<div class="stage-tools">
<div class="segmented" id="view-switch">
<button type="button" data-view="cutout" class="active">抠图</button>
<button type="button" data-view="mask">遮罩</button>
<button type="button" data-view="original">原图</button>
</div>
<button class="btn ghost sm" id="btn-zip" type="button" disabled>打包下载 ZIP</button>
<button class="btn ghost sm" id="btn-clear" type="button" title="清空整个结果列表" disabled>清空</button>
</div>
</header>
<p class="stage-tip">结果会一直保留在列表里(传新图、改参数都不会清空)· 点文件名或「重新处理」会套用它上次使用的参数 · 点卡片选中 · 点 × 移除单条</p>
<section class="batch-report" id="batch-report" hidden>
<header class="batch-report-head">
<h3>批量任务 <span class="badge" id="batch-badge">排队中</span></h3>
<span class="batch-report-path" id="batch-report-path" title=""></span>
<button class="btn ghost sm" id="btn-batch-hide" type="button">收起</button>
</header>
<p class="batch-report-sum" id="batch-report-sum"></p>
<ul class="batch-rows" id="batch-rows"></ul>
</section>
<div class="empty-state" id="empty">
<div class="empty-art" aria-hidden="true">
<svg viewBox="0 0 240 140" width="240" height="140">
<rect x="1" y="1" width="238" height="138" rx="14" fill="none" stroke="var(--border)" stroke-dasharray="6 6"/>
<circle cx="70" cy="62" r="22" fill="none" stroke="var(--accent)" stroke-width="2"/>
<path d="M104 92c14-4 18-40 52-40-14 4-18 40-52 40z" fill="var(--accent)" opacity=".85"/>
<path d="M46 108h148" stroke="var(--border)" stroke-width="2" stroke-linecap="round"/>
</svg>
</div>
<h3>还没有结果</h3>
<p>左侧拖入图片 → 选择模型 → 点击「开始抠图」。处理完成后可拖拽分割线对比原图与抠图效果,记录会累积在右侧供随时重新处理。</p>
</div>
<div class="grid" id="results"></div>
</section>
</main>
<script src="/static/zip.js"></script>
<script src="/static/app.js"></script>
</body>
</html>
+401
View File
@@ -0,0 +1,401 @@
/* =========================================================================
BiRefNet WebUI · 深色主题
设计约束:字号层级 4 档 · 字体 2 种(系统 UI + 等宽)· 色彩角色 4 个
(accent / ok / warn / danger)· 单焦点(开始抠图)
========================================================================= */
:root {
--bg: #0d0f13;
--surface: #141821;
--surface-2: #1a1f2a;
--surface-3: #202634;
--border: #252b38;
--border-soft: #1e2430;
--text: #e9edf5;
--text-dim: #95a0b3;
--text-faint: #6b7688;
--accent: #4f8cff;
--accent-hover: #6ba0ff;
--accent-soft: rgba(79, 140, 255, 0.14);
--ok: #35c98a;
--warn: #f0b429;
--danger: #f2555a;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", system-ui, sans-serif;
--mono: ui-monospace, SFMono-Regular, Consolas, "Courier New", monospace;
--radius: 12px;
--radius-sm: 8px;
--shadow: 0 8px 28px rgba(0, 0, 0, 0.35);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: var(--font);
font-size: 14px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
body { display: flex; flex-direction: column; overflow: hidden; }
h1, h2, h3 { margin: 0; font-weight: 600; }
button, input, select { font: inherit; color: inherit; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-thumb { background: #2b3242; border-radius: 8px; border: 2px solid var(--bg); }
::-webkit-scrollbar-track { background: transparent; }
/* ------------------------------- 顶栏 ------------------------------- */
.topbar {
display: flex;
align-items: center;
gap: 24px;
padding: 14px 22px;
background: var(--surface);
border-bottom: 1px solid var(--border);
flex: 0 0 auto;
}
.brand { display: flex; align-items: center; gap: 12px; }
.brand .logo { display: grid; place-items: center; }
.brand h1 { font-size: 28px; letter-spacing: -0.5px; line-height: 1.1; }
.brand h1 em { font-style: normal; font-weight: 300; color: var(--text-dim); }
.meta { display: flex; gap: 26px; margin: 0; margin-left: auto; }
.meta > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.meta dt { font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--text-faint); }
.meta dd { margin: 0; font-size: 13px; color: var(--text); font-family: var(--mono); }
.meta dd.path { max-width: 320px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-dim); }
.topbar-actions { display: flex; gap: 8px; }
/* ------------------------------- 主体 ------------------------------- */
.layout { flex: 1 1 auto; display: grid; grid-template-columns: 348px 1fr; min-height: 0; }
.sidebar {
background: var(--surface);
border-right: 1px solid var(--border);
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 14px;
}
.block {
background: var(--surface-2);
border: 1px solid var(--border-soft);
border-radius: var(--radius);
padding: 14px;
display: flex;
flex-direction: column;
gap: 10px;
}
.block-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
.block-head h2 { font-size: 13px; letter-spacing: 0.02em; color: var(--text); }
.hint { font-size: 11px; color: var(--text-faint); font-family: var(--mono); }
/* 表单 */
.field { display: flex; flex-direction: column; gap: 5px; min-width: 0; flex: 1; }
.field > span { font-size: 12px; color: var(--text-dim); }
.field-row { display: flex; gap: 10px; }
select, input[type="number"], input[type="text"] {
width: 100%;
padding: 7px 9px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-family: var(--mono);
font-size: 12.5px;
transition: border-color .15s, box-shadow .15s;
}
select:focus, input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
input[type="color"] {
width: 100%; height: 34px; padding: 3px; background: var(--bg);
border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: pointer;
}
.check { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--text-dim); cursor: pointer; }
.check input { accent-color: var(--accent); width: 15px; height: 15px; }
.hidden { display: none !important; }
.swatches { display: flex; align-items: center; gap: 6px; }
.swatches button {
width: 30px; height: 34px; border-radius: var(--radius-sm); cursor: pointer;
background: var(--c); border: 1px solid var(--border);
}
.swatches button:hover { border-color: var(--accent); }
/* 上传区 */
.dropzone {
border: 1.5px dashed var(--border);
border-radius: var(--radius);
background: linear-gradient(180deg, rgba(79, 140, 255, 0.04), transparent);
text-align: center;
cursor: pointer;
transition: border-color .15s, background .15s;
}
.dropzone.compact { padding: 18px 12px; }
.dropzone:hover, .dropzone:focus-visible, .dropzone.over {
border-color: var(--accent); background: var(--accent-soft); outline: none;
}
.dropzone p { margin: 0; font-size: 13px; }
.dropzone .sub { margin-top: 4px; font-size: 11.5px; color: var(--text-faint); }
kbd {
font-family: var(--mono); font-size: 11px; padding: 1px 5px;
border: 1px solid var(--border); border-radius: 4px; background: var(--bg);
}
/* 待处理槽(单张) */
.thumbs { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.thumbs:empty { display: none; }
.pending-item {
display: grid; grid-template-columns: 76px 1fr auto; align-items: center; gap: 10px;
padding: 8px; background: var(--bg);
border: 1px solid var(--accent); border-radius: var(--radius-sm);
box-shadow: 0 0 0 3px var(--accent-soft);
}
.thumb-wrap {
width: 76px; height: 76px; border-radius: 8px; overflow: hidden;
background-color: #0a0c10;
background-image:
linear-gradient(45deg, #171b23 25%, transparent 25%),
linear-gradient(-45deg, #171b23 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #171b23 75%),
linear-gradient(-45deg, transparent 75%, #171b23 75%);
background-size: 14px 14px;
background-position: 0 0, 0 7px, 7px -7px, -7px 0;
}
.thumb-wrap img { width: 100%; height: 100%; object-fit: contain; display: block; }
.pending-meta { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
.pending-meta .tname { font-size: 12.5px; color: var(--text); word-break: break-all; }
.pending-meta .tsize { font-size: 11px; color: var(--text-faint); font-family: var(--mono); }
.thumbs .tremove {
border: 0; background: transparent; color: var(--text-faint); cursor: pointer;
font-size: 17px; line-height: 1; padding: 3px 8px; border-radius: 6px;
}
.thumbs .tremove:hover { color: var(--danger); background: rgba(242, 85, 90, .12); }
.pending-note { margin: 0; font-size: 11.5px; line-height: 1.5; color: var(--accent); }
.pending-note:empty { display: none; }
/* 按钮 */
.btn {
border: 1px solid var(--border);
background: var(--surface-3);
color: var(--text);
border-radius: var(--radius-sm);
padding: 9px 14px;
cursor: pointer;
transition: background .15s, border-color .15s, transform .05s;
white-space: nowrap;
}
.btn:hover:not(:disabled) { border-color: var(--accent); }
.btn:active:not(:disabled) { transform: translateY(1px); }
.btn:disabled { opacity: .42; cursor: not-allowed; }
.btn.sm { padding: 6px 11px; font-size: 12.5px; }
.btn.ghost { background: transparent; }
.btn.primary {
background: var(--accent); border-color: var(--accent); color: #fff;
font-weight: 600; font-size: 15px; padding: 12px 16px;
}
.btn.primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn.link { background: none; border: 0; color: var(--accent); padding: 0; font-size: 12.5px; }
.actions { gap: 12px; }
.progress { display: flex; flex-direction: column; gap: 6px; }
.bar { height: 6px; border-radius: 99px; background: var(--bg); overflow: hidden; }
.bar > i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .25s ease; }
.progress-meta { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--text-dim); }
.error-text { margin: 0; font-size: 12.5px; color: var(--danger); word-break: break-all; }
/* 批量处理说明 */
.batch-note { margin: 0; font-size: 11px; line-height: 1.65; color: var(--text-faint); }
.field-tip { margin: -2px 0 0; font-size: 11px; line-height: 1.6; color: var(--text-faint); }
.batch-note strong { color: var(--text-dim); font-weight: 500; }
.batch-note code {
font-family: var(--mono); font-size: 10.5px; color: var(--text-dim);
background: var(--bg); border: 1px solid var(--border-soft); border-radius: 4px; padding: 0 4px;
}
/* ------------------------------- 结果区 ------------------------------- */
.stage { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.stage-head {
display: flex; align-items: center; justify-content: space-between;
padding: 14px 22px; border-bottom: 1px solid var(--border); gap: 16px;
}
.stage-head h2 { font-size: 15px; }
.stage-head .count { font-family: var(--mono); color: var(--text-dim); font-weight: 400; }
.stage-tools { display: flex; align-items: center; gap: 10px; }
.stage-tip {
flex: 0 0 auto; margin: 0; padding: 7px 22px; font-size: 11.5px; color: var(--text-faint);
border-bottom: 1px solid var(--border-soft); background: rgba(79, 140, 255, .04);
}
.segmented { display: flex; background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 2px; }.segmented button {
border: 0; background: transparent; color: var(--text-dim);
padding: 5px 12px; border-radius: 6px; cursor: pointer; font-size: 12.5px;
}
.segmented button.active { background: var(--accent-soft); color: var(--accent); }
/* 批量任务报告(结果区顶部,仅在跑过 / 存在批量任务时出现) */
.batch-report {
flex: 0 0 auto; margin: 14px 22px 0; padding: 12px 14px;
background: var(--surface); border: 1px solid var(--border-soft); border-radius: var(--radius);
display: flex; flex-direction: column; gap: 8px; max-height: 40vh;
}
.batch-report[hidden] { display: none; }
.batch-report-head { display: flex; align-items: center; gap: 10px; }
.batch-report-head h3 { font-size: 13px; display: flex; align-items: center; gap: 8px; }
.batch-report-path {
flex: 1; min-width: 0; font-family: var(--mono); font-size: 11px; color: var(--text-faint);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.batch-report-sum { margin: 0; font-family: var(--mono); font-size: 11.5px; color: var(--text-dim); }
.batch-rows {
list-style: none; margin: 0; padding: 0; overflow-y: auto;
display: flex; flex-direction: column; gap: 4px;
}
.batch-rows:empty { display: none; }
.batch-row {
display: grid; grid-template-columns: 34px minmax(0, 1fr) minmax(0, 1.4fr) auto auto;
align-items: center; gap: 10px; padding: 5px 9px;
background: var(--surface-2); border: 1px solid var(--border-soft); border-radius: var(--radius-sm);
font-family: var(--mono); font-size: 11.5px; color: var(--text-dim);
}
.batch-row .bi { text-align: right; color: var(--text-faint); }
.batch-row .bs,
.batch-row .bo { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.batch-row .bo { color: var(--text); }
.batch-row .bo::before { content: "→ "; color: var(--text-faint); }
.batch-row .bo:empty::before { content: ""; }
.batch-row .bt { color: var(--text-faint); font-size: 11px; }
.batch-row.running { border-color: rgba(79, 140, 255, .4); background: var(--accent-soft); }
.batch-row.failed { border-color: rgba(242, 85, 90, .35); }
.batch-row.canceled { opacity: .55; }
.grid {
flex: 1 1 auto; overflow-y: auto; padding: 18px 22px 28px;
display: grid; gap: 18px; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
align-content: start;
}
.card {
background: var(--surface); border: 1px solid var(--border-soft);
border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column;
transition: border-color .15s, box-shadow .15s;
}
.card-head { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-bottom: 1px solid var(--border-soft); cursor: pointer; }
.card-head .name {
flex: 1; min-width: 0; text-align: left; cursor: pointer;
border: 0; background: transparent; color: var(--text);
padding: 3px 6px; margin-left: -6px; border-radius: 6px;
font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
transition: color .15s, background .15s;
}
.card-head .name:hover {
color: var(--accent); background: var(--accent-soft);
text-decoration: underline; text-underline-offset: 3px;
}
.card-head .name:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--accent-soft); }
.card-del {
flex: 0 0 auto; border: 0; background: transparent; color: var(--text-faint);
cursor: pointer; font-size: 17px; line-height: 1; padding: 2px 8px; border-radius: 6px;
transition: color .15s, background .15s;
}
.card-del:hover { color: var(--danger); background: rgba(242, 85, 90, .12); }
/* 处理这条记录时用的参数:始终可见(便于对照历史),过长省略,完整 JSON 在 title 里 */
.card-params {
margin: 0; padding: 6px 12px;
font-family: var(--mono); font-size: 11px; color: var(--text-faint);
background: var(--surface-2); border-bottom: 1px solid var(--border-soft);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.card-params::before { content: "参数 "; color: var(--text-dim); }
.card-params:empty { display: none; }
/* 选中态:主题色一圈描边 + 头部同色底 */
.card.selected { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
.card.selected .card-head { background: var(--accent-soft); border-bottom-color: rgba(79, 140, 255, .35); }
.badge {
font-family: var(--mono); font-size: 11px; padding: 2px 7px; border-radius: 99px;
background: var(--surface-3); color: var(--text-dim); border: 1px solid var(--border);
}
.badge.ok { color: var(--ok); border-color: rgba(53, 201, 138, .35); background: rgba(53, 201, 138, .1); }
.badge.warn { color: var(--warn); border-color: rgba(240, 180, 41, .35); background: rgba(240, 180, 41, .1); }
.badge.err { color: var(--danger); border-color: rgba(242, 85, 90, .35); background: rgba(242, 85, 90, .1); }
/* 对比视图 */
.compare {
position: relative; width: 100%; aspect-ratio: 4 / 3; overflow: hidden;
background-color: #0a0c10;
background-image:
linear-gradient(45deg, #171b23 25%, transparent 25%),
linear-gradient(-45deg, #171b23 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #171b23 75%),
linear-gradient(-45deg, transparent 75%, #171b23 75%);
background-size: 18px 18px;
background-position: 0 0, 0 9px, 9px -9px, -9px 0;
}
.compare img {
position: absolute; inset: 0; width: 100%; height: 100%;
object-fit: contain; user-select: none; -webkit-user-drag: none; pointer-events: none;
}
.compare .after { clip-path: inset(0 calc(100% - var(--p, 50%)) 0 0); }
.compare .divider {
position: absolute; top: 0; bottom: 0; left: var(--p, 50%); width: 2px;
background: var(--accent); box-shadow: 0 0 12px rgba(79, 140, 255, .55); pointer-events: none;
}
.compare .divider::after {
content: ""; position: absolute; top: 50%; left: 50%; width: 26px; height: 26px;
transform: translate(-50%, -50%); border-radius: 50%;
background: var(--accent); border: 3px solid var(--surface);
}
.compare input[type="range"] {
position: absolute; inset: 0; width: 100%; height: 100%; margin: 0;
opacity: 0; cursor: ew-resize; -webkit-appearance: none; appearance: none;
}
.compare .tag {
position: absolute; bottom: 8px; font-family: var(--mono); font-size: 11px;
padding: 2px 7px; border-radius: 6px; background: rgba(8, 10, 14, .72); color: var(--text);
border: 1px solid var(--border); pointer-events: none;
}
.compare .tag.left { left: 8px; }
.compare .tag.right { right: 8px; color: var(--accent); }
.card-body { padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }
.card-stats { display: flex; flex-wrap: wrap; gap: 12px; font-family: var(--mono); font-size: 11.5px; color: var(--text-faint); }
.card-stats b { color: var(--text-dim); font-weight: 500; }
.card-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.card-note { margin: 0; font-size: 11.5px; color: var(--warn); }
.card-error { font-size: 12px; color: var(--danger); word-break: break-all; }
/* 卡片状态 */
.card.running .card-body, .card.pending .card-body { display: none; }
.card .status {
padding: 26px 12px; display: flex; flex-direction: column; align-items: center; gap: 10px;
color: var(--text-dim); font-size: 12.5px;
}
.spinner {
width: 22px; height: 22px; border-radius: 50%;
border: 2px solid var(--border); border-top-color: var(--accent);
animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.card.done .status, .card.failed .status, .card.canceled .status { display: none; }
.empty-state {
flex: 1 1 auto; display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 12px; text-align: center; padding: 40px; color: var(--text-dim);
}
.empty-state h3 { font-size: 28px; font-weight: 600; color: var(--text); letter-spacing: -0.4px; }
.empty-state p { margin: 0; max-width: 460px; font-size: 13px; line-height: 1.7; }
.empty-state.hidden { display: none; }
@media (max-width: 1100px) {
.layout { grid-template-columns: 1fr; }
.sidebar { border-right: 0; border-bottom: 1px solid var(--border); }
.meta { display: none; }
}
+587
View File
@@ -0,0 +1,587 @@
/* 前端回归测试:用最小假 DOM 在 Node 里跑 app.js,模拟完整交互链路。
用法:node web/test_app.js
覆盖:
① 单槽待处理:替换 / 去重 / 一次多张
② 结果历史:刷新后从服务端恢复、跨任务累积
③ 回归重点:添加新图并重新处理时,右侧已有结果绝不能被清空
④ 参数记录:每条记录带参数快照;「重新处理」把参数重新赋值到表单
⑤ 同一张图多次处理 → 参数记录更新为最新
⑥ 删除单条不被轮询复活 / 选中描边 / 打包 ZIP / 清空 */
'use strict';
const fs = require('fs');
const path = require('path');
const appSrc = fs.readFileSync(process.env.APP_SRC || path.join(__dirname, 'app.js'), 'utf8');
const zipSrc = fs.readFileSync(path.join(__dirname, 'zip.js'), 'utf8');
/* ---------------------------- 假 DOM ---------------------------- */
function makeNode(tag = 'div') {
const listeners = {};
const classes = new Set();
let text = '';
const node = {
tag,
parent: null,
children: [],
dataset: {},
style: { setProperty() {}, width: '' },
value: '',
checked: false,
hidden: false,
disabled: false,
title: '',
src: '',
href: '',
download: '',
files: null,
scrollTop: 0,
// textContent 与真实 DOM 一致:赋值会清空所有子节点
get textContent() { return text; },
set textContent(v) {
text = String(v);
for (const c of node.children) c.parent = null;
node.children.length = 0;
},
// className 与 classList 共享同一份类名集合
get className() { return [...classes].join(' '); },
set className(v) {
classes.clear();
for (const c of String(v).split(/\s+/)) if (c) classes.add(c);
},
classList: {
add(c) { classes.add(c); },
remove(c) { classes.delete(c); },
toggle(c, on) {
const want = on === undefined ? !classes.has(c) : !!on;
want ? classes.add(c) : classes.delete(c);
return want;
},
contains(c) { return classes.has(c); },
},
append(...kids) {
for (const k of kids) {
// 真实 DOM 里 append(undefined) 会塞进一个文本节点 —— 静默的视觉 bug,
// 所以这里直接抛错,逼出这类问题(app.js 的 el() 已过滤空子节点)
if (k === undefined || k === null) throw new Error('append() 收到了 undefined/null 子节点');
k.parent = node;
node.children.push(k);
}
},
remove() {
if (!node.parent) return;
const i = node.parent.children.indexOf(node);
if (i >= 0) node.parent.children.splice(i, 1);
node.parent = null;
},
addEventListener(type, fn) { (listeners[type] = listeners[type] || []).push(fn); },
dispatch(type, ev = {}) {
const event = { target: node, preventDefault() {}, stopPropagation() {}, ...ev };
for (const fn of listeners[type] || []) fn(event);
},
closest(sel) {
const parts = sel.split(',').map((s) => s.trim());
let cur = node;
while (cur) {
for (const p of parts) {
if (p.includes('[')) { // 形如 button[data-view]
const m = /^([\w-]*)\[([\w-]+)\]$/.exec(p);
if (m && (!m[1] || cur.tag === m[1]) && cur.dataset[m[2]] !== undefined) return cur;
} else if (p === cur.tag) {
return cur;
} else if (p.startsWith('.') && cur.className.split(/\s+/).includes(p.slice(1))) {
return cur;
}
}
cur = cur.parent;
}
return null;
},
querySelectorAll() { return []; },
setAttribute() {},
click() { node.dispatch('click'); },
scrollIntoView() {},
};
return node;
}
const byId = new Map();
const viewSwitch = makeNode('div');
global.document = {
body: makeNode('body'),
getElementById(id) {
if (!byId.has(id)) byId.set(id, id === 'view-switch' ? viewSwitch : makeNode());
return byId.get(id);
},
createElement(tag) { return makeNode(tag); },
createTextNode(text) { const n = makeNode('#text'); n.textContent = String(text); return n; },
addEventListener() {},
querySelectorAll() { return []; },
};
global.window = { location: { assign() {} } };
new Function('window', zipSrc)(global.window); // 让 window.BiRefNetZip 可用
const lsData = new Map();
global.localStorage = {
getItem: (k) => (lsData.has(k) ? lsData.get(k) : null),
setItem: (k, v) => lsData.set(k, String(v)),
removeItem: (k) => lsData.delete(k),
};
Object.defineProperty(global, 'navigator', { value: { clipboard: {} }, configurable: true });
Object.defineProperty(global, 'File', {
configurable: true,
value: class File {
constructor(parts, name, opts = {}) {
const first = Array.isArray(parts) ? parts[0] : parts;
this.name = name;
this.type = opts.type || '';
this.lastModified = opts.lastModified || 0;
this.size = (first && first.size) || 0;
}
},
});
let lastBlob = null;
Object.defineProperty(global, 'Blob', {
configurable: true,
value: class Blob {
constructor(parts, opts = {}) {
this.parts = parts;
this.type = opts.type || '';
lastBlob = this;
}
},
});
global.URL = { createObjectURL: () => `blob:${Math.random()}`, revokeObjectURL() {} };
global.ClipboardItem = class {};
global.FormData = class {
constructor() { this.entries = []; }
append(k, v, name) { this.entries.push([k, v, name]); }
};
/* ------------------------- 假服务端 ------------------------- */
const STATE = {
ok: true,
node_dir: 'F:\\BiRefNet_WebUI\\vendor\\comfyui_birefnet_ll',
output_dir: 'F:\\BiRefNet_WebUI\\outputs',
environment: {
python: '3.12.10', torch: '2.13.0+cu126', cuda: true,
devices: [{ index: 0, name: 'NVIDIA GeForce RTX 3070 Laptop GPU', free_mem: 7, total_mem: 8 }],
},
models: [{
key: 'Portrait', name: 'Portrait', file: 'Portrait.safetensors', arch: 'v1',
size_mb: 843.9, backbone: 'swin_v1_l', path: 'models/Portrait.safetensors',
}],
defaults: { model: 'Portrait' },
};
/** 与 index.html 里的默认值保持一致,供测试手动铺一遍表单初始值。 */
const FORM_DEFAULTS = {
'opt-model': 'Portrait', 'opt-device': 'auto', 'opt-dtype': 'auto', 'opt-arch': 'auto',
'opt-resolution-mode': 'square', 'opt-width': '1024', 'opt-height': '1024',
'opt-longest-side': '1024', 'opt-upscale': 'bilinear', 'opt-threshold': '0',
'opt-blur1': '90', 'opt-blur2': '6', 'opt-background': 'transparent',
'opt-bgcolor': '#ffffff', 'opt-final-side': '0',
};
const FORM_CHECKS = { 'opt-refine': true, 'opt-mask': false, 'batch-recursive': false };
const P_SQUARE = {
model: 'Portrait', device: 'auto', dtype: 'auto', arch: 'auto',
resolution_mode: 'square', width: 1024, height: 1024, longest_side: 1024,
upscale_method: 'bilinear', mask_threshold: 0, refine_foreground: true,
blur_size: 90, blur_size_two: 6, background: 'transparent', bg_color: '#ffffff',
output_mask: false, final_longest_side: 0,
};
const P_GREEN = {
...P_SQUARE, model: 'birefnet', resolution_mode: 'longest', longest_side: 512,
background: 'color', bg_color: '#00ff00', refine_foreground: false,
};
const stub = { polls: 0, posts: 0, detailFetches: 0, fileHits: 0, originalHits: 0, lastOptions: null, batchPolls: 0, batchPosts: 0, lastBatch: null };
const tasks = new Map();
let clock = 1;
function mkImage(index, name, over = {}) {
const done = (over.state || 'done') === 'done';
return {
index, name, label: name.replace(/\.[^.]+$/, ''),
state: 'done', stage: '完成', progress: 1,
width: 1920, height: 1080, input_size: [1024, 1024], coverage: 0.42, elapsed: 3.1,
error: null, warning: null,
urls: done
? { original: `/api/tasks/${over.task}/file/${index}/original`, cutout: `/api/tasks/${over.task}/file/${index}/cutout`, mask: `/api/tasks/${over.task}/file/${index}/mask` }
: {},
...over,
};
}
function mkTask(id, options, images, state = 'done') {
const task = { id, created: clock++, state, stage: state === 'done' ? '完成' : '排队中', progress: state === 'done' ? 1 : 0, options, images };
tasks.set(id, task);
return task;
}
// 历史:T1(无遮罩输出 + 列表里不带 options,逼前端补拉详情)+ T2(列表里直接带)
const T1 = mkTask('T100', P_SQUARE, [{ index: 0, name: 'old.jpg', label: 'old', state: 'done', stage: '完成', progress: 1, width: 800, height: 600, input_size: [1024, 1024], coverage: 0.3, elapsed: 2.2, error: null, warning: null, urls: {} }]);
T1.images[0].urls = { original: '/api/tasks/T100/file/0/original', cutout: '/api/tasks/T100/file/0/cutout' };
const T2 = mkTask('T200', P_GREEN, [mkImage(0, 'mid.jpg', { task: 'T200' })]);
T2.options = P_GREEN;
const taskList = () => [...tasks.values()]
.sort((a, b) => b.created - a.created)
.map((t) => ({
id: t.id, created: t.created, state: t.state, stage: t.stage, progress: t.progress,
mode: t.mode || 'upload', input_dir: t.input_dir || null, output_dir: t.output_dir || null,
// 模仿服务端列表:T100 不返回 options(触发补拉详情)
...(t.id === 'T100' ? {} : { options: t.options }),
images: t.images,
}));
global.fetch = async (url, options = {}) => {
const json = (body) => ({ ok: true, status: 200, text: async () => JSON.stringify(body) });
const bin = (size) => ({
ok: true, status: 200,
blob: async () => ({ size, type: 'image/png' }),
arrayBuffer: async () => new Uint8Array(size).buffer,
});
const method = options.method || 'GET';
if (url.includes('/api/state')) return json(STATE);
if (url.endsWith('/api/batch') && method === 'POST') {
stub.batchPosts += 1;
const body = JSON.parse(options.body);
stub.lastBatch = body;
const id = `B${400 + stub.batchPosts}`;
const names = ['photo.jpg', 'a_pretty_long_original_filename_here.png', 'third.png'];
const images = names.map((name, i) => ({
index: i, name, label: name, state: 'pending', stage: '排队中', progress: 0,
output_name: null, urls: {},
}));
const task = mkTask(id, body.options || {}, images, 'running');
task.mode = 'batch';
task.input_dir = body.input_dir;
task.output_dir = body.output_dir || STATE.output_dir;
return json({
ok: true, task_id: id, mode: 'batch', count: images.length,
input_dir: task.input_dir, output_dir: task.output_dir,
});
}
if (url.includes('/api/tasks') && method === 'POST') {
stub.posts += 1;
const opts = JSON.parse(options.body.entries.find((e) => e[0] === 'options')[1]);
stub.lastOptions = opts;
const name = options.body.entries.find((e) => e[0] === 'files')[2] || 'upload.png';
const id = `T${300 + stub.posts}`;
const images = [{ index: 0, name, label: name.replace(/\.[^.]+$/, ''), state: 'pending', stage: '排队中', progress: 0, urls: {} }];
mkTask(id, opts, images, 'running');
return json({ ok: true, task_id: id, count: 1 });
}
if (/\/file\/\d+\/(cutout|mask|original)$/.test(url)) {
stub.fileHits += 1;
if (url.endsWith('/original')) stub.originalHits += 1;
return bin(2048);
}
const detail = /\/api\/tasks\/([^/?]+)(?:\?([^#]*))?$/.exec(url);
if (detail && method === 'GET') {
stub.detailFetches += 1;
const task = tasks.get(detail[1]);
if (!task) return { ok: false, status: 404, text: async () => JSON.stringify({ ok: false, error: '任务不存在' }) };
const isBatch = task.mode === 'batch';
if (isBatch) stub.batchPolls += 1;
// 轮询时推进状态:running → done(第二次拿到该任务时)
if (task.state === 'running') {
task.polls = (task.polls || 0) + 1;
if (task.polls >= 2) {
task.state = 'done';
task.stage = '完成';
task.progress = 1;
task.images = task.images.map((img, i) => (isBatch
// 批量:只补上 output_name / 完成态(服务端就是按 RMBG_ 命名写盘的)
? { ...img, state: 'done', stage: '完成', progress: 1, elapsed: 4.2, output_name: `RMBG_${img.label.slice(0, 20)}_1791360000.png` }
: mkImage(i, img.name, { task: task.id })));
} else {
task.images = task.images.map((img) => ({ ...img, state: 'running', stage: '推理', progress: 0.5, urls: {} }));
}
stub.polls += 1;
}
// ?tail=N → 只回传最后 N 张(批量轮询用)
const tail = Number((new URLSearchParams(detail[2] || '').get('tail')) || 0);
const images = tail > 0 ? task.images.slice(Math.max(0, task.images.length - tail)) : task.images;
return json({ ok: true, task: { id: task.id, created: task.created, mode: task.mode || 'upload', input_dir: task.input_dir || null, output_dir: task.output_dir || null, state: task.state, stage: task.stage, progress: task.progress, error: null, counts: { total: task.images.length, done: task.state === 'done' ? task.images.length : 0, failed: 0, pending: 0 }, images_total: task.images.length, images_from: task.images.length - images.length, options: task.options, images } });
}
if (url.endsWith('/api/tasks')) return json({ ok: true, tasks: taskList() });
return json({ ok: false, error: '未知接口 ' + url });
};
/* ---------------------------- 执行 ---------------------------- */
for (const [id, v] of Object.entries(FORM_DEFAULTS)) byId.set(id, Object.assign(makeNode('input'), { id, value: v }));
for (const [id, v] of Object.entries(FORM_CHECKS)) byId.set(id, Object.assign(makeNode('input'), { id, checked: v }));
byId.set('thumbs', makeNode('ul'));
byId.set('results', makeNode('div'));
byId.set('empty', Object.assign(makeNode('div'), { className: 'empty-state' }));
byId.set('btn-run', makeNode('button'));
byId.set('btn-zip', Object.assign(makeNode('button'), { textContent: '打包下载 ZIP' }));
// 批量处理面板(index.html 里存在,但未被 app.js 主动触碰的节点要在这里铺好)
byId.set('batch-rows', makeNode('ul'));
byId.set('batch-report', Object.assign(makeNode('section'), { hidden: true }));
byId.set('batch-progress-bar', makeNode('i'));
// 预置一份「老版本(v1)」表单存档:当年 output_mask 默认是 true,参数名还是 max_output_side。
// 启动时的迁移逻辑必须把遮罩默认值修正掉、把旧尺寸参数搬到新输入框,且不动其它参数。
lsData.set('birefnet.webui.options', JSON.stringify({
background: 'transparent', output_mask: true, max_output_side: 2048,
}));
new Function(appSrc)();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(cond, timeout = 5000) {
const t0 = Date.now();
while (Date.now() - t0 < timeout) { if (cond()) return true; await sleep(15); }
return false;
}
const results = () => byId.get('results').children;
const cards = () => byId.get('results').children;
const cardState = (c) => c.className;
const head = (c) => c.children[0];
const nameBtnOf = (c) => head(c).children[0];
const badgeOf = (c) => head(c).children[1].textContent;
const delBtnOf = (c) => head(c).children[2];
const paramsLineOf = (c) => find(c, 'card-params');
const find = (node, cls) => {
for (const child of node.children || []) {
if (child.className.split(/\s+/).includes(cls)) return child;
const hit = find(child, cls);
if (hit) return hit;
}
return null;
};
const compareImgCount = (c) => ((find(c, 'compare')?.children || []).filter((n) => n.tag === 'img').length);
const statsCount = (c) => ((find(c, 'card-stats')?.children || []).length);
const actionsOf = (c) => find(c, 'card-actions');
const reuseBtnOf = (c) => actionsOf(c).children[0];
function pendingName() {
const ul = byId.get('thumbs');
if (ul.children.length !== 1) return `li×${ul.children.length}`;
const meta = ul.children[0].children.find((x) => x.className.includes('pending-meta'));
return meta ? meta.children[0].textContent : '(无 meta)';
}
function upload(files) {
const input = byId.get('file-input');
input.files = files;
input.dispatch('change');
}
const F = (name, size, mtime) => ({ name, size, lastModified: mtime, type: 'image/jpeg' });
const formValue = (id) => (id === 'opt-refine' || id === 'opt-mask' ? byId.get(id).checked : byId.get(id).value);
const setForm = (id, v) => { if (id === 'opt-refine' || id === 'opt-mask') byId.get(id).checked = v; else byId.get(id).value = v; };
const savedParams = () => JSON.parse(lsData.get('birefnet.webui.imageParams') || '{}');
(async () => {
await sleep(80); // init / loadState / loadHistory
const checks = [];
const check = (name, ok, detail) => checks.push([name, ok, detail]);
/* ============ 场景 0:老版本 localStorage 存档迁移 ============ */
check('⓪ 老存档的 output_mask 不覆盖新默认(默认不输出遮罩)', formValue('opt-mask') === false, `checked=${formValue('opt-mask')}`);
check('⓪ 老参数 max_output_side 搬到新的「最终尺寸 · 最长边」', formValue('opt-final-side') === '2048', formValue('opt-final-side'));
check('⓪ 其余老参数照常恢复', formValue('opt-background') === 'transparent', formValue('opt-background'));
check('⓪ 存档被标记为 v2(迁移只做一次)',
(JSON.parse(lsData.get('birefnet.webui.options') || '{}')._schema) === 2,
lsData.get('birefnet.webui.options'));
setForm('opt-final-side', '0'); // 复原,避免影响后续场景
/* ============ 场景 1:刷新后从服务端恢复历史结果 ============ */
check('① 启动即恢复 2 条历史记录', results().length === 2, `len=${results().length}`);
check('① 列表缺 options 时自动补拉详情', stub.detailFetches >= 1, `fetches=${stub.detailFetches}`);
check('① 历史记录显示参数行', (paramsLineOf(cards()[0])?.textContent || '').includes('Portrait'), paramsLineOf(cards()[0])?.textContent);
check('① 历史记录直接可用(done)', cardState(cards()[0]).includes('done') && compareImgCount(cards()[0]) === 2, cardState(cards()[0]));
check('① 无遮罩记录不产生 null 子节点', actionsOf(cards()[0]).children.every((c) => c.tag && c.tag !== '#text'), actionsOf(cards()[0]).children.map((c) => c.tag));
check('① 计数 = 2', byId.get('result-count').textContent === '2', byId.get('result-count').textContent);
/* ============ 场景 2:单槽待处理 ============ */
upload([F('first.jpg', 1000, 111)]);
await sleep(20);
check('② 上传后待处理 1 张', pendingName() === 'first.jpg', pendingName());
upload([F('second.jpg', 2000, 222)]);
await sleep(20);
check('② 新图替换旧图(仍只有 1 张)', pendingName() === 'second.jpg', pendingName());
upload([F('second.jpg', 2000, 222)]);
await sleep(20);
check('② 完全相同的图被忽略', pendingName() === 'second.jpg' && byId.get('thumbs').children.length === 1, pendingName());
upload([F('x.jpg', 10, 1), F('y.jpg', 20, 2), F('z.jpg', 30, 3)]);
await sleep(20);
check('② 一次多张只留最后一张', pendingName() === 'z.jpg', pendingName());
/* ============ 场景 3(回归重点):新任务不清空已有结果 ============ */
const before = results().slice();
upload([F('new.jpg', 5000, 9)]);
await sleep(20);
setForm('opt-background', 'transparent');
setForm('opt-bgcolor', '#ffffff');
setForm('opt-model', 'Portrait');
setForm('opt-resolution-mode', 'square');
byId.get('btn-run').dispatch('click');
await waitFor(() => stub.polls >= 1);
check('③ 新任务提交后旧结果仍在(核心回归)',
results().length === 3 && results()[0] === before[0] && results()[1] === before[1],
`len=${results().length}`);
check('③ 提交时参数带上了当前表单值', stub.lastOptions && stub.lastOptions.model === 'Portrait' && stub.lastOptions.background === 'transparent', JSON.stringify(stub.lastOptions));
check('③ 新卡片立刻显示参数行', (paramsLineOf(cards()[2])?.textContent || '').includes('透明'), paramsLineOf(cards()[2])?.textContent);
await waitFor(() => stub.polls >= 2);
await sleep(40);
check('③ 新卡片进入 done 且旧结果完好', cardState(cards()[2]).includes('done') && results().length === 3, `${cardState(cards()[2])} len=${results().length}`);
check('③ 旧卡片未被重建(DOM 复用)', results()[0] === before[0] && results()[1] === before[1], '被替换了');
check('③ 参数已写入 localStorage', savedParams()['new.jpg']?.background === 'transparent', JSON.stringify(savedParams()['new.jpg'] || null));
/* ============ 场景 4:重新处理 = 参数重新赋值 ============ */
setForm('opt-background', 'color');
setForm('opt-bgcolor', '#00ff00');
setForm('opt-resolution-mode', 'longest');
setForm('opt-longest-side', '512');
setForm('opt-refine', false);
await sleep(20);
reuseBtnOf(cards()[2]).dispatch('click');
await sleep(80);
check('④ 重新处理把图片放回待处理', pendingName() === 'new.jpg', pendingName());
check('④ 参数被重新赋值(背景透明)', formValue('opt-background') === 'transparent', formValue('opt-background'));
check('④ 参数被重新赋值(颜色/尺寸/精修)',
formValue('opt-bgcolor') === '#ffffff' && formValue('opt-resolution-mode') === 'square' && formValue('opt-refine') === true,
`${formValue('opt-bgcolor')} / ${formValue('opt-resolution-mode')} / ${formValue('opt-refine')}`);
/* ============ 场景 5:同一张图再次处理 → 参数更新为最新 ============ */
setForm('opt-background', 'color');
setForm('opt-bgcolor', '#00ff00');
byId.get('btn-run').dispatch('click');
await waitFor(() => stub.polls >= 3);
check('⑤ 同图二次处理生成新记录(历史保留)', results().length === 4, `len=${results().length}`);
check('⑤ 新记录参数为最新(纯色 #00ff00)', (paramsLineOf(cards()[3])?.textContent || '').includes('纯色 #00ff00'), paramsLineOf(cards()[3])?.textContent);
check('⑤ localStorage 参数被最新值覆盖', savedParams()['new.jpg']?.background === 'color' && savedParams()['new.jpg']?.bg_color === '#00ff00', JSON.stringify(savedParams()['new.jpg'] || null));
// 等这一轮真正跑完再进下一个场景(否则按钮仍处于「处理中」态,点击会被忽略)
await waitFor(() => stub.polls >= 4 && cardState(cards()[3]).includes('done'));
await sleep(30);
check('⑤ 本轮任务已结束(可再次提交)', cardState(cards()[3]).includes('done'), cardState(cards()[3]));
/* ============ 场景 6:删除单条 + 轮询不复活 ============ */
delBtnOf(cards()[1]).dispatch('click');
await sleep(20);
check('⑥ 删除后剩 3 条', results().length === 3, `len=${results().length}`);
check('⑥ 计数同步', byId.get('result-count').textContent === '3', byId.get('result-count').textContent);
const pollsBefore = stub.polls;
byId.get('btn-run').dispatch('click'); // 再起一个任务制造轮询
await waitFor(() => stub.polls > pollsBefore + 1);
await sleep(40);
check('⑥ 被删记录未被轮询复活', results().length === 4 && !results().some((c) => nameBtnOf(c).textContent.includes('mid.jpg')), `len=${results().length}`);
/* ============ 场景 7:选中描边 ============ */
cards()[0].dispatch('click');
await sleep(10);
check('⑦ 点击卡片出现选中态', cardState(cards()[0]).includes('selected'), cardState(cards()[0]));
cards()[0].dispatch('click');
await sleep(10);
check('⑦ 再点一次取消选中', !cardState(cards()[0]).includes('selected'), cardState(cards()[0]));
nameBtnOf(cards()[0]).dispatch('click');
await sleep(60);
check('⑦ 点文件名不触发选中', !cardState(cards()[0]).includes('selected'), cardState(cards()[0]));
/* ============ 场景 8:跨任务打包 ZIP ============ */
const visible = results().length;
byId.get('btn-zip').dispatch('click');
await sleep(120);
const zip = lastBlob ? Buffer.from(concat(lastBlob.parts)) : null;
const eocd = zip ? zip.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06])) : -1;
const entryCount = eocd >= 0 ? zip.readUInt16LE(eocd + 10) : -1;
check('⑧ ZIP 条目数 = 可见结果数', entryCount === visible, `entries=${entryCount} visible=${visible}`);
check('⑧ 打包后按钮恢复可用', byId.get('btn-zip').disabled === false, String(byId.get('btn-zip').disabled));
if (zip) fs.writeFileSync(path.join(__dirname, '..', 'outputs', 'test_zip_out.zip'), zip);
/* ============ 场景 9:清空 ============ */
byId.get('btn-clear').dispatch('click');
await sleep(20);
check('⑨ 清空后列表为空', results().length === 0, `len=${results().length}`);
check('⑨ 空状态重新显示', !byId.get('empty').classList.contains('hidden'), 'hidden 仍存在');
check('⑨ 清空不影响参数记忆', savedParams()['new.jpg']?.background === 'color', JSON.stringify(savedParams()['new.jpg'] || null));
/* ============ 场景 10:目录批量处理 ============ */
check('⑩ 输出目录默认预填为项目 outputs', byId.get('batch-output-dir').value === STATE.output_dir, byId.get('batch-output-dir').value);
setForm('batch-input-dir', 'F:\\photos\\待抠图');
setForm('batch-output-dir', ''); // 留空 → 由服务端兜底默认目录
setForm('opt-background', 'color');
byId.get('batch-recursive').checked = true;
byId.get('btn-batch').dispatch('click');
await waitFor(() => stub.batchPosts >= 1);
check('⑩ 提交了输入/输出目录与递归开关',
stub.lastBatch?.input_dir === 'F:\\photos\\待抠图' && stub.lastBatch?.output_dir === '' && stub.lastBatch?.recursive === true,
JSON.stringify(stub.lastBatch));
check('⑩ 抠图参数沿用左侧表单',
stub.lastBatch?.options?.background === 'color' && stub.lastBatch?.options?.model === 'Portrait',
JSON.stringify(stub.lastBatch?.options));
await waitFor(() => byId.get('batch-rows').children.length === 3);
check('⑩ 批量清单逐文件铺开', byId.get('batch-rows').children.length === 3, byId.get('batch-rows').children.length);
check('⑩ 清单标出输入 → 输出目录',
(byId.get('batch-report-path').textContent || '').includes('待抠图') && (byId.get('batch-report-path').textContent || '').includes('outputs'),
byId.get('batch-report-path').textContent);
check('⑩ 批量任务不铺单图结果卡片', results().length === 0, `cards=${results().length}`);
check('⑩ 清单展开时不显示空状态', byId.get('empty').classList.contains('hidden'), '空状态可见');
// 收尾会再拉一次全量(清单里每行都要是终态),所以要等按钮恢复才断言
await waitFor(() => byId.get('btn-batch').textContent === '开始批量抠图');
await sleep(60);
const rows = byId.get('batch-rows').children;
check('⑩ 收尾每行显示 RMBG_ 输出名', rows.every((r) => (r.cells.to.textContent || '').startsWith('RMBG_')), rows.map((r) => r.cells.to.textContent));
check('⑩ 收尾每行状态为完成', rows.every((r) => r.cells.badge.textContent === '完成'), rows.map((r) => r.cells.badge.textContent));
check('⑩ 汇总行给出张数', (byId.get('batch-report-sum').textContent || '').includes('共 3 张'), byId.get('batch-report-sum').textContent);
check('⑩ 按钮恢复可点', byId.get('btn-batch').disabled === false && byId.get('btn-batch').textContent === '开始批量抠图', byId.get('btn-batch').textContent);
check('⑩ 没有页面错误', byId.get('batch-error').hidden === true, byId.get('batch-error').textContent);
byId.get('btn-batch-hide').dispatch('click');
await sleep(20);
check('⑩ 收起后清单隐藏、空状态回归',
byId.get('batch-report').hidden === true && !byId.get('empty').classList.contains('hidden'), '收起逻辑异常');
/* ============ 场景 11:最终尺寸·最长边 + 遮罩默认关闭 ============ */
check('⑪ 「同时输出遮罩」默认不勾选(默认不产出遮罩文件)', formValue('opt-mask') === false, `checked=${formValue('opt-mask')}`);
check('⑪ 「最终尺寸 · 最长边」默认 0', formValue('opt-final-side') === '0', formValue('opt-final-side'));
setForm('opt-final-side', '1440');
setForm('opt-mask', true);
const posts11 = stub.posts;
const polls11 = stub.polls;
byId.get('btn-run').dispatch('click');
await waitFor(() => stub.posts > posts11);
check('⑪ 提交参数带 final_longest_side / output_mask',
stub.lastOptions?.final_longest_side === 1440 && stub.lastOptions?.output_mask === true,
JSON.stringify(stub.lastOptions));
await waitFor(() => stub.polls > polls11 + 1);
await sleep(50);
check('⑪ 结果卡片参数摘要显示最长边',
(paramsLineOf(cards()[0])?.textContent || '').includes('最长边 1440'),
paramsLineOf(cards()[0])?.textContent);
/* ============ 汇总 ============ */
const errs = byId.get('error-text').textContent;
console.log('='.repeat(64));
let fail = 0;
for (const [name, ok, detail] of checks) {
console.log(` ${ok ? '✔' : '✘'} ${name}${ok ? '' : ` -> 实际: ${JSON.stringify(detail)}`}`);
if (!ok) fail++;
}
if (errs) console.log(` ⚠ 页面上报错误: ${errs}`);
console.log('='.repeat(64));
console.log(fail || errs ? `失败 ${fail} 项${errs ? '(含页面错误)' : ''}` : `前端回归测试全部通过 ✔(${checks.length} 项)`);
console.log(`ZIP 样本:outputs/test_zip_out.zip(${zip ? zip.length : 0} bytes,${entryCount} 个条目)`);
process.exit(fail || errs ? 1 : 0);
})();
function concat(parts) {
const list = parts.map((p) => Buffer.from(p));
return Buffer.concat(list);
}
+108
View File
@@ -0,0 +1,108 @@
/* =========================================================================
BiRefNet WebUI · 极简 ZIP 打包器(无第三方依赖)
用途:结果列表里的记录可能来自多个不同任务,服务端的「按任务打包」不再适用,
所以在前端把所有可见结果打成一个 ZIP。
实现:ZIP 规范里最朴素的 STORE(不压缩)方式 —— 结果本来就是 PNG,
已经过 deflate,再压一次收益几乎为零,直接存更快更简单。
========================================================================= */
(function (root) {
'use strict';
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
table[i] = c >>> 0;
}
return table;
})();
function crc32(bytes) {
let c = 0xffffffff;
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
/** JS Date -> MS-DOS 时间/日期(ZIP 头里的老格式)。 */
function dosStamp(date) {
const time = ((date.getHours() & 0x1f) << 11) | ((date.getMinutes() & 0x3f) << 5) | ((date.getSeconds() >> 1) & 0x1f);
const day = (((date.getFullYear() - 1980) & 0x7f) << 9) | (((date.getMonth() + 1) & 0x0f) << 5) | (date.getDate() & 0x1f);
return { time, day };
}
/**
* 生成一个 ZIP 文件。
* @param {Array<{name: string, data: Uint8Array}>} entries
* @returns {Uint8Array}
*/
function buildZip(entries) {
const list = entries || [];
if (!list.length) throw new Error('没有可打包的文件');
const encoder = new TextEncoder();
const { time, day } = dosStamp(new Date());
const body = []; // 本地文件头 + 数据
const central = []; // 中央目录
let offset = 0;
for (const entry of list) {
const name = encoder.encode(String(entry.name));
const data = entry.data instanceof Uint8Array ? entry.data : new Uint8Array(entry.data);
const crc = crc32(data);
const local = new Uint8Array(30 + name.length);
const lv = new DataView(local.buffer);
lv.setUint32(0, 0x04034b50, true); // 本地文件头签名
lv.setUint16(4, 20, true); // 解压所需版本
lv.setUint16(6, 0x0800, true); // 标志位:文件名为 UTF-8
lv.setUint16(8, 0, true); // 压缩方式 0 = STORE
lv.setUint16(10, time, true);
lv.setUint16(12, day, true);
lv.setUint32(14, crc, true);
lv.setUint32(18, data.length, true); // 压缩后大小
lv.setUint32(22, data.length, true); // 原始大小
lv.setUint16(26, name.length, true);
lv.setUint16(28, 0, true); // 扩展字段长度
local.set(name, 30);
body.push(local, data);
const cd = new Uint8Array(46 + name.length);
const cv = new DataView(cd.buffer);
cv.setUint32(0, 0x02014b50, true); // 中央目录签名
cv.setUint16(4, 20, true); // 生成程序版本
cv.setUint16(6, 20, true); // 解压所需版本
cv.setUint16(8, 0x0800, true);
cv.setUint16(10, 0, true); // STORE
cv.setUint16(12, time, true);
cv.setUint16(14, day, true);
cv.setUint32(16, crc, true);
cv.setUint32(20, data.length, true);
cv.setUint32(24, data.length, true);
cv.setUint16(28, name.length, true);
cv.setUint32(42, offset, true); // 本地头偏移
cd.set(name, 46);
central.push(cd);
offset += local.length + data.length;
}
const centralSize = central.reduce((n, c) => n + c.length, 0);
const eocd = new Uint8Array(22);
const ev = new DataView(eocd.buffer);
ev.setUint32(0, 0x06054b50, true); // 中央目录结束标记
ev.setUint16(8, list.length, true); // 本盘条目数
ev.setUint16(10, list.length, true); // 总条目数
ev.setUint32(12, centralSize, true);
ev.setUint32(16, offset, true);
const out = new Uint8Array(offset + centralSize + 22);
let p = 0;
for (const part of body) { out.set(part, p); p += part.length; }
for (const c of central) { out.set(c, p); p += c.length; }
out.set(eocd, p);
return out;
}
root.BiRefNetZip = { buildZip, crc32 };
})(typeof window !== 'undefined' ? window : globalThis);