| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- from fastapi import APIRouter, HTTPException, UploadFile, File
- from app.schemas.models import VideoFrameRequest, CardInfoOutput
- from app.services.llm_service import LLMService
- from app.services.video_service import VideoService
- from typing import List
- import logging
- # 获取 logger 实例(如果 routes 也要打印日志的话)
- logger = logging.getLogger("API")
- router = APIRouter()
- llm_service = LLMService()
- video_service = VideoService()
- # --- 接口 1: 文本总结 (改为文件上传) ---
- @router.post("/summarize", response_model=List[CardInfoOutput])
- async def summarize_text(file: UploadFile = File(...)):
- """
- 上传 txt 文件,返回提取的卡片信息 JSON 列表
- """
- # 1. 基本校验:检查文件名或扩展名
- if not file.filename.endswith(".txt"):
- raise HTTPException(status_code=400, detail="Only .txt files are allowed")
- try:
- # 2. 读取文件内容
- # file.read() 返回的是 bytes,需要解码
- content_bytes = await file.read()
- # 尝试解码 (优先 UTF-8,兼容 Windows 的 GBK)
- try:
- text = content_bytes.decode("utf-8")
- except UnicodeDecodeError:
- # 如果 utf-8 失败,尝试 gbk (常见于 Windows 记事本)
- try:
- text = content_bytes.decode("gbk")
- except UnicodeDecodeError:
- raise HTTPException(status_code=400, detail="File encoding not supported. Please use UTF-8.")
- if not text.strip():
- raise HTTPException(status_code=400, detail="File is empty")
- logger.info(f"📂 接收到文件: {file.filename}, 大小: {len(content_bytes)} bytes")
- # 3. 调用服务层处理
- results = llm_service.process_text(text)
- return results
- except Exception as e:
- logger.error(f"❌ 处理文件上传时出错: {e}")
- raise HTTPException(status_code=500, detail=str(e))
- # --- 接口 2: 截取视频帧---
- @router.post("/capture-frames", response_model=List[CardInfoOutput])
- def capture_video_frames(request: VideoFrameRequest):
- try:
- result = video_service.capture_frames(request.video_path, request.cards)
- return result
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
|