32 lines
1.0 KiB
Python
32 lines
1.0 KiB
Python
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import StreamingResponse
|
|
from service import MidjourneyService
|
|
from utils import jingrow_api_verify_and_billing
|
|
from settings import settings
|
|
import json
|
|
import asyncio
|
|
from typing import AsyncGenerator, List
|
|
|
|
router = APIRouter(prefix=settings.router_prefix)
|
|
service = MidjourneyService()
|
|
|
|
@router.post(settings.generate_route)
|
|
@jingrow_api_verify_and_billing(api_name=settings.api_name)
|
|
async def generate_image(data: dict, request: Request):
|
|
|
|
if "prompt" not in data:
|
|
raise HTTPException(status_code=400, detail="缺少prompt参数")
|
|
|
|
prompt = data["prompt"]
|
|
config = data.get("config", {})
|
|
|
|
async def generate() -> AsyncGenerator[str, None]:
|
|
async for result in service.generate_image(prompt, config):
|
|
yield json.dumps(result, ensure_ascii=False) + "\n"
|
|
|
|
return StreamingResponse(
|
|
generate(),
|
|
media_type="application/x-ndjson",
|
|
headers={"X-Content-Type-Options": "nosniff"}
|
|
)
|