528 lines
27 KiB
Python
528 lines
27 KiB
Python
"""PartTrainer worker. JSON request file in, JSON-line events out. No UI dependencies.
|
||
|
||
SAM2 is optional and imported only for propagation. Never silently substitute another tracker.
|
||
"""
|
||
import base64
|
||
import hashlib
|
||
from contextlib import nullcontext
|
||
import importlib.util
|
||
import json
|
||
import math
|
||
import os
|
||
from pathlib import Path
|
||
import shutil
|
||
import sys
|
||
import tempfile
|
||
import traceback
|
||
import urllib.request
|
||
import uuid
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
os.environ.setdefault("YOLO_CONFIG_DIR", str(ROOT / ".cache" / "ultralytics"))
|
||
os.environ.setdefault("HF_HOME", str(ROOT / ".cache" / "huggingface"))
|
||
os.environ["TORCHINDUCTOR_CACHE_DIR"] = str(ROOT / ".cache" / "torch")
|
||
os.environ["TRITON_CACHE_DIR"] = str(ROOT / ".cache" / "triton")
|
||
os.environ["MPLCONFIGDIR"] = str(ROOT / ".cache" / "matplotlib")
|
||
os.environ.setdefault("TORCH_HOME", str(ROOT / ".cache" / "torch-hub"))
|
||
os.environ["YOLO_AUTOINSTALL"] = "false"
|
||
|
||
|
||
def emit(message, **values):
|
||
print(json.dumps({"message": message, **values}, ensure_ascii=False), flush=True)
|
||
|
||
|
||
def save_json(path, data):
|
||
path = Path(path)
|
||
temporary = path.with_suffix(path.suffix + ".tmp")
|
||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
temporary.replace(path)
|
||
|
||
|
||
def read_json(path):
|
||
return json.loads(Path(path).read_text(encoding="utf-8-sig"))
|
||
|
||
|
||
def sha256_file(path):
|
||
digest = hashlib.sha256()
|
||
with Path(path).open("rb") as source:
|
||
while chunk := source.read(1024 * 1024):
|
||
digest.update(chunk)
|
||
return digest.hexdigest()
|
||
|
||
|
||
def validate_box(box, width, height):
|
||
if (not isinstance(box, list) or len(box) != 4
|
||
or not all(isinstance(v, (int, float)) and math.isfinite(v) for v in box)
|
||
or not (0 <= box[0] < box[2] <= width and 0 <= box[1] < box[3] <= height)):
|
||
raise ValueError("无效标注框:需要图像范围内的 [x1,y1,x2,y2] 像素坐标")
|
||
return box
|
||
|
||
|
||
def load_project(path):
|
||
path = Path(path).resolve()
|
||
data = read_json(path)
|
||
if data["width"] <= 0 or data["height"] <= 0 or not data["frames"]:
|
||
raise ValueError("项目没有有效的视频帧")
|
||
for frame in data["frames"]:
|
||
image = (path.parent / frame["image"]).resolve()
|
||
if not image.is_relative_to(path.parent):
|
||
raise ValueError("帧路径超出项目目录")
|
||
if frame.get("box") is not None:
|
||
validate_box(frame["box"], data["width"], data["height"])
|
||
return path, data
|
||
|
||
|
||
def doctor(request):
|
||
modules = {m: importlib.util.find_spec(m) is not None for m in ("cv2", "numpy", "torch", "ultralytics", "sam2", "onnx")}
|
||
emit("Python " + sys.version.split()[0], modules=modules)
|
||
if modules["torch"]:
|
||
import torch
|
||
emit(f"PyTorch {torch.__version__} · CUDA {'可用' if torch.cuda.is_available() else '不可用,将使用 CPU'}")
|
||
if not all(modules[m] for m in ("cv2", "numpy", "torch", "ultralytics")):
|
||
setup = "tools/Setup-Python.ps1 -Sam2" if sys.platform == "win32" else "PYTHON=python3.12 bash tools/Setup-Python.sh 程序目录 --sam2"
|
||
raise RuntimeError(f"标注运行环境依赖不完整,请运行 {setup} 安装")
|
||
if not modules["sam2"]:
|
||
emit("尚未安装 SAM2;手动标注、导出、训练仍可用,自动传播需安装 SAM2")
|
||
if request.get("strict"):
|
||
for name in ("cv2", "numpy", "torch", "ultralytics", "sam2", "onnx", "onnxruntime", "onnxscript"):
|
||
importlib.import_module(name)
|
||
initial = ROOT / "tools" / "yolo11n.pt"
|
||
checkpoint = ROOT / "models" / "sam2.1_hiera_tiny.pt"
|
||
if not initial.is_file() or not checkpoint.is_file():
|
||
raise FileNotFoundError("独立运行目录缺少 YOLO 初始权重或 SAM2 权重")
|
||
from ultralytics import YOLO
|
||
YOLO(str(initial))
|
||
from sam2.build_sam import build_sam2_video_predictor
|
||
torch.set_num_threads(min(4, os.cpu_count() or 1))
|
||
build_sam2_video_predictor("configs/sam2.1/sam2.1_hiera_t.yaml", str(default_checkpoint()), device="cpu")
|
||
emit("独立训练环境检查通过:本地 YOLO 与 SAM2 权重均成功加载")
|
||
|
||
|
||
def extract(request):
|
||
import cv2
|
||
import numpy as np
|
||
video = Path(request["video"]).resolve()
|
||
target = Path(request["output"]).resolve()
|
||
stride = int(request.get("stride", 1))
|
||
limit = int(request.get("maxFrames", 600))
|
||
if stride < 1 or not 2 <= limit <= 10000:
|
||
raise ValueError("抽帧间隔需 ≥1,帧数上限需在 2–10000 之间")
|
||
if target.exists():
|
||
raise ValueError("输出项目目录已存在,请选择新的项目名称")
|
||
cap = cv2.VideoCapture(str(video))
|
||
if not cap.isOpened():
|
||
raise ValueError("视频无法打开")
|
||
staging = target.with_name(target.name + ".importing-" + uuid.uuid4().hex[:8])
|
||
staging.mkdir(parents=True)
|
||
try:
|
||
if request.get("recipeDirectory"):
|
||
directory = Path(request["recipeDirectory"]).resolve() / "recordings"
|
||
directory.mkdir(parents=True, exist_ok=True)
|
||
if not video.is_relative_to(directory.parent):
|
||
stored = directory / video.name
|
||
if stored.exists() and sha256_file(stored) != sha256_file(video):
|
||
stored = directory / (video.stem + "-" + sha256_file(video)[:10] + video.suffix)
|
||
if not stored.exists():
|
||
shutil.copy2(video, stored)
|
||
video = stored
|
||
frames_dir = staging / "frames"
|
||
frames_dir.mkdir()
|
||
fps = cap.get(cv2.CAP_PROP_FPS)
|
||
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||
# Bound RAM/disk use and preserve coverage across the entire source video.
|
||
stride = max(stride, math.ceil(total / limit)) if total > 0 else stride
|
||
data = {"name": request.get("name", "零件"), "video": str(video), "fps": fps if math.isfinite(fps) else 0,
|
||
"width": 0, "height": 0, "stride": stride, "frames": [],
|
||
"recipeName": request.get("recipeName", ""), "recipeDirectory": request.get("recipeDirectory", "")}
|
||
index = 0
|
||
while True:
|
||
ok, image = cap.read()
|
||
if not ok:
|
||
break
|
||
if index % stride == 0:
|
||
if len(data["frames"]) >= limit:
|
||
emit("已达到帧数上限,剩余视频未导入")
|
||
break
|
||
h, w = image.shape[:2]
|
||
data["width"], data["height"] = w, h
|
||
number = len(data["frames"])
|
||
name = f"frames/{number:06d}.jpg"
|
||
success, buffer = cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 95])
|
||
if not success:
|
||
raise RuntimeError("帧编码失败")
|
||
buffer.tofile(str(staging / name))
|
||
data["frames"].append({"index": number, "sourceIndex": index, "image": name,
|
||
"box": None, "status": "unlabeled", "prompt": False})
|
||
if number % 25 == 0:
|
||
emit(f"已抽取 {number + 1} 帧", progress=min(0.99, index / max(total, 1)))
|
||
index += 1
|
||
if len(data["frames"]) < 2:
|
||
raise ValueError("视频有效帧不足两帧")
|
||
save_json(staging / "project.json", data)
|
||
staging.rename(target)
|
||
if data.get("recipeDirectory"):
|
||
recipe_context({"project": str(target / "project.json")})
|
||
emit(f"导入完成:{len(data['frames'])} 帧,原视频每 {stride} 帧采样一次", progress=1)
|
||
except BaseException:
|
||
shutil.rmtree(staging, ignore_errors=True)
|
||
raise
|
||
finally:
|
||
cap.release()
|
||
|
||
|
||
def propagate(request):
|
||
import numpy as np
|
||
import torch
|
||
from sam2.build_sam import build_sam2_video_predictor
|
||
path, data = load_project(request["project"])
|
||
prompts = [f for f in data["frames"] if f.get("prompt") and f.get("box") and f["status"] == "reviewed"]
|
||
if not prompts:
|
||
raise ValueError("请至少手动画一个关键帧标注框")
|
||
device = request.get("device", "auto")
|
||
device = ("cuda" if torch.cuda.is_available() else "cpu") if device == "auto" else device
|
||
if str(device).isdigit():
|
||
device = "cuda:" + str(device)
|
||
if device == "cpu":
|
||
torch.set_num_threads(min(8, os.cpu_count() or 4))
|
||
checkpoint = request.get("checkpoint", "").strip()
|
||
emit(f"加载 SAM2.1 · {device};首次使用默认模型需要联网下载")
|
||
if checkpoint:
|
||
predictor = build_sam2_video_predictor(request.get("config", "configs/sam2.1/sam2.1_hiera_t.yaml"), checkpoint, device=device)
|
||
else:
|
||
checkpoint = default_checkpoint()
|
||
predictor = build_sam2_video_predictor("configs/sam2.1/sam2.1_hiera_t.yaml", str(checkpoint), device=device)
|
||
context = torch.autocast("cuda", dtype=torch.bfloat16) if device.startswith("cuda") and torch.cuda.is_bf16_supported() else nullcontext()
|
||
with torch.inference_mode(), context:
|
||
state = predictor.init_state(str(path.parent / "frames"), offload_video_to_cpu=True, offload_state_to_cpu=True)
|
||
for frame in prompts:
|
||
predictor.add_new_points_or_box(state, frame_idx=frame["index"], obj_id=1, box=np.array(frame["box"], dtype=np.float32))
|
||
start = min(f["index"] for f in prompts)
|
||
# Run both directions so a seed drawn in the middle covers earlier frames too.
|
||
directions = [False, True] if start > 0 else [False]
|
||
count = 0
|
||
for reverse in directions:
|
||
for index, ids, logits in predictor.propagate_in_video(state, start_frame_idx=start, reverse=reverse):
|
||
frame = data["frames"][index]
|
||
if frame["status"] in ("reviewed", "absent", "excluded"):
|
||
continue
|
||
mask = (logits[0, 0] > 0).cpu().numpy()
|
||
ys, xs = np.where(mask)
|
||
frame["box"] = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1] if len(xs) else None
|
||
frame["status"] = "auto" # Empty predictions still require review, never become negative labels automatically.
|
||
frame["prompt"] = False
|
||
count += 1
|
||
if count % 20 == 0:
|
||
save_json(path, data)
|
||
emit(f"传播帧 {index + 1}/{len(data['frames'])}" + (" · 未找到目标" if not len(xs) else ""), progress=count / len(data["frames"]))
|
||
save_json(path, data)
|
||
emit("SAM2 传播完成,请复核自动标注", progress=1)
|
||
|
||
|
||
def default_checkpoint():
|
||
"""Download the official fixed SAM2.1 tiny checkpoint, atomically, with bounded network waits."""
|
||
target = ROOT / "models" / "sam2.1_hiera_tiny.pt"
|
||
expected_hash = "7402e0d864fa82708a20fbd15bc84245c2f26dff0eb43a4b5b93452deb34be69"
|
||
if target.is_file():
|
||
if sha256_file(target) != expected_hash:
|
||
raise IOError("默认 SAM2 模型校验失败,请移走 models/sam2.1_hiera_tiny.pt 后重新下载")
|
||
return target
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
temporary = target.with_suffix(".pt.download")
|
||
url = "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_tiny.pt"
|
||
downloaded = 0
|
||
try:
|
||
with urllib.request.urlopen(url, timeout=30) as response, temporary.open("wb") as output:
|
||
total = int(response.headers.get("Content-Length", 0))
|
||
while chunk := response.read(1024 * 1024):
|
||
output.write(chunk)
|
||
downloaded += len(chunk)
|
||
if downloaded % (10 * 1024 * 1024) < len(chunk):
|
||
emit(f"下载 SAM2 模型 {downloaded // 1048576}/{total // 1048576} MB")
|
||
if total and downloaded != total:
|
||
raise IOError("模型下载不完整,请重试")
|
||
if downloaded < 100_000_000:
|
||
raise IOError("模型文件尺寸异常,请手动下载官方模型")
|
||
if sha256_file(temporary) != expected_hash:
|
||
raise IOError("SAM2 模型 SHA256 校验失败,请重试")
|
||
temporary.replace(target)
|
||
finally:
|
||
temporary.unlink(missing_ok=True)
|
||
return target
|
||
|
||
|
||
def recipe_context(request):
|
||
path, data = load_project(request["project"])
|
||
directory = data.get("recipeDirectory", "")
|
||
if not directory:
|
||
return path.parent, [(path, data)], [data["name"]]
|
||
root = Path(directory).resolve()
|
||
root.mkdir(parents=True, exist_ok=True)
|
||
registry = root / "recipe-training.json"
|
||
state = read_json(registry) if registry.exists() else {"projects": [], "classes": []}
|
||
config_path = root / (data.get("recipeName", root.name) + ".yaml")
|
||
catalog = None
|
||
if config_path.exists():
|
||
import yaml
|
||
catalog = (yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}).get("sop", {}).get("parts")
|
||
if catalog is not None:
|
||
if (not isinstance(catalog, list) or any(not isinstance(n, str) or not n.strip() or n != n.strip() for n in catalog)
|
||
or len(catalog) != len(set(catalog))):
|
||
raise ValueError("配方零件列表无效,请在配方编辑中维护")
|
||
state["classes"] = list(catalog)
|
||
current = str(path)
|
||
if current not in state["projects"]:
|
||
state["projects"].append(current)
|
||
labels = state.setdefault("labels", {})
|
||
projects = []
|
||
missing = []
|
||
for item in state["projects"]:
|
||
if not Path(item).exists():
|
||
missing.append(item)
|
||
continue
|
||
projects.append(load_project(item))
|
||
for source, project in projects:
|
||
if catalog is not None and project["name"] not in catalog:
|
||
raise ValueError(f"零件“{project['name']}”不在配方零件列表中,请先在配方编辑中维护")
|
||
previous = labels.get(str(source))
|
||
# A corrected name keeps its class ID when it is the sole video for that part.
|
||
if catalog is None and previous and previous != project["name"] and previous in state["classes"] and project["name"] not in state["classes"]:
|
||
others = [p["name"] for other, p in projects if other != source]
|
||
if previous not in others:
|
||
state["classes"][state["classes"].index(previous)] = project["name"]
|
||
labels[str(source)] = project["name"]
|
||
if Path(project.get("recipeDirectory", "")).resolve() != root:
|
||
raise ValueError(f"零件项目的配方归属不一致:{source}")
|
||
if project["name"] not in state["classes"]:
|
||
state["classes"].append(project["name"])
|
||
if missing:
|
||
archived = state.setdefault("missingProjects", [])
|
||
for item in missing:
|
||
if item not in archived:
|
||
archived.append(item)
|
||
labels.pop(item, None)
|
||
emit(f"标注项目已不存在,已自动从训练名单移除:{item}。继续使用其余项目训练,类别编号保留。")
|
||
# Reopening a restored project reactivates it through the current request.
|
||
if "missingProjects" in state:
|
||
state["missingProjects"] = [item for item in state["missingProjects"] if item not in {str(p) for p, _ in projects}]
|
||
state["projects"] = [str(p) for p, _ in projects]
|
||
save_json(registry, state)
|
||
return root, projects, state["classes"]
|
||
|
||
|
||
def export_dataset(request):
|
||
root, projects, classes = recipe_context(request)
|
||
every = int(request.get("every", 5))
|
||
ratio = float(request.get("valRatio", 0.2))
|
||
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):
|
||
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):
|
||
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 = []
|
||
for number, (path, data, training, validation) in enumerate(samples):
|
||
class_id = classes.index(data["name"])
|
||
for split, frames in (("train", training), ("val", validation)):
|
||
(output / "images" / split).mkdir(parents=True, exist_ok=True)
|
||
(output / "labels" / split).mkdir(parents=True, exist_ok=True)
|
||
for frame in frames:
|
||
stem = f"{number:04d}_{frame['index']:06d}"
|
||
shutil.copy2(path.parent / frame["image"], output / "images" / split / (stem + ".jpg"))
|
||
label = ""
|
||
if frame.get("box") is not None and frame["status"] != "absent":
|
||
x1, y1, x2, y2 = validate_box(frame["box"], data["width"], data["height"])
|
||
label = str(class_id) + " " + " ".join(f"{v:.8f}" for v in ((x1+x2)/2/data["width"], (y1+y2)/2/data["height"],
|
||
(x2-x1)/data["width"], (y2-y1)/data["height"])) + "\n"
|
||
(output / "labels" / split / (stem + ".txt")).write_text(label, encoding="utf-8")
|
||
manifest.append({"project": str(path), "classId": class_id, "train": [f["index"] for f in training], "val": [f["index"] for f in validation]})
|
||
yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n"
|
||
yaml += "".join(f" {i}: {json.dumps(name, ensure_ascii=False)}\n" for i, name in enumerate(classes))
|
||
(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(samples)} 个视频", output=str(output), progress=1)
|
||
return output / "data.yaml"
|
||
|
||
|
||
def train(request):
|
||
from ultralytics import YOLO
|
||
import torch
|
||
path, data = load_project(request["project"])
|
||
epochs = int(request.get("epochs", 50))
|
||
size = int(request.get("imageSize", 640))
|
||
batch = int(request.get("batch", 4))
|
||
if not 1 <= epochs <= 10000 or not 32 <= size <= 2048 or size % 32 or batch < 1:
|
||
raise ValueError("训练参数无效:尺寸需为32的倍数,轮数与批次需为正数")
|
||
yaml = export_dataset(request) # Fresh export prevents training with stale review changes.
|
||
root, _, classes = recipe_context(request)
|
||
latest = root / "latest-model.json"
|
||
initial = read_json(latest)["weights"] if latest.exists() else request.get("model", "yolo11n.pt")
|
||
emit(f"自动加载初始模型:{initial}")
|
||
model = YOLO(initial)
|
||
if model.task != "detect":
|
||
raise ValueError("当前项目导出矩形检测框,请选择 YOLO detect 模型(非 seg / pose / classify)")
|
||
reported_epoch = 0
|
||
history = []
|
||
def finite_metrics(values):
|
||
output = {}
|
||
for key, value in values.items():
|
||
try:
|
||
number = float(value)
|
||
if math.isfinite(number):
|
||
output[str(key)] = number
|
||
except (TypeError, ValueError):
|
||
pass
|
||
return output
|
||
def started(trainer):
|
||
emit("训练已启动", event="training_started", runDirectory=str(trainer.save_dir), device=str(device), progress=0)
|
||
def epoch_end(trainer):
|
||
nonlocal reported_epoch
|
||
current = min(epochs, trainer.epoch + 1)
|
||
if current <= reported_epoch:
|
||
return
|
||
reported_epoch = current
|
||
metrics = finite_metrics(trainer.metrics or {})
|
||
if trainer.tloss is not None:
|
||
metrics.update(finite_metrics(trainer.label_loss_items(trainer.tloss, prefix="train")))
|
||
record = {"epoch": current, "epochs": epochs, "metrics": metrics}
|
||
history.append(record)
|
||
save_json(Path(trainer.save_dir) / "training-metrics.json", history)
|
||
emit(f"训练轮次 {current}/{epochs}", event="training_epoch", **record, progress=current / epochs)
|
||
model.add_callback("on_train_start", started)
|
||
model.add_callback("on_fit_epoch_end", epoch_end)
|
||
device = request.get("device", "auto")
|
||
device = (0 if torch.cuda.is_available() else "cpu") if device == "auto" else device
|
||
if device == "cuda":
|
||
device = "0"
|
||
output_directory = root / "runs"
|
||
output_directory.mkdir(parents=True, exist_ok=True)
|
||
model.train(data=str(yaml), epochs=epochs, imgsz=size, batch=batch, device=device,
|
||
workers=0, resume=False, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8])
|
||
best = Path(model.trainer.best)
|
||
if not best.is_file():
|
||
raise RuntimeError("训练未生成 best.pt")
|
||
# Publish a versioned recipe-named checkpoint before atomically switching the latest pointer.
|
||
recipe_name = data.get("recipeName") or data["name"]
|
||
safe_name = "".join("_" if c in '<>:"/\\|?*' or ord(c) < 32 else c for c in recipe_name).strip(" .") or "recipe"
|
||
published = root / "models" / Path(model.trainer.save_dir).name / (safe_name + ".pt")
|
||
published.parent.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(best, published)
|
||
emit("训练已结束,正在导出配方 ONNX…", event="onnx_export_started", weights=str(published),
|
||
runDirectory=str(model.trainer.save_dir))
|
||
try:
|
||
onnx = export_checkpoint_onnx(published, size)
|
||
except Exception as error:
|
||
raise RuntimeError(f"训练权重已保存到 {published};ONNX 导出失败,配方继续保留上一版模型:{error}") from error
|
||
summary = {"recipeName": recipe_name, "classes": classes, "weights": str(published), "dataset": str(yaml), "runDirectory": str(model.trainer.save_dir),
|
||
"metrics": finite_metrics(model.trainer.metrics or {}), "epochs": reported_epoch,
|
||
"imageSize": size, "device": str(device), "onnx": str(onnx)}
|
||
save_json(Path(model.trainer.save_dir) / "training-result.json", summary)
|
||
save_json(root / "latest-model.json", summary)
|
||
emit("训练完成,配方 ONNX 已自动导出", event="training_completed", **summary, output=str(onnx), progress=1)
|
||
|
||
|
||
def export_checkpoint_onnx(weights, size):
|
||
from ultralytics import YOLO
|
||
output = Path(YOLO(str(weights)).export(format="onnx", imgsz=size,
|
||
opset=17, dynamic=False, simplify=False, nms=False))
|
||
if not output.is_file():
|
||
raise RuntimeError("未生成 ONNX 文件")
|
||
return output.resolve()
|
||
|
||
|
||
def export_onnx(request):
|
||
root, _, _ = recipe_context(request)
|
||
summary = read_json(root / "latest-model.json")
|
||
# A manual re-export must retain the trained recipe's input size.
|
||
output = export_checkpoint_onnx(summary["weights"], int(summary.get("imageSize", request.get("imageSize", 640))))
|
||
summary["onnx"] = str(output)
|
||
save_json(Path(summary["runDirectory"]) / "training-result.json", summary)
|
||
save_json(root / "latest-model.json", summary)
|
||
emit("配方 ONNX 导出完成(检测框输出,不含 NMS)", onnx=str(output), output=str(output), progress=1)
|
||
|
||
|
||
def suggest(request):
|
||
path, data = load_project(request["project"])
|
||
frame = data["frames"][int(request["index"])]
|
||
key = os.environ.get("PARTTRAINER_API_KEY", "")
|
||
if not key:
|
||
raise ValueError("请填写视觉 API Key(只保存在当前进程内)")
|
||
url = request["endpoint"].rstrip("/") + "/chat/completions"
|
||
if not url.startswith("https://") and not url.startswith(("http://localhost:", "http://127.0.0.1:")):
|
||
raise ValueError("远程视觉接口必须使用 HTTPS;本地服务可使用 HTTP")
|
||
# Resize to bound request size, request normalized coordinates so no resize ambiguity occurs.
|
||
import cv2
|
||
import numpy as np
|
||
image = cv2.imdecode(np.fromfile(str(path.parent / frame["image"]), dtype=np.uint8), cv2.IMREAD_COLOR)
|
||
if image is None:
|
||
raise ValueError("图像无法打开")
|
||
h, w = image.shape[:2]
|
||
scale = min(1, 1280 / max(h, w))
|
||
image = cv2.resize(image, (round(w*scale), round(h*scale)))
|
||
ok, buffer = cv2.imencode(".jpg", image)
|
||
if not ok:
|
||
raise ValueError("图像编码失败")
|
||
prompt = f"Locate the single main object described as: {data['name']}. {request.get('description', '')} Return ONLY JSON: {{\"box\":[x1,y1,x2,y2]}} with coordinates normalized to 0..1. If absent, return {{\"box\":null}}."
|
||
payload = {"model": request["apiModel"], "messages": [{"role": "user", "content": [
|
||
{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(buffer).decode()}}]}], "max_tokens": 300}
|
||
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
|
||
# Do not forward the API key across redirects.
|
||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||
def redirect_request(self, *args, **kwargs):
|
||
return None
|
||
with urllib.request.build_opener(NoRedirect).open(req, timeout=120) as response:
|
||
reply = json.load(response)["choices"][0]["message"]["content"].strip()
|
||
if reply.startswith("```"):
|
||
reply = reply.split("\n", 1)[1].rsplit("```", 1)[0]
|
||
box = json.loads(reply)["box"]
|
||
if box is not None:
|
||
validate_box(box, 1, 1)
|
||
box = [box[0]*data["width"], box[1]*data["height"], box[2]*data["width"], box[3]*data["height"]]
|
||
# This becomes a conditioning frame only after the user approves it.
|
||
frame.update(box=box, status="auto", prompt=box is not None)
|
||
save_json(path, data)
|
||
emit("视觉模型已给出建议,请检查并确认当前帧", progress=1)
|
||
|
||
|
||
def main():
|
||
request = read_json(sys.argv[1])
|
||
actions = {"doctor": doctor, "extract": extract, "propagate": propagate, "export": export_dataset,
|
||
"train": train, "onnx": export_onnx, "suggest": suggest}
|
||
actions[request["action"]](request)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
main()
|
||
except Exception as error:
|
||
emit(str(error), error=True)
|
||
traceback.print_exc(file=sys.stderr)
|
||
sys.exit(1)
|