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()
# 1. عند فتح الرابط، اعرض الواجهة
@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 "
خطأ: ملف index.html غير موجود
"
# 2. عند طلب إزالة الخلفية
@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))
# استخدام rembg للمعالجة
output_image = remove(input_image)
# حفظ النتيجة كصورة PNG في الذاكرة
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)