yolo_service.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. YOLO 隐患识别服务
  3. """
  4. import httpx
  5. from typing import Dict, Any
  6. from utils.config import settings
  7. from utils.logger import logger
  8. class YoloService:
  9. def __init__(self):
  10. self.base_url = settings.yolo.base_url
  11. async def detect_hazards(self, image_url: str, scene_type: str = "") -> Dict[str, Any]:
  12. """检测图片中的隐患"""
  13. try:
  14. data = {
  15. "image_url": image_url,
  16. "scene_type": scene_type
  17. }
  18. async with httpx.AsyncClient(timeout=30.0) as client:
  19. response = await client.post(
  20. f"{self.base_url}/detect",
  21. json=data
  22. )
  23. response.raise_for_status()
  24. return response.json()
  25. except httpx.HTTPError as e:
  26. logger.warning(f"YOLO API 调用失败,返回模拟数据: {e}")
  27. # 返回模拟数据
  28. return {
  29. "hazards": [],
  30. "count": 0,
  31. "message": "YOLO服务暂时不可用,返回模拟数据"
  32. }
  33. except Exception as e:
  34. logger.error(f"YOLO 服务异常: {e}")
  35. return {
  36. "hazards": [],
  37. "count": 0,
  38. "message": "识别服务异常"
  39. }
  40. # 全局实例
  41. yolo_service = YoloService()