image.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import logging
  2. import os
  3. import uuid
  4. from typing import List
  5. from fastapi import APIRouter, UploadFile, File, Form, HTTPException
  6. import shutil
  7. from starlette.concurrency import run_in_threadpool
  8. from setting import UPLOAD_DIR
  9. import service.ai_image_ollama as ai_image
  10. logger = logging.getLogger(__name__)
  11. # 创建路由对象,可以统一设置前缀 (prefix) 和 标签 (tags)
  12. router = APIRouter(
  13. prefix="/api1/image",
  14. tags=["video"]
  15. )
  16. @router.post("/analyze")
  17. async def upload_image(
  18. file: UploadFile = File(...),
  19. prompts: List[str] = Form(...)
  20. ):
  21. if not file:
  22. raise HTTPException(status_code=400, detail="文件不能为空")
  23. if not prompts:
  24. raise HTTPException(status_code=400, detail="Prompts 不能为空")
  25. task_id = str(uuid.uuid4())[:8]
  26. ext = file.filename.split('.')[-1]
  27. save_filename = f"{task_id}.{ext}"
  28. save_path = os.path.join(UPLOAD_DIR, save_filename)
  29. # 异步保存文件
  30. def save_file():
  31. with open(save_path, "wb") as buffer:
  32. shutil.copyfileobj(file.file, buffer)
  33. await run_in_threadpool(save_file)
  34. try:
  35. # 读取字节流进行 AI 处理
  36. with open(save_path, 'rb') as f:
  37. image_bytes = f.read()
  38. result = ai_image.describe_image(prompts, image_bytes)
  39. return {
  40. "task_id": task_id,
  41. "model_name": result['model_name'],
  42. "image_url": f"/api1/file/image/{save_filename}",
  43. "results": result['results']
  44. }
  45. except Exception as e:
  46. # 记录日志并抛出错误
  47. raise HTTPException(status_code=500, detail=f"AI 推理失败: {str(e)}")