routes.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import base64
  2. from datetime import datetime
  3. from fastapi import APIRouter, HTTPException
  4. from utils.device_id import get_device_id
  5. from .models import ChatRequest, ChatResponse, OCRRequest, MessageCreateBill
  6. from core.chat_service import chat_service
  7. from core.agent_manager import agent_manager
  8. from utils.logger import chat_logger
  9. from tools.tool_factory import get_all_tools
  10. import time
  11. from utils.registration_manager import registration_manager
  12. from core.ocr_service import PaddleOCRService
  13. from core.document_processor.document_service import DocumentProcessingService
  14. # 初始化服务
  15. ocr_service = PaddleOCRService(
  16. api_url="https://a8l0g1qda8zd48nb.aistudio-app.com/ocr",
  17. token="f97d214abf87d5ea3c156e21257732a3b19661cb",
  18. )
  19. doc_service = DocumentProcessingService(ocr_service=ocr_service)
  20. router = APIRouter()
  21. @router.post("/chat", response_model=ChatResponse)
  22. async def chat_endpoint(request: ChatRequest):
  23. """聊天接口"""
  24. try:
  25. result = await chat_service.process_chat_request(request.model_dump())
  26. return ChatResponse(**result)
  27. except Exception as e:
  28. chat_logger.error(f"API处理失败: {str(e)}")
  29. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  30. @router.post("/ocr")
  31. async def orc(request: OCRRequest):
  32. """OCR接口"""
  33. try:
  34. chat_logger.info(f"开始进行图片识别")
  35. # 1. 解码Base64图片
  36. try:
  37. if "," in request.image:
  38. # 去掉 data:image/xxx;base64, 前缀
  39. base64_str = request.image.split(",", 1)[1]
  40. else:
  41. base64_str = request.image
  42. image_bytes = base64.b64decode(base64_str)
  43. except Exception as e:
  44. chat_logger.error(f"图片解码失败: {e}")
  45. raise HTTPException(400, f"图片格式错误: {str(e)}")
  46. # 2. OCR识别
  47. result = await doc_service.pure_ocr(image_bytes=image_bytes)
  48. # 3. 返回结果
  49. return result
  50. except HTTPException:
  51. raise
  52. except Exception as e:
  53. chat_logger.error(f"处理失败: {e}")
  54. raise HTTPException(500, f"处理失败: {str(e)}")
  55. @router.post("/ocr_create_bill")
  56. async def ocr_create_bill_endpoint(request: OCRRequest):
  57. """
  58. 处理单张图片
  59. 请求格式:
  60. {
  61. "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
  62. "type": "invoice",
  63. }
  64. """
  65. try:
  66. chat_logger.info(f"开始处理 {request.type} 单据")
  67. # 1. 解码Base64图片
  68. try:
  69. if "," in request.image:
  70. # 去掉 data:image/xxx;base64, 前缀
  71. base64_str = request.image.split(",", 1)[1]
  72. else:
  73. base64_str = request.image
  74. image_bytes = base64.b64decode(base64_str)
  75. except Exception as e:
  76. chat_logger.error(f"图片解码失败: {e}")
  77. raise HTTPException(400, f"图片格式错误: {str(e)}")
  78. # 2. 处理单据
  79. result = await doc_service.ocr_create_bill(
  80. image_bytes=image_bytes, document_type=request.type
  81. )
  82. # 3. 返回结果
  83. return {
  84. "success": True,
  85. "type": request.type,
  86. "text": result.get("ocr_text", ""), # 识别出的文本
  87. "data": result.get("parsed_data", {}), # 结构化数据
  88. "timestamp": datetime.now().isoformat(),
  89. }
  90. except HTTPException:
  91. raise
  92. except Exception as e:
  93. chat_logger.error(f"处理失败: {e}")
  94. raise HTTPException(500, f"处理失败: {str(e)}")
  95. @router.post("/message_create_bill")
  96. async def message_create_bill_endpoint(request: MessageCreateBill):
  97. """
  98. 通过文本消息辅助建立单据
  99. 请求格式:
  100. {
  101. "message": "这是一条单据描述",
  102. "document_type": "invoice",
  103. }
  104. """
  105. try:
  106. result = await doc_service.message_create_bill(
  107. message=request.message, document_type=request.document_type
  108. )
  109. return result
  110. except Exception as e:
  111. chat_logger.error(f"处理失败: {e}")
  112. raise HTTPException(500, f"处理失败: {str(e)}")
  113. @router.get("/cache/status")
  114. async def cache_status():
  115. """查看缓存状态 - 修复版本"""
  116. try:
  117. cache_status = await agent_manager.get_cache_status()
  118. # ✅ 确保返回完整信息
  119. return {
  120. "success": True,
  121. "cache_size": cache_status.get("cache_size", 0),
  122. "cache_expiry_seconds": cache_status.get("cache_expiry_seconds", 3600),
  123. "cache_entries_count": len(cache_status.get("cache_entries", [])),
  124. "cache_entries": cache_status.get("cache_entries", []),
  125. "timestamp": time.time(),
  126. }
  127. except Exception as e:
  128. chat_logger.error(f"获取缓存状态失败: {str(e)}")
  129. return {
  130. "success": False,
  131. "error": str(e),
  132. "cache_size": 0,
  133. "cache_entries_count": 0,
  134. "cache_entries": [],
  135. }
  136. @router.delete("/cache/clear")
  137. async def clear_cache():
  138. """清空缓存"""
  139. try:
  140. # ✅ 使用异步版本
  141. cleared = await agent_manager.clear_cache()
  142. chat_logger.info(f"清空agent缓存, 清理数量={cleared}")
  143. return {
  144. "cleared_entries": cleared,
  145. "message": "缓存已清空",
  146. "status": "success",
  147. }
  148. except Exception as e:
  149. chat_logger.error(f"清空缓存失败: {str(e)}")
  150. raise HTTPException(status_code=500, detail=f"清空缓存失败: {str(e)}")
  151. @router.get("/health")
  152. async def health_check():
  153. """健康检查"""
  154. try:
  155. # ✅ 使用异步版本
  156. registration_status = await registration_manager.check_registration()
  157. return {
  158. "status": "healthy",
  159. "service": "龙嘉软件AI助手API",
  160. "registration_status": (
  161. "已注册" if registration_status else "未注册或注册过期"
  162. ),
  163. "device_id": get_device_id(),
  164. "timestamp": time.time(),
  165. }
  166. except Exception as e:
  167. return {
  168. "status": "unhealthy",
  169. "service": "龙嘉软件AI助手API",
  170. "error": str(e),
  171. "timestamp": time.time(),
  172. }
  173. @router.get("/tools/status")
  174. async def tools_status():
  175. """查看工具状态"""
  176. try:
  177. tools = get_all_tools()
  178. tool_info = []
  179. for i, tool in enumerate(tools):
  180. tool_info.append(
  181. {
  182. "index": i + 1,
  183. "name": getattr(tool, "name", "unknown"),
  184. "description": getattr(tool, "description", "unknown")[:100]
  185. + "...",
  186. }
  187. )
  188. return {"total_tools": len(tools), "tools": tool_info, "status": "success"}
  189. except Exception as e:
  190. chat_logger.error(f"获取工具状态失败: {str(e)}")
  191. raise HTTPException(status_code=500, detail=f"获取工具状态失败: {str(e)}")
  192. @router.post("/cache/initialize")
  193. async def initialize_cache():
  194. """初始化缓存系统"""
  195. try:
  196. # ✅ 使用异步版本
  197. await agent_manager.initialize()
  198. chat_logger.info("缓存系统初始化完成")
  199. return {"status": "success", "message": "缓存系统初始化完成"}
  200. except Exception as e:
  201. chat_logger.error(f"初始化缓存失败: {str(e)}")
  202. raise HTTPException(status_code=500, detail=f"初始化缓存失败: {str(e)}")
  203. @router.post("/cache/shutdown")
  204. async def shutdown_cache():
  205. """关闭缓存系统"""
  206. try:
  207. # ✅ 使用异步版本
  208. cleared = await agent_manager.shutdown()
  209. chat_logger.info(f"缓存系统已关闭,清理了 {cleared} 个实例")
  210. return {
  211. "cleared_entries": cleared,
  212. "message": "缓存系统已关闭",
  213. "status": "success",
  214. }
  215. except Exception as e:
  216. chat_logger.error(f"关闭缓存失败: {str(e)}")
  217. raise HTTPException(status_code=500, detail=f"关闭缓存失败: {str(e)}")
  218. @router.post("/admin/refresh-registration")
  219. async def refresh_registration():
  220. """手动刷新注册状态(管理员用)"""
  221. registration_manager.force_refresh()
  222. return {"status": "success", "message": "注册状态已刷新"}
  223. @router.get("/admin/registration-status")
  224. async def get_registration_status():
  225. """获取注册状态(管理员用)"""
  226. status = await registration_manager.check_registration()
  227. status_info = registration_manager.get_status()
  228. return {"is_registered": status, "status_info": status_info}
  229. @router.get("/")
  230. async def root():
  231. registration_status = await registration_manager.check_registration()
  232. base_info = {
  233. "service": "龙嘉软件AI助手API",
  234. "version": "1.0.0",
  235. "registration_status": "active" if registration_status else "expired",
  236. "device_id": get_device_id(),
  237. }
  238. if registration_status:
  239. base_info.update(
  240. {
  241. "endpoints": {
  242. "POST /chat": "聊天",
  243. "GET /health": "健康检查",
  244. "GET /cache/status": "查看agent缓存状态",
  245. "DELETE /cache/clear": "清空agent缓存",
  246. "GET /": "API信息",
  247. }
  248. }
  249. )
  250. else:
  251. base_info.update(
  252. {
  253. "message": "⚠️ 服务注册已过期,部分功能受限",
  254. "available_endpoints": {
  255. "GET /health": "健康检查",
  256. "GET /registration/status": "查看注册状态",
  257. "GET /service/info": "服务完整信息",
  258. "GET /": "API信息",
  259. },
  260. "restricted_endpoints": {"POST /chat": "AI聊天功能(需续费)"},
  261. "support_contact": "请联系管理员续费服务",
  262. }
  263. )
  264. return base_info