132 lines
4.0 KiB
Python
132 lines
4.0 KiB
Python
"""
|
||||
|
|
文件上传 API
|
|||
|
|
============
|
|||
|
|
|
|||
|
|
【功能说明】接收前端上传的图片,保存到本地 D:\\Agent\\agent\\data\\uploads\\ 目录。
|
|||
|
|
【安全设计】只允许常见图片格式;限制文件大小;文件名用时间戳+随机数避免冲突。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import logging
|
|||
|
|
import uuid
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from fastapi import APIRouter, UploadFile, File
|
|||
|
|
from pydantic import BaseModel
|
|||
|
|
|
|||
|
|
from app.config.settings import load_settings
|
|||
|
|
from app.schemas.project import ApiResponse
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.upload.api")
|
|||
|
|
|
|||
|
|
router = APIRouter(prefix="/api/uploads", tags=["文件上传"])
|
|||
|
|
|
|||
|
|
# 允许的图片格式
|
|||
|
|
ALLOWED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"}
|
|||
|
|
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
|
|||
|
|
|
|||
|
|
|
|||
|
|
class UploadResult(BaseModel):
|
|||
|
|
"""上传结果"""
|
|||
|
|
|
|||
|
|
filename: str
|
|||
|
|
url: str
|
|||
|
|
size: int
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post(
|
|||
|
|
"/images", response_model=ApiResponse[UploadResult], summary="上传图片"
|
|||
|
|
)
|
|||
|
|
async def upload_image(
|
|||
|
|
file: UploadFile = File(...),
|
|||
|
|
) -> ApiResponse[UploadResult]:
|
|||
|
|
"""
|
|||
|
|
上传图片文件(需求描述附件)。
|
|||
|
|
|
|||
|
|
【支持格式】png / jpg / jpeg / gif / bmp / webp
|
|||
|
|
【大小限制】10MB
|
|||
|
|
【存储位置】D:\\Agent\\agent\\data\\uploads\\images\\
|
|||
|
|
"""
|
|||
|
|
if not file.filename:
|
|||
|
|
return ApiResponse(code=422, message="文件名不能为空", data=None)
|
|||
|
|
|
|||
|
|
# 校验扩展名
|
|||
|
|
ext = Path(file.filename).suffix.lower()
|
|||
|
|
if ext not in ALLOWED_EXTENSIONS:
|
|||
|
|
return ApiResponse(
|
|||
|
|
code=422,
|
|||
|
|
message=f"不支持的文件格式:{ext}(支持:{', '.join(sorted(ALLOWED_EXTENSIONS))})",
|
|||
|
|
data=None,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 读取内容
|
|||
|
|
content = await file.read()
|
|||
|
|
if len(content) > MAX_FILE_SIZE:
|
|||
|
|
return ApiResponse(
|
|||
|
|
code=422,
|
|||
|
|
message=f"文件过大({len(content) / 1024 / 1024:.1f}MB),最大 10MB",
|
|||
|
|
data=None,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 保存文件(用时间戳+随机数避免冲突)
|
|||
|
|
settings = load_settings()
|
|||
|
|
upload_dir = settings.data_root / "uploads" / "images"
|
|||
|
|
upload_dir.mkdir(parents=True, exist_ok=True)
|
|||
|
|
|
|||
|
|
safe_name = f"{uuid.uuid4().hex[:12]}_{Path(file.filename).name}"
|
|||
|
|
file_path = upload_dir / safe_name
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
file_path.write_bytes(content)
|
|||
|
|
except Exception as exc:
|
|||
|
|
logger.exception("图片保存失败")
|
|||
|
|
return ApiResponse(code=500, message=f"保存失败:{exc}", data=None)
|
|||
|
|
|
|||
|
|
url = f"/uploads/images/{safe_name}"
|
|||
|
|
logger.info("图片已上传:%s(%d 字节)", safe_name, len(content))
|
|||
|
|
|
|||
|
|
return ApiResponse(
|
|||
|
|
code=0,
|
|||
|
|
message="上传成功",
|
|||
|
|
data=UploadResult(filename=safe_name, url=url, size=len(content)),
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post(
|
|||
|
|
"/images/analyze", response_model=ApiResponse[dict], summary="识别图片内容"
|
|||
|
|
)
|
|||
|
|
async def analyze_image_endpoint(payload: dict) -> ApiResponse[dict]:
|
|||
|
|
"""
|
|||
|
|
调用智谱 GLM-4V-Flash 识别图片内容(Bug 截图、UI 稿等)。
|
|||
|
|
|
|||
|
|
【请求体】{"urls": ["/uploads/images/xxx.png", ...]}
|
|||
|
|
【返回】{"description": "图片内容的文字描述"}
|
|||
|
|
"""
|
|||
|
|
urls = payload.get("urls", [])
|
|||
|
|
if not urls:
|
|||
|
|
return ApiResponse(code=422, message="请提供图片 URL 列表", data=None)
|
|||
|
|
|
|||
|
|
from app.services.vision_service import analyze_images
|
|||
|
|
|
|||
|
|
# URL 转本地文件路径
|
|||
|
|
settings = load_settings()
|
|||
|
|
upload_dir = settings.data_root / "uploads"
|
|||
|
|
file_paths = []
|
|||
|
|
for url in urls:
|
|||
|
|
url = str(url).lstrip("/")
|
|||
|
|
# "/uploads/images/xxx.png" → "D:\Agent\agent\data\uploads\images\xxx.png"
|
|||
|
|
file_path = upload_dir / url.replace("uploads/", "", 1) if url.startswith("uploads/") else upload_dir / url
|
|||
|
|
file_paths.append(str(file_path))
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
description = analyze_images(file_paths)
|
|||
|
|
except Exception as exc:
|
|||
|
|
return ApiResponse(code=500, message=f"图片识别失败:{exc}", data=None)
|
|||
|
|
|
|||
|
|
return ApiResponse(
|
|||
|
|
code=0,
|
|||
|
|
message="识别完成",
|
|||
|
|
data={"description": description, "count": len(urls)},
|
|||
|
|
)
|