Преглед изворни кода

feat(scripts): 标注骨架生成器 label_template.py(现场素材到位即用)

为什么改:
现场一段片段 step 1 就有几千帧,手工写 labels.json 的键名不现实;而且 domain 标错会让
数据静默进不了精度统计。素材一到就需要一个“扫目录 → 出待填骨架”的工具。

改了什么:
- scripts/label_template.py(新):递归扫帧目录,按 --step 抽样(默认 15 ≈ 15fps 下 1 张/秒),
  生成/追加 labels 骨架(domain 填好、label/expect/note 留空),并打印标签词表与后续命令;
  --merge 只补新帧,已有条目原样保留。
- scripts/dataset_harness.py:load_labels 跳过“label 为空”的条目并计数(报告显示
  “未标 N 条已跳过”);整份 labels 都没填时直接 rc=2 报错,避免“什么都没标却跑出一张全绿的表”。
- docs/field_capture_spec.md §5:补“骨架怎么来”与跳过语义。

验证:
- label_template.py 对 ctl_original 生成 4 条骨架;再跑一次 --merge -> 新增 0 条;
- 全空 labels 跑 harness -> rc=2,提示先用 label_template.py;
- 只填 1 条(02_C70E=empty_gondola)-> 图片 1 张(人工判读 1 条,未标 3 条已跳过),
  发布 3 命中。
kwass пре 3 дана
родитељ
комит
6b26560b61
3 измењених фајлова са 175 додато и 7 уклоњено
  1. 14 0
      docs/field_capture_spec.md
  2. 21 7
      scripts/dataset_harness.py
  3. 140 0
      scripts/label_template.py

+ 14 - 0
docs/field_capture_spec.md

@@ -78,6 +78,20 @@ python scripts/extract_frames.py --clip 现场.mp4 --out runs/frames_yard1_front
 
 真值必须**人工**判读并留依据;同一条争议样本至少两人复核。
 
