Kims12 commited on
Commit
1d7bc9d
·
verified ·
1 Parent(s): a3d9765

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2 -72
app.py CHANGED
@@ -1,72 +1,2 @@
1
- import gradio as gr
2
- from gradio_imageslider import ImageSlider
3
- from loadimg import load_img
4
- import spaces
5
- from transformers import AutoModelForImageSegmentation
6
- import torch
7
- from torchvision import transforms
8
-
9
- torch.set_float32_matmul_precision(["high", "highest"][0])
10
-
11
- birefnet = AutoModelForImageSegmentation.from_pretrained(
12
- "ZhengPeng7/BiRefNet", trust_remote_code=True
13
- )
14
- birefnet.to("cuda")
15
-
16
- transform_image = transforms.Compose(
17
- [
18
- transforms.Resize((1024, 1024)),
19
- transforms.ToTensor(),
20
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
21
- ]
22
- )
23
-
24
- def fn(image):
25
- im = load_img(image, output_type="pil")
26
- im = im.convert("RGB")
27
- origin = im.copy()
28
- processed_image = process(im)
29
- return (processed_image, origin)
30
-
31
- @spaces.GPU
32
- def process(image):
33
- image_size = image.size
34
- input_images = transform_image(image).unsqueeze(0).to("cuda")
35
- # Prediction
36
- with torch.no_grad():
37
- preds = birefnet(input_images)[-1].sigmoid().cpu()
38
- pred = preds[0].squeeze()
39
- pred_pil = transforms.ToPILImage()(pred)
40
- mask = pred_pil.resize(image_size)
41
- image.putalpha(mask)
42
- return image
43
-
44
- def process_file(f):
45
- name_path = f.rsplit(".", 1)[0] + ".png"
46
- im = load_img(f, output_type="pil")
47
- im = im.convert("RGB")
48
- transparent = process(im)
49
- transparent.save(name_path)
50
- return name_path
51
-
52
- slider1 = ImageSlider(label="Processed Image", type="pil")
53
- slider2 = ImageSlider(label="Processed Image from URL", type="pil")
54
- image_upload = gr.Image(label="Upload an image")
55
- image_file_upload = gr.Image(label="Upload an image", type="filepath")
56
- url_input = gr.Textbox(label="Paste an image URL")
57
- output_file = gr.File(label="Output PNG File")
58
-
59
- # Example images
60
- chameleon = load_img("butterfly.jpg", output_type="pil")
61
- url_example = "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg"
62
-
63
- tab1 = gr.Interface(fn, inputs=image_upload, outputs=slider1, examples=[chameleon], api_name="image")
64
- tab2 = gr.Interface(fn, inputs=url_input, outputs=slider2, examples=[url_example], api_name="text")
65
- tab3 = gr.Interface(process_file, inputs=image_file_upload, outputs=output_file, examples=["butterfly.jpg"], api_name="png")
66
-
67
- demo = gr.TabbedInterface(
68
- [tab1, tab2, tab3], ["Image Upload", "URL Input", "File Output"], title="Background Removal Tool"
69
- )
70
-
71
- if __name__ == "__main__":
72
- demo.launch(show_error=True)
 
1
+ import os
2
+ exec(os.environ.get('APP'))