Spaces:
Sleeping
Sleeping
Create routers/images.py
Browse files- routers/images.py +44 -0
routers/images.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# routers/images.py
|
| 2 |
+
from fastapi import APIRouter, Depends, HTTPException, status
|
| 3 |
+
from starlette.concurrency import run_in_threadpool
|
| 4 |
+
import models
|
| 5 |
+
import config
|
| 6 |
+
from services import generation, security
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
router = APIRouter(
|
| 11 |
+
prefix="/images",
|
| 12 |
+
tags=["Image Generation"],
|
| 13 |
+
dependencies=[Depends(security.get_api_key)]
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
@router.post("/text-to-image", response_model=models.ImageResponse, status_code=status.HTTP_201_CREATED)
|
| 17 |
+
async def create_image_from_text(request: models.ImageRequest):
|
| 18 |
+
"""
|
| 19 |
+
Generates an image based on a text prompt using a diffusion model.
|
| 20 |
+
"""
|
| 21 |
+
try:
|
| 22 |
+
logger.info(f"Received text-to-image request: prompt='{request.prompt}'")
|
| 23 |
+
image_base64 = await run_in_threadpool(
|
| 24 |
+
generation.generate_image_sync,
|
| 25 |
+
prompt=request.prompt,
|
| 26 |
+
negative_prompt=request.negative_prompt,
|
| 27 |
+
height=request.height,
|
| 28 |
+
width=request.width,
|
| 29 |
+
num_inference_steps=request.num_inference_steps,
|
| 30 |
+
guidance_scale=request.guidance_scale
|
| 31 |
+
)
|
| 32 |
+
logger.info(f"Successfully generated image for prompt: '{request.prompt}'")
|
| 33 |
+
return models.ImageResponse(
|
| 34 |
+
image_base64=image_base64,
|
| 35 |
+
prompt=request.prompt,
|
| 36 |
+
model_name=config.IMAGE_MODEL_NAME,
|
| 37 |
+
format="PNG"
|
| 38 |
+
)
|
| 39 |
+
except RuntimeError as e:
|
| 40 |
+
logger.error(f"Model runtime error during image generation: {e}", exc_info=True)
|
| 41 |
+
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"Model inference failed: {e}")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
logger.error(f"Unexpected error during image generation: {e}", exc_info=True)
|
| 44 |
+
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"An unexpected error occurred: {e}")
|