routes.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from fastapi import APIRouter, HTTPException, UploadFile, File
  2. from app.schemas.models import VideoFrameRequest, CardInfoOutput
  3. from app.services.llm_service import LLMService
  4. from app.services.video_service import VideoService
  5. from typing import List
  6. import logging
  7. # 获取 logger 实例(如果 routes 也要打印日志的话)
  8. logger = logging.getLogger("API")
  9. router = APIRouter()
  10. llm_service = LLMService()
  11. video_service = VideoService()
  12. # --- 接口 1: 文本总结 (改为文件上传) ---
  13. @router.post("/summarize", response_model=List[CardInfoOutput])
  14. async def summarize_text(file: UploadFile = File(...)):
  15. """
  16. 上传 txt 文件,返回提取的卡片信息 JSON 列表
  17. """
  18. # 1. 基本校验:检查文件名或扩展名
  19. if not file.filename.endswith(".txt"):
  20. raise HTTPException(status_code=400, detail="Only .txt files are allowed")
  21. try:
  22. # 2. 读取文件内容
  23. # file.read() 返回的是 bytes,需要解码
  24. content_bytes = await file.read()
  25. # 尝试解码 (优先 UTF-8,兼容 Windows 的 GBK)
  26. try:
  27. text = content_bytes.decode("utf-8")
  28. except UnicodeDecodeError:
  29. # 如果 utf-8 失败,尝试 gbk (常见于 Windows 记事本)
  30. try:
  31. text = content_bytes.decode("gbk")
  32. except UnicodeDecodeError:
  33. raise HTTPException(status_code=400, detail="File encoding not supported. Please use UTF-8.")
  34. if not text.strip():
  35. raise HTTPException(status_code=400, detail="File is empty")
  36. logger.info(f"📂 接收到文件: {file.filename}, 大小: {len(content_bytes)} bytes")
  37. # 3. 调用服务层处理
  38. results = llm_service.process_text(text)
  39. return results
  40. except Exception as e:
  41. logger.error(f"❌ 处理文件上传时出错: {e}")
  42. raise HTTPException(status_code=500, detail=str(e))
  43. # --- 接口 2: 截取视频帧---
  44. @router.post("/capture-frames", response_model=List[CardInfoOutput])
  45. def capture_video_frames(request: VideoFrameRequest):
  46. try:
  47. result = video_service.capture_frames(request.video_path, request.cards)
  48. return result
  49. except FileNotFoundError as e:
  50. raise HTTPException(status_code=404, detail=str(e))
  51. except Exception as e:
  52. raise HTTPException(status_code=500, detail=str(e))