+**骨架怎么来**(几千帧别手工写键名):
+
+```bash
+# 每 15 帧取一张(15 fps 下 ≈ 1 张/秒),生成待填骨架;现场素材自动填 domain=field
+python scripts/label_template.py --images runs/frames_yard1_front_boxed40_day \
+    --domain field --out labels_yard1.json --step 15
+# 后来又补拍了:只追加新帧,已有条目原样保留
+python scripts/label_template.py --images runs/frames_yard1_front_boxed40_day \
+    --out labels_yard1.json --merge
+```
+
+没填 `label` 的条目会被 `dataset_harness.py` **跳过并计数**(报告里显示"未标 N 条已跳过"),
+不会静默当成判对/判错;如果整份 labels 一条都没填,harness 直接报错退出(rc=2)。
+
 ## 6. 怎么跑
 
 ```bash

+ 21 - 7
scripts/dataset_harness.py

@@ -245,14 +245,19 @@ def short_reason(row: dict) -> str:
     return text.replace(" ", " ")
 
 
-def load_labels(path: str) -> dict[str, dict]:
-    """读人工判读表:``{"NX70_001.jpg": {"label": "empty_flatbed", "expect": 3}}``。"""
+def load_labels(path: str) -> tuple[dict[str, dict], int]:
+    """读人工判读表:``{"NX70_001.jpg": {"label": "empty_flatbed", "expect": 3}}``。
+
+    返回 ``(可用条目, 未填 label 的条目数)``:`scripts/label_template.py` 生成的骨架里
+    `label` 是空的,这类条目**跳过**(报告里会显示“未标 N 条”),不静默当成判对/判错。
+    """
 
     if not path:
-        return {}
+        return {}, 0
     with open(path, encoding="utf-8-sig") as handle:
         raw = json.load(handle)
     out: dict[str, dict] = {}
+    skipped = 0
     for name, item in raw.items():
         if name.startswith("_"):
             continue  # `_note` / `_source` 这类说明键
@@ -260,6 +265,9 @@ def load_labels(path: str) -> dict[str, dict]:
             item = {"label": item}
         entry = dict(item)
         label = str(entry.get("label", "")).strip()
+        if not label:
+            skipped += 1
+            continue
         if label not in LABEL_EXPECT:
             raise SystemExit("labels.json 里 %s 的 label 不认识:%r(可选:%s)"
                              % (name, label, ", ".join(sorted(LABEL_EXPECT))))
@@ -269,10 +277,10 @@ def load_labels(path: str) -> dict[str, dict]:
             raise SystemExit("labels.json 里 %s 的 domain 不认识:%r(可选:%s)"
                              % (name, domain, ", ".join(DOMAINS)))
         entry["domain"] = domain
-        if "expect" not in entry:
+        if "expect" not in entry or entry["expect"] is None:
             entry["expect"] = LABEL_EXPECT[label]
         out[os.path.basename(name)] = entry
-    return out
+    return out, skipped
 
 
 def parse_args(argv=None) -> argparse.Namespace:
@@ -335,7 +343,11 @@ def main(argv=None) -> int:
         return 2
     if args.limit > 0:
         images = images[:args.limit]
-    labels = load_labels(args.labels)
+    labels, unlabeled = load_labels(args.labels)
+    if args.labels and not labels:
+        print("labels 文件里没有可用的判读条目(label 全是空的?)—— 先用 "
+              "scripts/label_template.py 生成骨架并把 label 填上", file=sys.stderr)
+        return 2
     if args.domain:
         wanted = {item.strip().lower() for item in args.domain.split(",") if item.strip()}
         bad = wanted - set(DOMAINS)
@@ -362,7 +374,9 @@ def main(argv=None) -> int:
 
     print("可执行    : %s" % exe)
     print("配置模板  : %s" % os.path.relpath(config, ROOT))
-    print("图片      : %d 张(人工判读 %d 条)" % (len(images), len(labels)))
+    print("图片      : %d 张(人工判读 %d 条%s)"
+          % (len(images), len(labels),
+             ",未标 %d 条已跳过" % unlabeled if unlabeled else ""))
     print("口径      : 本帧候选 = require_commit=false 单帧 / 发布值 = require_commit=true"
           " + 同图 %d 帧" % args.repeats)
     print("")

+ 140 - 0
scripts/label_template.py

@@ -0,0 +1,140 @@
+"""给「现场素材到位」准备的标注骨架:把帧目录变成 `labels.json` 的待填条目。
+
+为什么需要它:`scripts/dataset_harness.py` 认的是 `labels.json`(`{"文件名": {"domain","label",...}}`),
+而现场一段 5 分钟的片段 step 1 就有几千帧 —— 手工写键名不现实,而且**标错 domain 会让数据
+进不了精度统计**。这个脚本只做三件事:
+
+1. 扫帧目录(递归),按文件名排序后每 `--step` 帧取一张(默认 15 = 15 fps 下的 1 张/秒);
+2. 生成/追加条目:`domain` 填好(现场素材必须是 `field`),`label` / `expect` / `note` 留空待填;
+3. 打印标签词表与"填完之后跑什么",并把还缺几条讲清楚。
+
+用法::
+
+    # 生成骨架(现场素材:domain=field)
+    python scripts/label_template.py --images runs/frames_yard1_front_boxed40_day \
+        --domain field --out labels_yard1.json --step 15
+
+    # 已经标过一部分:只补新帧,已有条目原样保留
+    python scripts/label_template.py --images runs/frames_yard1_front_boxed40_day \
+        --out labels_yard1.json --merge
+
+    # 填完之后(未填 label 的条目会被 harness 跳过并计数)
+    python scripts/dataset_harness.py --images runs/frames_yard1_front_boxed40_day \
+        --labels labels_yard1.json --domain field --out runs/harness_field
+
+只依赖标准库。
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+IMAGE_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".pgm")
+
+#: 与 `scripts/dataset_harness.py::LABEL_EXPECT` 同一张表(这里只用于打印提示)
+LABEL_HINT = {
+    "boxed_flatbed": "平车坐箱(真值 2)",
+    "boxed_gondola": "敞车坐箱(真值 1)",
+    "empty_gondola": "空敞车(真值 3)",
+    "empty_flatbed": "空平车(真值 3)",
+    "working": "作业中 / 吊具仍夹箱 / 箱体高悬(不判,真值 0)",
+}
+
+
+def collect_images(dirs: list[str]) -> list[str]:
+    out: list[str] = []
+    for base in dirs:
+        if os.path.isfile(base):
+            out.append(base)
+            continue
+        for cur, _sub, files in os.walk(base):
+            for name in sorted(files):
+                if name.lower().endswith(IMAGE_EXT):
+                    out.append(os.path.join(cur, name))
+    return sorted(out)
+
+
+def main(argv=None) -> int:
+    parser = argparse.ArgumentParser(
+        description="帧目录 → labels.json 待填骨架(现场素材标注用)")
+    parser.add_argument("--images", nargs="+", required=True, help="帧目录(递归)或图片")
+    parser.add_argument("--out", required=True, help="输出 labels JSON(可已存在,配合 --merge)")
+    parser.add_argument("--domain", default="field", choices=("field", "near", "web"),
+                        help="数据域(现场素材必须 field;默认 field)")
+    parser.add_argument("--step", type=int, default=15,
+                        help="每 N 帧取一张(15 fps 下 15 ≈ 1 张/秒;默认 15)")
+    parser.add_argument("--merge", action="store_true",
+                        help="与已有 --out 合并:已有条目原样保留,只补新文件")
+    parser.add_argument("--limit", type=int, default=0, help="最多生成多少条(0=全部)")
+    args = parser.parse_args(argv)
+
+    if args.step < 1:
+        print("--step 至少 1", file=sys.stderr)
+        return 2
+    images = collect_images(args.images)
+    if not images:
+        print("没有找到图片:%s" % " ".join(args.images), file=sys.stderr)
+        return 2
+    picked = images[::args.step]
+    if args.limit > 0:
+        picked = picked[:args.limit]
+
+    existing: dict = {}
+    if os.path.exists(args.out):
+        if not args.merge:
+            print("%s 已存在;要增量补条目请加 --merge(或换个 --out)" % args.out,
+                  file=sys.stderr)
+            return 2
+        with open(args.out, encoding="utf-8-sig") as handle:
+            existing = json.load(handle)
+    elif args.merge:
+        print("提示:%s 不存在,--merge 按新文件处理" % args.out)
+
+    added = 0
+    for path in picked:
+        name = os.path.basename(path)
+        if name in existing and not name.startswith("_"):
+            continue
+        existing[name] = {
+            "domain": args.domain,
+            "label": "",
+            "expect": None,
+            "note": "",
+        }
+        added += 1
+
+    existing.setdefault("_note", [
+        "由 scripts/label_template.py 生成骨架:label / expect / note 需要人工填。",
+        "label 词表:" + ";".join("%s = %s" % (k, v) for k, v in LABEL_HINT.items()),
+        "domain 必须是 field(现场实拍)才计入精度;near/web 只作回归参照或域外负样本。",
+        "填完跑:python scripts/dataset_harness.py --images <目录> --labels <本文件> --domain field",
+        "未填 label 的条目会被 harness 跳过并在报告里计数(不会静默当成判对/判错)。",
+    ])
+
+    with open(args.out, "w", encoding="utf-8", newline="") as handle:
+        json.dump(existing, handle, ensure_ascii=False, indent=2)
+        handle.write("\n")
+
+    todo = [k for k, v in existing.items()
+            if not k.startswith("_") and not str(v.get("label") or "").strip()]
+    print("帧目录    : %s(%d 张,按 step=%d 取 %d 张)"
+          % (" ".join(args.images), len(images), args.step, len(picked)))
+    print("输出      : %s(新增 %d 条,共 %d 条,待填 %d 条)"
+          % (args.out, added,
+             len([k for k in existing if not k.startswith("_")]), len(todo)))
+    print("标签词表  :")
+    for key, hint in LABEL_HINT.items():
+        print("  %-14s %s" % (key, hint))
+    print("下一步    : 填好 label(必要时 expect/note)后运行")
+    print("            python scripts/dataset_harness.py --images %s --labels %s --domain %s"
+          % (" ".join(args.images), args.out, args.domain))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())