face_detection_api_v0.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- coding: utf-8 -*-
  2. import base64
  3. from fastapi import APIRouter, Form, UploadFile
  4. from fastapi.responses import JSONResponse
  5. from digitalHuman.server.reponse import Response
  6. from digitalHuman.server.header import HeaderInfo
  7. from digitalHuman.server.models import FaceDetectionOutput
  8. # 延迟导入,避免启动时触发 uniface 导入(可能导致 DLL 加载失败)
  9. # 只在 API 调用时才导入
  10. def _get_face_detection_infer():
  11. """延迟导入 face_detection_infer"""
  12. from digitalHuman.server.core.api_face_detection_v0_impl import face_detection_infer
  13. return face_detection_infer
  14. router = APIRouter(prefix="/face_detection/v0")
  15. # ========================= 人脸检测 ===========================
  16. @router.post("/detect", summary="Face Detection")
  17. async def api_face_detection(header: HeaderInfo, file: UploadFile):
  18. """
  19. 执行人脸检测
  20. 接收图片文件,返回检测到的人脸信息
  21. """
  22. response = Response()
  23. try:
  24. file_data = await file.read()
  25. face_detection_infer = _get_face_detection_infer()
  26. result = await face_detection_infer(header, file_data)
  27. response.data = result
  28. except Exception as e:
  29. response.data = {"hasFace": False, "faceCount": 0, "faces": []}
  30. response.error(str(e))
  31. return JSONResponse(content=response.validate(FaceDetectionOutput), status_code=200)
  32. # ========================= 人脸检测 (Base64) ===========================
  33. @router.post("/detect/base64", summary="Face Detection (Base64)")
  34. async def api_face_detection_base64(header: HeaderInfo, image_data: str = Form(...)):
  35. """
  36. 执行人脸检测 (Base64格式)
  37. 接收Base64编码的图片数据,返回检测到的人脸信息
  38. """
  39. response = Response()
  40. try:
  41. # 解码Base64图片
  42. if image_data.startswith('data:image'):
  43. # 处理 data:image/jpeg;base64,xxx 格式
  44. image_data = image_data.split(',')[1]
  45. file_data = base64.b64decode(image_data)
  46. face_detection_infer = _get_face_detection_infer()
  47. result = await face_detection_infer(header, file_data)
  48. response.data = result
  49. except Exception as e:
  50. response.data = {"hasFace": False, "faceCount": 0, "faces": []}
  51. response.error(str(e))
  52. return JSONResponse(content=response.validate(FaceDetectionOutput), status_code=200)