|
|
import io |
|
|
from fastapi import FastAPI, Request, File, UploadFile |
|
|
from fastapi.responses import HTMLResponse, StreamingResponse |
|
|
from rembg import remove |
|
|
from PIL import Image |
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
@app.get("/", response_class=HTMLResponse) |
|
|
async def read_root(): |
|
|
try: |
|
|
with open("index.html", "r", encoding="utf-8") as f: |
|
|
return f.read() |
|
|
except FileNotFoundError: |
|
|
return "<h1>خطأ: ملف index.html غير موجود</h1>" |
|
|
|
|
|
|
|
|
@app.post("/remove-bg") |
|
|
async def remove_background(file: UploadFile = File(...)): |
|
|
try: |
|
|
|
|
|
input_bytes = await file.read() |
|
|
input_image = Image.open(io.BytesIO(input_bytes)) |
|
|
|
|
|
|
|
|
output_image = remove(input_image) |
|
|
|
|
|
|
|
|
output_bytes_io = io.BytesIO() |
|
|
output_image.save(output_bytes_io, format="PNG") |
|
|
output_bytes_io.seek(0) |
|
|
|
|
|
|
|
|
return StreamingResponse(output_bytes_io, media_type="image/png") |
|
|
|
|
|
except Exception as e: |
|
|
return {"error": f"حدث خطأ: {str(e)}"} |
|
|
|
|
|
if __name__ == "__main__": |
|
|
import uvicorn |
|
|
uvicorn.run(app, host="0.0.0.0", port=7860) |