joermd commited on
Commit
57a842b
·
verified ·
1 Parent(s): 85379fa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from loadimg import load_img
3
+ from transformers import AutoModelForImageSegmentation
4
+ import torch
5
+ from torchvision import transforms
6
+ from PIL import Image
7
+ import requests
8
+ from io import BytesIO
9
+
10
+ # إعداد الجهاز
11
+ torch.set_float32_matmul_precision("high")
12
+ birefnet = AutoModelForImageSegmentation.from_pretrained(
13
+ "ZhengPeng7/BiRefNet", trust_remote_code=True
14
+ )
15
+ birefnet.to("cuda")
16
+
17
+ transform_image = transforms.Compose(
18
+ [
19
+ transforms.Resize((1024, 1024)),
20
+ transforms.ToTensor(),
21
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
22
+ ]
23
+ )
24
+
25
+ # دالة المعالجة
26
+ def process(image):
27
+ image_size = image.size
28
+ input_images = transform_image(image).unsqueeze(0).to("cuda")
29
+ with torch.no_grad():
30
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
31
+ pred = preds[0].squeeze()
32
+ pred_pil = transforms.ToPILImage()(pred)
33
+ mask = pred_pil.resize(image_size)
34
+ image.putalpha(mask)
35
+ return image
36
+
37
+ st.title("أداة إزالة الخلفية")
38
+
39
+ # واجهة المستخدم
40
+ tab = st.sidebar.selectbox("اختر طريقة الإدخال:", ["رفع صورة", "رابط صورة", "ملف"])
41
+
42
+ if tab == "رفع صورة":
43
+ uploaded_file = st.file_uploader("ارفع صورة:")
44
+ if uploaded_file is not None:
45
+ image = Image.open(uploaded_file).convert("RGB")
46
+ st.image(image, caption="الصورة الأصلية", use_column_width=True)
47
+ processed_image = process(image)
48
+ st.image(processed_image, caption="الصورة المعالجة", use_column_width=True)
49
+
50
+ elif tab == "رابط صورة":
51
+ url = st.text_input("أدخل رابط الصورة:")
52
+ if url:
53
+ try:
54
+ response = requests.get(url)
55
+ image = Image.open(BytesIO(response.content)).convert("RGB")
56
+ st.image(image, caption="الصورة الأصلية", use_column_width=True)
57
+ processed_image = process(image)
58
+ st.image(processed_image, caption="الصورة المعالجة", use_column_width=True)
59
+ except Exception as e:
60
+ st.error(f"خطأ أثناء تحميل الصورة: {e}")
61
+
62
+ elif tab == "ملف":
63
+ uploaded_file = st.file_uploader("ارفع ملف:")
64
+ if uploaded_file is not None:
65
+ image = Image.open(uploaded_file).convert("RGB")
66
+ processed_image = process(image)
67
+ output_path = uploaded_file.name.rsplit(".", 1)[0] + ".png"
68
+ processed_image.save(output_path)
69
+ st.image(processed_image, caption="الصورة المعالجة", use_column_width=True)
70
+ st.download_button("تحميل الصورة المعالجة", data=open(output_path, "rb"), file_name=output_path)