训练时自动移除不合格的历史项目

This commit is contained in:
tfarcraw 2026-11-10 18:39:42 +08:00
parent 8ceb2cb57b
commit 46225993dc
2 changed files with 62 additions and 3 deletions

View File

@ -14,6 +14,47 @@ spec.loader.exec_module(worker)
class RecipeTrainingTests(unittest.TestCase):
def test_unqualified_old_projects_removed_but_current_still_validated(self):
for defect in ("unreviewed", "no_validation", "missing_box", "missing_image"):
with self.subTest(defect=defect), tempfile.TemporaryDirectory() as temporary:
root = Path(temporary).resolve()
paths = [root / name / "project.json" for name in ("old", "valid", "current")]
for path in paths:
path.parent.mkdir()
(path.parent / "frame.jpg").write_bytes(b"test-image")
worker.save_json(path, {"name": path.parent.name, "recipeDirectory": str(root),
"width": 100, "height": 100, "frames": [
{"index": i, "image": "frame.jpg", "status": "reviewed", "box": [10, 10, 50, 50]}
for i in range(30)]})
worker.recipe_context({"project": str(path)})
old, valid, current = paths
data = worker.read_json(old)
if defect == "missing_image":
(old.parent / "frame.jpg").unlink()
elif defect == "missing_box":
data["frames"][0]["box"] = None
else:
for frame in data["frames"][1 if defect == "unreviewed" else 24:]:
frame["status"] = "auto"
worker.save_json(old, data)
before = old.read_bytes()
request = {"project": str(current), "every": 1}
with patch.object(worker, "emit"):
dataset = worker.export_dataset(request).parent
state = worker.read_json(root / "recipe-training.json")
self.assertEqual(state["projects"], [str(valid), str(current)])
self.assertNotIn(str(old), state["labels"])
self.assertEqual(state["classes"], ["old", "valid", "current"])
manifest = worker.read_json(dataset / "manifest.json")
self.assertEqual([p["project"] for p in manifest["projects"]], [str(valid), str(current)])
self.assertEqual([p["classId"] for p in manifest["projects"]], [1, 2])
self.assertEqual(old.read_bytes(), before)
# Removal persists across exports; opening it explicitly restores validation.
worker.export_dataset(request)
with self.assertRaises(ValueError):
worker.export_dataset({"project": str(old), "every": 1})
self.assertIn(str(old), worker.read_json(root / "recipe-training.json")["projects"])
def test_managed_catalog_is_authoritative(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary).resolve()

View File

@ -316,16 +316,34 @@ def export_dataset(request):
if every < 1 or not 0 < ratio < 0.5:
raise ValueError("训练抽样间隔需 ≥1,验证比例需在 0–0.5 之间")
samples = []
current = Path(request["project"]).resolve()
rejected = []
for path, data in projects:
selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")]
reason = None
if any(f["status"] == "reviewed" and not f.get("box") for f in selected):
raise ValueError(f"{data['name']}:已复核的正样本缺少标注框")
reason = "已复核的正样本缺少标注框"
boundary = int(len(data["frames"]) * (1 - ratio))
training = [f for f in selected if f["index"] < boundary - every and f["index"] % every == 0]
validation = [f for f in selected if f["index"] >= boundary and f["index"] % every == 0]
if len(training) < 2 or not validation or not any(f.get("box") for f in training) or not any(f.get("box") for f in validation):
raise ValueError(f"{data['name']}:复核样本不足,训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。请补充复核或减小训练抽样间隔")
reason = reason or "复核样本不足,训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。请补充复核或减小训练抽样间隔"
if any(not (path.parent / f["image"]).is_file() for f in training + validation):
reason = reason or "训练样本的图像文件不存在"
if reason:
if path == current:
raise ValueError(f"{data['name']}:{reason}")
rejected.append(str(path))
emit(f"旧项目不符合训练要求,已自动从训练名单移除:{path}({reason})。继续使用其余项目训练,类别编号保留。")
continue
samples.append((path, data, training, validation))
if rejected:
registry = root / "recipe-training.json"
state = read_json(registry)
state["projects"] = [p for p in state["projects"] if p not in rejected]
for item in rejected:
state.get("labels", {}).pop(item, None)
save_json(registry, state)
output = root / "datasets" / ("dataset-" + uuid.uuid4().hex[:10])
output.mkdir(parents=True)
manifest = []
@ -349,7 +367,7 @@ def export_dataset(request):
(output / "data.yaml").write_text(yaml, encoding="utf-8")
save_json(output / "manifest.json", {"projects": manifest, "classes": classes, "gap": every})
save_json(root / "latest-dataset.json", {"yaml": str(output / "data.yaml")})
emit(f"配方数据导出完成 · {len(classes)} 类零件 / {len(projects)} 个视频", output=str(output), progress=1)
emit(f"配方数据导出完成 · {len(classes)} 类零件 / {len(samples)} 个视频", output=str(output), progress=1)
return output / "data.yaml"