score_inference.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from fastapi import APIRouter, File, UploadFile, Depends, HTTPException
  2. from fastapi.responses import FileResponse, JSONResponse
  3. from fastapi.concurrency import run_in_threadpool
  4. from enum import Enum
  5. from ..core.config import settings
  6. from app.services.score_service import ScoreService
  7. import numpy as np
  8. import cv2
  9. import json
  10. from app.core.logger import get_logger
  11. logger = get_logger(__name__)
  12. router = APIRouter()
  13. score_names = settings.SCORE_TYPE
  14. ScoreType = Enum("InferenceType", {name: name for name in score_names})
  15. @router.post("/score_inference", description="输入卡片类型(正反面, 缺陷类型), 是否为反射卡")
  16. async def card_model_inference(
  17. score_type: ScoreType,
  18. is_reflect_card: bool = False,
  19. file: UploadFile = File(...)
  20. ):
  21. """
  22. 接收一张卡片图片,使用指定类型的模型进行推理,并返回JSON结果。
  23. - **inference_type**: 要使用的模型类型(从下拉列表中选择)。
  24. - **file**: 要上传的图片文件。
  25. """
  26. service = ScoreService()
  27. image_bytes = await file.read()
  28. # 将字节数据转换为numpy数组
  29. np_arr = np.frombuffer(image_bytes, np.uint8)
  30. # 从numpy数组中解码图像
  31. img_bgr = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
  32. if img_bgr is None:
  33. raise ValueError("无法解码图像,请确保上传的是有效的图片格式 (JPG, PNG, etc.)")
  34. try:
  35. json_result = await run_in_threadpool(
  36. service.score_inference,
  37. score_type=score_type.value,
  38. is_reflect_card=is_reflect_card,
  39. img_bgr=img_bgr
  40. )
  41. return json_result
  42. except ValueError as e:
  43. raise HTTPException(status_code=400, detail=str(e))
  44. except Exception as e:
  45. raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}")