Spaces:
Sleeping
Sleeping
File size: 2,253 Bytes
8cc7f47 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 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",
)
|