routes.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import base64
  2. from datetime import datetime
  3. from typing import List
  4. from fastapi import APIRouter, HTTPException
  5. from utils.device_id import get_device_id
  6. from .models import (
  7. ChatRequest, ChatResponse, OCRRequest, MessageCreateBill,
  8. ImageVectorRequest, ImageVectorResponse, BuildIndexRequest, BuildIndexResponse,
  9. SearchRequest, SearchResponse, SearchResultItem
  10. )
  11. from core.chat_service import chat_service
  12. from core.agent_manager import agent_manager
  13. from core.image_search_service import image_search_service
  14. from utils.logger import chat_logger
  15. from tools.tool_factory import get_all_tools
  16. import time
  17. from utils.registration_manager import registration_manager
  18. from core.ocr_service import PaddleOCRService
  19. from core.document_processor.document_service import DocumentProcessingService
  20. # 初始化服务
  21. ocr_service = PaddleOCRService(
  22. api_url="https://a8l0g1qda8zd48nb.aistudio-app.com/ocr",
  23. token="f97d214abf87d5ea3c156e21257732a3b19661cb",
  24. )
  25. doc_service = DocumentProcessingService(ocr_service=ocr_service)
  26. router = APIRouter()
  27. @router.post("/chat", response_model=ChatResponse)
  28. async def chat_endpoint(request: ChatRequest):
  29. """聊天接口"""
  30. try:
  31. result = await chat_service.process_chat_request(request.model_dump())
  32. return ChatResponse(**result)
  33. except Exception as e:
  34. chat_logger.error(f"API处理失败: {str(e)}")
  35. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  36. @router.post("/ocr")
  37. async def orc(request: OCRRequest):
  38. """OCR接口"""
  39. try:
  40. chat_logger.info(f"开始进行图片识别")
  41. # 1. 解码Base64图片
  42. try:
  43. if "," in request.image:
  44. # 去掉 data:image/xxx;base64, 前缀
  45. base64_str = request.image.split(",", 1)[1]
  46. else:
  47. base64_str = request.image
  48. image_bytes = base64.b64decode(base64_str)
  49. except Exception as e:
  50. chat_logger.error(f"图片解码失败: {e}")
  51. raise HTTPException(400, f"图片格式错误: {str(e)}")
  52. # 2. OCR识别
  53. result = await doc_service.pure_ocr(image_bytes=image_bytes)
  54. # 3. 返回结果
  55. return result
  56. except HTTPException:
  57. raise
  58. except Exception as e:
  59. chat_logger.error(f"处理失败: {e}")
  60. raise HTTPException(500, f"处理失败: {str(e)}")
  61. @router.post("/ocr_create_bill")
  62. async def ocr_create_bill_endpoint(request: OCRRequest):
  63. """
  64. 处理单张图片
  65. 请求格式:
  66. {
  67. "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
  68. "type": "invoice",
  69. }
  70. """
  71. try:
  72. chat_logger.info(f"开始处理 {request.type} 单据")
  73. # 1. 解码Base64图片
  74. try:
  75. if "," in request.image:
  76. # 去掉 data:image/xxx;base64, 前缀
  77. base64_str = request.image.split(",", 1)[1]
  78. else:
  79. base64_str = request.image
  80. image_bytes = base64.b64decode(base64_str)
  81. except Exception as e:
  82. chat_logger.error(f"图片解码失败: {e}")
  83. raise HTTPException(400, f"图片格式错误: {str(e)}")
  84. # 2. 处理单据
  85. result = await doc_service.ocr_create_bill(
  86. image_bytes=image_bytes, document_type=request.type
  87. )
  88. # 3. 返回结果
  89. return {
  90. "success": True,
  91. "type": request.type,
  92. "text": result.get("ocr_text", ""), # 识别出的文本
  93. "data": result.get("parsed_data", {}), # 结构化数据
  94. "timestamp": datetime.now().isoformat(),
  95. }
  96. except HTTPException:
  97. raise
  98. except Exception as e:
  99. chat_logger.error(f"处理失败: {e}")
  100. raise HTTPException(500, f"处理失败: {str(e)}")
  101. @router.post("/message_create_bill")
  102. async def message_create_bill_endpoint(request: MessageCreateBill):
  103. """
  104. 通过文本消息辅助建立单据
  105. 请求格式:
  106. {
  107. "message": "这是一条单据描述",
  108. "document_type": "invoice",
  109. }
  110. """
  111. try:
  112. result = await doc_service.message_create_bill(
  113. message=request.message, document_type=request.document_type
  114. )
  115. return result
  116. except Exception as e:
  117. chat_logger.error(f"处理失败: {e}")
  118. raise HTTPException(500, f"处理失败: {str(e)}")
  119. @router.get("/cache/status")
  120. async def cache_status():
  121. """查看缓存状态 - 修复版本"""
  122. try:
  123. cache_status = await agent_manager.get_cache_status()
  124. # ✅ 确保返回完整信息
  125. return {
  126. "success": True,
  127. "cache_size": cache_status.get("cache_size", 0),
  128. "cache_expiry_seconds": cache_status.get("cache_expiry_seconds", 3600),
  129. "cache_entries_count": len(cache_status.get("cache_entries", [])),
  130. "cache_entries": cache_status.get("cache_entries", []),
  131. "timestamp": time.time(),
  132. }
  133. except Exception as e:
  134. chat_logger.error(f"获取缓存状态失败: {str(e)}")
  135. return {
  136. "success": False,
  137. "error": str(e),
  138. "cache_size": 0,
  139. "cache_entries_count": 0,
  140. "cache_entries": [],
  141. }
  142. @router.delete("/cache/clear")
  143. async def clear_cache():
  144. """清空缓存"""
  145. try:
  146. # ✅ 使用异步版本
  147. cleared = await agent_manager.clear_cache()
  148. chat_logger.info(f"清空agent缓存, 清理数量={cleared}")
  149. return {
  150. "cleared_entries": cleared,
  151. "message": "缓存已清空",
  152. "status": "success",
  153. }
  154. except Exception as e:
  155. chat_logger.error(f"清空缓存失败: {str(e)}")
  156. raise HTTPException(status_code=500, detail=f"清空缓存失败: {str(e)}")
  157. @router.get("/health")
  158. async def health_check():
  159. """健康检查"""
  160. try:
  161. # ✅ 使用异步版本
  162. registration_status = await registration_manager.check_registration()
  163. return {
  164. "status": "healthy",
  165. "service": "龙嘉软件AI助手API",
  166. "registration_status": (
  167. "已注册" if registration_status else "未注册或注册过期"
  168. ),
  169. "device_id": get_device_id(),
  170. "timestamp": time.time(),
  171. }
  172. except Exception as e:
  173. return {
  174. "status": "unhealthy",
  175. "service": "龙嘉软件AI助手API",
  176. "error": str(e),
  177. "timestamp": time.time(),
  178. }
  179. @router.get("/tools/status")
  180. async def tools_status():
  181. """查看工具状态"""
  182. try:
  183. tools = get_all_tools()
  184. tool_info = []
  185. for i, tool in enumerate(tools):
  186. tool_info.append(
  187. {
  188. "index": i + 1,
  189. "name": getattr(tool, "name", "unknown"),
  190. "description": getattr(tool, "description", "unknown")[:100]
  191. + "...",
  192. }
  193. )
  194. return {"total_tools": len(tools), "tools": tool_info, "status": "success"}
  195. except Exception as e:
  196. chat_logger.error(f"获取工具状态失败: {str(e)}")
  197. raise HTTPException(status_code=500, detail=f"获取工具状态失败: {str(e)}")
  198. @router.post("/cache/initialize")
  199. async def initialize_cache():
  200. """初始化缓存系统"""
  201. try:
  202. # ✅ 使用异步版本
  203. await agent_manager.initialize()
  204. chat_logger.info("缓存系统初始化完成")
  205. return {"status": "success", "message": "缓存系统初始化完成"}
  206. except Exception as e:
  207. chat_logger.error(f"初始化缓存失败: {str(e)}")
  208. raise HTTPException(status_code=500, detail=f"初始化缓存失败: {str(e)}")
  209. @router.post("/cache/shutdown")
  210. async def shutdown_cache():
  211. """关闭缓存系统"""
  212. try:
  213. # ✅ 使用异步版本
  214. cleared = await agent_manager.shutdown()
  215. chat_logger.info(f"缓存系统已关闭,清理了 {cleared} 个实例")
  216. return {
  217. "cleared_entries": cleared,
  218. "message": "缓存系统已关闭",
  219. "status": "success",
  220. }
  221. except Exception as e:
  222. chat_logger.error(f"关闭缓存失败: {str(e)}")
  223. raise HTTPException(status_code=500, detail=f"关闭缓存失败: {str(e)}")
  224. @router.post("/admin/refresh-registration")
  225. async def refresh_registration():
  226. """手动刷新注册状态(管理员用)"""
  227. registration_manager.force_refresh()
  228. return {"status": "success", "message": "注册状态已刷新"}
  229. @router.get("/admin/registration-status")
  230. async def get_registration_status():
  231. """获取注册状态(管理员用)"""
  232. status = await registration_manager.check_registration()
  233. status_info = registration_manager.get_status()
  234. return {"is_registered": status, "status_info": status_info}
  235. @router.get("/")
  236. async def root():
  237. registration_status = await registration_manager.check_registration()
  238. base_info = {
  239. "service": "龙嘉软件AI助手API",
  240. "version": "1.0.0",
  241. "registration_status": "active" if registration_status else "expired",
  242. "device_id": get_device_id(),
  243. }
  244. if registration_status:
  245. base_info.update(
  246. {
  247. "endpoints": {
  248. "POST /chat": "聊天",
  249. "GET /health": "健康检查",
  250. "GET /cache/status": "查看agent缓存状态",
  251. "DELETE /cache/clear": "清空agent缓存",
  252. "GET /": "API信息",
  253. }
  254. }
  255. )
  256. else:
  257. base_info.update(
  258. {
  259. "message": "⚠️ 服务注册已过期,部分功能受限",
  260. "available_endpoints": {
  261. "GET /health": "健康检查",
  262. "GET /registration/status": "查看注册状态",
  263. "GET /service/info": "服务完整信息",
  264. "GET /": "API信息",
  265. },
  266. "restricted_endpoints": {"POST /chat": "AI聊天功能(需续费)"},
  267. "support_contact": "请联系管理员续费服务",
  268. }
  269. )
  270. return base_info
  271. @router.post("/image/vector/batch", response_model=List[ImageVectorResponse])
  272. async def batch_calculate_vectors_endpoint(requests: List[ImageVectorRequest]):
  273. """批量计算图片特征向量"""
  274. try:
  275. # 构建请求数据
  276. image_items = []
  277. for req in requests:
  278. image_items.append({
  279. "image": req.image,
  280. "image_id": req.image_id
  281. })
  282. # 调用服务
  283. results = await image_search_service.batch_calculate_vectors(image_items)
  284. # 构建响应
  285. responses = []
  286. for result in results:
  287. response = ImageVectorResponse(
  288. success=result.get("success", False),
  289. image_id=result.get("image_id"),
  290. vector=result.get("vector"),
  291. error=result.get("error")
  292. )
  293. responses.append(response)
  294. return responses
  295. except Exception as e:
  296. chat_logger.error(f"批量计算图片特征向量失败: {str(e)}")
  297. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  298. @router.post("/image/index/build", response_model=BuildIndexResponse)
  299. async def build_index_endpoint(request: BuildIndexRequest):
  300. """构建索引及映射关系"""
  301. try:
  302. # 构建请求数据
  303. image_vectors = []
  304. for item in request.image_vectors:
  305. image_vectors.append({
  306. "image_id": item.image_id,
  307. "vector": item.vector,
  308. "image_name": item.image_name,
  309. "image_path": item.image_path
  310. })
  311. # 调用服务
  312. indexed_count = await image_search_service.build_index(image_vectors)
  313. # 构建响应
  314. response = BuildIndexResponse(
  315. success=True,
  316. indexed_count=indexed_count
  317. )
  318. return response
  319. except Exception as e:
  320. chat_logger.error(f"构建索引失败: {str(e)}")
  321. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  322. @router.post("/image/search", response_model=SearchResponse)
  323. async def search_endpoint(request: SearchRequest):
  324. """搜索相似图片(支持以图搜图和以文搜图)"""
  325. try:
  326. import time
  327. start_time = time.time()
  328. # 处理图片数据
  329. image_bytes = None
  330. if request.image:
  331. try:
  332. if "," in request.image:
  333. base64_str = request.image.split(",", 1)[1]
  334. else:
  335. base64_str = request.image
  336. image_bytes = base64.b64decode(base64_str)
  337. except Exception as e:
  338. chat_logger.error(f"图片解码失败: {e}")
  339. raise HTTPException(400, f"图片格式错误: {str(e)}")
  340. # 调用服务
  341. results = await image_search_service.search(
  342. image_bytes=image_bytes,
  343. text=request.text,
  344. top_k=request.top_k
  345. )
  346. # 计算处理时间
  347. processing_time = time.time() - start_time
  348. # 构建响应
  349. search_results = []
  350. for result in results:
  351. item = SearchResultItem(
  352. image_id=result.get("image_id"),
  353. similarity=result.get("similarity"),
  354. image_name=result.get("image_name"),
  355. image_path=result.get("image_path")
  356. )
  357. search_results.append(item)
  358. response = SearchResponse(
  359. success=True,
  360. results=search_results,
  361. total_count=len(search_results),
  362. processing_time=round(processing_time, 4)
  363. )
  364. return response
  365. except HTTPException:
  366. raise
  367. except Exception as e:
  368. chat_logger.error(f"搜索失败: {str(e)}")
  369. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  370. @router.get("/image/index/status")
  371. async def get_index_status_endpoint():
  372. """获取索引状态"""
  373. try:
  374. status = await image_search_service.get_index_status()
  375. return {
  376. "success": True,
  377. "status": status
  378. }
  379. except Exception as e:
  380. chat_logger.error(f"获取索引状态失败: {str(e)}")
  381. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  382. @router.post("/image/index/clear")
  383. async def clear_index_endpoint():
  384. """清空索引"""
  385. try:
  386. await image_search_service.clear_index()
  387. return {
  388. "success": True,
  389. "message": "索引已清空"
  390. }
  391. except Exception as e:
  392. chat_logger.error(f"清空索引失败: {str(e)}")
  393. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")