Files
AntiCaptcha/trainer/export_apache_models.py
T
Cmake 66b11944fe
Build and Push / build (push) Successful in 5m46s
feat: 换掉 AGPL 模型,改用 YOLOX-s(Apache-2.0) + MobileNetV3(BSD-3),并加两段式识别
- 检测:YOLOX-s 8.96M 参数 [1,3,640,640] → [1,8400,85],网格偏移 + exp(w/h) 解码,类内 NMS
- 分类:MobileNetV3-Large 5.47M 参数,torchvision 预处理(短边232→裁224→ImageNet 归一化)+ softmax
- 新增 /api/detection/object/detail:检测框逐个裁出再分类,给出 fine_class(最多 12 个框)
- 类型展示同步更新模型信息(架构/参数量/预处理说明)
- 导出脚本 trainer/export_apache_models.py(容器内一键导出,含兜底自写 exporter)
2026-12-03 23:50:40 +08:00

108 lines
5.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""尝试导出许可宽松的两个模型(替代 AGPL 的 yolo11n / yolo11n-cls):
检测:YOLOX-s(Megvii,Apache-2.0) → /app/models/Detection_Object.onnx
分类:torchvision mobilenet_v3_large(BSD-3)→ /app/models/Classification_Object.onnx
顺带把 ImageNet 类别名从 torchvision 的 weights.meta 里取出来写 txt。
"""
import json
import os
import subprocess
import sys
from pathlib import Path
MODELS = Path("/app/models")
WORK = Path("/tmp/export2")
WORK.mkdir(parents=True, exist_ok=True)
os.chdir(WORK)
def sh(cmd, check=False):
print("$", cmd, flush=True)
return subprocess.run(cmd, shell=True, check=check)
def fetch(url, dst):
import urllib.request
if Path(dst).exists() and Path(dst).stat().st_size > 1000:
print("已存在:", dst, flush=True)
return dst
print("下载:", url, flush=True)
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=180) as r, open(dst, "wb") as f:
f.write(r.read())
print(f" → {dst} {Path(dst).stat().st_size/1e6:.1f} MB", flush=True)
return dst
def export_yolox():
if not Path("YOLOX-0.3.0").exists():
import tarfile
fetch("https://github.com/Megvii-BaseDetection/YOLOX/archive/refs/tags/0.3.0.tar.gz", "yolox.tgz")
with tarfile.open("yolox.tgz") as t:
t.extractall(".")
os.chdir("YOLOX-0.3.0")
# 只装导出需要的(apex/pycocotools 之类 demo 依赖跳过)
sh("/opt/trainer/bin/pip install -q loguru tqdm thop onnxsim onnxscript")
fetch("https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.pth", "yolox_s.pth")
print("权重:", Path("yolox_s.pth").stat().st_size / 1e6, "MB", flush=True)
# export_onnx.py 里 `from yolox.exp import get_exp`,必须把仓库根目录放进 PYTHONPATH
os.environ["PYTHONPATH"] = os.getcwd() + ":" + os.environ.get("PYTHONPATH", "")
# opset 必须显式给 12:torch 默认 17,往下转 11 时会在 Squeeze/Unsqueeze 的 axes 上断言失败
r = sh("/opt/trainer/bin/python tools/export_onnx.py --output-name yolox_s.onnx --opset 12 --no-onnxsim "
"-f exps/default/yolox_s.py -c yolox_s.pth")
if not Path("yolox_s.onnx").exists():
print("!! YOLOX 导出失败", flush=True)
return False
import shutil
shutil.copyfile("yolox_s.onnx", MODELS / "Detection_Object.onnx")
names = ["person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
"fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
"elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
"skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
"tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
"sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
"potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard",
"cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase",
"scissors", "teddy bear", "hair drier", "toothbrush"]
(MODELS / "object_labels.txt").write_text("\n".join(names) + "\n", encoding="utf-8")
print("YOLOX 导出完成", flush=True)
os.chdir(WORK)
return True
def export_cls():
import torch
import torchvision
from torchvision.models import MobileNet_V3_Large_Weights
w = MobileNet_V3_Large_Weights.IMAGENET1K_V2
net = torchvision.models.mobilenet_v3_large(weights=w).eval()
dummy = torch.randn(1, 3, 224, 224)
out_path = MODELS / "Classification_Object.onnx"
# dynamo=False 用老 exporter,权重内嵌进单个 .onnx;新 exporter 会把权重拆成 .onnx.data 旁文件
torch.onnx.export(net, dummy, str(out_path), input_names=["images"], output_names=["output0"],
opset_version=12, do_constant_folding=True, dynamo=False)
cats = w.meta["categories"]
(MODELS / "imagenet_labels.txt").write_text("\n".join(cats) + "\n", encoding="utf-8")
print(f"分类模型导出完成 {out_path.stat().st_size/1e6:.2f} MB, {len(cats)} 类", flush=True)
tf = w.transforms()
print("预处理(torchvision 官方):", tf, flush=True)
import json as _json
meta = {"resize": int(tf.resize_size[0]), "crop": int(tf.crop_size[0]),
"mean": list(tf.mean), "std": list(tf.std)}
(MODELS / "classify_meta.json").write_text(_json.dumps(meta), encoding="utf-8")
print("meta:", meta, flush=True)
return True
if __name__ == "__main__":
ok1 = export_yolox()
ok2 = export_cls()
print("\n结果: YOLOX =", ok1, " cls =", ok2, flush=True)
for f in ("Detection_Object.onnx", "Classification_Object.onnx", "object_labels.txt", "imagenet_labels.txt"):
p = MODELS / f
if p.exists():
print(f" {f:28s} {p.stat().st_size/1e6:7.2f} MB")