File size: 2,719 Bytes
57a842b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from loadimg import load_img
from transformers import AutoModelForImageSegmentation
import torch
from torchvision import transforms
from PIL import Image
import requests
from io import BytesIO

# إعداد الجهاز
torch.set_float32_matmul_precision("high")
birefnet = AutoModelForImageSegmentation.from_pretrained(
    "ZhengPeng7/BiRefNet", trust_remote_code=True
)
birefnet.to("cuda")

transform_image = transforms.Compose(
    [
        transforms.Resize((1024, 1024)),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    ]
)

# دالة المعالجة
def process(image):
    image_size = image.size
    input_images = transform_image(image).unsqueeze(0).to("cuda")
    with torch.no_grad():
        preds = birefnet(input_images)[-1].sigmoid().cpu()
    pred = preds[0].squeeze()
    pred_pil = transforms.ToPILImage()(pred)
    mask = pred_pil.resize(image_size)
    image.putalpha(mask)
    return image

st.title("أداة إزالة الخلفية")

# واجهة المستخدم
tab = st.sidebar.selectbox("اختر طريقة الإدخال:", ["رفع صورة", "رابط صورة", "ملف"])

if tab == "رفع صورة":
    uploaded_file = st.file_uploader("ارفع صورة:")
    if uploaded_file is not None:
        image = Image.open(uploaded_file).convert("RGB")
        st.image(image, caption="الصورة الأصلية", use_column_width=True)
        processed_image = process(image)
        st.image(processed_image, caption="الصورة المعالجة", use_column_width=True)

elif tab == "رابط صورة":
    url = st.text_input("أدخل رابط الصورة:")
    if url:
        try:
            response = requests.get(url)
            image = Image.open(BytesIO(response.content)).convert("RGB")
            st.image(image, caption="الصورة الأصلية", use_column_width=True)
            processed_image = process(image)
            st.image(processed_image, caption="الصورة المعالجة", use_column_width=True)
        except Exception as e:
            st.error(f"خطأ أثناء تحميل الصورة: {e}")

elif tab == "ملف":
    uploaded_file = st.file_uploader("ارفع ملف:")
    if uploaded_file is not None:
        image = Image.open(uploaded_file).convert("RGB")
        processed_image = process(image)
        output_path = uploaded_file.name.rsplit(".", 1)[0] + ".png"
        processed_image.save(output_path)
        st.image(processed_image, caption="الصورة المعالجة", use_column_width=True)
        st.download_button("تحميل الصورة المعالجة", data=open(output_path, "rb"), file_name=output_path)