yulu2 commited on
Commit
4f619cd
1 Parent(s): afa4646

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -1
app.py CHANGED
@@ -1,3 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- gr.Interface.load("models/alaa-lab/InstructCV").launch()
 
 
1
+ # ------------------------------------------------------------------------------
2
+ # Copyright (c) 2023, Alaa lab, UC Berkeley. All rights reserved.
3
+ #
4
+ # Written by Yulu Gan.
5
+ # ------------------------------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import cv2
11
+ import random
12
+ from fnmatch import fnmatch
13
+ import numpy as np
14
+
15
  import gradio as gr
16
+ import torch
17
+ from PIL import Image, ImageOps
18
+ from diffusers import StableDiffusionInstructPix2PixPipeline
19
+
20
+ title = "InstructCV"
21
+
22
+ description = """
23
+ <p style='text-align: center'> <a href='https://huggingface.co/spaces/yulu2/InstructCV/' target='_blank'>Project Page</a> | <a href='https://arxiv.org' target='_blank'>Paper</a> | <a href='https://github.com' target='_blank'>Code</a></p>
24
+ Gradio demo for InstructCV: Towards Universal Text-to-Image Vision Generalists. \n
25
+ You may upload any images you like and try to let the model do vision tasks following your intent. \n
26
+ Some examples: You could use "Segment the dog" for segmentation, "Detect the dog" for object detection, "Estimate the depth map of this image" for depth estimation, etc.
27
+ """ # noqa
28
+
29
+ Intro_text = """
30
+ This space showcases a demo for our paper titled "InstructCV: Towards Universal Text-to-Image Vision Generalists." We are excited to present some impressive features of our model:
31
+
32
+ 1. Zero-shot Capability:
33
+ * Our model was trained on the MS-COCO, NYUv2, Oxford-Pets, and ADE20k datasets. However, it is not limited to these datasets. You can upload any image of your choice and prompt the model to perform various vision tasks, even if they were not part of the original training set.
34
+
35
+ 2. Semantic Disentangling:
36
+ * Our model excels at handling diverse languages and instructions for different vision tasks. You can provide instructions in different languages without worrying about task confusion. The model can effectively disentangle the semantics and understand each task separately.
37
+
38
+ 3. Category / Data Generalization:
39
+ * Feel free to explore any category and experiment with images of different styles. While our model generally performs well, please note that it may not always provide optimal results for all cases. Nonetheless, we encourage you to test its capabilities across various categories and styles.
40
+
41
+ """
42
+
43
+
44
+ example_instructions = [
45
+ "Please help me detect Buzz.",
46
+ "Please help me detect Woody's face.",
47
+ "Create a monocular depth map.",
48
+ ]
49
+
50
+ model_id = "yulu2/InstructCV"
51
+
52
+ def main():
53
+ # pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16, safety_checker=None).to("cpu")
54
+ pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, safety_checker=None).to("cpu")
55
+ example_image = Image.open("imgs/example2.jpg").convert("RGB")
56
+
57
+
58
+ def load_example(seed: int, randomize_seed:bool):
59
+ example_instruction = random.choice(example_instructions)
60
+ return [example_image, example_instruction] + generate(
61
+ example_image,
62
+ example_instruction,
63
+ seed,
64
+ randomize_seed,
65
+ )
66
+
67
+ def generate(
68
+ input_image: Image.Image,
69
+ instruction: str,
70
+ seed: int,
71
+ randomize_seed:bool,
72
+ ):
73
+ seed = random.randint(0, 100000) if randomize_seed else seed
74
+ width, height = input_image.size
75
+ factor = 512 / max(width, height)
76
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
77
+ width = int((width * factor) // 64) * 64
78
+ height = int((height * factor) // 64) * 64
79
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
80
+
81
+ if instruction == "":
82
+ return [input_image]
83
+
84
+ generator = torch.manual_seed(seed)
85
+ edited_image = pipe(
86
+ instruction, image=input_image,
87
+ guidance_scale=7.5, image_guidance_scale=1.5,
88
+ num_inference_steps=20, generator=generator,
89
+ ).images[0]
90
+ instruction_ = instruction.lower()
91
+
92
+ if fnmatch(instruction_, "*segment*") or fnmatch(instruction_, "*split*") or fnmatch(instruction_, "*divide*"):
93
+ input_image = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR) #numpy.ndarray
94
+ edited_image = cv2.cvtColor(np.array(edited_image), cv2.COLOR_RGB2GRAY)
95
+ ret, thresh = cv2.threshold(edited_image, 127, 255, cv2.THRESH_BINARY)
96
+ img2 = input_image.copy()
97
+ seed_seg = np.random.randint(0,10000)
98
+ np.random.seed(seed_seg)
99
+ colors = np.random.randint(0,255,(3))
100
+ colors2 = np.random.randint(0,255,(3))
101
+ contours,_ = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
102
+ edited_image = cv2.drawContours(input_image,contours,-1,(int(colors[0]),int(colors[1]),int(colors[2])),3)
103
+ for j in range(len(contours)):
104
+ edited_image_2 = cv2.fillPoly(img2, [contours[j]], (int(colors2[0]),int(colors2[1]),int(colors2[2])))
105
+ img_merge = cv2.addWeighted(edited_image, 0.5,edited_image_2, 0.5, 0)
106
+ edited_image = Image.fromarray(cv2.cvtColor(img_merge, cv2.COLOR_BGR2RGB))
107
+
108
+ if fnmatch(instruction_, "*depth*"):
109
+ edited_image = cv2.cvtColor(np.array(edited_image), cv2.COLOR_RGB2GRAY)
110
+ n_min = np.min(edited_image)
111
+ n_max = np.max(edited_image)
112
+
113
+ edited_image = (edited_image-n_min)/(n_max-n_min+1e-8)
114
+ edited_image = (255*edited_image).astype(np.uint8)
115
+ edited_image = cv2.applyColorMap(edited_image, cv2.COLORMAP_JET)
116
+ edited_image = Image.fromarray(cv2.cvtColor(edited_image, cv2.COLOR_BGR2RGB))
117
+
118
+ text_cfg_scale = 7.5
119
+ image_cfg_scale = 1.5
120
+ return [seed, text_cfg_scale, image_cfg_scale, edited_image]
121
+
122
+
123
+ with gr.Blocks() as demo:
124
+ # gr.HTML("""<h1 style="font-weight: 900; margin-bottom: 7px;">
125
+ # InstructCV: Towards Universal Text-to-Image Vision Generalists
126
+ # </h1>""")
127
+ gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>" + title + "</h1>")
128
+ gr.Markdown(description)
129
+ with gr.Row():
130
+ with gr.Column(scale=1.5, min_width=100):
131
+ generate_button = gr.Button("Generate result")
132
+ with gr.Column(scale=1.5, min_width=100):
133
+ load_button = gr.Button("Load example")
134
+ with gr.Column(scale=3):
135
+ instruction = gr.Textbox(lines=1, label="Instruction", interactive=True)
136
+
137
+ with gr.Row():
138
+ input_image = gr.Image(label="Input Image", type="pil", interactive=True)
139
+ edited_image = gr.Image(label=f"Output Image", type="pil", interactive=False)
140
+ input_image.style(height=512, width=512)
141
+ edited_image.style(height=512, width=512)
142
+
143
+ with gr.Row():
144
+ randomize_seed = gr.Radio(
145
+ ["Fix Seed", "Randomize Seed"],
146
+ value="Randomize Seed",
147
+ type="index",
148
+ show_label=False,
149
+ interactive=True,
150
+ )
151
+
152
+ seed = gr.Number(value=26000, precision=0, label="Seed", interactive=True)
153
+ text_cfg_scale = gr.Number(value=7.5, label=f"Text weight", interactive=False)
154
+ image_cfg_scale = gr.Number(value=1.5, label=f"Image weight", interactive=False)
155
+
156
+
157
+ gr.Markdown(Intro_text)
158
+
159
+ load_button.click(
160
+ fn=load_example,
161
+ inputs=[seed, randomize_seed],
162
+ outputs=[input_image, instruction, seed, text_cfg_scale, image_cfg_scale, edited_image],
163
+ )
164
+ generate_button.click(
165
+ fn=generate,
166
+ inputs=[
167
+ input_image,
168
+ instruction,
169
+ seed,
170
+ randomize_seed,
171
+ ],
172
+ outputs=[seed, text_cfg_scale, image_cfg_scale, edited_image],
173
+ )
174
+
175
+ demo.queue(concurrency_count=1)
176
+ demo.launch(share=False)
177
+
178
 
179
+ if __name__ == "__main__":
180
+ main()