File size: 1,514 Bytes
d12af8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 "<h1>خطأ: ملف index.html غير موجود</h1>"

# 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)