aisop/tests/Training.Smoke/test_recipe_training.py

227 lines
14 KiB
Python

"""Recipe training regression: real dataset export, simulated training lifecycle."""
import importlib.util
import json
from pathlib import Path
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location("worker", Path(__file__).parents[2] / "tools" / "worker.py")
worker = importlib.util.module_from_spec(spec)
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()
current = root / "parts" / "current" / "project.json"
current.parent.mkdir(parents=True)
(current.parent / "frame.jpg").write_bytes(b"test-image")
data = {"name": "螺丝", "recipeName": root.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.save_json(current, data)
config = root / (root.name + ".yaml")
config.write_text('sop:\n parts: [支架, 螺丝]\n', encoding="utf-8")
worker.save_json(root / "recipe-training.json", {"projects": [str(current)], "classes": ["螺丝", "旧名称"]})
_, _, classes = worker.recipe_context({"project": str(current)})
self.assertEqual(classes, ["支架", "螺丝"])
dataset = worker.export_dataset({"project": str(current), "every": 1}).parent
self.assertEqual(worker.read_json(dataset / "manifest.json")["classes"], ["支架", "螺丝"])
self.assertEqual({p.read_text().split()[0] for p in (dataset / "labels" / "train").glob("*.txt")}, {"1"})
before = (root / "recipe-training.json").read_bytes()
worker.save_json(current, {**data, "name": "随意输入"})
with self.assertRaisesRegex(ValueError, "不在配方零件列表"):
worker.recipe_context({"project": str(current)})
self.assertEqual((root / "recipe-training.json").read_bytes(), before)
worker.save_json(current, data)
config.write_text('sop:\n parts: [螺丝, 螺丝]\n', encoding="utf-8")
with self.assertRaisesRegex(ValueError, "零件列表无效"):
worker.recipe_context({"project": str(current)})
config.write_text('sop:\n parts: []\n', encoding="utf-8")
with self.assertRaisesRegex(ValueError, "不在配方零件列表"):
worker.recipe_context({"project": str(current)})
def test_missing_project_removed_and_restored(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary).resolve()
current = root / "parts" / "current" / "project.json"
missing = root / "parts" / "missing" / "project.json"
current.parent.mkdir(parents=True)
data = {"name": "已训练", "recipeDirectory": str(root), "width": 100, "height": 100,
"frames": [{"index": 0, "image": "frame.jpg"}]}
worker.save_json(current, data)
registry = root / "recipe-training.json"
state = {"projects": [str(current), str(missing)], "classes": ["已训练", "未训练"],
"labels": {str(current): "已训练", str(missing): "未训练"}}
worker.save_json(registry, state)
with patch.object(worker, "emit") as emit:
_, projects, classes = worker.recipe_context({"project": str(current)})
self.assertEqual([p for p, _ in projects], [current])
self.assertEqual(classes, state["classes"])
self.assertEqual(worker.read_json(registry)["missingProjects"], [str(missing)])
self.assertEqual(worker.read_json(registry)["projects"], [str(current)])
self.assertNotIn(str(missing), worker.read_json(registry)["labels"])
self.assertIn("自动从训练名单移除", emit.call_args.args[0])
# Persisted retirement allows subsequent exports without renumbering.
worker.recipe_context({"project": str(current)})
missing.parent.mkdir(parents=True)
worker.save_json(missing, {**data, "name": "未训练"})
_, projects, classes = worker.recipe_context({"project": str(missing)})
self.assertEqual(len(projects), 2)
self.assertEqual(classes, state["classes"])
self.assertEqual(worker.read_json(registry)["missingProjects"], [])
def test_incremental_recipe(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary) / "装配配方"
def part(name, folder):
directory = root / "parts" / folder
directory.mkdir(parents=True)
(directory / "frame.jpg").write_bytes(b"test-image")
path = directory / "project.json"
worker.save_json(path, {"name": name, "recipeName": root.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)})
return path
first = part("零件1", "first")
loaded = []
options = []
exports = []
class FakeYolo:
task = "detect"
fail = False
fail_export = False
def __init__(self, weights):
loaded.append(str(weights))
self.weights = Path(weights)
def add_callback(self, *args):
pass
def train(self, **kwargs):
options.append(kwargs)
if self.fail:
raise RuntimeError("simulated failure")
directory = Path(kwargs["project"]) / kwargs["name"]
directory.mkdir(parents=True)
best = directory / "best.pt"
best.write_bytes(b"checkpoint")
self.trainer = SimpleNamespace(best=best, save_dir=directory, metrics={"mAP": 0.9})
def export(self, **kwargs):
exports.append(kwargs)
if self.fail_export:
raise RuntimeError("simulated export failure")
output = self.weights.with_suffix(".onnx")
output.write_bytes(b"onnx-model")
return str(output)
request = {"project": str(first), "every": 1, "epochs": 1, "imageSize": 32}
with patch.dict(sys.modules, {"ultralytics": SimpleNamespace(YOLO=FakeYolo),
"torch": SimpleNamespace(cuda=SimpleNamespace(is_available=lambda: False))}):
worker.train(request)
previous = worker.read_json(root / "latest-model.json")
self.assertEqual(Path(previous["weights"]).name, "装配配方.pt")
self.assertEqual(Path(previous["onnx"]).name, "装配配方.onnx")
self.assertTrue(Path(previous["onnx"]).is_file())
second = part("零件2", "second")
request["project"] = str(second)
worker.train(request)
latest = worker.read_json(root / "latest-model.json")
self.assertEqual(loaded, ["yolo11n.pt", previous["weights"], previous["weights"], latest["weights"]])
self.assertEqual(exports[-1], {"format": "onnx", "imgsz": 32, "opset": 17,
"dynamic": False, "simplify": False, "nms": False})
self.assertNotEqual(previous["onnx"], latest["onnx"])
self.assertTrue(Path(previous["onnx"]).is_file())
self.assertEqual(worker.read_json(Path(latest["runDirectory"]) / "training-result.json"), latest)
self.assertFalse(options[-1]["resume"])
self.assertEqual(latest["classes"], ["零件1", "零件2"])
dataset = Path(latest["dataset"]).parent
self.assertEqual(len(list((dataset / "images" / "train").glob("*.jpg"))), 46)
self.assertEqual({p.read_text().split()[0] for p in (dataset / "labels" / "train").glob("*.txt")}, {"0", "1"})
self.assertTrue(Path(previous["weights"]).is_file())
# Reopening an older video retains all classes and their identifiers.
worker.export_dataset({**request, "project": str(first)})
self.assertEqual(worker.read_json(root / "recipe-training.json")["classes"], ["零件1", "零件2"])
worker.export_onnx({**request, "imageSize": 640})
self.assertEqual(exports[-1]["imgsz"], 32)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
# A different recipe publishes into its own directory and starts independently.
other = Path(temporary) / "另一配方"
other.mkdir()
(other / "frame.jpg").write_bytes(b"test-image")
other_project = other / "project.json"
worker.save_json(other_project, {**worker.read_json(second), "recipeName": other.name,
"recipeDirectory": str(other)})
worker.train({**request, "project": str(other_project)})
other_latest = worker.read_json(other / "latest-model.json")
self.assertEqual(loaded[-2], "yolo11n.pt")
self.assertEqual(Path(other_latest["onnx"]).name, "另一配方.onnx")
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
FakeYolo.fail_export = True
with self.assertRaisesRegex(RuntimeError, "ONNX 导出失败"):
worker.train(request)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
self.assertTrue(Path(latest["onnx"]).is_file())
FakeYolo.fail_export = False
FakeYolo.fail = True
with self.assertRaisesRegex(RuntimeError, "simulated failure"):
worker.train(request)
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
# Missing old data is removed automatically, even for trained classes.
first.unlink()
yaml = worker.export_dataset(request)
manifest = worker.read_json(yaml.parent / "manifest.json")
self.assertEqual([p["project"] for p in manifest["projects"]], [str(second.resolve())])
self.assertEqual(manifest["classes"], ["零件1", "零件2"])
self.assertEqual(worker.read_json(root / "recipe-training.json")["projects"], [str(second.resolve())])
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
if __name__ == "__main__":
unittest.main()