MykolaL commited on
Commit
353c01a
·
verified ·
1 Parent(s): 1b277ab

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -142
app.py CHANGED
@@ -1,142 +1,145 @@
1
- import os
2
- import sys
3
- import numpy as np
4
- from PIL import Image
5
- import torch
6
- import torch.nn.functional as F
7
- import torchvision.transforms as transforms
8
- import gradio as gr
9
- import cv2
10
- from transformers import AutoModel, CLIPTokenizer
11
-
12
- # Add paths for stable-diffusion, taming-transformers, clip, depth, refer
13
- sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'depth')))
14
- sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'refer')))
15
- sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'stable-diffusion')))
16
- sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src/taming-transformers')))
17
-
18
- os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), 'depth')))
19
- # Device
20
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
-
22
- # ---------------- CSS ----------------
23
- css = """
24
- #img-display-container {
25
- max-height: 50vh;
26
- }
27
- #img-display-input {
28
- max-height: 40vh;
29
- }
30
- #img-display-output {
31
- max-height: 40vh;
32
- }
33
- """
34
-
35
- # ---------------- Load models ----------------
36
- print("Loading models...")
37
- depth_model = AutoModel.from_pretrained("MykolaL/evp_depth", trust_remote_code=True).to(device).eval()
38
- tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
39
- refseg_model = AutoModel.from_pretrained("MykolaL/evp_refer", trust_remote_code=True).to(device).eval()
40
- print("Models loaded successfully.")
41
-
42
- # ---------------- Depth Demo ----------------
43
- def create_depth_demo():
44
- gr.Markdown("### Depth Prediction Demo")
45
- with gr.Row():
46
- input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
47
- depth_image = gr.Image(label="Depth Map", elem_id='img-display-output')
48
- raw_file = gr.File(label="16-bit raw depth, multiplier:256")
49
- submit = gr.Button("Submit")
50
-
51
- def on_submit(image):
52
- transform = transforms.ToTensor()
53
- img_tensor = transform(image).unsqueeze(0).to(device)
54
- shape = img_tensor.shape
55
- img_tensor = F.interpolate(img_tensor, (440, 480), mode='bilinear', align_corners=True)
56
- img_tensor = F.pad(img_tensor, (0, 0, 40, 0))
57
- with torch.no_grad():
58
- pred = depth_model(img_tensor)['pred_d']
59
-
60
- pred = pred[:, :, 40:, :]
61
- pred = F.interpolate(pred, shape[2:], mode='bilinear', align_corners=True)
62
- pred_np = pred.squeeze().cpu().numpy()
63
- from utils_depth.misc import colorize
64
- colored_depth, _, _ = colorize(pred_np, cmap='gray_r')
65
-
66
- import tempfile
67
- tmp = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
68
- raw_depth = Image.fromarray((pred_np * 256).astype('uint16'))
69
- raw_depth.save(tmp.name)
70
- return [colored_depth, tmp.name]
71
-
72
- submit.click(on_submit, inputs=[input_image], outputs=[depth_image, raw_file])
73
- gr.Examples(
74
- examples=["imgs/test_img1.jpg", "imgs/test_img2.jpg", "imgs/test_img3.jpg", "imgs/test_img4.jpg", "imgs/test_img5.jpg"],
75
- inputs=[input_image]
76
- )
77
-
78
- # ---------------- Referring Segmentation Demo ----------------
79
- def create_refseg_demo():
80
- gr.Markdown("### Referring Segmentation Demo")
81
- with gr.Row():
82
- input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
83
- refseg_image = gr.Image(label="Output Mask", elem_id='img-display-output')
84
- input_text = gr.Textbox(label='Prompt', placeholder='Describe object', lines=2)
85
- submit = gr.Button("Submit")
86
-
87
- def on_submit(image, text):
88
- img_np = np.array(image)
89
- img_tensor = transforms.ToTensor()(img_np).unsqueeze(0).to(device)
90
- img_tensor = transforms.Normalize(mean=[0.5]*3, std=[0.5]*3)(img_tensor)
91
- shape = img_tensor.shape
92
- img_tensor = F.interpolate(img_tensor, (512, 512), mode='bilinear', align_corners=True)
93
- input_ids = tokenizer(text, truncation=True, max_length=40, padding="max_length", return_tensors="pt")['input_ids'].to(device)
94
-
95
- with torch.no_grad():
96
- pred = refseg_model(img_tensor, input_ids)
97
-
98
- pred = F.interpolate(pred, shape[2:], mode='bilinear', align_corners=True)
99
- output_mask = pred.cpu().argmax(1).data.numpy().squeeze()
100
-
101
- alpha = 0.65
102
- img_np[output_mask == 0] = (img_np[output_mask == 0]*alpha).astype(np.uint8)
103
- contours, _ = cv2.findContours(output_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
104
- cv2.drawContours(img_np, contours, -1, (0, 255, 0), 2)
105
- return Image.fromarray(img_np)
106
-
107
- submit.click(on_submit, inputs=[input_image, input_text], outputs=refseg_image)
108
- gr.Examples(
109
- examples=[
110
- ["imgs/test_img2.jpg", "green plant"],
111
- ["imgs/test_img3.jpg", "chair"],
112
- ["imgs/test_img4.jpg", "left green plant"],
113
- ["imgs/test_img5.jpg", "man walking on foot"],
114
- ["imgs/test_img5.jpg", "the rightest camel"]
115
- ],
116
- inputs=[input_image, input_text]
117
- )
118
-
119
- # ---------------- Main App ----------------
120
- def main():
121
- title = "# EVP"
122
- description = """Official demo for **EVP: Enhanced Visual Perception using Inverse Multi-Attentive Feature
123
- Refinement and Regularized Image-Text Alignment**.
124
- EVP is a deep learning model for metric depth estimation from a single image as well as referring segmentation.
125
- Please refer to our [project page](https://lavreniuk.github.io/EVP) or [paper](https://arxiv.org/abs/2312.08548) or [github](https://github.com/Lavreniuk/EVP) for more details."""
126
-
127
- with gr.Blocks(css=css) as demo:
128
- gr.Markdown(title)
129
- gr.Markdown(description)
130
- with gr.Tab("Depth Prediction"):
131
- create_depth_demo()
132
- with gr.Tab("Referring Segmentation"):
133
- create_refseg_demo()
134
- gr.HTML('''<br><br><br><center>You can duplicate this Space to skip the queue:
135
- <a href="https://huggingface.co/spaces/MykolaL/evp?duplicate=true">
136
- <img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
137
- <p><img src="https://visitor-badge.glitch.me/badge?page_id=MykolaL/evp" alt="visitors"></p></center>''')
138
-
139
- demo.queue().launch(share=True)
140
-
141
- if __name__ == "__main__":
142
- main()
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'depth')))
5
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'refer')))
6
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'stable-diffusion')))
7
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src/taming-transformers')))
8
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src/clip')))
9
+
10
+
11
+ os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), 'depth')))
12
+
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import torch
17
+ from depth.models_depth.model import EVPDepth
18
+ from models_refer.model import EVPRefer
19
+ from depth.configs.train_options import TrainOptions
20
+ from depth.configs.test_options import TestOptions
21
+ import glob
22
+ import utils
23
+ import torchvision.transforms as transforms
24
+ from utils_depth.misc import colorize
25
+ from PIL import Image
26
+ import torch.nn.functional as F
27
+ import gradio as gr
28
+ import tempfile
29
+ from transformers import CLIPTokenizer, AutoModel
30
+
31
+
32
+ css = """
33
+ #img-display-container {
34
+ max-height: 50vh;
35
+ }
36
+ #img-display-input {
37
+ max-height: 40vh;
38
+ }
39
+ #img-display-output {
40
+ max-height: 40vh;
41
+ }
42
+
43
+ """
44
+
45
+ def create_depth_demo(model, device):
46
+ gr.Markdown("### Depth Prediction demo")
47
+ with gr.Row():
48
+ input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
49
+ depth_image = gr.Image(label="Depth Map", elem_id='img-display-output')
50
+ raw_file = gr.File(label="16-bit raw depth, multiplier:256")
51
+ submit = gr.Button("Submit")
52
+
53
+ def on_submit(image):
54
+ transform = transforms.ToTensor()
55
+ image = transform(image).unsqueeze(0).to(device)
56
+ shape = image.shape
57
+ image = torch.nn.functional.interpolate(image, (440,480), mode='bilinear', align_corners=True)
58
+ image = F.pad(image, (0, 0, 40, 0))
59
+ with torch.no_grad():
60
+ pred = model(image)['pred_d']
61
+
62
+ pred = pred[:,:,40:,:]
63
+ pred = torch.nn.functional.interpolate(pred, shape[2:], mode='bilinear', align_corners=True)
64
+ pred_d_numpy = pred.squeeze().cpu().numpy()
65
+ colored_depth, _, _ = colorize(pred_d_numpy, cmap='gray_r')
66
+
67
+ tmp = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
68
+ raw_depth = Image.fromarray((pred_d_numpy*256).astype('uint16'))
69
+ raw_depth.save(tmp.name)
70
+ return [colored_depth, tmp.name]
71
+
72
+ submit.click(on_submit, inputs=[input_image], outputs=[depth_image, raw_file])
73
+ examples = gr.Examples(examples=["imgs/test_img1.jpg", "imgs/test_img2.jpg", "imgs/test_img3.jpg", "imgs/test_img4.jpg", "imgs/test_img5.jpg"],
74
+ inputs=[input_image])
75
+
76
+
77
+ def create_refseg_demo(model, tokenizer, device):
78
+ gr.Markdown("### Referring Segmentation demo")
79
+ with gr.Row():
80
+ input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input')
81
+ refseg_image = gr.Image(label="Output Mask", elem_id='img-display-output')
82
+ input_text = gr.Textbox(label='Prompt', placeholder='Please upload your image first', lines=2)
83
+ submit = gr.Button("Submit")
84
+
85
+ def on_submit(image, text):
86
+ image = np.array(image)
87
+ image_t = transforms.ToTensor()(image).unsqueeze(0).to(device)
88
+ image_t = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])(image_t)
89
+ shape = image_t.shape
90
+ image_t = torch.nn.functional.interpolate(image_t, (512,512), mode='bilinear', align_corners=True)
91
+ input_ids = tokenizer(text=text, truncation=True, max_length=40, return_length=True,
92
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")['input_ids'].to(device)
93
+
94
+ with torch.no_grad():
95
+ pred = model(image_t, input_ids)
96
+
97
+ pred = torch.nn.functional.interpolate(pred, shape[2:], mode='bilinear', align_corners=True)
98
+ output_mask = pred.cpu().argmax(1).data.numpy().squeeze()
99
+ alpha = 0.65
100
+ image[output_mask == 0] = (image[output_mask == 0]*alpha).astype(np.uint8)
101
+ contours, _ = cv2.findContours(output_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
102
+ cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
103
+ return Image.fromarray(image)
104
+
105
+ submit.click(on_submit, inputs=[input_image, input_text], outputs=refseg_image)
106
+ examples = gr.Examples(examples=[["imgs/test_img2.jpg", "green plant"], ["imgs/test_img3.jpg", "chair"], ["imgs/test_img4.jpg", "left green plant"], ["imgs/test_img5.jpg", "man walking on foot"], ["imgs/test_img5.jpg", "the rightest camel"]],
107
+ inputs=[input_image, input_text])
108
+
109
+
110
+ def main():
111
+ upload_2_models = True
112
+
113
+ opt = TestOptions().initialize()
114
+ args = opt.parse_args()
115
+
116
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
117
+ if upload_2_models:
118
+ model = AutoModel.from_pretrained("MykolaL/evp_depth", trust_remote_code=True).to(device).eval()
119
+
120
+ tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
121
+ model_refseg = AutoModel.from_pretrained("MykolaL/evp_refer", trust_remote_code=True).to(device).eval()
122
+ print('Models uploaded successfully')
123
+
124
+ title = "# EVP"
125
+ description = """Official demo for **EVP: Enhanced Visual Perception using Inverse Multi-Attentive Feature
126
+ Refinement and Regularized Image-Text Alignment**.
127
+ EVP is a deep learning model for metric depth estimation from a single image as well as referring segmentation.
128
+ Please refer to our [project page](https://lavreniuk.github.io/EVP) or [paper](https://arxiv.org/abs/2312.08548) or [github](https://github.com/Lavreniuk/EVP) for more details."""
129
+
130
+ with gr.Blocks() as demo:
131
+ gr.Markdown(title)
132
+ gr.Markdown(description)
133
+ if upload_2_models:
134
+ with gr.Tab("Depth Prediction"):
135
+ create_depth_demo(model, device)
136
+ with gr.Tab("Referring Segmentation"):
137
+ create_refseg_demo(model_refseg, tokenizer, device)
138
+ gr.HTML('''<br><br><br><center>You can duplicate this Space to skip the queue:<a href="https://huggingface.co/spaces/MykolaL/evp?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
139
+ <p><img src="https://visitor-badge.glitch.me/badge?page_id=MykolaL/evp" alt="visitors"></p></center>''')
140
+
141
+ demo.queue().launch(share=True)
142
+
143
+
144
+ if __name__ == '__main__':
145
+ main()