JeweleryInpaintingAPI / app /api /endpoints.py
utkarsh134's picture
Update app/api/endpoints.py
8cc7f47 verified
Raw History Blame Contribute Delete
2.25 kB
import logging
from io import BytesIO
from fastapi import APIRouter, File, UploadFile, Form, HTTPException
from fastapi.responses import StreamingResponse
from PIL import Image
from app.services.gemini_service import GeminiService
logger = logging.getLogger(__name__)
router = APIRouter()
gemini_service = GeminiService()
@router.post("/edit-jewelry/")
async def edit_jewelry_image(
file: UploadFile = File(...),
prompt: str = Form(...),
):
try:
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(
status_code=400, detail="File must be an image (JPEG, PNG, etc.)"
)
try:
image_data = await file.read()
image = Image.open(BytesIO(image_data))
if image.mode != "RGB":
image = image.convert("RGB")
except Exception as e:
logger.error(f"Error processing uploaded image: {str(e)}")
raise HTTPException(
status_code=400, detail="Invalid image file or corrupted data"
)
if not prompt.strip():
raise HTTPException(status_code=400, detail="Prompt cannot be empty")
try:
edited_image, response_text = await gemini_service.edit_jewelry_image(
image, prompt
)
img_buffer = BytesIO()
edited_image.save(img_buffer, format="PNG")
img_buffer.seek(0)
return StreamingResponse(
BytesIO(img_buffer.read()),
media_type="image/png",
headers={
"Content-Disposition": "attachment; filename=edited_jewelry.png"
},
)
except Exception as e:
logger.error(f"Error processing image: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Failed to process image: {str(e)}"
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Unexpected error in edit_jewelry_image endpoint: {str(e)}")
raise HTTPException(
status_code=500,
detail="An unexpected error occurred while processing the request",
)