EntropyDrop commited on
Commit ·
77880b8
1
Parent(s): 4b013c5
Add meat preselection, manual model updates, and LAN deployment
Browse files- best_annotator/.gitignore +3 -0
- best_annotator/README.md +45 -2
- best_annotator/app.py +18 -2
- best_annotator/deploy/ddj-annotator.service +17 -0
- best_annotator/meat_annotations.py +8 -0
- best_annotator/meat_model.py +120 -0
- best_annotator/meat_model_config.example.json +6 -0
- best_annotator/src/MeatEditor.jsx +59 -26
- best_annotator/src/MeatModel.jsx +77 -0
- best_annotator/src/main.jsx +5 -2
- best_annotator/src/meat.css +3 -0
- best_annotator/src/meatGeometry.js +24 -0
- best_annotator/src/meatSelection.js +32 -0
- best_annotator/static/assets/MeatEditor-C4N_uiLJ.js +5 -0
- best_annotator/static/assets/OrbitControls-CInKUGFx.js +0 -0
- best_annotator/static/assets/SkinEditor-CO_iRmVE.js +0 -0
- best_annotator/static/assets/index-D0g9WvcQ.css +1 -0
- best_annotator/static/assets/index-Dk3WlUGQ.js +0 -0
- best_annotator/static/index.html +2 -2
- best_annotator/test_meat_model.py +64 -0
- best_annotator/test_meat_selection.mjs +42 -0
best_annotator/.gitignore
CHANGED
|
@@ -3,3 +3,6 @@ __pycache__/
|
|
| 3 |
server.log
|
| 4 |
server.pid
|
| 5 |
node_modules/
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
server.log
|
| 4 |
server.pid
|
| 5 |
node_modules/
|
| 6 |
+
.meat_model/
|
| 7 |
+
meat_model_config.json
|
| 8 |
+
meat_model_config_test.json
|
best_annotator/README.md
CHANGED
|
@@ -5,8 +5,8 @@
|
|
| 5 |
进入“已标注”,在“标注类型”选择“Perfect · 待标 meat”,点击“标注 meat”。
|
| 6 |
优先使用当前修复后的 `{id}_perfect.png`;没有修复图时,使用 perfect/best 指向的原候选。
|
| 7 |
|
| 8 |
-
- 3D
|
| 9 |
-
-
|
| 10 |
- 选中的格子在 3D 与 UV 中以绿色呼吸高亮。可关闭呼吸,系统减少动态效果时默认静态高亮。
|
| 11 |
- 可切换内层+外层、仅内层、仅外层,以及正面、背面、侧面、头顶和底部视角。被遮挡区域也可直接在 UV 上选择。
|
| 12 |
- meat 包括脸、眼睛、嘴巴、裸露身体和手脚;头发、胡须、眉毛、眼镜、帽子、皇冠、衣服、鞋和饰品不选。内层也可能是非 meat,外层也可能是 meat。
|
|
@@ -180,3 +180,46 @@ npm test
|
|
| 180 |
```
|
| 181 |
|
| 182 |
3D 组件:[skinview3d 3.4.2](https://github.com/bs-community/skinview3d),MIT 许可证,见 `static/vendor/skinview3d-LICENSE`。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
进入“已标注”,在“标注类型”选择“Perfect · 待标 meat”,点击“标注 meat”。
|
| 6 |
优先使用当前修复后的 `{id}_perfect.png`;没有修复图时,使用 perfect/best 指向的原候选。
|
| 7 |
|
| 8 |
+
- 3D 左键直接拖拽旋转,点击切换选中,滚轮缩放;UV 图保留点击和拖动涂选。
|
| 9 |
+
- Ctrl+点击按相连颜色泛洪,颜色容差可调;再次点击高亮格取消。支持擦除、撤销/重做和 Ctrl/Cmd+Z。
|
| 10 |
- 选中的格子在 3D 与 UV 中以绿色呼吸高亮。可关闭呼吸,系统减少动态效果时默认静态高亮。
|
| 11 |
- 可切换内层+外层、仅内层、仅外层,以及正面、背面、侧面、头顶和底部视角。被遮挡区域也可直接在 UV 上选择。
|
| 12 |
- meat 包括脸、眼睛、嘴巴、裸露身体和手脚;头发、胡须、眉毛、眼镜、帽子、皇冠、衣服、鞋和饰品不选。内层也可能是非 meat,外层也可能是 meat。
|
|
|
|
| 180 |
```
|
| 181 |
|
| 182 |
3D 组件:[skinview3d 3.4.2](https://github.com/bs-community/skinview3d),MIT 许可证,见 `static/vendor/skinview3d-LICENSE`。
|
| 183 |
+
|
| 184 |
+
### Meat 交互更新(2026-10-29)
|
| 185 |
+
|
| 186 |
+
- 3D 直接左键拖拽旋转;移动超过 5px 视为旋转,不产生标注。右键也可旋转。
|
| 187 |
+
- 默认点击未高亮格选为 meat,再次点击高亮格取消;另有独立擦除模式。
|
| 188 |
+
- Ctrl+点击在同一部件、同一层上按相连颜色泛洪,支持跨立方体面的真实接缝。不会跨身体部件、图层或透明格。
|
| 189 |
+
- 颜色容差范围 0–100%,默认 12%;采用相对起始格的 RGB 均方根距离,0% 仅选相同颜色,避免渐变链无限扩张。
|
| 190 |
+
- Ctrl+点击已选格会批量取消相连相近颜色;一次泛洪是一条撤销记录。
|
| 191 |
+
- UV 图保留左键连续涂选;按下时确定本笔选择或擦除,经过同一个格子不会反复翻转。Ctrl 泛洪也可在 UV 图使用。
|
| 192 |
+
- 保存格式和人工标签不变;原数据与 `.meat_history` 均保留。
|
| 193 |
+
|
| 194 |
+
验证:`node test_meat_selection.mjs` 覆盖 classic/slim、跨面接缝、部件/层隔离、透明障碍、固定起点容差和拖拽判定。
|
| 195 |
+
|
| 196 |
+
## Meat 模型预选与手动更新
|
| 197 |
+
|
| 198 |
+
在 perfect 皮肤的 meat 编辑器中点击「模型预选」,使用 ds 上当前模型替换当前选区。结果以相同呼吸灯高亮显示,可以撤销、手动点选或 Ctrl 泛洪修正;只有点击「保存 meat」才写入人工标签。退出未保存编辑不会把预测变成训练数据。
|
| 199 |
+
|
| 200 |
+
页面顶部的「训练并更新预选模型」由使用者主动点击,保存标注不会自动训练。训练读取本机当前已保存的完整标签(不要求先 commit/push),冻结标签及皮肤快照,按近重复皮肤分组留一验证,训练完并核验后原子切换预选模型。期间旧模型仍可用;失败保留旧模型及错误状态,不覆盖历史训练。
|
| 201 |
+
|
| 202 |
+
当前模型只验证了标准手臂和二值 alpha;纤细手臂、半透明皮肤仍可人工标注,但暂不加入预选训练。无标签、过期标签、历史备份不当作非 meat 标签。已保存的全黑 mask 是完整负例。预选辅助来源随人工保存记录到 metadata。
|
| 203 |
+
|
| 204 |
+
`meat_model_config.json` 是本机配置(不提交凭据);参考 `meat_model_config.example.json`。本机后端通过固定 SSH JSON 命令调用 `/home/ds/llms/github/mc_meat/model_service.py`,不开放新的 ds HTTP 端口。状态查询不加载模型;DINO 特征提取仅在任务进程运行期间占用显存,分类头训练使用 CPU。`/.meat_model` 保存本机任务绑定,ds `service_runtime` 保存独立任务、快照、日志、模型和旧版本。
|
| 205 |
+
|
| 206 |
+
部署前运行:`python -m unittest discover -p 'test_*.py'`、`npm test`、`node test_meat_selection.mjs`、`node test_meat_geometry.mjs`、`npm run build`。
|
| 207 |
+
|
| 208 |
+
## ds 局域网部署
|
| 209 |
+
|
| 210 |
+
地址:`http://192.168.0.111:8765/`。该实例直接读写 ds 的 `/home/ds/llms/SKING_DDJ_Dataset`;本机 `localhost:8765` 若仍运行,使用的是本机数据目录,两者标签不会自动同步。局域网协作时统一使用 ds 地址。
|
| 211 |
+
|
| 212 |
+
`meat_model_config.json` 以示例文件为基础,增加 `"transport": "local"`,复用 ds 已安装的 mc_meat 环境和 `service_runtime/production`。该配置文件不纳入版本控制。服务不因启动、刷新或保存标签而自动训练。
|
| 213 |
+
|
| 214 |
+
安装用户服务(ds 用户):
|
| 215 |
+
|
| 216 |
+
```sh
|
| 217 |
+
mkdir -p ~/.config/systemd/user
|
| 218 |
+
cp deploy/ddj-annotator.service ~/.config/systemd/user/
|
| 219 |
+
systemctl --user daemon-reload
|
| 220 |
+
systemctl --user enable --now ddj-annotator.service
|
| 221 |
+
systemctl --user status ddj-annotator.service
|
| 222 |
+
journalctl --user -u ddj-annotator.service -n 50
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
首次迁移需先停止占用相同地址端口的旧标注进程,随后由 systemd 管理。模板仅绑定 ds 的局域网地址,其他机��需修改绑定地址和绝对路径。ds 已启用用户 lingering,服务可在退出 SSH 后继续运行并随机器启动。HTTP 服务重启不会终止已发起的独立模型任务。
|
best_annotator/app.py
CHANGED
|
@@ -320,7 +320,7 @@ def decode_skin_png(value):
|
|
| 320 |
raise ReviewError('请提交有效的 64×64 PNG 皮肤')
|
| 321 |
|
| 322 |
|
| 323 |
-
def make_server(dataset, host, port):
|
| 324 |
class Handler(BaseHTTPRequestHandler):
|
| 325 |
server_version = 'DDJReview/1.0'
|
| 326 |
|
|
@@ -344,6 +344,12 @@ def make_server(dataset, host, port):
|
|
| 344 |
return self.send(200, dataset.state())
|
| 345 |
if request.path == '/api/meat':
|
| 346 |
return self.send(200, dataset.meat.load(parse_qs(request.query).get('key', [''])[0]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
if request.path == '/api/health':
|
| 348 |
return self.send(200, {'status': 'ok', 'sources': len(dataset.records)})
|
| 349 |
if request.path == '/media':
|
|
@@ -374,6 +380,10 @@ def make_server(dataset, host, port):
|
|
| 374 |
body = json.loads(self.rfile.read(length) or b'{}')
|
| 375 |
if not isinstance(body, dict):
|
| 376 |
raise ReviewError('无效请求')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
if self.path == '/api/refresh':
|
| 378 |
dataset.scan()
|
| 379 |
return self.send(200, dataset.state())
|
|
@@ -383,6 +393,7 @@ def make_server(dataset, host, port):
|
|
| 383 |
raise ReviewError('缺少条目编号')
|
| 384 |
if self.path == '/api/meat':
|
| 385 |
item = dataset.meat.save(body)
|
|
|
|
| 386 |
elif self.path in {'/api/perfect', '/api/repair'}:
|
| 387 |
item = dataset.save_annotation(body['key'], body.get('revision'), self.path.rsplit('/', 1)[1], body.get('result'), body.get('png'))
|
| 388 |
elif self.path == '/api/reject':
|
|
@@ -402,10 +413,15 @@ def main():
|
|
| 402 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 403 |
parser.add_argument('--root', type=Path, default=APP_DIR.parent)
|
| 404 |
parser.add_argument('--host', default='127.0.0.1')
|
|
|
|
| 405 |
parser.add_argument('--port', type=int, default=8765)
|
| 406 |
args = parser.parse_args()
|
| 407 |
dataset = Dataset(args.root)
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
print(json.dumps({'url': f'http://{args.host}:{server.server_port}', 'root': str(dataset.root),
|
| 410 |
'stats': dataset.state()['stats']}, ensure_ascii=False), flush=True)
|
| 411 |
try:
|
|
|
|
| 320 |
raise ReviewError('请提交有效的 64×64 PNG 皮肤')
|
| 321 |
|
| 322 |
|
| 323 |
+
def make_server(dataset, host, port, meat_model=None):
|
| 324 |
class Handler(BaseHTTPRequestHandler):
|
| 325 |
server_version = 'DDJReview/1.0'
|
| 326 |
|
|
|
|
| 344 |
return self.send(200, dataset.state())
|
| 345 |
if request.path == '/api/meat':
|
| 346 |
return self.send(200, dataset.meat.load(parse_qs(request.query).get('key', [''])[0]))
|
| 347 |
+
if request.path == '/api/meat-model/status':
|
| 348 |
+
if meat_model is None: raise ReviewError('预选服务尚未配置', 503)
|
| 349 |
+
return self.send(200, meat_model.status())
|
| 350 |
+
if request.path == '/api/meat-model/job':
|
| 351 |
+
if meat_model is None: raise ReviewError('预选服务尚未配置', 503)
|
| 352 |
+
return self.send(200, meat_model.job(parse_qs(request.query).get('id', [''])[0]))
|
| 353 |
if request.path == '/api/health':
|
| 354 |
return self.send(200, {'status': 'ok', 'sources': len(dataset.records)})
|
| 355 |
if request.path == '/media':
|
|
|
|
| 380 |
body = json.loads(self.rfile.read(length) or b'{}')
|
| 381 |
if not isinstance(body, dict):
|
| 382 |
raise ReviewError('无效请求')
|
| 383 |
+
if self.path in {'/api/meat-model/predict', '/api/meat-model/train'}:
|
| 384 |
+
if meat_model is None: raise ReviewError('预选服务尚未配置', 503)
|
| 385 |
+
result = meat_model.train() if self.path.endswith('/train') else meat_model.predict(body)
|
| 386 |
+
return self.send(200, result)
|
| 387 |
if self.path == '/api/refresh':
|
| 388 |
dataset.scan()
|
| 389 |
return self.send(200, dataset.state())
|
|
|
|
| 393 |
raise ReviewError('缺少条目编号')
|
| 394 |
if self.path == '/api/meat':
|
| 395 |
item = dataset.meat.save(body)
|
| 396 |
+
if meat_model is not None: meat_model.cached_at = 0
|
| 397 |
elif self.path in {'/api/perfect', '/api/repair'}:
|
| 398 |
item = dataset.save_annotation(body['key'], body.get('revision'), self.path.rsplit('/', 1)[1], body.get('result'), body.get('png'))
|
| 399 |
elif self.path == '/api/reject':
|
|
|
|
| 413 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 414 |
parser.add_argument('--root', type=Path, default=APP_DIR.parent)
|
| 415 |
parser.add_argument('--host', default='127.0.0.1')
|
| 416 |
+
parser.add_argument('--meat-model-config', type=Path, default=APP_DIR/'meat_model_config.json')
|
| 417 |
parser.add_argument('--port', type=int, default=8765)
|
| 418 |
args = parser.parse_args()
|
| 419 |
dataset = Dataset(args.root)
|
| 420 |
+
model = None
|
| 421 |
+
if args.meat_model_config.exists():
|
| 422 |
+
from meat_model import MeatModel
|
| 423 |
+
model = MeatModel(dataset, ReviewError, json.loads(args.meat_model_config.read_text()), APP_DIR/'.meat_model')
|
| 424 |
+
server = make_server(dataset, args.host, args.port, model)
|
| 425 |
print(json.dumps({'url': f'http://{args.host}:{server.server_port}', 'root': str(dataset.root),
|
| 426 |
'stats': dataset.state()['stats']}, ensure_ascii=False), flush=True)
|
| 427 |
try:
|
best_annotator/deploy/ddj-annotator.service
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[Unit]
|
| 2 |
+
Description=DDJ skin annotation tool (LAN)
|
| 3 |
+
After=network-online.target
|
| 4 |
+
|
| 5 |
+
[Service]
|
| 6 |
+
Type=simple
|
| 7 |
+
WorkingDirectory=/home/ds/llms/SKING_DDJ_Dataset/best_annotator
|
| 8 |
+
Environment=PYTHONUNBUFFERED=1
|
| 9 |
+
ExecStart=/usr/bin/python3 app.py --root /home/ds/llms/SKING_DDJ_Dataset --host 192.168.0.111 --port 8765
|
| 10 |
+
Restart=on-failure
|
| 11 |
+
RestartSec=3
|
| 12 |
+
# Model workers have durable job state and must survive HTTP server restarts.
|
| 13 |
+
KillMode=process
|
| 14 |
+
TimeoutStopSec=15
|
| 15 |
+
|
| 16 |
+
[Install]
|
| 17 |
+
WantedBy=default.target
|
best_annotator/meat_annotations.py
CHANGED
|
@@ -159,6 +159,14 @@ class MeatAnnotations:
|
|
| 159 |
mask_sha256=digest(png),model=current['model'],selected=chosen,selected_count=len(chosen),
|
| 160 |
encoding={'meat':255,'non_meat':0,'invalid':'ignore using original skin alpha and UV layout'},
|
| 161 |
complete=True,updated_at=datetime.now(timezone.utc).isoformat())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
files,previous_revision=self.read_files(r);paths=self.paths(r)
|
| 163 |
if any(b is not None for b in files):
|
| 164 |
archive=r['source'].parent/'.meat_history'/r['id']/uuid4().hex
|
|
|
|
| 159 |
mask_sha256=digest(png),model=current['model'],selected=chosen,selected_count=len(chosen),
|
| 160 |
encoding={'meat':255,'non_meat':0,'invalid':'ignore using original skin alpha and UV layout'},
|
| 161 |
complete=True,updated_at=datetime.now(timezone.utc).isoformat())
|
| 162 |
+
assistance=body.get('assistance')
|
| 163 |
+
if assistance is not None:
|
| 164 |
+
if not isinstance(assistance,dict) or not isinstance(assistance.get('model_id'),str) or len(assistance['model_id'])>120:
|
| 165 |
+
raise self.Error('预选来源格式无效')
|
| 166 |
+
ck=assistance.get('checkpoint_sha256','')
|
| 167 |
+
if not isinstance(ck,str) or len(ck)!=64 or any(c not in '0123456789abcdef' for c in ck):raise self.Error('预选来源校验无效')
|
| 168 |
+
metadata['assistance']={'model_id':assistance['model_id'],'checkpoint_sha256':ck,'human_saved':True,
|
| 169 |
+
'note':'Model suggestions were available; final selection explicitly saved by user.'}
|
| 170 |
files,previous_revision=self.read_files(r);paths=self.paths(r)
|
| 171 |
if any(b is not None for b in files):
|
| 172 |
archive=r['source'].parent/'.meat_history'/r['id']/uuid4().hex
|
best_annotator/meat_model.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local annotation API -> SSH worker. No prediction is a human label until Save."""
|
| 2 |
+
import base64
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import shlex
|
| 6 |
+
import subprocess
|
| 7 |
+
import struct
|
| 8 |
+
import zlib
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
from uuid import uuid4
|
| 12 |
+
|
| 13 |
+
from meat_annotations import digest, decode_rgba, skin_parts, encode_mask
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MeatModel:
|
| 17 |
+
def __init__(self, dataset, error, config, runtime):
|
| 18 |
+
self.ds, self.Error = dataset, error
|
| 19 |
+
self.config = config
|
| 20 |
+
self.runtime = Path(runtime); self.runtime.mkdir(parents=True, exist_ok=True)
|
| 21 |
+
self.lock = threading.RLock()
|
| 22 |
+
self.cached = None; self.cached_at = 0
|
| 23 |
+
|
| 24 |
+
def remote(self, command, body=None):
|
| 25 |
+
c=self.config
|
| 26 |
+
args=[c['python'],c['root']+'/model_service.py',command,'--state',c['state']]
|
| 27 |
+
if c.get('transport') == 'local':
|
| 28 |
+
cmd=args
|
| 29 |
+
else:
|
| 30 |
+
cmd=['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','-o','ServerAliveInterval=10',c['host'],shlex.join(args)]
|
| 31 |
+
try:
|
| 32 |
+
p=subprocess.run(cmd,input=json.dumps(body or {}),text=True,capture_output=True,timeout=45)
|
| 33 |
+
except (OSError,subprocess.TimeoutExpired):
|
| 34 |
+
raise self.Error('无法连接 ds 预选服务。人工标注仍可使用,请稍后重试。',503)
|
| 35 |
+
try: result=json.loads(p.stdout)
|
| 36 |
+
except ValueError: raise self.Error('ds 预选服务未返回有效结果,人工标注不受影响。',503)
|
| 37 |
+
if p.returncode or 'error' in result:raise self.Error(result.get('error','预选服务请求失败'),409)
|
| 38 |
+
return result
|
| 39 |
+
|
| 40 |
+
def snapshot(self, include_bytes=False):
|
| 41 |
+
examples=[];excluded=[]
|
| 42 |
+
with self.ds.lock:
|
| 43 |
+
for r in self.ds.records.values():
|
| 44 |
+
paths=self.ds.meat.paths(r)
|
| 45 |
+
if not any(p.exists() for p in paths):continue
|
| 46 |
+
try:
|
| 47 |
+
skin_path,skin,_=self.ds.meat.effective_skin(r)
|
| 48 |
+
files,_=self.ds.meat.read_files(r);mask,mb=files
|
| 49 |
+
if mask is None or mb is None:raise ValueError('标注文件不完整')
|
| 50 |
+
meta=json.loads(mb)
|
| 51 |
+
assert meta.get('complete') is True and meta.get('schema')=='mc-meat-v1','标注未完成'
|
| 52 |
+
assert meta['skin_file']==skin_path.name and meta['skin_sha256']==digest(skin),'皮肤已变化'
|
| 53 |
+
assert meta['mask_sha256']==digest(mask),'标签校验失败'
|
| 54 |
+
raw=decode_rgba(skin);_,valid,model=skin_parts(raw)
|
| 55 |
+
selected=meta['selected']
|
| 56 |
+
assert model=='classic','当前预选模型暂不支持纤细手臂'
|
| 57 |
+
assert set(raw[3::4]) <= {0,255},'当前预选模型暂不支持半透明皮肤'
|
| 58 |
+
assert isinstance(selected,list) and all(type(i) is int and 0<=i<4096 and valid[i] for i in selected),'无效选区'
|
| 59 |
+
assert len(set(selected))==len(selected) and meta['selected_count']==len(selected),'选区数量不符'
|
| 60 |
+
assert meta['id']==r['id'] and meta['model']==model and encode_mask(selected)==mask,'标签内容不一致'
|
| 61 |
+
e=dict(id=r['id'],skin_sha256=digest(skin),mask_sha256=digest(mask),key=r['key'],
|
| 62 |
+
source_skin=str(skin_path.relative_to(self.ds.root)),source_annotation=str(paths[1].relative_to(self.ds.root)))
|
| 63 |
+
if include_bytes:e.update(skin=base64.b64encode(skin).decode(),mask=base64.b64encode(mask).decode(),metadata=base64.b64encode(mb).decode())
|
| 64 |
+
examples.append(e)
|
| 65 |
+
except (self.Error,ValueError,AssertionError,KeyError,TypeError,OSError,struct.error,zlib.error) as e:
|
| 66 |
+
excluded.append(dict(id=r['id'],reason=str(e) or '标注无效'))
|
| 67 |
+
examples.sort(key=lambda r:r['key'])
|
| 68 |
+
signature=[(r['key'],r['skin_sha256'],r['mask_sha256']) for r in examples]
|
| 69 |
+
return dict(examples=examples,excluded=excluded,fingerprint=digest(json.dumps(signature,sort_keys=True).encode()),
|
| 70 |
+
dataset_root=str(self.ds.root),dataset_commit='saved-working-tree')
|
| 71 |
+
|
| 72 |
+
def status(self):
|
| 73 |
+
with self.lock:
|
| 74 |
+
if self.cached is not None and time.monotonic()-self.cached_at<5:return self.cached
|
| 75 |
+
remote=self.remote('status');snap=self.snapshot()
|
| 76 |
+
active=remote.get('active') or {};old={(r['id'],r['skin_sha256'],r['mask_sha256']) for r in active.get('examples',[])}
|
| 77 |
+
new={(r['id'],r['skin_sha256'],r['mask_sha256']) for r in snap['examples']}
|
| 78 |
+
remote['dataset']=dict(count=len(snap['examples']),excluded=snap['excluded'],changed=len(new-old),removed=len({r[0] for r in old}-{r[0] for r in new}))
|
| 79 |
+
self.cached=remote;self.cached_at=time.monotonic()
|
| 80 |
+
return remote
|
| 81 |
+
|
| 82 |
+
def predict(self, body):
|
| 83 |
+
with self.ds.lock:
|
| 84 |
+
current=self.ds.meat.load(body.get('key'))
|
| 85 |
+
if current['skin_revision']!=body.get('skin_revision'):raise self.Error('皮肤已变化,请重新打开标注器',409)
|
| 86 |
+
if current['model']!='classic':raise self.Error('预选模型目前只支持标准手臂;此皮肤请继续人工标注。',409)
|
| 87 |
+
raw=base64.b64decode(current['rgba'])
|
| 88 |
+
if not set(raw[3::4]) <= {0,255}:raise self.Error('预选模型暂不支持半透明皮肤;请继续人工标注。',409)
|
| 89 |
+
_,skin,_=self.ds.meat.effective_skin(self.ds.records[current['key']])
|
| 90 |
+
ident=uuid4().hex
|
| 91 |
+
self.ds.write_bytes(self.runtime/(ident+'.json'),json.dumps(dict(key=current['key'],skin_revision=current['skin_revision'])).encode())
|
| 92 |
+
result=self.remote('start_predict',dict(request_id=ident,skin=base64.b64encode(skin).decode(),skin_revision=current['skin_revision']))
|
| 93 |
+
return result
|
| 94 |
+
|
| 95 |
+
def train(self):
|
| 96 |
+
with self.lock:
|
| 97 |
+
# Remote also locks/checks this, so browser retries or multiple local clients cannot double-launch.
|
| 98 |
+
current=self.remote('status').get('training')
|
| 99 |
+
if current and current['stage'] not in {'complete','failed'}:return current
|
| 100 |
+
bundle=self.snapshot(True)
|
| 101 |
+
if len(bundle['examples'])<3:raise self.Error('至少需要 3 张有效、已保存的标准手臂人工标注。',409)
|
| 102 |
+
if len({r['id'] for r in bundle['examples']})!=len(bundle['examples']):raise self.Error('存在重复皮肤 ID,请先消除歧义。',409)
|
| 103 |
+
result=self.remote('start_train',dict(request_id=uuid4().hex,bundle=bundle))
|
| 104 |
+
self.cached_at=0
|
| 105 |
+
return result
|
| 106 |
+
|
| 107 |
+
def job(self, ident):
|
| 108 |
+
if len(ident)!=32 or any(c not in '0123456789abcdef' for c in ident):raise self.Error('无效任务编号')
|
| 109 |
+
path=self.runtime/(ident+'.json')
|
| 110 |
+
if not path.exists():raise self.Error('此预选任务不属于当前标注服务',404)
|
| 111 |
+
info=json.loads(path.read_text());result=self.remote('job',dict(id=ident))
|
| 112 |
+
if result['stage']=='complete':
|
| 113 |
+
with self.ds.lock:
|
| 114 |
+
current=self.ds.meat.load(info['key'])
|
| 115 |
+
pred=result['prediction']
|
| 116 |
+
if current['skin_revision']!=info['skin_revision'] or pred['skin_revision']!=info['skin_revision']:
|
| 117 |
+
raise self.Error('皮肤已变化,已丢弃旧预选结果,请重新打开。',409)
|
| 118 |
+
valid=base64.b64decode(current['valid'])
|
| 119 |
+
if any(type(i) is not int or not 0<=i<4096 or not valid[i] for i in pred['selected']):raise self.Error('模型返回了无效格子',409)
|
| 120 |
+
return result
|
best_annotator/meat_model_config.example.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"host": "ds@192.168.0.111",
|
| 3 |
+
"python": "/home/ds/miniconda3/envs/qwen-image-train/bin/python",
|
| 4 |
+
"root": "/home/ds/llms/github/mc_meat",
|
| 5 |
+
"state": "/home/ds/llms/github/mc_meat/service_runtime/production"
|
| 6 |
+
}
|
best_annotator/src/MeatEditor.jsx
CHANGED
|
@@ -2,51 +2,59 @@ import React, { useEffect, useMemo, useRef, useState } from "react";
|
|
| 2 |
import { Canvas, useFrame, useThree } from "@react-three/fiber";
|
| 3 |
import { OrbitControls } from "@react-three/drei";
|
| 4 |
import * as THREE from "three";
|
| 5 |
-
import { applySelection, buildMeatGeometry, makePulseMaterial } from "./meatGeometry";
|
|
|
|
| 6 |
import "./meat.css";
|
|
|
|
| 7 |
|
| 8 |
const bytes = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
| 9 |
const initialMask = (selected) => { const a = new Uint8Array(4096); selected.forEach(i => a[i] = 1); return a; };
|
| 10 |
|
| 11 |
-
function Part({ part, rgba, mask, pulse,
|
| 12 |
const geometry = useMemo(() => buildMeatGeometry(part, rgba), [part, rgba]);
|
| 13 |
const material = useMemo(() => makePulseMaterial(pulse), [pulse]);
|
| 14 |
useEffect(() => { applySelection(geometry, mask); }, [geometry, mask]);
|
| 15 |
useEffect(() => () => { geometry.dispose(); material.dispose(); }, [geometry, material]);
|
| 16 |
-
const hit = (e,
|
| 17 |
e.stopPropagation();
|
| 18 |
const id = geometry.userData.triangleIds[e.faceIndex];
|
| 19 |
if (id === undefined) return;
|
| 20 |
hover(id);
|
| 21 |
-
if
|
|
|
|
| 22 |
};
|
| 23 |
return <mesh geometry={geometry} material={material} position={part.center}
|
| 24 |
-
onPointerDown={e => hit(e,
|
| 25 |
}
|
| 26 |
|
| 27 |
-
function Scene({ data, rgba, mask, layer, animate, view,
|
| 28 |
const pulse = useMemo(() => ({ value: .6 }), []), controls = useRef();
|
| 29 |
const { camera } = useThree();
|
| 30 |
useFrame(({ clock }) => { pulse.value = animate ? .48 + .28 * Math.sin(clock.elapsedTime * Math.PI) : .6; });
|
| 31 |
useEffect(() => {
|
| 32 |
const poses = { angle:[30,22,38], front:[0,0,48], back:[0,0,-48], left:[48,0,0], right:[-48,0,0], top:[0,50,.01], bottom:[0,-52,.01] };
|
| 33 |
camera.position.set(...poses[view]); camera.lookAt(0,-2,0); controls.current?.update();
|
| 34 |
-
}, [view, camera]);
|
| 35 |
return <>
|
| 36 |
{data.parts.filter(p => layer === "both" || p.layer === (layer === "inner" ? 0 : 1)).map(p =>
|
| 37 |
-
<Part key={p.name+p.layer} part={p} rgba={rgba} mask={mask} pulse={pulse}
|
| 38 |
-
<OrbitControls ref={controls} target={[0,-2,0]} mouseButtons={{ LEFT:
|
| 39 |
</>;
|
| 40 |
}
|
| 41 |
|
| 42 |
-
export default function MeatEditor({ data, busy, onSave, onDirty }) {
|
|
|
|
|
|
|
| 43 |
const rgba = useMemo(() => bytes(data.rgba), [data.rgba]), valid = useMemo(() => bytes(data.valid), [data.valid]);
|
| 44 |
const initial = useMemo(() => initialMask(data.selected), [data]);
|
| 45 |
const [mask, setMask] = useState(initial), current = useRef(initial);
|
| 46 |
-
const [mode, setMode] = useState("
|
|
|
|
|
|
|
|
|
|
| 47 |
const [animate,setAnimate] = useState(!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
|
| 48 |
const [hover,setHover] = useState(null), [history,setHistory] = useState({ entries:[initial], index:0 });
|
| 49 |
-
const stroke = useRef(null), uvCanvas = useRef(null), maskRef = useRef(mask);
|
| 50 |
const counts = useMemo(() => ({ selected:mask.reduce((a,b)=>a+b,0), valid:valid.reduce((a,b)=>a+b,0) }), [mask,valid]);
|
| 51 |
const dirty = mask.some((v,i)=>v!==initial[i]);
|
| 52 |
const layerIds = useMemo(() => {
|
|
@@ -58,18 +66,29 @@ export default function MeatEditor({ data, busy, onSave, onDirty }) {
|
|
| 58 |
const update = (m) => { current.current=m; maskRef.current=m; setMask(m); };
|
| 59 |
const finish = () => {
|
| 60 |
if (!stroke.current) return;
|
| 61 |
-
if (current.current.some((v,i)=>v!==stroke.current[i])) {
|
| 62 |
setHistory(h => { const entries=[...h.entries.slice(0,h.index+1),current.current].slice(-60); return {entries,index:entries.length-1}; });
|
| 63 |
}
|
| 64 |
stroke.current=null;
|
| 65 |
};
|
| 66 |
-
const paint = (id,down=false) => {
|
| 67 |
if (busy || !valid[id] || !layerIds[id]) return;
|
| 68 |
-
if(down
|
|
|
|
|
|
|
|
|
|
| 69 |
if(!stroke.current)return;
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
};
|
| 74 |
useEffect(() => { onDirty(dirty); }, [dirty,onDirty]);
|
| 75 |
useEffect(() => { window.addEventListener("pointerup",finish); window.addEventListener("pointercancel",finish); window.addEventListener("blur",finish); return ()=>{window.removeEventListener("pointerup",finish);window.removeEventListener("pointercancel",finish);window.removeEventListener("blur",finish);}; }, []);
|
|
@@ -103,29 +122,43 @@ export default function MeatEditor({ data, busy, onSave, onDirty }) {
|
|
| 103 |
const r=e.currentTarget.getBoundingClientRect(),x=Math.floor((e.clientX-r.left)/r.width*64),y=Math.floor((e.clientY-r.top)/r.height*64);
|
| 104 |
if(x<0||x>=64||y<0||y>=64)return;
|
| 105 |
const id=y*64+x;setHover(id);
|
| 106 |
-
if(e.buttons===1
|
|
|
|
|
|
|
|
|
|
| 107 |
};
|
| 108 |
return <div className="meat-editor">
|
| 109 |
<p className="meat-definition">meat:脸、眼睛、嘴巴和裸露身体。头发、胡须、眼镜、帽子、衣物和饰品不选。内外层分别标注。</p>
|
| 110 |
{data.meat_status==="stale"&&<p className="meat-warning">perfect 皮肤已变化,本次从空白标注开始;旧标注会在保存时归档。</p>}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
<div className="meat-toolbar">
|
| 112 |
-
<div role="group" aria-label="标注方式"><button className={mode==="
|
|
|
|
| 113 |
<label>查看图层 <select value={layer} onChange={e=>setLayer(e.target.value)}><option value="both">内层+外层</option><option value="inner">仅内层</option><option value="outer">仅外层</option></select></label>
|
| 114 |
<button disabled={busy||history.index===0} onClick={()=>undo(-1)}>撤销</button><button disabled={busy||history.index===history.entries.length-1} onClick={()=>undo(1)}>重做</button>
|
| 115 |
<label><input type="checkbox" checked={animate} onChange={e=>setAnimate(e.target.checked)}/>呼吸高亮</label>
|
| 116 |
</div>
|
| 117 |
<div className="meat-workspace">
|
| 118 |
-
<section><h3>3D 选
|
| 119 |
-
<div className="meat-views">{Object.entries({angle:"斜视",front:"正面",back:"背面",left:"左侧",right:"右侧",top:"头顶",bottom:"底部"}).map(([k,v])=><button key={k} className={view===k?"active":""} onClick={()=>setView(k)}>{v}</button>)}</div>
|
| 120 |
-
<div className="meat-stage" onContextMenu={e=>e.preventDefault()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
</section>
|
| 122 |
<section><h3>UV 逐格选择 <small>{hover===null?"可标注被遮住的表面":`UV (${hover%64}, ${Math.floor(hover/64)})`}</small></h3>
|
| 123 |
-
<canvas className="meat-uv" aria-label="64×64 meat UV 标注" width={512} height={512} ref={uvCanvas} onPointerDown={e=>uvHit(e,true)} onPointerMove={e=>uvHit(e,false)} onPointerUp={finish} />
|
| 124 |
</section>
|
| 125 |
</div>
|
|
|
|
| 126 |
<footer className="meat-footer"><span aria-live="polite">已选 {counts.selected} / {counts.valid} 格{dirty?" · 未保存":""}<small>保存为 {data.id}_meat.png;未选择的有效格为非 meat。</small></span>
|
| 127 |
-
<button className="button secondary" disabled={busy} onClick={()=>{finish();onSave(Array.from(current.current.keys()).filter(i=>current.current[i]),false);}}>保存 meat</button>
|
| 128 |
-
<button className="button" disabled={busy} onClick={()=>{finish();onSave(Array.from(current.current.keys()).filter(i=>current.current[i]),true);}}>保存并标注下一张</button>
|
| 129 |
</footer>
|
| 130 |
</div>;
|
| 131 |
}
|
|
|
|
| 2 |
import { Canvas, useFrame, useThree } from "@react-three/fiber";
|
| 3 |
import { OrbitControls } from "@react-three/drei";
|
| 4 |
import * as THREE from "three";
|
| 5 |
+
import { applySelection, buildMeatGeometry, buildSurfaceAdjacency, makePulseMaterial } from "./meatGeometry";
|
| 6 |
+
import { beginGesture, moveGesture, canPick, floodCells } from "./meatSelection";
|
| 7 |
import "./meat.css";
|
| 8 |
+
import { MeatPreselect } from "./MeatModel";
|
| 9 |
|
| 10 |
const bytes = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
| 11 |
const initialMask = (selected) => { const a = new Uint8Array(4096); selected.forEach(i => a[i] = 1); return a; };
|
| 12 |
|
| 13 |
+
function Part({ part, rgba, mask, pulse, pickDown, pickUp, hover }) {
|
| 14 |
const geometry = useMemo(() => buildMeatGeometry(part, rgba), [part, rgba]);
|
| 15 |
const material = useMemo(() => makePulseMaterial(pulse), [pulse]);
|
| 16 |
useEffect(() => { applySelection(geometry, mask); }, [geometry, mask]);
|
| 17 |
useEffect(() => () => { geometry.dispose(); material.dispose(); }, [geometry, material]);
|
| 18 |
+
const hit = (e, action) => {
|
| 19 |
e.stopPropagation();
|
| 20 |
const id = geometry.userData.triangleIds[e.faceIndex];
|
| 21 |
if (id === undefined) return;
|
| 22 |
hover(id);
|
| 23 |
+
if(action==="down")pickDown(id);
|
| 24 |
+
if(action==="up")pickUp();
|
| 25 |
};
|
| 26 |
return <mesh geometry={geometry} material={material} position={part.center}
|
| 27 |
+
onPointerDown={e => hit(e, "down")} onPointerMove={e => hit(e, "hover")} onPointerUp={e=>hit(e,"up")} />;
|
| 28 |
}
|
| 29 |
|
| 30 |
+
function Scene({ data, rgba, mask, layer, animate, view, viewEpoch, pickDown, pickUp, hover }) {
|
| 31 |
const pulse = useMemo(() => ({ value: .6 }), []), controls = useRef();
|
| 32 |
const { camera } = useThree();
|
| 33 |
useFrame(({ clock }) => { pulse.value = animate ? .48 + .28 * Math.sin(clock.elapsedTime * Math.PI) : .6; });
|
| 34 |
useEffect(() => {
|
| 35 |
const poses = { angle:[30,22,38], front:[0,0,48], back:[0,0,-48], left:[48,0,0], right:[-48,0,0], top:[0,50,.01], bottom:[0,-52,.01] };
|
| 36 |
camera.position.set(...poses[view]); camera.lookAt(0,-2,0); controls.current?.update();
|
| 37 |
+
}, [view, viewEpoch, camera]);
|
| 38 |
return <>
|
| 39 |
{data.parts.filter(p => layer === "both" || p.layer === (layer === "inner" ? 0 : 1)).map(p =>
|
| 40 |
+
<Part key={p.name+p.layer} part={p} rgba={rgba} mask={mask} pulse={pulse} pickDown={pickDown} pickUp={pickUp} hover={hover} />)}
|
| 41 |
+
<OrbitControls ref={controls} target={[0,-2,0]} enablePan={false} enableDamping={false} mouseButtons={{ LEFT:THREE.MOUSE.ROTATE, MIDDLE:THREE.MOUSE.DOLLY, RIGHT:THREE.MOUSE.ROTATE }} minDistance={10} maxDistance={100} />
|
| 42 |
</>;
|
| 43 |
}
|
| 44 |
|
| 45 |
+
export default function MeatEditor({ data, busy: saving, onSave, onDirty }) {
|
| 46 |
+
const [predicting,setPredicting]=useState(false), [assistance,setAssistance]=useState(null);
|
| 47 |
+
const busy=saving||predicting;
|
| 48 |
const rgba = useMemo(() => bytes(data.rgba), [data.rgba]), valid = useMemo(() => bytes(data.valid), [data.valid]);
|
| 49 |
const initial = useMemo(() => initialMask(data.selected), [data]);
|
| 50 |
const [mask, setMask] = useState(initial), current = useRef(initial);
|
| 51 |
+
const [mode, setMode] = useState("toggle"), [layer, setLayer] = useState("both"), [view,setView] = useState("angle");
|
| 52 |
+
const [tolerance,setTolerance] = useState(12);
|
| 53 |
+
const [viewEpoch,setViewEpoch] = useState(0);
|
| 54 |
+
const neighbors = useMemo(()=>buildSurfaceAdjacency(data.parts,rgba),[data.parts,rgba]);
|
| 55 |
const [animate,setAnimate] = useState(!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
|
| 56 |
const [hover,setHover] = useState(null), [history,setHistory] = useState({ entries:[initial], index:0 });
|
| 57 |
+
const stroke = useRef(null), uvCanvas = useRef(null), maskRef = useRef(mask), gesture = useRef(null);
|
| 58 |
const counts = useMemo(() => ({ selected:mask.reduce((a,b)=>a+b,0), valid:valid.reduce((a,b)=>a+b,0) }), [mask,valid]);
|
| 59 |
const dirty = mask.some((v,i)=>v!==initial[i]);
|
| 60 |
const layerIds = useMemo(() => {
|
|
|
|
| 66 |
const update = (m) => { current.current=m; maskRef.current=m; setMask(m); };
|
| 67 |
const finish = () => {
|
| 68 |
if (!stroke.current) return;
|
| 69 |
+
if (current.current.some((v,i)=>v!==stroke.current.before[i])) {
|
| 70 |
setHistory(h => { const entries=[...h.entries.slice(0,h.index+1),current.current].slice(-60); return {entries,index:entries.length-1}; });
|
| 71 |
}
|
| 72 |
stroke.current=null;
|
| 73 |
};
|
| 74 |
+
const paint = (id,down=false,ctrl=false) => {
|
| 75 |
if (busy || !valid[id] || !layerIds[id]) return;
|
| 76 |
+
if(down) {
|
| 77 |
+
finish();
|
| 78 |
+
stroke.current={before:current.current,value:mode==="erase"?0:1-current.current[id],flood:ctrl};
|
| 79 |
+
}
|
| 80 |
if(!stroke.current)return;
|
| 81 |
+
if(!down && stroke.current.flood)return;
|
| 82 |
+
const value=stroke.current.value;
|
| 83 |
+
const ids=ctrl&&down ? floodCells(id,rgba,valid,layerIds,neighbors,tolerance) : [id];
|
| 84 |
+
if(ids.every(i=>current.current[i]===value))return;
|
| 85 |
+
const m=current.current.slice();ids.forEach(i=>m[i]=value);update(m);
|
| 86 |
+
};
|
| 87 |
+
const pickDown = id => { if(gesture.current)gesture.current.id=id; };
|
| 88 |
+
const pickUp = () => {
|
| 89 |
+
const g=gesture.current;
|
| 90 |
+
if(canPick(g)){paint(g.id,true,g.ctrl);finish();}
|
| 91 |
+
if(g)g.cancelled=true;
|
| 92 |
};
|
| 93 |
useEffect(() => { onDirty(dirty); }, [dirty,onDirty]);
|
| 94 |
useEffect(() => { window.addEventListener("pointerup",finish); window.addEventListener("pointercancel",finish); window.addEventListener("blur",finish); return ()=>{window.removeEventListener("pointerup",finish);window.removeEventListener("pointercancel",finish);window.removeEventListener("blur",finish);}; }, []);
|
|
|
|
| 122 |
const r=e.currentTarget.getBoundingClientRect(),x=Math.floor((e.clientX-r.left)/r.width*64),y=Math.floor((e.clientY-r.top)/r.height*64);
|
| 123 |
if(x<0||x>=64||y<0||y>=64)return;
|
| 124 |
const id=y*64+x;setHover(id);
|
| 125 |
+
if(e.buttons===1 || (down&&e.ctrlKey&&e.button===2)){
|
| 126 |
+
if(down)e.currentTarget.setPointerCapture(e.pointerId);
|
| 127 |
+
paint(id,down,e.ctrlKey);
|
| 128 |
+
}
|
| 129 |
};
|
| 130 |
return <div className="meat-editor">
|
| 131 |
<p className="meat-definition">meat:脸、眼睛、嘴巴和裸露身体。头发、胡须、眼镜、帽子、衣物和饰品不选。内外层分别标注。</p>
|
| 132 |
{data.meat_status==="stale"&&<p className="meat-warning">perfect 皮肤已变化,本次从空白标注开始;旧标注会在保存时归档。</p>}
|
| 133 |
+
<MeatPreselect data={data} disabled={busy} onStart={()=>{finish();setPredicting(true);}} onEnd={()=>setPredicting(false)} onApply={p=>{
|
| 134 |
+
const next=initialMask(p.selected);update(next);setHistory(h=>{const entries=[...h.entries.slice(0,h.index+1),next].slice(-60);return {entries,index:entries.length-1};});
|
| 135 |
+
setAssistance({model_id:p.model_id,checkpoint_sha256:p.checkpoint_sha256});
|
| 136 |
+
}}/>
|
| 137 |
<div className="meat-toolbar">
|
| 138 |
+
<div role="group" aria-label="标注方式"><button className={mode==="toggle"?"active":""} onClick={()=>setMode("toggle")}>点击切换选中</button><button className={mode==="erase"?"active":""} onClick={()=>setMode("erase")}>擦除</button></div>
|
| 139 |
+
<label className="meat-tolerance">颜色容差 <input aria-label="泛洪颜色容差" type="range" min="0" max="100" step="1" value={tolerance} onChange={e=>setTolerance(Number(e.target.value))}/><output>{tolerance}%</output></label>
|
| 140 |
<label>查看图层 <select value={layer} onChange={e=>setLayer(e.target.value)}><option value="both">内层+外层</option><option value="inner">仅内层</option><option value="outer">仅外层</option></select></label>
|
| 141 |
<button disabled={busy||history.index===0} onClick={()=>undo(-1)}>撤销</button><button disabled={busy||history.index===history.entries.length-1} onClick={()=>undo(1)}>重做</button>
|
| 142 |
<label><input type="checkbox" checked={animate} onChange={e=>setAnimate(e.target.checked)}/>呼吸高亮</label>
|
| 143 |
</div>
|
| 144 |
<div className="meat-workspace">
|
| 145 |
+
<section><h3>3D 选��� <small>拖拽旋转 · 点击切换 · Ctrl+点击泛洪 · 滚轮缩放</small></h3>
|
| 146 |
+
<div className="meat-views">{Object.entries({angle:"斜视",front:"正面",back:"背面",left:"左侧",right:"右侧",top:"头顶",bottom:"底部"}).map(([k,v])=><button key={k} className={view===k?"active":""} onClick={()=>{setView(k);setViewEpoch(n=>n+1);}}>{v}</button>)}</div>
|
| 147 |
+
<div className="meat-stage" onContextMenu={e=>e.preventDefault()}
|
| 148 |
+
onPointerDownCapture={e=>{if(e.isPrimary===false){if(gesture.current)gesture.current.cancelled=true;}else gesture.current=beginGesture(e);}}
|
| 149 |
+
onPointerMoveCapture={e=>moveGesture(gesture.current,e)} onPointerUpCapture={e=>moveGesture(gesture.current,e)}
|
| 150 |
+
onPointerCancelCapture={()=>{if(gesture.current)gesture.current.cancelled=true;}}>
|
| 151 |
+
<Canvas camera={{position:[30,22,38],fov:43}}><Scene data={data} rgba={rgba} mask={mask} layer={layer} animate={animate} view={view} viewEpoch={viewEpoch} pickDown={pickDown} pickUp={pickUp} hover={setHover}/></Canvas>
|
| 152 |
+
</div>
|
| 153 |
</section>
|
| 154 |
<section><h3>UV 逐格选择 <small>{hover===null?"可标注被遮住的表面":`UV (${hover%64}, ${Math.floor(hover/64)})`}</small></h3>
|
| 155 |
+
<canvas className="meat-uv" aria-label="64×64 meat UV 标注" width={512} height={512} ref={uvCanvas} onContextMenu={e=>e.preventDefault()} onPointerDown={e=>uvHit(e,true)} onPointerMove={e=>uvHit(e,false)} onPointerUp={finish} />
|
| 156 |
</section>
|
| 157 |
</div>
|
| 158 |
+
<p className="meat-help">Ctrl+点击:沿同一部件、同一层的相连表面选择近似颜色;已选区域再次点击即可取消,Ctrl+点击已选格可批量取消。容差越大,包含颜色越多。UV 图可按住左键连续涂选或擦除。</p>
|
| 159 |
<footer className="meat-footer"><span aria-live="polite">已选 {counts.selected} / {counts.valid} 格{dirty?" · 未保存":""}<small>保存为 {data.id}_meat.png;未选择的有效格为非 meat。</small></span>
|
| 160 |
+
<button className="button secondary" disabled={busy} onClick={()=>{finish();onSave(Array.from(current.current.keys()).filter(i=>current.current[i]),false,assistance);}}>保存 meat</button>
|
| 161 |
+
<button className="button" disabled={busy} onClick={()=>{finish();onSave(Array.from(current.current.keys()).filter(i=>current.current[i]),true,assistance);}}>保存并标注下一张</button>
|
| 162 |
</footer>
|
| 163 |
</div>;
|
| 164 |
}
|
best_annotator/src/MeatModel.jsx
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import React, { useEffect, useRef, useState } from "react";
|
| 2 |
+
|
| 3 |
+
export async function modelAPI(path, body, signal) {
|
| 4 |
+
const r = await fetch('/api/meat-model/' + path, body === undefined ? {signal} : {
|
| 5 |
+
method:'POST', headers:{'Content-Type':'application/json','X-Annotation-Client':'ddj-review'},
|
| 6 |
+
body:JSON.stringify(body), signal
|
| 7 |
+
});
|
| 8 |
+
const d=await r.json();if(!r.ok)throw Error(d.error || '预选服务暂不可用');return d;
|
| 9 |
+
}
|
| 10 |
+
const terminal=s=>['complete','failed'].includes(s);
|
| 11 |
+
export function stageText(job) {
|
| 12 |
+
const names={queued:'等待启动',validating:'检查人工标签',waiting_gpu:'等待特征提取',features:'提取图像特征',
|
| 13 |
+
training:'训练与交叉验证',verifying:'核验并更新模型',predicting:'正在识别 meat',complete:'已完成',failed:'失败'};
|
| 14 |
+
const p=job?.progress;
|
| 15 |
+
return (names[job?.stage] || '正在预选') + (p?.fold ? ` · ${p.variant==='local'?'局部特征':'DINO+局部特征'} ${p.fold}/${p.total} 组` : p?.remaining ? ` · 剩余 ${p.remaining} 张` : p?.stage==='final_fit' ? ' · 拟合最终模型' : '');
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
export function MeatModelPanel() {
|
| 19 |
+
const [state,setState]=useState(null),[error,setError]=useState(''),[starting,setStarting]=useState(false);
|
| 20 |
+
const mounted=useRef(true),timer=useRef(null),locked=useRef(false);
|
| 21 |
+
const refresh=async()=>{
|
| 22 |
+
try { const s=await modelAPI('status');if(mounted.current){setState(s);setError('');} }
|
| 23 |
+
catch(e){if(mounted.current)setError(e.message);}
|
| 24 |
+
};
|
| 25 |
+
useEffect(()=>{
|
| 26 |
+
mounted.current=true;refresh();
|
| 27 |
+
const update=()=>refresh();window.addEventListener('meat-saved',update);
|
| 28 |
+
timer.current=setInterval(refresh,10000);
|
| 29 |
+
return()=>{mounted.current=false;clearInterval(timer.current);window.removeEventListener('meat-saved',update);};
|
| 30 |
+
},[]);
|
| 31 |
+
const running=state?.training&&!terminal(state.training.stage);
|
| 32 |
+
const train=async()=>{
|
| 33 |
+
if(locked.current)return;locked.current=true;setStarting(true);setError('');
|
| 34 |
+
try { const j=await modelAPI('train',{});if(mounted.current)setState(s=>({...s,training:j})); }
|
| 35 |
+
catch(e){if(mounted.current)setError(e.message);}
|
| 36 |
+
finally{locked.current=false;if(mounted.current){setStarting(false);refresh();}}
|
| 37 |
+
};
|
| 38 |
+
return <section className="meat-model-panel" aria-label="Meat 预选模型">
|
| 39 |
+
<div><strong>Meat 预选模型</strong><span>{state?.active ? ` ${state.active.id} · 已学习 ${state.active.count} 张` : ' 正在连接 ds…'}</span>
|
| 40 |
+
<p>仅在点击按钮时训练;保存标注不会自动更新模型。训练期间仍使用当前模型。</p>
|
| 41 |
+
{state?.dataset&&<p>当前可训练 {state.dataset.count} 张 · 新增或修改 {state.dataset.changed} 张{state.dataset.removed>0?` · 移除或失效 ${state.dataset.removed} 张`:''}</p>}
|
| 42 |
+
</div>
|
| 43 |
+
<div className="meat-model-actions"><button className="button" onClick={train} disabled={starting||running||!state?.active||state?.dataset?.count<3}>{starting?'正在启动…':running?'训练进行中…':'训练并更新预选模型'}</button>
|
| 44 |
+
<button className="button secondary" onClick={refresh}>刷新模型状态</button></div>
|
| 45 |
+
{state?.training&&<p role="status">{stageText(state.training)}{state.training.stage==='complete'?' · 新模型已启用':''}{state.training.error?`:${state.training.error}。原模型保持可用。`:''}</p>}
|
| 46 |
+
{state?.active?.metrics&&<small>历史皮肤分组验证 IoU {(state.active.metrics.iou*100).toFixed(1)}%;这不是新皮肤准确率,预选仍需人工检查。</small>}
|
| 47 |
+
{!!state?.dataset?.excluded?.length&&<details><summary>{state.dataset.excluded.length} 张未纳入本轮训练</summary>{state.dataset.excluded.map((x,i)=><p key={i}>{x.id}:{x.reason}</p>)}</details>}
|
| 48 |
+
{error&&<p className="meat-warning" role="alert">{error}</p>}
|
| 49 |
+
</section>;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
export function MeatPreselect({data,disabled,onStart,onEnd,onApply}) {
|
| 53 |
+
const [pending,setPending]=useState(false),[message,setMessage]=useState(''),[error,setError]=useState('');
|
| 54 |
+
const life=useRef(true),controller=useRef(null),inflight=useRef(false);
|
| 55 |
+
useEffect(()=>{life.current=true;return()=>{life.current=false;controller.current?.abort();};},[]);
|
| 56 |
+
const run=async()=>{
|
| 57 |
+
if(inflight.current)return;inflight.current=true;setPending(true);setError('');setMessage('正在请求预选…');onStart();
|
| 58 |
+
controller.current=new AbortController();const signal=controller.current.signal;
|
| 59 |
+
try {
|
| 60 |
+
let job=await modelAPI('predict',{key:data.key,skin_revision:data.skin_revision},signal);
|
| 61 |
+
while(!terminal(job.stage)){
|
| 62 |
+
if(!life.current)return;setMessage(stageText(job));
|
| 63 |
+
await new Promise(resolve=>setTimeout(resolve,1500));
|
| 64 |
+
if(!life.current)return;
|
| 65 |
+
job=await modelAPI('job?id='+encodeURIComponent(job.id),undefined,signal);
|
| 66 |
+
}
|
| 67 |
+
if(job.stage==='failed')throw Error(job.error || '预选失败,请稍后重试');
|
| 68 |
+
if(job.prediction.skin_revision!==data.skin_revision)throw Error('皮肤版本已变化,未应用预选');
|
| 69 |
+
if(life.current){onApply(job.prediction);setMessage(`预选来自 ${job.prediction.model_id} · ${job.prediction.selected.length} 格。请检查并修改,再保存。`);}
|
| 70 |
+
}catch(e){if(life.current&&e.name!=='AbortError'){setError(e.message);setMessage('');}}
|
| 71 |
+
finally{inflight.current=false;if(life.current){setPending(false);onEnd();}}
|
| 72 |
+
};
|
| 73 |
+
return <div className="meat-preselect"><button className="button secondary" onClick={run} disabled={disabled||pending||data.model!=='classic'}>{pending?'模型预选中…':'模型预选'}</button>
|
| 74 |
+
<span>{data.model!=='classic'?'当前模型暂不支持纤细手臂,请人工标注。':'替换当前选区,可撤销;只有点击保存才写入人工标签。'}</span>
|
| 75 |
+
{message&&<p role="status">{message}</p>}{error&&<p role="alert" className="meat-warning">{error}</p>}
|
| 76 |
+
</div>;
|
| 77 |
+
}
|
best_annotator/src/main.jsx
CHANGED
|
@@ -7,6 +7,7 @@ const SkinEditor = lazy(() =>
|
|
| 7 |
);
|
| 8 |
const MeatEditor = lazy(() => import("./MeatEditor"));
|
| 9 |
import "./meat.css";
|
|
|
|
| 10 |
const done = (x) => !!(x.best || x.rejection);
|
| 11 |
const modelOf = (x) => x.model ?? x.folder;
|
| 12 |
const rejectionLabel = (x) =>
|
|
@@ -177,11 +178,12 @@ function App() {
|
|
| 177 |
if (meatDirty && !window.confirm("meat 标注尚未保存,放弃本次修改?")) return;
|
| 178 |
setMeat(null); setMeatDirty(false);
|
| 179 |
};
|
| 180 |
-
async function saveMeat(selected, advance) {
|
| 181 |
if (busyRef.current || !meat) return;
|
| 182 |
busyRef.current = true; setBusy(true);
|
| 183 |
try {
|
| 184 |
-
const data = await api("/api/meat", { key:meat.key, revision:meat.revision, skin_revision:meat.skin_revision, meat_revision:meat.meat_revision, selected });
|
|
|
|
| 185 |
const updated = items.map(x => x.key === meat.key ? data.item : x);
|
| 186 |
setItems(updated); setMeat(null); setMeatDirty(false);
|
| 187 |
toast("meat 已保存 · " + meat.id + " · " + selected.length + " 格");
|
|
@@ -394,6 +396,7 @@ function App() {
|
|
| 394 |
<span>可与数据目录、编号搜索组合筛选</span>
|
| 395 |
</section>
|
| 396 |
)}
|
|
|
|
| 397 |
<main>
|
| 398 |
{item ? (
|
| 399 |
<>
|
|
|
|
| 7 |
);
|
| 8 |
const MeatEditor = lazy(() => import("./MeatEditor"));
|
| 9 |
import "./meat.css";
|
| 10 |
+
import { MeatModelPanel } from "./MeatModel";
|
| 11 |
const done = (x) => !!(x.best || x.rejection);
|
| 12 |
const modelOf = (x) => x.model ?? x.folder;
|
| 13 |
const rejectionLabel = (x) =>
|
|
|
|
| 178 |
if (meatDirty && !window.confirm("meat 标注尚未保存,放弃本次修改?")) return;
|
| 179 |
setMeat(null); setMeatDirty(false);
|
| 180 |
};
|
| 181 |
+
async function saveMeat(selected, advance, assistance) {
|
| 182 |
if (busyRef.current || !meat) return;
|
| 183 |
busyRef.current = true; setBusy(true);
|
| 184 |
try {
|
| 185 |
+
const data = await api("/api/meat", { key:meat.key, revision:meat.revision, skin_revision:meat.skin_revision, meat_revision:meat.meat_revision, selected, assistance });
|
| 186 |
+
window.dispatchEvent(new Event("meat-saved"));
|
| 187 |
const updated = items.map(x => x.key === meat.key ? data.item : x);
|
| 188 |
setItems(updated); setMeat(null); setMeatDirty(false);
|
| 189 |
toast("meat 已保存 · " + meat.id + " · " + selected.length + " 格");
|
|
|
|
| 396 |
<span>可与数据目录、编号搜索组合筛选</span>
|
| 397 |
</section>
|
| 398 |
)}
|
| 399 |
+
<MeatModelPanel/>
|
| 400 |
<main>
|
| 401 |
{item ? (
|
| 402 |
<>
|
best_annotator/src/meat.css
CHANGED
|
@@ -1 +1,4 @@
|
|
| 1 |
.meat-dialog{width:min(1440px,96vw);max-width:96vw;max-height:96vh;padding:0;border:0;border-radius:16px;color:#243341;background:#f5f7f9}.meat-dialog::backdrop{background:#14202bb3}.meat-dialog .dialog-top{position:sticky;top:0;z-index:2;background:#fff}.meat-editor{padding:0 22px 20px}.meat-definition{line-height:1.6;color:#526371}.meat-warning{padding:12px;background:#fff0c8;border-radius:8px}.meat-toolbar{display:flex;gap:14px;align-items:center;flex-wrap:wrap;padding:14px 0}.meat-toolbar label{display:flex;align-items:center;gap:7px}.meat-editor button,.meat-editor select{padding:9px 13px;border:1px solid #c7d3db;border-radius:8px;background:white;cursor:pointer;color:#253747}.meat-editor button.active{background:#daf6e9;border-color:#24916a;color:#126847}.meat-editor button:disabled{opacity:.45;cursor:default}.meat-workspace{display:grid;grid-template-columns:1.1fr 1fr;gap:20px}.meat-workspace section{min-width:0;padding:14px;background:#fff;border:1px solid #dce3e8;border-radius:12px}.meat-workspace h3{margin:0 0 12px;font-size:16px}.meat-workspace small{font-weight:400;font-size:12px;color:#607584;margin-left:8px}.meat-stage{height:490px;background:#e7ecf1;border-radius:8px;touch-action:none}.meat-views{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px}.meat-views button{padding:6px 9px}.meat-uv{width:100%;max-width:540px;display:block;margin:auto;image-rendering:pixelated;touch-action:none;cursor:crosshair;background:repeating-conic-gradient(#e4e9ed 0% 25%,#f7f9fa 0% 50%) 50%/16px 16px}.meat-footer{display:flex;gap:12px;align-items:center;justify-content:flex-end;margin-top:18px}.meat-footer>span{margin-right:auto}.meat-footer small{display:block;font-size:12px;color:#607584;margin-top:5px}.meat-footer .button:not(.secondary){background:#18775e;color:white;border-color:#18775e}.meat-entry{margin-top:12px}.meat-status{font-size:12px;color:#597567;margin:8px 0}@media(max-width:900px){.meat-workspace{grid-template-columns:1fr}.meat-stage{height:390px}.meat-footer{flex-wrap:wrap}.meat-footer>span{width:100%}.meat-editor{padding:0 12px 15px}}
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
.meat-dialog{width:min(1440px,96vw);max-width:96vw;max-height:96vh;padding:0;border:0;border-radius:16px;color:#243341;background:#f5f7f9}.meat-dialog::backdrop{background:#14202bb3}.meat-dialog .dialog-top{position:sticky;top:0;z-index:2;background:#fff}.meat-editor{padding:0 22px 20px}.meat-definition{line-height:1.6;color:#526371}.meat-warning{padding:12px;background:#fff0c8;border-radius:8px}.meat-toolbar{display:flex;gap:14px;align-items:center;flex-wrap:wrap;padding:14px 0}.meat-toolbar label{display:flex;align-items:center;gap:7px}.meat-editor button,.meat-editor select{padding:9px 13px;border:1px solid #c7d3db;border-radius:8px;background:white;cursor:pointer;color:#253747}.meat-editor button.active{background:#daf6e9;border-color:#24916a;color:#126847}.meat-editor button:disabled{opacity:.45;cursor:default}.meat-workspace{display:grid;grid-template-columns:1.1fr 1fr;gap:20px}.meat-workspace section{min-width:0;padding:14px;background:#fff;border:1px solid #dce3e8;border-radius:12px}.meat-workspace h3{margin:0 0 12px;font-size:16px}.meat-workspace small{font-weight:400;font-size:12px;color:#607584;margin-left:8px}.meat-stage{height:490px;background:#e7ecf1;border-radius:8px;touch-action:none}.meat-views{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px}.meat-views button{padding:6px 9px}.meat-uv{width:100%;max-width:540px;display:block;margin:auto;image-rendering:pixelated;touch-action:none;cursor:crosshair;background:repeating-conic-gradient(#e4e9ed 0% 25%,#f7f9fa 0% 50%) 50%/16px 16px}.meat-footer{display:flex;gap:12px;align-items:center;justify-content:flex-end;margin-top:18px}.meat-footer>span{margin-right:auto}.meat-footer small{display:block;font-size:12px;color:#607584;margin-top:5px}.meat-footer .button:not(.secondary){background:#18775e;color:white;border-color:#18775e}.meat-entry{margin-top:12px}.meat-status{font-size:12px;color:#597567;margin:8px 0}@media(max-width:900px){.meat-workspace{grid-template-columns:1fr}.meat-stage{height:390px}.meat-footer{flex-wrap:wrap}.meat-footer>span{width:100%}.meat-editor{padding:0 12px 15px}}
|
| 2 |
+
.meat-tolerance input{width:130px;accent-color:#18775e}.meat-tolerance output{min-width:3ch;font-variant-numeric:tabular-nums}.meat-help{font-size:13px;line-height:1.7;color:#526371;margin:12px 0}.meat-stage{cursor:grab}.meat-stage:active{cursor:grabbing}
|
| 3 |
+
|
| 4 |
+
.meat-model-panel{margin:16px 0;padding:16px 20px;border:1px solid #d6dedb;border-radius:12px;background:#f4f8f6;display:flex;flex-wrap:wrap;gap:8px 24px;align-items:center}.meat-model-panel p{margin:4px 0;font-size:13px;color:#4b6058}.meat-model-panel small,.meat-model-panel>p,.meat-model-panel>details{flex-basis:100%}.meat-model-actions{display:flex;gap:8px;margin-left:auto}.meat-preselect{padding:12px;background:#ecf6f0;border-radius:8px;margin-bottom:12px;display:flex;flex-wrap:wrap;gap:8px 14px;align-items:center}.meat-preselect span,.meat-preselect p{font-size:13px;margin:0}.meat-preselect p{flex-basis:100%}
|
best_annotator/src/meatGeometry.js
CHANGED
|
@@ -45,6 +45,30 @@ export function applySelection(geometry, mask) {
|
|
| 45 |
a.needsUpdate = true;
|
| 46 |
}
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
export function makePulseMaterial(uniform) {
|
| 49 |
const material = new THREE.MeshBasicMaterial({ vertexColors: true, side: THREE.DoubleSide });
|
| 50 |
material.onBeforeCompile = (shader) => {
|
|
|
|
| 45 |
a.needsUpdate = true;
|
| 46 |
}
|
| 47 |
|
| 48 |
+
// Surface connectivity, not adjacency in the unfolded UV atlas. An edge may join
|
| 49 |
+
// two faces of one cuboid, but never joins separate parts or inner/outer layers.
|
| 50 |
+
export function buildSurfaceAdjacency(parts, rgba) {
|
| 51 |
+
const neighbors = Array.from({ length:4096 }, () => new Set());
|
| 52 |
+
for (const part of parts) {
|
| 53 |
+
const geometry = buildMeatGeometry(part, rgba), edges = new Map();
|
| 54 |
+
const pos = geometry.getAttribute("position"), ids = geometry.userData.triangleIds;
|
| 55 |
+
const key = i => [pos.getX(i),pos.getY(i),pos.getZ(i)].map(v=>Math.round(v*10000)).join(",");
|
| 56 |
+
for (let t=0;t<ids.length;t++) {
|
| 57 |
+
const points=[key(t*3),key(t*3+1),key(t*3+2)], id=ids[t];
|
| 58 |
+
for (let e=0;e<3;e++) {
|
| 59 |
+
const k=[points[e],points[(e+1)%3]].sort().join("|");
|
| 60 |
+
if(!edges.has(k))edges.set(k,new Set());
|
| 61 |
+
edges.get(k).add(id);
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
for (const ids of edges.values()) for(const a of ids) for(const b of ids) {
|
| 65 |
+
if(a!==b)neighbors[a].add(b);
|
| 66 |
+
}
|
| 67 |
+
geometry.dispose();
|
| 68 |
+
}
|
| 69 |
+
return neighbors.map(s=>Array.from(s));
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
export function makePulseMaterial(uniform) {
|
| 73 |
const material = new THREE.MeshBasicMaterial({ vertexColors: true, side: THREE.DoubleSide });
|
| 74 |
material.onBeforeCompile = (shader) => {
|
best_annotator/src/meatSelection.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// RGB RMS distance expressed as a percentage of the full 0..255 range.
|
| 2 |
+
// Compare every cell to the original seed; do not drift along a color gradient.
|
| 3 |
+
export function floodCells(seed, rgba, valid, allowed, neighbors, tolerance) {
|
| 4 |
+
if (!valid[seed] || !allowed[seed]) return [];
|
| 5 |
+
const limit = Math.max(0,Math.min(100,Number(tolerance)||0));
|
| 6 |
+
const seen = new Uint8Array(4096), stack=[seed], result=[];
|
| 7 |
+
seen[seed]=1;
|
| 8 |
+
while(stack.length) {
|
| 9 |
+
const id=stack.pop();
|
| 10 |
+
if(!valid[id] || !allowed[id])continue;
|
| 11 |
+
let squared=0;
|
| 12 |
+
for(let c=0;c<3;c++)squared+=(rgba[id*4+c]-rgba[seed*4+c])**2;
|
| 13 |
+
if(Math.sqrt(squared/3)/255*100 > limit + 1e-9)continue;
|
| 14 |
+
result.push(id);
|
| 15 |
+
for(const next of neighbors[id])if(!seen[next]){seen[next]=1;stack.push(next);}
|
| 16 |
+
}
|
| 17 |
+
return result;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export function beginGesture(e) {
|
| 21 |
+
return {pointerId:e.pointerId,x:e.clientX,y:e.clientY,ctrl:e.ctrlKey,button:e.button,dragged:false,cancelled:!e.isPrimary&&e.isPrimary!==undefined};
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
export function moveGesture(g,e) {
|
| 25 |
+
if(g && g.pointerId===e.pointerId && Math.hypot(e.clientX-g.x,e.clientY-g.y)>5)g.dragged=true;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export function canPick(g) {
|
| 29 |
+
// Ctrl + secondary button also supports browsers that turn macOS Ctrl-click
|
| 30 |
+
// into a context click. Plain secondary-button rotation never labels.
|
| 31 |
+
return !!g && !g.dragged && !g.cancelled && (g.button===0 || (g.button===2&&g.ctrl)) && Number.isInteger(g.id);
|
| 32 |
+
}
|
best_annotator/static/assets/MeatEditor-C4N_uiLJ.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import{r as i,j as r,M as le}from"./index-Dk3WlUGQ.js";import{aA as ue,h as fe,am as de,t as me,u as z,ae as he,D as pe,aw as ge,a0 as xe,a3 as ve,ay as be,aE as W}from"./OrbitControls-CInKUGFx.js";const ye=["left","right","top","bottom","front","back"];function ie(t,a){const[c,m,x]=t.size,g=t.inflate,w=new ue(c+g,m+g,x+g,c,m,x),f=w.toNonIndexed();w.dispose();const u=f.getAttribute("position"),s=f.getAttribute("uv"),o=[],d=[],l=[],p=[],v=new fe;for(const I of f.groups){const[N,K,U,O,_,V]=t.faces[ye[I.materialIndex]];for(let S=I.start;S<I.start+I.count;S+=3){let B=(s.getX(S)+s.getX(S+1)+s.getX(S+2))/3,Y=(s.getY(S)+s.getY(S+1)+s.getY(S+2))/3;_&&(B=1-B),V&&(Y=1-Y);const T=N+Math.min(U-1,Math.floor(B*U)),j=(K+Math.min(O-1,Math.floor((1-Y)*O)))*64+T;if(a[j*4+3]){v.setRGB(a[j*4]/255,a[j*4+1]/255,a[j*4+2]/255,de),l.push(j);for(let D=S;D<S+3;D++)o.push(u.getX(D),u.getY(D),u.getZ(D)),d.push(v.r,v.g,v.b),p.push(j)}}}f.dispose();const P=new me;return P.setAttribute("position",new z(o,3)),P.setAttribute("color",new z(d,3)),P.setAttribute("meatSelected",new z(new Float32Array(p.length),1)),P.userData={triangleIds:l,vertexIds:p},P}function we(t,a){const c=t.getAttribute("meatSelected");t.userData.vertexIds.forEach((m,x)=>{c.array[x]=a[m]?1:0}),c.needsUpdate=!0}function je(t,a){const c=Array.from({length:4096},()=>new Set);for(const m of t){const x=ie(m,a),g=new Map,w=x.getAttribute("position"),f=x.userData.triangleIds,u=s=>[w.getX(s),w.getY(s),w.getZ(s)].map(o=>Math.round(o*1e4)).join(",");for(let s=0;s<f.length;s++){const o=[u(s*3),u(s*3+1),u(s*3+2)],d=f[s];for(let l=0;l<3;l++){const p=[o[l],o[(l+1)%3]].sort().join("|");g.has(p)||g.set(p,new Set),g.get(p).add(d)}}for(const s of g.values())for(const o of s)for(const d of s)o!==d&&c[o].add(d);x.dispose()}return c.map(m=>Array.from(m))}function Me(t){const a=new he({vertexColors:!0,side:pe});return a.onBeforeCompile=c=>{c.uniforms.meatPulse=t,c.vertexShader=`attribute float meatSelected; varying float vMeatSelected;
|
| 2 |
+
`+c.vertexShader,c.vertexShader=c.vertexShader.replace("#include <begin_vertex>",`#include <begin_vertex>
|
| 3 |
+
vMeatSelected = meatSelected;`),c.fragmentShader=`uniform float meatPulse; varying float vMeatSelected;
|
| 4 |
+
`+c.fragmentShader,c.fragmentShader=c.fragmentShader.replace("#include <color_fragment>",`#include <color_fragment>
|
| 5 |
+
diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.04, 1.0, 0.46), vMeatSelected * meatPulse);`)},a.customProgramCacheKey=()=>"meat-pulse-v1",a}function Se(t,a,c,m,x,g){if(!c[t]||!m[t])return[];const w=Math.max(0,Math.min(100,Number(g)||0)),f=new Uint8Array(4096),u=[t],s=[];for(f[t]=1;u.length;){const o=u.pop();if(!c[o]||!m[o])continue;let d=0;for(let l=0;l<3;l++)d+=(a[o*4+l]-a[t*4+l])**2;if(!(Math.sqrt(d/3)/255*100>w+1e-9)){s.push(o);for(const l of x[o])f[l]||(f[l]=1,u.push(l))}}return s}function Ce(t){return{pointerId:t.pointerId,x:t.clientX,y:t.clientY,ctrl:t.ctrlKey,button:t.button,dragged:!1,cancelled:!t.isPrimary&&t.isPrimary!==void 0}}function re(t,a){t&&t.pointerId===a.pointerId&&Math.hypot(a.clientX-t.x,a.clientY-t.y)>5&&(t.dragged=!0)}function Ee(t){return!!t&&!t.dragged&&!t.cancelled&&(t.button===0||t.button===2&&t.ctrl)&&Number.isInteger(t.id)}const se=t=>Uint8Array.from(atob(t),a=>a.charCodeAt(0)),oe=t=>{const a=new Uint8Array(4096);return t.forEach(c=>a[c]=1),a};function ke({part:t,rgba:a,mask:c,pulse:m,pickDown:x,pickUp:g,hover:w}){const f=i.useMemo(()=>ie(t,a),[t,a]),u=i.useMemo(()=>Me(m),[m]);i.useEffect(()=>{we(f,c)},[f,c]),i.useEffect(()=>()=>{f.dispose(),u.dispose()},[f,u]);const s=(o,d)=>{o.stopPropagation();const l=f.userData.triangleIds[o.faceIndex];l!==void 0&&(w(l),d==="down"&&x(l),d==="up"&&g())};return r.jsx("mesh",{geometry:f,material:u,position:t.center,onPointerDown:o=>s(o,"down"),onPointerMove:o=>s(o,"hover"),onPointerUp:o=>s(o,"up")})}function Ae({data:t,rgba:a,mask:c,layer:m,animate:x,view:g,viewEpoch:w,pickDown:f,pickUp:u,hover:s}){const o=i.useMemo(()=>({value:.6}),[]),d=i.useRef(),{camera:l}=xe();return ve(({clock:p})=>{o.value=x?.48+.28*Math.sin(p.elapsedTime*Math.PI):.6}),i.useEffect(()=>{const p={angle:[30,22,38],front:[0,0,48],back:[0,0,-48],left:[48,0,0],right:[-48,0,0],top:[0,50,.01],bottom:[0,-52,.01]};l.position.set(...p[g]),l.lookAt(0,-2,0),d.current?.update()},[g,w,l]),r.jsxs(r.Fragment,{children:[t.parts.filter(p=>m==="both"||p.layer===(m==="inner"?0:1)).map(p=>r.jsx(ke,{part:p,rgba:a,mask:c,pulse:o,pickDown:f,pickUp:u,hover:s},p.name+p.layer)),r.jsx(be,{ref:d,target:[0,-2,0],enablePan:!1,enableDamping:!1,mouseButtons:{LEFT:W.ROTATE,MIDDLE:W.DOLLY,RIGHT:W.ROTATE},minDistance:10,maxDistance:100})]})}function Ie({data:t,busy:a,onSave:c,onDirty:m}){const[x,g]=i.useState(!1),[w,f]=i.useState(null),u=a||x,s=i.useMemo(()=>se(t.rgba),[t.rgba]),o=i.useMemo(()=>se(t.valid),[t.valid]),d=i.useMemo(()=>oe(t.selected),[t]),[l,p]=i.useState(d),v=i.useRef(d),[P,I]=i.useState("toggle"),[N,K]=i.useState("both"),[U,O]=i.useState("angle"),[_,V]=i.useState(12),[S,B]=i.useState(0),Y=i.useMemo(()=>je(t.parts,s),[t.parts,s]),[T,Z]=i.useState(!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches),[j,D]=i.useState(null),[R,q]=i.useState({entries:[d],index:0}),L=i.useRef(null),J=i.useRef(null),Q=i.useRef(l),k=i.useRef(null),ee=i.useMemo(()=>({selected:l.reduce((e,n)=>e+n,0),valid:o.reduce((e,n)=>e+n,0)}),[l,o]),F=l.some((e,n)=>e!==d[n]),X=i.useMemo(()=>{const e=new Uint8Array(4096);return t.parts.forEach(n=>{N!=="both"&&n.layer!==(N==="inner"?0:1)||Object.values(n.faces).forEach(([h,b,C,A])=>{for(let E=b;E<b+A;E++)for(let G=h;G<h+C;G++)e[E*64+G]=1})}),e},[t,N]),H=e=>{v.current=e,Q.current=e,p(e)},M=()=>{L.current&&(v.current.some((e,n)=>e!==L.current.before[n])&&q(e=>{const n=[...e.entries.slice(0,e.index+1),v.current].slice(-60);return{entries:n,index:n.length-1}}),L.current=null)},te=(e,n=!1,h=!1)=>{if(u||!o[e]||!X[e]||(n&&(M(),L.current={before:v.current,value:P==="erase"?0:1-v.current[e],flood:h}),!L.current)||!n&&L.current.flood)return;const b=L.current.value,C=h&&n?Se(e,s,o,X,Y,_):[e];if(C.every(E=>v.current[E]===b))return;const A=v.current.slice();C.forEach(E=>A[E]=b),H(A)},ae=e=>{k.current&&(k.current.id=e)},ce=()=>{const e=k.current;Ee(e)&&(te(e.id,!0,e.ctrl),M()),e&&(e.cancelled=!0)};i.useEffect(()=>{m(F)},[F,m]),i.useEffect(()=>(window.addEventListener("pointerup",M),window.addEventListener("pointercancel",M),window.addEventListener("blur",M),()=>{window.removeEventListener("pointerup",M),window.removeEventListener("pointercancel",M),window.removeEventListener("blur",M)}),[]),i.useEffect(()=>{const e=n=>{F&&(n.preventDefault(),n.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[F]);const $=e=>{if(u)return;M();const n=R.index+e;n<0||n>=R.entries.length||(H(R.entries[n]),q({...R,index:n}))};i.useEffect(()=>{const e=n=>{(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="z"&&(n.preventDefault(),$(n.shiftKey?1:-1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)}),i.useEffect(()=>{const e=J.current,n=e.getContext("2d"),h=document.createElement("canvas");h.width=64,h.height=64,h.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(s),64,64),0,0);let b,C=0;const A=E=>{if(E-C>40){C=E,n.clearRect(0,0,512,512),n.imageSmoothingEnabled=!1,n.drawImage(h,0,0,512,512);const G=T?.48+.28*Math.sin(E/1e3*Math.PI):.6;for(let y=0;y<4096;y++)!o[y]||!X[y]?(n.fillStyle="rgba(27,33,44,.72)",n.fillRect(y%64*8,Math.floor(y/64)*8,8,8)):Q.current[y]&&(n.fillStyle=`rgba(25,255,157,${G})`,n.fillRect(y%64*8,Math.floor(y/64)*8,8,8));n.strokeStyle="rgba(0,0,0,.18)",n.lineWidth=.5,n.beginPath();for(let y=0;y<=64;y++)n.moveTo(y*8,0),n.lineTo(y*8,512),n.moveTo(0,y*8),n.lineTo(512,y*8);n.stroke(),j!==null&&(n.strokeStyle="#fff",n.lineWidth=2,n.strokeRect(j%64*8+1,Math.floor(j/64)*8+1,6,6))}b=requestAnimationFrame(A)};return b=requestAnimationFrame(A),()=>cancelAnimationFrame(b)},[s,o,X,T,j]);const ne=(e,n)=>{const h=e.currentTarget.getBoundingClientRect(),b=Math.floor((e.clientX-h.left)/h.width*64),C=Math.floor((e.clientY-h.top)/h.height*64);if(b<0||b>=64||C<0||C>=64)return;const A=C*64+b;D(A),(e.buttons===1||n&&e.ctrlKey&&e.button===2)&&(n&&e.currentTarget.setPointerCapture(e.pointerId),te(A,n,e.ctrlKey))};return r.jsxs("div",{className:"meat-editor",children:[r.jsx("p",{className:"meat-definition",children:"meat:脸、眼睛、嘴巴和裸露身体。头发、胡须、眼镜、帽子、衣物和饰品不选。内外层分别标注。"}),t.meat_status==="stale"&&r.jsx("p",{className:"meat-warning",children:"perfect 皮肤已变化,本次从空白标注开始;旧标注会在保存时归档。"}),r.jsx(le,{data:t,disabled:u,onStart:()=>{M(),g(!0)},onEnd:()=>g(!1),onApply:e=>{const n=oe(e.selected);H(n),q(h=>{const b=[...h.entries.slice(0,h.index+1),n].slice(-60);return{entries:b,index:b.length-1}}),f({model_id:e.model_id,checkpoint_sha256:e.checkpoint_sha256})}}),r.jsxs("div",{className:"meat-toolbar",children:[r.jsxs("div",{role:"group","aria-label":"标注方式",children:[r.jsx("button",{className:P==="toggle"?"active":"",onClick:()=>I("toggle"),children:"点击切换选中"}),r.jsx("button",{className:P==="erase"?"active":"",onClick:()=>I("erase"),children:"擦除"})]}),r.jsxs("label",{className:"meat-tolerance",children:["颜色容差 ",r.jsx("input",{"aria-label":"泛洪颜色容差",type:"range",min:"0",max:"100",step:"1",value:_,onChange:e=>V(Number(e.target.value))}),r.jsxs("output",{children:[_,"%"]})]}),r.jsxs("label",{children:["查看图层 ",r.jsxs("select",{value:N,onChange:e=>K(e.target.value),children:[r.jsx("option",{value:"both",children:"内层+外层"}),r.jsx("option",{value:"inner",children:"仅内层"}),r.jsx("option",{value:"outer",children:"仅外层"})]})]}),r.jsx("button",{disabled:u||R.index===0,onClick:()=>$(-1),children:"撤销"}),r.jsx("button",{disabled:u||R.index===R.entries.length-1,onClick:()=>$(1),children:"重做"}),r.jsxs("label",{children:[r.jsx("input",{type:"checkbox",checked:T,onChange:e=>Z(e.target.checked)}),"呼吸高亮"]})]}),r.jsxs("div",{className:"meat-workspace",children:[r.jsxs("section",{children:[r.jsxs("h3",{children:["3D 选择 ",r.jsx("small",{children:"拖拽旋转 · 点击切换 · Ctrl+点击泛洪 · 滚轮缩放"})]}),r.jsx("div",{className:"meat-views",children:Object.entries({angle:"斜视",front:"正面",back:"背面",left:"左侧",right:"右侧",top:"头顶",bottom:"底部"}).map(([e,n])=>r.jsx("button",{className:U===e?"active":"",onClick:()=>{O(e),B(h=>h+1)},children:n},e))}),r.jsx("div",{className:"meat-stage",onContextMenu:e=>e.preventDefault(),onPointerDownCapture:e=>{e.isPrimary===!1?k.current&&(k.current.cancelled=!0):k.current=Ce(e)},onPointerMoveCapture:e=>re(k.current,e),onPointerUpCapture:e=>re(k.current,e),onPointerCancelCapture:()=>{k.current&&(k.current.cancelled=!0)},children:r.jsx(ge,{camera:{position:[30,22,38],fov:43},children:r.jsx(Ae,{data:t,rgba:s,mask:l,layer:N,animate:T,view:U,viewEpoch:S,pickDown:ae,pickUp:ce,hover:D})})})]}),r.jsxs("section",{children:[r.jsxs("h3",{children:["UV 逐格选择 ",r.jsx("small",{children:j===null?"可标注被遮住的表面":`UV (${j%64}, ${Math.floor(j/64)})`})]}),r.jsx("canvas",{className:"meat-uv","aria-label":"64×64 meat UV 标注",width:512,height:512,ref:J,onContextMenu:e=>e.preventDefault(),onPointerDown:e=>ne(e,!0),onPointerMove:e=>ne(e,!1),onPointerUp:M})]})]}),r.jsx("p",{className:"meat-help",children:"Ctrl+点击:沿同一部件、同一层的相连表面选择近似颜色;已选区域再次点击即可取消,Ctrl+点击已选格可批量取消。容差越大,包含颜色越多。UV 图可按住左键连续涂选或擦除。"}),r.jsxs("footer",{className:"meat-footer",children:[r.jsxs("span",{"aria-live":"polite",children:["已选 ",ee.selected," / ",ee.valid," 格",F?" · 未保存":"",r.jsxs("small",{children:["保存为 ",t.id,"_meat.png;未选择的有效格为非 meat。"]})]}),r.jsx("button",{className:"button secondary",disabled:u,onClick:()=>{M(),c(Array.from(v.current.keys()).filter(e=>v.current[e]),!1,w)},children:"保存 meat"}),r.jsx("button",{className:"button",disabled:u,onClick:()=>{M(),c(Array.from(v.current.keys()).filter(e=>v.current[e]),!0,w)},children:"保存并标注下一张"})]})]})}export{Ie as default};
|
best_annotator/static/assets/OrbitControls-CInKUGFx.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
best_annotator/static/assets/SkinEditor-CO_iRmVE.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
best_annotator/static/assets/index-D0g9WvcQ.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
:root{font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Microsoft YaHei,sans-serif;color:#1f2c3c;background:#f3f5f8;font-size:14px;--accent:#147d72;--border:#dfe5ed;--muted:#758194}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #68b4ac;outline-offset:3px}button{color:inherit}h1,h2,p{margin:0}h1{font-size:19px;letter-spacing:-.4px}h2{font-size:24px;letter-spacing:.3px}button{transition:background .15s,border-color .15s}button:hover:not(:disabled){filter:brightness(.97)}[hidden]{display:none!important}.topbar{display:flex;align-items:center;gap:30px;justify-content:space-between;padding:22px 30px;background:#fff;border-bottom:1px solid var(--border)}.brand{display:flex;gap:12px;align-items:center}.brand-icon{display:grid;place-items:center;background:#183b39;color:#d5f5ed;border-radius:12px;width:42px;height:42px;font-size:25px;font-weight:750}.brand p{font-size:12px;color:var(--muted);margin-top:5px}.progress{width:235px;margin-left:auto}.progress>div:first-child{display:flex;justify-content:space-between;font-size:12px;margin-bottom:9px;color:var(--muted)}.progress strong{color:var(--accent);font-weight:650}.progress-track{height:5px;background:#e9eeef;border-radius:10px;overflow:hidden}.progress-track i{height:100%;width:0;display:block;background:var(--accent);transition:width .25s}.button{border:1px solid var(--border);border-radius:8px;background:#fff;padding:10px 15px;font-weight:550;white-space:nowrap}.button.primary{background:var(--accent);border-color:var(--accent);color:#fff}.button.tiny{padding:6px 11px;font-size:12px}.button.tiny[aria-pressed=true]{color:var(--accent);background:#e4f2ee;border-color:#94c8be}.filters{display:flex;align-items:center;gap:12px;padding:15px 30px;border-bottom:1px solid var(--border);background:#fff}.segments{display:flex;gap:3px;background:#f0f3f6;padding:4px;border-radius:9px;margin-right:auto}.segments button{border:0;background:transparent;border-radius:6px;padding:7px 12px;color:#677284;font-size:13px}.segments button.active{color:#175d55;background:#fff;box-shadow:0 1px 4px #20304016}.segments b{margin-left:6px;font-size:11px;font-weight:600;opacity:.8}select,input[type=search]{border:1px solid var(--border);border-radius:8px;background:#fff;padding:9px 11px;color:#48566a;min-width:0}input[type=search]{width:210px}#folder{max-width:255px}main{padding:24px 30px 115px;max-width:1900px;margin:auto}.item-heading{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:20px}.eyebrow{font-size:11px;color:var(--accent);font-weight:650;letter-spacing:.4px;display:block;margin-bottom:7px}.item-heading p{color:var(--muted);font-size:12px;margin-top:7px}.jump{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--muted)}#jump{max-width:285px}.workspace{display:grid;grid-template-columns:minmax(270px,29%) minmax(0,1fr);gap:24px;align-items:start}.panel{border:1px solid var(--border);border-radius:12px;background:#fff;overflow:hidden}.panel-title{padding:13px 14px;border-bottom:1px solid var(--border)}.source-image-button{display:block;width:100%;height:min(33vw,455px);min-height:300px;border:0;padding:16px;background:#fafbfc;cursor:zoom-in}.source-image-button img{height:100%;width:100%;object-fit:contain}.source-caption{display:flex;justify-content:space-between;padding:12px 16px;font-size:11px;color:var(--muted)}#sourceFlag{color:#9a7031}.save-note{padding:15px 16px;border-top:1px solid #edf0f4;color:#8891a1;font-size:11px;line-height:1.8}.save-note code{font-family:monospace;color:#657388}.saved-box{margin:5px 15px 15px;padding:12px;background:#edf7f2;border:1px solid #c6e2d7;border-radius:8px;display:flex;flex-direction:column;gap:7px;font-size:11px;color:#45746a}.saved-box strong{font-size:12px;word-break:break-all;color:#1d6758}.text-button{align-self:start;border:0;background:transparent;padding:0;font-size:11px;text-decoration:underline;color:#6e817b}.comparison-toolbar{display:flex;justify-content:space-between;align-items:center;gap:8px;margin:0 0 13px;min-height:36px;flex-wrap:wrap}.camera-buttons{display:flex;align-items:center;gap:3px}.camera-buttons span{font-size:11px;color:var(--muted);margin-right:7px}.camera-buttons button{font-size:12px;border:1px solid transparent;background:transparent;border-radius:6px;padding:6px 9px;color:#687689}.camera-buttons button.active{background:#fff;border-color:var(--border);color:#263e49}.view-options{display:flex;align-items:center;gap:12px}.view-options label{display:flex;gap:4px;align-items:center;font-size:11px;color:#687689}input[type=checkbox]{accent-color:var(--accent)}.result-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px}.result-card{background:#fff;border:1px solid var(--border);border-radius:12px;overflow:hidden;min-width:0;display:flex;flex-direction:column}.result-card.selected{border:2px solid var(--accent);box-shadow:0 0 0 3px #147d7210}.result-header{display:flex;align-items:center;justify-content:space-between;padding:14px 12px 10px}.version-name{font-size:15px;font-weight:680}.version-number{display:inline-grid;place-items:center;border:1px solid #e1e5eb;border-radius:5px;width:21px;height:21px;font-size:11px;color:#929baa}.chosen-badge{font-size:10px;background:#e3f4ec;color:var(--accent);padding:3px 6px;border-radius:4px}.skin-stage{height:300px;background:radial-gradient(ellipse at 50% 45%,#fff,#edf1f5);position:relative;overflow:hidden}.skin-stage canvas{display:block;width:100%;height:100%;touch-action:none}.preview-status{position:absolute;inset:0;display:grid;place-items:center;padding:20px;color:#85909e;font-size:11px;text-align:center;pointer-events:none}.uv-area{padding:13px 10px;display:flex;align-items:center;justify-content:center;gap:12px;border-top:1px solid #edf0f4}.uv-button{padding:0;border:1px solid #e3e7ed;border-radius:4px;display:block;width:88px;height:88px;background-color:#f8f8f8;background-image:linear-gradient(45deg,#e1e4e8 25%,transparent 25%),linear-gradient(-45deg,#e1e4e8 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#e1e4e8 75%),linear-gradient(-45deg,transparent 75%,#e1e4e8 75%);background-size:16px 16px;background-position:0 0,0 8px,8px -8px,-8px 0;cursor:zoom-in;overflow:hidden}.uv-button img{display:block;width:100%;height:100%;object-fit:contain;image-rendering:pixelated}.uv-caption{display:flex;flex-direction:column;gap:5px;font-size:10px;color:#96a0ad}.uv-caption strong{font-size:11px;color:#738095;font-weight:500}.result-actions{padding:0 12px 13px;margin-top:auto}.result-file{font-size:9px;color:#909aab;margin-bottom:9px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,monospace}.choose-button{width:100%;border-radius:7px;border:1px solid #bdd7cf;color:var(--accent);background:#edf6f2;padding:10px 4px;font-size:12px;font-weight:600}.selected .choose-button{color:#fff;background:var(--accent);border-color:var(--accent)}.preview-hint{font-size:11px;color:#8a95a6;text-align:center;margin-top:15px;line-height:1.8}.uv-only .skin-stage{display:none}.uv-only .uv-area{min-height:280px;padding:20px 12px;flex-direction:column;border-top:0}.uv-only .uv-button{width:100%;height:auto;aspect-ratio:1;max-width:300px}.uv-only .uv-caption{flex-direction:row}.no-result-card{padding:65px 30px;color:var(--muted);text-align:center;background:#fff;border:1px dashed #ccd5df;border-radius:12px;grid-column:1/-1}.no-result-card p{font-size:12px;margin-top:10px}.empty{text-align:center;padding:70px 20px;margin-top:30px}.empty-icon{display:grid;place-items:center;width:52px;height:52px;background:#eaf3ed;color:var(--accent);font-size:25px;border-radius:50%;margin:0 auto 18px}.empty h2{font-size:22px}.empty p{color:var(--muted);margin:12px 0 24px;line-height:1.8}.footer{position:fixed;bottom:0;left:0;right:0;background:#ffffffed;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);border-top:1px solid var(--border);padding:15px 30px;display:flex;align-items:center;justify-content:space-between;gap:20px;z-index:5}.navigation{display:flex;gap:10px}.keyboard-hint,.session-note{font-size:11px;color:#8190a0}kbd{font-family:inherit;font-size:10px;border:1px solid #d8dee6;background:#f8fafc;padding:2px 5px;border-radius:4px}.toast{position:fixed;bottom:89px;left:50%;transform:translate(-50%);max-width:85vw;padding:13px 22px;background:#1f433c;color:#fff;border-radius:9px;box-shadow:0 5px 22px #0002;z-index:10;font-size:13px}.toast.error{background:#9d3e3e}dialog{border:1px solid var(--border);border-radius:13px;padding:0;max-width:92vw;width:1000px;max-height:92vh;box-shadow:0 20px 100px #0004}dialog::backdrop{background:#14232bb3;-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px)}.dialog-top{display:flex;align-items:center;justify-content:space-between;padding:15px 20px;border-bottom:1px solid var(--border);gap:20px;font-size:13px}.dialog-image{display:grid;place-items:center;padding:20px;overflow:auto;max-height:80vh;background:#eef0f2}.dialog-image img{display:block;max-width:100%;max-height:73vh;object-fit:contain}.dialog-image img.pixelated{image-rendering:pixelated;width:700px;height:700px}.busy{cursor:progress}@media(min-width:1700px){.skin-stage{height:370px}}@media(max-width:1100px){.workspace{grid-template-columns:280px minmax(0,1fr)}.result-grid{grid-template-columns:repeat(2,minmax(170px,1fr))}.skin-stage{height:255px}.keyboard-hint{display:none}.filters{flex-wrap:wrap}.segments{margin-right:0}main{padding-left:20px;padding-right:20px}.topbar,.filters{padding-left:20px;padding-right:20px}}@media(max-width:700px){.topbar{gap:10px;padding:15px}.brand p,.progress{display:none}.filters{padding:10px 15px}.segments{width:100%;justify-content:space-between}.segments button{padding:6px 8px}#folder,input[type=search]{width:calc(50% - 6px);max-width:none}main{padding:18px 15px 125px}.workspace{display:block}.source-panel{margin-bottom:20px}.source-image-button{height:280px;min-height:0}.item-heading{align-items:start;flex-direction:column;gap:12px}h2{font-size:19px}.jump{width:100%}#jump{max-width:none;flex:1}.result-grid{gap:9px;grid-template-columns:repeat(2,minmax(0,1fr))}.skin-stage{height:255px}.result-header{padding:12px 9px}.uv-area{gap:5px}.uv-button{width:74px;height:74px}.uv-caption{display:none}.footer{padding:12px 15px;flex-wrap:wrap;gap:9px}.navigation{width:100%}.navigation .button{flex:1}.session-note{font-size:10px}.comparison-toolbar{gap:10px}.view-options{margin-left:auto}}.reference-images{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));background:#fafbfc}.reference-image{min-width:0}.reference-image+.reference-image{border-left:1px solid var(--border)}.reference-image .panel-title{display:flex;align-items:center;gap:6px;padding:14px 12px;background:#fff;min-height:48px}.reference-image h3{font-size:12px;font-weight:650;margin:0;white-space:nowrap}.reference-image #sourceFlag{font-size:10px}.reference-image .source-image-button{height:295px;min-height:0;padding:10px}.missing-edited{height:295px;display:grid;place-items:center;font-size:12px;color:var(--muted);padding:12px}.reject-actions{padding:4px 14px 15px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.reject-button{font-size:12px;padding:10px 5px;white-space:normal;border-color:#e7c9bb;color:#8b4b36;background:#fff7f2}.reject-actions p{grid-column:1/-1;font-size:11px;color:var(--muted);line-height:1.7;margin-top:2px}.saved-box.rejected{background:#fff7f2;border-color:#e7c9bb;color:#8b4b36}.saved-box.rejected strong{color:#8b4b36}@media(min-width:1101px){.workspace{grid-template-columns:minmax(340px,29%) minmax(0,1fr)}}@media(min-width:701px)and (max-width:1100px){.reference-images{grid-template-columns:1fr}.reference-image+.reference-image{border-left:0;border-top:1px solid var(--border)}.reference-image .source-image-button,.missing-edited{height:200px}}@media(max-width:700px){.segments{flex-wrap:wrap;justify-content:flex-start;gap:3px}.segments button{flex:1 0 auto;padding:6px}.segments b{margin-left:3px}.reference-image .source-image-button,.missing-edited{height:240px}.source-caption{font-size:10px}.eyebrow{overflow-wrap:anywhere}}.perfect-button,.repair-button{display:block;width:100%;padding:10px 4px;border:1px solid #9ed9bb;border-radius:8px;background:#e9f8ef;color:#17704c;font-weight:600;margin-top:8px;cursor:pointer}.repair-button{background:#edf3ff;border-color:#b9c9ed;color:#35598a}button:disabled{opacity:.5;cursor:not-allowed}.editor-dialog{width:96vw;max-width:1600px;height:94vh;max-height:96vh;padding:16px}.editor-content{height:calc(100% - 68px);min-height:400px}.editor-surface{position:relative;color:#fff}.editor-submit{position:absolute;z-index:40;top:12px;left:50%;transform:translate(-50%);background:#237847;color:#fff;border-radius:8px;padding:10px 18px;font-weight:700}.editor-surface button{line-height:1.5}.editor-dialog .dialog-top{margin-bottom:8px}.annotation-filters{display:flex;align-items:center;flex-wrap:wrap;gap:12px;padding:12px 30px;background:#fff;border-bottom:1px solid var(--border)}.annotation-filters label{font-weight:600}.annotation-filters span{color:var(--muted);font-size:12px}@media(max-width:700px){.annotation-filters{padding:12px 15px}}.editor-content{display:grid;grid-template-columns:clamp(200px,23vw,320px) minmax(0,1fr);gap:16px}.editor-reference{display:flex;flex-direction:column;min-height:0;padding:16px;background:#f4f6f8;border:1px solid var(--border);border-radius:8px;overflow:auto}.editor-reference h3{margin:0 0 12px;font-size:14px}.editor-reference img{width:100%;flex:1;min-height:0;object-fit:contain}.editor-reference p{color:var(--muted);line-height:1.7}.editor-canvas-panel{min-width:0;min-height:0;height:100%}.editor-surface button[title]{min-width:44px;min-height:44px;padding:9px;display:inline-flex;align-items:center;justify-content:center}.editor-surface button[title] svg{width:24px;height:24px;font-size:24px}.editor-surface .editor-submit{left:16px;transform:none}.editor-surface .editor-history-tools{top:64px}@media(max-width:800px){.editor-content{grid-template-columns:minmax(0,1fr);grid-template-rows:150px minmax(420px,1fr);height:auto;min-height:100%;gap:10px}.editor-reference{padding:10px;display:grid;grid-template-columns:110px minmax(0,1fr);align-items:center;gap:10px}.editor-reference h3{margin:0}.editor-reference img{height:128px}.editor-canvas-panel{height:620px}}.meat-dialog{width:min(1440px,96vw);max-width:96vw;max-height:96vh;padding:0;border:0;border-radius:16px;color:#243341;background:#f5f7f9}.meat-dialog::backdrop{background:#14202bb3}.meat-dialog .dialog-top{position:sticky;top:0;z-index:2;background:#fff}.meat-editor{padding:0 22px 20px}.meat-definition{line-height:1.6;color:#526371}.meat-warning{padding:12px;background:#fff0c8;border-radius:8px}.meat-toolbar{display:flex;gap:14px;align-items:center;flex-wrap:wrap;padding:14px 0}.meat-toolbar label{display:flex;align-items:center;gap:7px}.meat-editor button,.meat-editor select{padding:9px 13px;border:1px solid #c7d3db;border-radius:8px;background:#fff;cursor:pointer;color:#253747}.meat-editor button.active{background:#daf6e9;border-color:#24916a;color:#126847}.meat-editor button:disabled{opacity:.45;cursor:default}.meat-workspace{display:grid;grid-template-columns:1.1fr 1fr;gap:20px}.meat-workspace section{min-width:0;padding:14px;background:#fff;border:1px solid #dce3e8;border-radius:12px}.meat-workspace h3{margin:0 0 12px;font-size:16px}.meat-workspace small{font-weight:400;font-size:12px;color:#607584;margin-left:8px}.meat-stage{height:490px;background:#e7ecf1;border-radius:8px;touch-action:none}.meat-views{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px}.meat-views button{padding:6px 9px}.meat-uv{width:100%;max-width:540px;display:block;margin:auto;image-rendering:pixelated;touch-action:none;cursor:crosshair;background:repeating-conic-gradient(#e4e9ed 0% 25%,#f7f9fa 0% 50%) 50%/16px 16px}.meat-footer{display:flex;gap:12px;align-items:center;justify-content:flex-end;margin-top:18px}.meat-footer>span{margin-right:auto}.meat-footer small{display:block;font-size:12px;color:#607584;margin-top:5px}.meat-footer .button:not(.secondary){background:#18775e;color:#fff;border-color:#18775e}.meat-entry{margin-top:12px}.meat-status{font-size:12px;color:#597567;margin:8px 0}@media(max-width:900px){.meat-workspace{grid-template-columns:1fr}.meat-stage{height:390px}.meat-footer{flex-wrap:wrap}.meat-footer>span{width:100%}.meat-editor{padding:0 12px 15px}}.meat-tolerance input{width:130px;accent-color:#18775e}.meat-tolerance output{min-width:3ch;font-variant-numeric:tabular-nums}.meat-help{font-size:13px;line-height:1.7;color:#526371;margin:12px 0}.meat-stage{cursor:grab}.meat-stage:active{cursor:grabbing}.meat-model-panel{margin:16px 0;padding:16px 20px;border:1px solid #d6dedb;border-radius:12px;background:#f4f8f6;display:flex;flex-wrap:wrap;gap:8px 24px;align-items:center}.meat-model-panel p{margin:4px 0;font-size:13px;color:#4b6058}.meat-model-panel small,.meat-model-panel>p,.meat-model-panel>details{flex-basis:100%}.meat-model-actions{display:flex;gap:8px;margin-left:auto}.meat-preselect{padding:12px;background:#ecf6f0;border-radius:8px;margin-bottom:12px;display:flex;flex-wrap:wrap;gap:8px 14px;align-items:center}.meat-preselect span,.meat-preselect p{font-size:13px;margin:0}.meat-preselect p{flex-basis:100%}
|
best_annotator/static/assets/index-Dk3WlUGQ.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
best_annotator/static/index.html
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
-
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DDJ · 最佳结果标注</title><script src="/vendor/skinview3d-3.4.2.bundle.js" defer></script> <script type="module" crossorigin src="/assets/index-
|
| 2 |
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
| 3 |
</head><body><div id="root"></div></body></html>
|
|
|
|
| 1 |
+
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DDJ · 最佳结果标注</title><script src="/vendor/skinview3d-3.4.2.bundle.js" defer></script> <script type="module" crossorigin src="/assets/index-Dk3WlUGQ.js"></script>
|
| 2 |
+
<link rel="stylesheet" crossorigin href="/assets/index-D0g9WvcQ.css">
|
| 3 |
</head><body><div id="root"></div></body></html>
|
best_annotator/test_meat_model.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import tempfile
|
| 5 |
+
import unittest
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
from app import Dataset, ReviewError
|
| 9 |
+
from meat_model import MeatModel
|
| 10 |
+
from test_perfect import skin_png
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ModelBridgeTests(unittest.TestCase):
|
| 14 |
+
def setUp(self):
|
| 15 |
+
self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name)
|
| 16 |
+
for ident in ['A','B','C']:
|
| 17 |
+
for suffix in ['source','result']:(self.root/f'{ident}_{suffix}.png').write_bytes(skin_png())
|
| 18 |
+
self.ds=Dataset(self.root)
|
| 19 |
+
for key in self.ds.records:
|
| 20 |
+
self.ds.save_annotation(key,'missing','perfect',self.ds.records[key]['id']+'_result.png')
|
| 21 |
+
d=self.ds.meat.load(key)
|
| 22 |
+
self.ds.meat.save(dict(key=key,revision=d['revision'],skin_revision=d['skin_revision'],meat_revision=d['meat_revision'],selected=[]))
|
| 23 |
+
self.model=MeatModel(self.ds,ReviewError,{},self.root/'runtime')
|
| 24 |
+
def tearDown(self):self.tmp.cleanup()
|
| 25 |
+
def test_snapshot_only_explicitly_saved_and_zero_mask_is_valid(self):
|
| 26 |
+
s=self.model.snapshot(True);self.assertEqual(len(s['examples']),3)
|
| 27 |
+
self.assertEqual(json.loads(base64.b64decode(s['examples'][0]['metadata']))['selected_count'],0)
|
| 28 |
+
(self.root/'A_meat.png').unlink()
|
| 29 |
+
s=self.model.snapshot();self.assertEqual(len(s['examples']),2);self.assertEqual(len(s['excluded']),1)
|
| 30 |
+
def test_prediction_does_not_save_and_stale_result_is_rejected(self):
|
| 31 |
+
key=next(iter(self.ds.records));d=self.ds.meat.load(key)
|
| 32 |
+
before={p.name:p.read_bytes() for p in self.root.glob('*_meat.*')}
|
| 33 |
+
with patch.object(self.model,'remote',return_value={'id':'1'*32,'stage':'queued'}) as call:
|
| 34 |
+
self.model.predict(dict(key=key,skin_revision=d['skin_revision']))
|
| 35 |
+
actual=call.call_args.args[1]['request_id']
|
| 36 |
+
self.assertEqual(before,{p.name:p.read_bytes() for p in self.root.glob('*_meat.*')})
|
| 37 |
+
with patch.object(self.model,'remote',return_value={'stage':'complete','prediction':dict(selected=[520],skin_revision='wrong')}):
|
| 38 |
+
with self.assertRaises(ReviewError):self.model.job(actual)
|
| 39 |
+
def test_training_snapshot_and_double_launch_guard(self):
|
| 40 |
+
with patch.object(self.model,'remote',side_effect=[{'training':None},{'id':'1'*32,'stage':'queued'}]) as call:
|
| 41 |
+
self.model.train();req=call.call_args.args[1]
|
| 42 |
+
self.assertEqual(len(req['bundle']['examples']),3)
|
| 43 |
+
with patch.object(self.model,'remote',return_value={'training':{'stage':'training','id':'1'*32}}) as call:
|
| 44 |
+
self.assertEqual(self.model.train()['id'],'1'*32);self.assertEqual(call.call_count,1)
|
| 45 |
+
def test_input_revision_and_job_path_guard(self):
|
| 46 |
+
with patch.object(self.model,'remote') as call:
|
| 47 |
+
with self.assertRaises(ReviewError):self.model.predict(dict(key=next(iter(self.ds.records)),skin_revision='stale'))
|
| 48 |
+
call.assert_not_called()
|
| 49 |
+
with self.assertRaises(ReviewError):self.model.job('../active.json')
|
| 50 |
+
def test_offline_and_status_never_start_training(self):
|
| 51 |
+
with patch.object(self.model,'remote',return_value={'active':{'examples':[]},'training':None}) as call:
|
| 52 |
+
self.model.status();self.model.status()
|
| 53 |
+
call.assert_called_once_with('status')
|
| 54 |
+
with patch('meat_model.subprocess.run',side_effect=OSError('offline')):
|
| 55 |
+
self.model.config=dict(host='ds',python='python',root='/repo',state='/state')
|
| 56 |
+
with self.assertRaises(ReviewError):self.model.remote('status')
|
| 57 |
+
def test_preselection_provenance_is_saved_only_by_save(self):
|
| 58 |
+
key=next(iter(self.ds.records));d=self.ds.meat.load(key)
|
| 59 |
+
self.ds.meat.save(dict(key=key,revision=d['revision'],skin_revision=d['skin_revision'],meat_revision=d['meat_revision'],selected=[520],
|
| 60 |
+
assistance=dict(model_id='test-model',checkpoint_sha256='a'*64)))
|
| 61 |
+
meta=json.loads((self.root/'A_meat.json').read_text())
|
| 62 |
+
self.assertTrue(meta['assistance']['human_saved']);self.assertEqual(meta['selected'],[520])
|
| 63 |
+
|
| 64 |
+
if __name__=='__main__':unittest.main()
|
best_annotator/test_meat_selection.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from 'node:assert/strict';
|
| 2 |
+
import {spawnSync} from 'node:child_process';
|
| 3 |
+
import {buildSurfaceAdjacency} from './src/meatGeometry.js';
|
| 4 |
+
import {floodCells,beginGesture,moveGesture,canPick} from './src/meatSelection.js';
|
| 5 |
+
|
| 6 |
+
function fixture(slim=false) {
|
| 7 |
+
const run=spawnSync(process.env.PYTHON||'python3',['-c',`import json\nfrom meat_annotations import skin_parts\na=bytearray([100,100,100,255]*4096)\na[(20*64+55)*4+3]=${slim?0:255}\np,v,m=skin_parts(a)\nprint(json.dumps(dict(parts=p,valid=list(v),rgba=list(a))))`],{encoding:'utf8'});
|
| 8 |
+
assert.equal(run.status,0,run.stderr);const d=JSON.parse(run.stdout);
|
| 9 |
+
return {...d,rgba:Uint8Array.from(d.rgba),valid:Uint8Array.from(d.valid)};
|
| 10 |
+
}
|
| 11 |
+
for(const slim of [false,true]) {
|
| 12 |
+
const {parts,rgba,valid}=fixture(slim),allowed=valid.slice();
|
| 13 |
+
const graph=buildSurfaceAdjacency(parts,rgba),seed=8*64+8;
|
| 14 |
+
const chosen=floodCells(seed,rgba,valid,allowed,graph,0);
|
| 15 |
+
assert.equal(chosen.length,384,'head must connect across all six faces');
|
| 16 |
+
assert(chosen.includes(8*64+24),'front must connect to back through physical seams');
|
| 17 |
+
assert(!chosen.includes(8*64+40),'must not jump to outer layer');
|
| 18 |
+
assert(!chosen.includes(20*64+20),'must not jump to body');
|
| 19 |
+
for(const id of chosen)assert.equal(graph[id].length,4,`head cell ${id} has four surface neighbors`);
|
| 20 |
+
const faceOnly=new Uint8Array(4096);for(let y=8;y<16;y++)for(let x=8;x<16;x++)faceOnly[y*64+x]=1;
|
| 21 |
+
assert.equal(floodCells(seed,rgba,valid,faceOnly,graph,100).length,64,'respect allowed selection scope');
|
| 22 |
+
rgba[seed*4+3]=0;valid[seed]=0;
|
| 23 |
+
assert.equal(floodCells(seed,rgba,valid,allowed,graph,100).length,0,'transparent seed cannot label');
|
| 24 |
+
}
|
| 25 |
+
// Seed-relative distance, transparent barriers, threshold monotonicity.
|
| 26 |
+
const rgba=new Uint8Array(4096*4),valid=new Uint8Array(4096),allowed=new Uint8Array(4096);
|
| 27 |
+
const graph=Array.from({length:4096},()=>[]);
|
| 28 |
+
for(let i=0;i<5;i++) {
|
| 29 |
+
valid[i]=allowed[i]=1;rgba.set([100+i*20,100+i*20,100+i*20,255],i*4);
|
| 30 |
+
if(i>0){graph[i].push(i-1);graph[i-1].push(i);}
|
| 31 |
+
}
|
| 32 |
+
assert.deepEqual(floodCells(0,rgba,valid,allowed,graph,0),[0]);
|
| 33 |
+
assert.deepEqual(floodCells(0,rgba,valid,allowed,graph,8),[0,1]);
|
| 34 |
+
assert.deepEqual(floodCells(0,rgba,valid,allowed,graph,16),[0,1,2]);
|
| 35 |
+
valid[2]=0;assert.deepEqual(floodCells(0,rgba,valid,allowed,graph,100),[0,1]);
|
| 36 |
+
const pointer={pointerId:1,clientX:0,clientY:0,ctrlKey:false,button:0,isPrimary:true};
|
| 37 |
+
let g=beginGesture(pointer);g.id=520;assert(canPick(g));
|
| 38 |
+
moveGesture(g,{...pointer,clientX:30});moveGesture(g,pointer);assert(!canPick(g),'drag and return must not paint');
|
| 39 |
+
g=beginGesture({...pointer,button:2});g.id=520;assert(!canPick(g),'right drag/click only rotates');
|
| 40 |
+
g=beginGesture({...pointer,button:2,ctrlKey:true});g.id=520;assert(canPick(g),'macOS Ctrl-context-click supported');
|
| 41 |
+
g.cancelled=true;assert(!canPick(g));
|
| 42 |
+
console.log('surface flood classic/slim, seams, part/layer isolation, fixed-seed tolerance, alpha/scope, click-vs-drag verified');
|