"""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") 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: 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": []} 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) 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 export_dataset(request): path, data = load_project(request["project"]) 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 之间") selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")] if any(f["status"] == "reviewed" and not f.get("box") for f in selected): raise ValueError("已复核的正样本缺少标注框") # Hold out one contiguous time segment, with a gap around the boundary. 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("复核样本不足:训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。可减小训练抽样间隔") output = path.parent / "datasets" / ("dataset-" + uuid.uuid4().hex[:10]) output.mkdir(parents=True) for split, frames in (("train", training), ("val", validation)): (output / "images" / split).mkdir(parents=True) (output / "labels" / split).mkdir(parents=True) for frame in frames: stem = f"{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 = "0 " + " ".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") # JSON-quoted scalars are valid YAML and safely handle user-entered class names and Windows paths. yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n 0: {json.dumps(data['name'], ensure_ascii=False)}\n" (output / "data.yaml").write_text(yaml, encoding="utf-8") save_json(output / "manifest.json", {"project": str(path), "train": [f["index"] for f in training], "val": [f["index"] for f in validation], "gap": every}) save_json(path.parent / "latest-dataset.json", {"yaml": str(output / "data.yaml")}) emit(f"导出完成 · 训练 {len(training)} / 验证 {len(validation)}", 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. model = YOLO(request.get("model", "yolo11n.pt")) 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 = str(request.get("outputDirectory", "")).strip() output_directory = Path(output_directory).resolve() if output_directory else path.parent / "runs" output_directory.mkdir(parents=True, exist_ok=True) model.train(data=str(yaml), epochs=epochs, imgsz=size, batch=batch, device=device, workers=0, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8]) best = Path(model.trainer.best) if not best.is_file(): raise RuntimeError("训练未生成 best.pt") summary = {"weights": str(best), "dataset": str(yaml), "runDirectory": str(model.trainer.save_dir), "metrics": finite_metrics(model.trainer.metrics or {}), "epochs": reported_epoch, "imageSize": size, "device": str(device)} save_json(Path(model.trainer.save_dir) / "training-result.json", summary) save_json(path.parent / "latest-model.json", summary) emit("训练完成", event="training_completed", **summary, output=str(best), progress=1) def export_onnx(request): from ultralytics import YOLO path, _ = load_project(request["project"]) weights = read_json(path.parent / "latest-model.json")["weights"] output = YOLO(weights).export(format="onnx", imgsz=int(request.get("imageSize", 640)), opset=17, dynamic=False, simplify=False, nms=False) emit("ONNX 导出完成(检测框输出,不含 NMS)", 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)