如何为检测模型自动标注并反馈?
解读
在国内工业界,检测模型(如目标检测、缺陷检测)上线后,每天都会产生大量“未标注”图片。面试官想知道:
- 你能否用 FastAPI 把“模型推理 → 自动打伪标签 → 人工确认 → 回流训练”做成一条闭环数据管线;
- 你能否兼顾高并发、低延迟、可扩展、可灰度、可审计;
- 你能否把“反馈”做成可观测、可回滚、可量化收益的系统,而不是简单写个接口收图。
一句话:不是问“怎么调用模型”,而是问“怎么用 FastAPI 搭一套可持续迭代的自动标注与反馈平台”。
知识点
- 异步服务设计:async/await、BackgroundTasks、asyncio.Queue、aioredis 流控
- 数据管道:Pydantic 模型分层(RawImage → PredBBox → PseudoLabel → ConfirmedLabel)
- 伪标签策略:置信度过滤、NMS、IoF 阈值、主动学习(uncertainty/entropy)
- 人工复核:FastAPI + WebSocket 推送标注页面,支持快捷键打标签、多角色权限(标注员、审核员、管理员)
- 反馈闭环:
- 确认后的标签写入“金标准库”(MySQL/TiDB),同时发 Kafka 消息触发重训练;
- 伪标签与人工标签差异写入 Prometheus metric,用于监控“模型漂移”;
- 支持回滚:每次重训练生成新模型版本,FastAPI 通过灰度流量切换(Header 路由 + Consul)。
- 高可用:
- 推理服务独立容器,GPU 池化用 triton-server,FastAPI 只做网关;
- 限流:漏桶算法 + Redis cell;
- 鉴权:JWT + 企业微信 SSO;
- 审计:每次标注/反馈写 ClickHouse,方便 BI 统计“单张标签成本”。
- 法规合规:满足《个人信息保护法》—若图片含人脸,自动打码并走脱敏通道。
答案
下面给出一套可直接落地的 FastAPI 核心代码骨架,突出“自动标注 + 反馈”闭环,全部用国内开源组件,方便在面试时白板手写。
# main.py
from fastapi import FastAPI, File, Form, UploadFile, WebSocket, Depends, HTTPException, BackgroundTasks
from pydantic import BaseModel, Field
import aiofiles, asyncio, aioredis, json, uuid, time
from typing import List, Optional
from datetime import datetime
app = FastAPI(title="检测模型自动标注反馈平台", version="1.0.0")
# 1. 数据模型
class BBox(BaseModel):
x1: float
y1: float
x2: float
y2: float
score: float = Field(ge=0, le=1)
label: str
class PredOut(BaseModel):
image_id: str
bboxes: List[BBox]
class ConfirmIn(BaseModel):
image_id: str
bboxes: List[BBox]
operator: str # 人工账号
# 2. 依赖注入:Redis 连接池
async def get_redis():
redis = await aioredis.from_url("redis://localhost:6379", encoding="utf-8", decode_responses=True)
try:
yield redis
finally:
await redis.close()
# 3. 异步推理(伪代码,实际走 triton)
async def infer(image_bytes: bytes) -> PredOut:
# 用 onnxruntime-gpu 异步推理,返回伪标签
await asyncio.sleep(0.1) # 模拟 gpu 延迟
return PredOut(image_id=str(uuid.uuid4()),
bboxes=[BBox(x1=10, y1=20, x2=50, y2=80, score=0.92, label="scratch")])
# 4. 自动标注接口
@app.post("/auto_label", response_model=PredOut)
async def auto_label(background: BackgroundTasks,
file: UploadFile = File(...),
conf_thresh: float = Form(0.8),
redis=Depends(get_redis)):
# 限流:简单令牌桶
ok = await redis.exists(f"bucket:{file.filename}")
if ok:
raise HTTPException(429, "请求过快")
await redis.setex(f"bucket:{file.filename}", 1, "1")
content = await file.read()
pred = await infer(content)
# 过滤低置信度
pred.bboxes = [b for b in pred.bboxes if b.score >= conf_thresh]
# 落盘原图 + 伪标签
async with aiofiles.open(f"/data/raw/{pred.image_id}.jpg", "wb") as f:
await f.write(content)
async with aiofiles.open(f"/data/pseudo/{pred.image_id}.json", "w") as f:
await f.write(pred.json())
# 推送到人工队列
await redis.lpush("queue:human_review", pred.image_id)
# 后台写监控
background.add_task(write_monitor, pred.image_id, len(pred.bboxes))
return pred
async def write_monitor(image_id: str, num_box: int):
# 写 prometheus pushgateway 或自研监控
pass
# 5. WebSocket 人工复核
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket, redis=Depends(get_redis)):
await ws.accept()
while True:
image_id = await redis.brpop("queue:human_review", timeout=5)
if not image_id:
continue
image_id = image_id[1]
pseudo = json.loads(await aioredis.open_file(f"/data/pseudo/{image_id}.json"))
await ws.send_json({"type": "review", "data": pseudo})
# 等待人工确认
msg = await ws.receive_json()
confirm = ConfirmIn(**msg)
# 写入金标准库
await save_to_gold(confirm)
# 发 Kafka 触发训练
await redis.publish("topic:retrain", confirm.json())
async def save_to_gold(c: ConfirmIn):
# 写 MySQL,省略 ORM
pass
# 6. 反馈指标查询
@app.get("/metrics/{image_id}")
async def get_metrics(image_id: str, redis=Depends(get_redis)):
pseudo = json.loads(await aioredis.open_file(f"/data/pseudo/{image_id}.json"))
gold = json.loads(await aioredis.open_file(f"/data/gold/{image_id}.json"))
# 计算 IoU、召回、精确率
return {"iou": calc_iou(pseudo, gold)}
运行方式:
uvicorn main:app --workers 4 --loop uvloop --port 8000
面试亮点:
- 用 BackgroundTasks 把“写监控”异步化,避免阻塞响应;
- WebSocket 实现实时推送,标注员无需刷新页面;
- Redis 既做限流又做队列,简化组件;
- 所有关键路径都落盘,方便事后审计;
- 灰度切换未展开,但预留了 image_id 版本字段,可快速接入 Consul + Nginx 分流。
拓展思考
- 主动学习:在自动标注接口里增加 entropy 排序,把“最难”样本优先推给人,提高标注 ROI;
- 联邦学习:若客户数据不出本地,可用 FastAPI 暴露“梯度上传”接口,聚合后再分发,满足国内数据出境监管;
- 标签众包:对接“阿里众包”或“京东众智”,用 FastAPI 的 OAuth2 授权码模式打通 SSO,实现外部人员复核;
- 端到端 CI/CD:GitLab Runner 监听 Kafka “retrain” 话题,自动拉新数据、训练、评估,评估通过后再回调 FastAPI 的 /model/deploy 接口做热更新;
- 大模型辅助:用视觉大模型做“预标注”,FastAPI 只负责调度,降低 60% 人工点击次数,进一步压缩单张标签成本。