report_parse.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. from fastapi import APIRouter, HTTPException
  2. from pydantic import BaseModel
  3. from typing import Optional, Any
  4. from app.agents.report_parse_agent import ReportParseAgent
  5. import logging
  6. import os
  7. import json
  8. logger = logging.getLogger(__name__)
  9. router = APIRouter(prefix="/api/v1", tags=["report_parse"])
  10. _agent = None
  11. def get_agent():
  12. global _agent
  13. if _agent is None:
  14. _agent = ReportParseAgent()
  15. return _agent
  16. class ParseRequest(BaseModel):
  17. file_path: str
  18. family_id: Optional[int] = None
  19. user_id: Optional[int] = None
  20. class ParseResponse(BaseModel):
  21. code: int = 200
  22. message: str = "ok"
  23. data: dict = {}
  24. @router.post("/report/parse", response_model=ParseResponse)
  25. async def parse_report(req: ParseRequest):
  26. if not os.path.exists(req.file_path):
  27. raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
  28. logger.info("report_parse: file_path=%s family_id=%s user_id=%s",
  29. req.file_path, req.family_id, req.user_id)
  30. agent = get_agent()
  31. try:
  32. result = await agent.parse(req.file_path)
  33. return ParseResponse(data=result)
  34. except Exception as e:
  35. logger.error("报告解析失败: %s", e, exc_info=True)
  36. return ParseResponse(code=500, message=f"解析失败: {str(e)}", data={})
  37. class GenericParseRequest(BaseModel):
  38. file_path: str
  39. extra_context: Optional[dict] = None
  40. class GenericParseResponse(BaseModel):
  41. code: int = 200
  42. message: str = "ok"
  43. data: dict = {}
  44. @router.post("/report/parse-generic", response_model=GenericParseResponse)
  45. async def parse_report_generic(req: GenericParseRequest):
  46. """通用报告 LLM 兜底解析。
  47. 适用于指纹检测未匹配的未知类型报告。
  48. 直接交给 LLM 提取结构化数据,不经过算法预解析。
  49. """
  50. if not os.path.exists(req.file_path):
  51. raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
  52. logger.info("report_parse_generic: file_path=%s", req.file_path)
  53. agent = get_agent()
  54. try:
  55. result = await agent.parse_generic(req.file_path, req.extra_context)
  56. return GenericParseResponse(data=result)
  57. except Exception as e:
  58. logger.error("通用报告解析失败: %s", e, exc_info=True)
  59. return GenericParseResponse(code=500, message=f"解析失败: {str(e)}", data={})
  60. class TypedParseRequest(BaseModel):
  61. file_path: str
  62. report_type: str = "auto"
  63. extra_context: Optional[dict] = None
  64. class TypedParseResponse(BaseModel):
  65. code: int = 200
  66. message: str = "ok"
  67. data: dict = {}
  68. @router.post("/report/parse-typed", response_model=TypedParseResponse)
  69. async def parse_report_typed(req: TypedParseRequest):
  70. """按报告类型解析。
  71. 支持的报告类型:
  72. - auto: 自动检测(默认)
  73. - brain_status: 脑状态测量报告
  74. - cognitive_aptitude: 先天智力潜能/皮纹学测评报告
  75. - scanned_image: 扫描图片 PDF(无文字层,需多模态 LLM)
  76. - generic: 通用 LLM 解析
  77. - gut_flora: 肠道菌群报告(算法解析 + LLM 兜底)
  78. """
  79. if not os.path.exists(req.file_path):
  80. raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
  81. logger.info("report_parse_typed: file_path=%s type=%s",
  82. req.file_path, req.report_type)
  83. agent = get_agent()
  84. try:
  85. result = await agent.parse_by_type(req.file_path, req.report_type, req.extra_context)
  86. return TypedParseResponse(data=result)
  87. except Exception as e:
  88. logger.error("类型报告解析失败: %s", e, exc_info=True)
  89. return TypedParseResponse(code=500, message=f"解析失败: {str(e)}", data={})
  90. class TypedParseRequest2(BaseModel):
  91. file_path: str
  92. @router.post("/report/detect-type", response_model=TypedParseResponse)
  93. async def detect_report_type(req: TypedParseRequest2):
  94. """检测报告类型,返回检测结果(不执行解析)。"""
  95. if not os.path.exists(req.file_path):
  96. raise HTTPException(status_code=400, detail=f"文件不存在: {req.file_path}")
  97. agent = get_agent()
  98. try:
  99. detected = agent._detect_report_type(req.file_path)
  100. return TypedParseResponse(data={"detectedType": detected})
  101. except Exception as e:
  102. logger.error("报告类型检测失败: %s", e, exc_info=True)
  103. return TypedParseResponse(code=500, message=f"检测失败: {str(e)}", data={})