Arrcttacsrks commited on
Commit
167bdc6
·
verified ·
1 Parent(s): c3023f5

Upload appStable.py

Browse files
Files changed (1) hide show
  1. Backup/appStable.py +60 -0
Backup/appStable.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ from model import U2NET
5
+ from torch.autograd import Variable
6
+ import numpy as np
7
+ from huggingface_hub import hf_hub_download
8
+ import gradio as gr
9
+
10
+ # Chuẩn hóa dự đoán
11
+ def normPRED(d):
12
+ return (d - torch.min(d)) / (torch.max(d) - torch.min(d))
13
+
14
+ # Hàm suy luận với U2NET
15
+ def inference(net, input_img):
16
+ input_img = input_img / np.max(input_img)
17
+ tmpImg = np.zeros((input_img.shape[0], input_img.shape[1], 3))
18
+ tmpImg[:, :, 0] = (input_img[:, :, 2] - 0.406) / 0.225
19
+ tmpImg[:, :, 1] = (input_img[:, :, 1] - 0.456) / 0.224
20
+ tmpImg[:, :, 2] = (input_img[:, :, 0] - 0.485) / 0.229
21
+ tmpImg = torch.from_numpy(tmpImg.transpose((2, 0, 1))[np.newaxis, :, :, :]).type(torch.FloatTensor)
22
+ tmpImg = Variable(tmpImg.cuda() if torch.cuda.is_available() else tmpImg)
23
+ d1, _, _, _, _, _, _ = net(tmpImg)
24
+ pred = normPRED(1.0 - d1[:, 0, :, :])
25
+ return pred.cpu().data.numpy().squeeze()
26
+
27
+ # Hàm chính để xử lý ảnh đầu vào và trả về ảnh chân dung
28
+ def process_image(img, bw_option):
29
+ # Chuyển đổi ảnh thành đen trắng nếu được chọn
30
+ if bw_option:
31
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
32
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # Chuyển lại thành ảnh 3 kênh cho mô hình
33
+ # Chạy suy luận để tạo ảnh chân dung
34
+ result = inference(u2net, img)
35
+ return (result * 255).astype(np.uint8)
36
+
37
+ # Tải mô hình từ Hugging Face Hub
38
+ def load_u2net_model():
39
+ model_path = hf_hub_download(repo_id="Arrcttacsrks/U2net", filename="u2net_portrait.pth", use_auth_token=os.getenv("HF_TOKEN"))
40
+ net = U2NET(3, 1)
41
+ net.load_state_dict(torch.load(model_path, map_location="cuda" if torch.cuda.is_available() else "cpu"))
42
+ net.eval()
43
+ return net
44
+
45
+ # Khởi tạo mô hình U2NET
46
+ u2net = load_u2net_model()
47
+
48
+ # Tạo giao diện với Gradio
49
+ iface = gr.Interface(
50
+ fn=process_image,
51
+ inputs=[
52
+ gr.Image(type="numpy", label="Upload your image"),
53
+ gr.Checkbox(label="Convert to Black & White?", value=False) # Thêm tùy chọn tick
54
+ ],
55
+ outputs=gr.Image(type="numpy", label="Portrait Result"),
56
+ title="Portrait Generation with U2NET",
57
+ description="Upload an image to generate its portrait."
58
+ )
59
+
60
+ iface.launch()