| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- from fastapi import APIRouter, File, UploadFile, Depends, HTTPException
- from fastapi.responses import FileResponse, JSONResponse
- from fastapi.concurrency import run_in_threadpool
- from enum import Enum
- from typing import Optional, Dict, Any
- from ..core.config import settings
- from app.services.score_service import ScoreService
- import numpy as np
- import cv2
- import json
- from app.core.logger import get_logger
- logger = get_logger(__name__)
- router = APIRouter()
- score_names = settings.SCORE_TYPE
- ScoreType = Enum("InferenceType", {name: name for name in score_names})
- @router.post("/score_inference", summary="输入卡片类型(正反面, 缺陷类型), 是否为反射卡")
- async def card_model_inference(
- score_type: ScoreType,
- is_reflect_card: bool = False,
- file: UploadFile = File(...)
- ):
- """
- 接收一张卡片图片,使用指定类型的模型进行推理,并返回JSON结果。
- - **inference_type**: 要使用的模型类型(从下拉列表中选择)。
- - **file**: 要上传的图片文件。
- """
- service = ScoreService()
- image_bytes = await file.read()
- # 将字节数据转换为numpy数组
- np_arr = np.frombuffer(image_bytes, np.uint8)
- # 从numpy数组中解码图像
- img_bgr = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
- if img_bgr is None:
- raise ValueError("无法解码图像,请确保上传的是有效的图片格式 (JPG, PNG, etc.)")
- try:
- json_result = await run_in_threadpool(
- service.score_inference,
- score_type=score_type.value,
- is_reflect_card=is_reflect_card,
- img_bgr=img_bgr
- )
- return json_result
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}")
- @router.post("/score_recalculate", summary="输入卡片类型(正反面, 缺陷类型)",
- description="输入的json数据结构为 "
- "{'result': {'center_result':..., 'defect_result':...}}")
- async def score_recalculate(score_type: ScoreType, json_data: Dict[str, Any]):
- """
- 接收分数推理后的结果, 然后重新根据json数据计算居中和缺陷等分数
- """
- service = ScoreService()
- try:
- json_result = await run_in_threadpool(
- service.recalculate_defect_score,
- score_type=score_type.value,
- json_data=json_data
- )
- return json_result
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}")
|