Metadata-Version: 2.4
Name: spine-infer
Version: 0.2.0
Summary: 脊柱侧弯 X 光 YOLOv8-Pose 推理 SDK（ONNX Runtime 后端）
Project-URL: Repository, https://github.com/yuanzhixingtu/spine-discern
Author: Spine Discern Team
License: Proprietary
Keywords: medical-imaging,onnxruntime,scoliosis,spine,yolov8
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24
Requires-Dist: onnxruntime>=1.17
Requires-Dist: opencv-python-headless>=4.8
Requires-Dist: pillow>=10.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: torch
Requires-Dist: torch>=2.2; extra == 'torch'
Requires-Dist: ultralytics>=8.2; extra == 'torch'
Description-Content-Type: text/markdown

# spine-infer

脊柱侧弯 X 光 YOLOv8 推理 SDK。

- 默认后端：**ONNX Runtime**（轻量、跨平台、零 torch 依赖）
- 可选后端：**Ultralytics + PyTorch**（用于研发/调试，与 ONNX 输出对照）
- 仅返回**数值结果**（`dataclass` + JSON），可视化由上游软件自行完成
- 提供 `spine-infer` 命令行入口，便于工程验证与冒烟测试

类别（与训练数据集一致）：

| class_id | class_name        | 含义                  |
| -------- | ----------------- | --------------------- |
| 0        | `Vertebra`        | 单节椎体              |
| 1        | `scoliosis spine` | 整体脊柱：侧弯阳性    |
| 2        | `normal spine`    | 整体脊柱：未见侧弯    |

> **权重托管说明**：当前版本 SDK 不内置任何权重，也不联网下载。
> 上游建模软件需要自行管理 `.onnx` 权重文件（医疗合规：数据/模型不出域）。

---

## 1. 安装

本包属于 monorepo `spine-discern/packages/spine-discern-infer`。

### 1.1 开发模式安装（仓库内联调）

```bash
# 在仓库根目录
uv pip install -e ./packages/spine-discern-infer

# 如果需要 .pt 调试后端（会拉 torch + ultralytics，体积较大）
uv pip install -e "./packages/spine-discern-infer[torch]"
```

### 1.2 本地构建 wheel（手动）

```bash
cd packages/spine-discern-infer
uv build
# 产物：dist/spine_infer-0.1.0-py3-none-any.whl
```

### 1.3 方案 B：GitHub Release 一键安装（推荐给内部团队）

仓库配置了自动发布工作流：当推送 `v*` tag（如 `v0.1.0`）时，会自动：

1. 在 CI 中构建 `spine-infer` 的 `wheel` 与 `sdist`
2. 创建/更新同名 GitHub Release
3. 上传构建产物到 Release Assets

内部团队直接安装某个发布版本：

```bash
pip install "https://github.com/yuanzhixingtu/spine-discern/releases/download/v0.1.0/spine_infer-0.1.0-py3-none-any.whl"
```

如果仓库是 private，请先配置 GitHub 访问凭据（PAT / SSH / 企业代理），再执行安装。

---

## 2. Python API

```python
from spine_infer import SpineDetector

detector = SpineDetector(
    weights="weights/cloud_best.onnx",
    device="auto",          # auto / cpu / cuda / coreml / mps
    input_size=960,
    conf_threshold=0.25,
    iou_threshold=0.7,
)

result = detector.predict("patient.jpg")
print(result.spine_class)           # SpineClass.SCOLIOSIS / NORMAL / UNKNOWN
print(len(result.vertebrae))        # 椎体节数
print(result.to_json())             # 结构化 JSON，可直接落盘或跨进程传递
```

### 2.1 数据契约

```python
@dataclass
class Detection:
    class_id: int
    class_name: str       # "Vertebra" | "scoliosis spine" | "normal spine"
    score: float
    x1: float; y1: float
    x2: float; y2: float  # 原图像素坐标系

@dataclass
class InferenceResult:
    image_size: tuple[int, int]      # (W, H)
    input_size: tuple[int, int]      # letterbox 后尺寸
    detections: list[Detection]      # 全部检测框
    # 派生属性：
    #   vertebrae    -> list[Detection]，按 y1 升序（从上到下）
    #   spine        -> Detection | None，最高分整体脊柱框
    #   spine_class  -> SpineClass
```

### 2.2 输入支持

- 文件路径（str / `pathlib.Path`，支持中文路径）
- `numpy.ndarray`（H×W×3，RGB，uint8）
- `PIL.Image.Image`

### 2.3 设备策略

`device="auto"` 的回退顺序：

- onnx 后端：`CUDA` → `CoreML`（macOS）→ `CPU`
- torch 后端：`CUDA` → `MPS`（macOS）→ `CPU`

---

## 3. 命令行（CLI）

安装后即可使用 `spine-infer` 命令：

```bash
# 单图推理（仅终端摘要）
spine-infer predict test/wangyihang.jpg --weights weights/cloud_best.onnx

# 目录批量推理 + 写 JSON
spine-infer predict test \
    --weights weights/cloud_best.onnx \
    --output runs/sdk_predict \
    --save-json

# 工程调试：同时生成可视化图（默认隐藏类别与置信度）
spine-infer predict test \
    --weights weights/cloud_best.onnx \
    --output runs/sdk_predict \
    --save-json --visualize --line-width 3

# 仅显示整体脊柱框，过滤所有 Vertebra
spine-infer predict test \
    --weights weights/cloud_best.onnx \
    --output runs/sdk_predict \
    --visualize --spine-only --show-labels --show-conf

# 查看 SDK / runtime 信息
spine-infer info --weights weights/cloud_best.onnx
```

完整参数：`spine-infer predict -h` / `spine-infer info -h`（全中文）。

---

## 4. 与训练侧的关系

```
spine-discern/                                  # 仓库根
├─ train_scoliosis_yolov8.py                    # 训练脚本（本地 MPS）
├─ infer_scoliosis_yolov8.py                    # 旧的推理脚本（仍可用）
├─ tools/
│  └─ export_onnx.py                            # .pt -> .onnx 导出工具
└─ packages/
   └─ spine-discern-infer/                      # 本 SDK，可独立发版
      ├─ pyproject.toml
      └─ src/spine_infer/
```

把训练得到的 `weights/cloud_best.pt` 导出为 `.onnx`：

```bash
# 仓库根目录执行
python tools/export_onnx.py \
    --weights weights/cloud_best.pt \
    --imgsz 960 --opset 12 \
    --output weights/cloud_best.onnx
```

导出后即可用 `spine-infer` 对同一批图片做 `.pt` vs `.onnx` 对比，确认输出一致。
