2025-12-17 20:15:18 +08:00

79 lines
2.0 KiB
Python

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
from app.services.qwen_service import get_qwen_service
app = FastAPI(title="Qwen2-VL 物体识别 API")
# CORS 配置
app.add_middleware(
CORSMiddleware,
allow_origins=["https://ai.yydd.ai", "http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 获取 Qwen 服务(全局单例)
qwen_service = get_qwen_service()
class DetectRequest(BaseModel):
imageUrl: str
clickX: int
clickY: int
imageIndex: int
imageWidth: int
imageHeight: int
class DetectResponse(BaseModel):
success: bool
data: dict | None
error: str | None
@app.on_event("startup")
async def startup_event():
"""启动时加载模型"""
print("🚀 正在加载 Qwen2-VL-2B 模型...")
await qwen_service.load_model()
print("✅ 模型加载完成!")
@app.post("/api/detect-object", response_model=DetectResponse)
async def detect_object(request: DetectRequest):
"""检测图片中点击位置的物体"""
try:
result = await qwen_service.detect_object_at_point(
image_url=request.imageUrl,
click_x=request.clickX,
click_y=request.clickY,
image_index=request.imageIndex,
image_width=request.imageWidth,
image_height=request.imageHeight
)
return DetectResponse(
success=True,
data=result,
error=None
)
except Exception as e:
print(f"❌ 检测失败: {str(e)}")
import traceback
traceback.print_exc()
return DetectResponse(
success=False,
data=None,
error=f"物体识别失败: {str(e)}"
)
@app.get("/health")
async def health_check():
"""健康检查"""
return {"status": "ok", "model_loaded": qwen_service.is_loaded}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8002)