(req: PredictRequest)
| 125 | @app.post("/predict", response_model=PredictResponse) |
| 126 | @app.post("/predict_logits", response_model=PredictResponse) # 别名路由,防备队友写错路径 |
| 127 | async def predict(req: PredictRequest): |
| 128 | if model is None: raise HTTPException(500, "Model not ready") |
| 129 | if len(req.image) != FLATTENED_SIZE: raise HTTPException(400, "Shape Error") |
| 130 | |
| 131 | try: |
| 132 | input_tensor = torch.tensor(req.image).float().to(DEVICE).view(1, 3, 32, 32) |
| 133 | |
| 134 | with torch.no_grad(): # 必加:防止 OOM |
| 135 | output = model(input_tensor) |
| 136 | pred_label = output.argmax(dim=1).item() |
| 137 | logits_list = output.cpu().squeeze().tolist() |
| 138 | |
| 139 | return PredictResponse(label=pred_label, logits=logits_list) |
| 140 | |
| 141 | except Exception as e: |
| 142 | raise HTTPException(500, str(e)) |
| 143 | |
| 144 | # 接口 2: 批量预测 (支撑 5x11 并发) |
| 145 | @app.post("/predict_batch", response_model=BatchPredictResponse) |
no test coverage detected