80 lines
3.8 KiB
Python
80 lines
3.8 KiB
Python
"""Exercise the real annotation worker, with optional SAM2 propagation, in a temporary project."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
import cv2
|
|
import numpy as np
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("worker", type=Path)
|
|
parser.add_argument("--sam2", action="store_true")
|
|
options = parser.parse_args()
|
|
worker = options.worker.resolve()
|
|
|
|
with tempfile.TemporaryDirectory(prefix="sophelper-worker-") as directory:
|
|
root = Path(directory)
|
|
|
|
def run(request):
|
|
request_file = root / "request.json"
|
|
request_file.write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8")
|
|
process = subprocess.run([sys.executable, "-u", str(worker), str(request_file)],
|
|
capture_output=True, text=True, encoding="utf-8", timeout=240,
|
|
env=dict(os.environ, PYTHONUTF8="1"))
|
|
if process.returncode:
|
|
raise RuntimeError(process.stdout + process.stderr)
|
|
events = []
|
|
for line in process.stdout.splitlines():
|
|
try:
|
|
events.append(json.loads(line))
|
|
except json.JSONDecodeError:
|
|
pass
|
|
return events
|
|
|
|
events = run({"action": "doctor"})
|
|
modules = next(event["modules"] for event in events if "modules" in event)
|
|
required = ["cv2", "numpy", "torch", "ultralytics", "onnx"] + (["sam2"] if options.sam2 else [])
|
|
assert all(modules[name] for name in required), modules
|
|
print("PASS: annotation worker dependency check", flush=True)
|
|
|
|
video = root / "input.avi"
|
|
writer = cv2.VideoWriter(str(video), cv2.VideoWriter_fourcc(*"MJPG"), 10, (320, 240))
|
|
assert writer.isOpened(), "MJPEG encoder unavailable"
|
|
for index in range(6):
|
|
image = np.full((240, 320, 3), 25, dtype=np.uint8)
|
|
cv2.rectangle(image, (40 + index * 3, 60), (120 + index * 3, 140), (30, 200, 40), -1)
|
|
writer.write(image)
|
|
writer.release()
|
|
|
|
project = root / "标注 测试项目"
|
|
run({"action": "extract", "video": str(video), "output": str(project), "name": "测试零件", "maxFrames": 6})
|
|
project_file = project / "project.json"
|
|
data = json.loads(project_file.read_text(encoding="utf-8"))
|
|
assert len(data["frames"]) == 6 and data["width"] == 320 and data["height"] == 240
|
|
assert all((project / frame["image"]).is_file() for frame in data["frames"])
|
|
print("PASS: actual video import, frame extraction, Unicode and space paths", flush=True)
|
|
|
|
data["frames"][0].update(box=[40, 60, 120, 140], status="reviewed", prompt=True)
|
|
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
if options.sam2:
|
|
run({"action": "propagate", "project": str(project_file), "device": "cpu"})
|
|
data = json.loads(project_file.read_text(encoding="utf-8"))
|
|
assert data["frames"][0]["status"] == "reviewed" and data["frames"][0]["prompt"]
|
|
assert all(frame["status"] == "auto" for frame in data["frames"][1:])
|
|
assert any(frame["box"] for frame in data["frames"][1:]), "SAM2 produced no tracked boxes"
|
|
print("PASS: SAM2 model load and propagation preserve the reviewed seed", flush=True)
|
|
|
|
for index, frame in enumerate(data["frames"]):
|
|
frame.update(box=[40 + index * 3, 60, 120 + index * 3, 140], status="reviewed")
|
|
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
events = run({"action": "export", "project": str(project_file), "every": 1})
|
|
output = Path(next(event["output"] for event in events if "output" in event))
|
|
assert (output / "data.yaml").is_file()
|
|
assert len(list((output / "labels" / "train").glob("*.txt"))) >= 2
|
|
assert list((output / "labels" / "val").glob("*.txt"))
|
|
print("PASS: reviewed annotations export into training and validation data", flush=True)
|