from fastapi import APIRouter, UploadFile, File, HTTPException, Request from fastapi.responses import StreamingResponse, JSONResponse from service import AddBgService from utils import jingrow_api_verify_and_billing from settings import settings import json import asyncio router = APIRouter(prefix=settings.router_prefix) service = AddBgService() @router.post(settings.batch_route) @jingrow_api_verify_and_billing(api_name=settings.api_name) async def add_background_batch(data: dict, request: Request): """ 批量处理多个URL图片 Args: data: 包含图片URL列表和配置参数的字典 request: FastAPI 请求对象 Returns: 流式响应,包含每个图片的处理结果 """ if "urls" not in data: raise HTTPException(status_code=400, detail="缺少urls参数") config = data.get("config", {}) async def process_and_stream(): total = len(data["urls"]) for index, url in enumerate(data["urls"], 1): try: result = await service.add_background(url, config) result.update({ "index": index, "total": total, "original_url": url }) yield json.dumps(result) + "\n" except Exception as e: yield json.dumps({ "status": "error", "message": str(e), "index": index, "total": total, "original_url": url }) + "\n" return StreamingResponse( process_and_stream(), media_type="application/x-ndjson" ) @router.post(settings.file_route) @jingrow_api_verify_and_billing(api_name=settings.api_name) async def add_background_file(file: UploadFile = File(...), config: str = None, request: Request = None): """ 为上传的文件添加背景 Args: file: 上传的图片文件 config: JSON格式的配置参数 request: FastAPI 请求对象 Returns: 处理后的图片内容 """ content = await file.read() # 解析配置参数 config_dict = {} if config: try: config_dict = json.loads(config) except json.JSONDecodeError: raise HTTPException(status_code=400, detail="配置参数格式错误") result = await service.add_background_from_file(content, config_dict) return result