|
|
from fastapi import FastAPI, Request |
|
|
from fastapi.responses import JSONResponse |
|
|
import base64 |
|
|
import io |
|
|
from PIL import Image |
|
|
import traceback |
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
@app.get("/") |
|
|
def root(): |
|
|
return {"status": "ok"} |
|
|
|
|
|
@app.post("/generate") |
|
|
async def generate_image(request: Request): |
|
|
try: |
|
|
body = await request.json() |
|
|
base64_image = body.get("image") |
|
|
prompt = body.get("prompt", "") |
|
|
|
|
|
if not base64_image: |
|
|
return JSONResponse(status_code=400, content={"success": False, "error": "image is required"}) |
|
|
|
|
|
|
|
|
image_data = base64.b64decode(base64_image.split(",")[-1]) |
|
|
image = Image.open(io.BytesIO(image_data)).convert("RGB") |
|
|
|
|
|
buffered = io.BytesIO() |
|
|
image.save(buffered, format="PNG") |
|
|
encoded_img = base64.b64encode(buffered.getvalue()).decode("utf-8") |
|
|
|
|
|
return JSONResponse(content={ |
|
|
"success": True, |
|
|
"echo_prompt": prompt, |
|
|
"image_base64": f"data:image/png;base64,{encoded_img}" |
|
|
}) |
|
|
|
|
|
except Exception as e: |
|
|
print("=== ERROR OCCURRED ===") |
|
|
traceback.print_exc() |
|
|
print("======================") |
|
|
return JSONResponse(status_code=500, content={"success": False, "error": str(e)}) |
|
|
|