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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
VISUAL_CHATGPT_PREFIX = """Visual ChatGPT is designed to be able to assist with a wide range of text and visual related tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. Visual ChatGPT is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
|
2 |
+
|
3 |
+
Visual ChatGPT is able to process and understand large amounts of text and image. As a language model, Visual ChatGPT can not directly read images, but it has a list of tools to finish different visual tasks. Each image will have a file name formed as "image/xxx.png", and Visual ChatGPT can invoke different tools to indirectly understand pictures. When talking about images, Visual ChatGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, Visual ChatGPT is also known that the image may not be the same as user's demand, and will use other visual question answering tools or description tools to observe the real image. Visual ChatGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.
|
4 |
+
|
5 |
+
Human may provide new figures to Visual ChatGPT with a description. The description helps Visual ChatGPT to understand this image, but Visual ChatGPT should use tools to finish following tasks, rather than directly imagine from the description.
|
6 |
+
|
7 |
+
Overall, Visual ChatGPT is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.
|
8 |
+
|
9 |
+
|
10 |
+
TOOLS:
|
11 |
+
------
|
12 |
+
|
13 |
+
Visual ChatGPT has access to the following tools:"""
|
14 |
+
|
15 |
+
VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
|
16 |
+
|
17 |
+
```
|
18 |
+
Thought: Do I need to use a tool? Yes
|
19 |
+
Action: the action to take, should be one of [{tool_names}]
|
20 |
+
Action Input: the input to the action
|
21 |
+
Observation: the result of the action
|
22 |
+
```
|
23 |
+
|
24 |
+
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
|
25 |
+
|
26 |
+
```
|
27 |
+
Thought: Do I need to use a tool? No
|
28 |
+
{ai_prefix}: [your response here]
|
29 |
+
```
|
30 |
+
"""
|
31 |
+
|
32 |
+
VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if not exists.
|
33 |
+
You will remember to provide the image file name loyally if it's provided in the last tool observation.
|
34 |
+
|
35 |
+
Begin!
|
36 |
+
|
37 |
+
Previous conversation history:
|
38 |
+
{chat_history}
|
39 |
+
|
40 |
+
New input: {input}
|
41 |
+
Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
|
42 |
+
The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human.
|
43 |
+
Thought: Do I need to use a tool? {agent_scratchpad}"""
|
44 |
+
|
45 |
+
import uuid
|
46 |
+
import os
|
47 |
+
import cv2
|
48 |
+
import random
|
49 |
+
from PIL import Image
|
50 |
+
import torch
|
51 |
+
import numpy as np
|
52 |
+
from pytorch_lightning import seed_everything
|
53 |
+
import re
|
54 |
+
import gradio as gr
|
55 |
+
|
56 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline
|
57 |
+
from diffusers import EulerAncestralDiscreteScheduler
|
58 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
|
59 |
+
from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector
|
60 |
+
|
61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation
|
62 |
+
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
|
63 |
+
from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
|
64 |
+
|
65 |
+
from langchain.agents.initialize import initialize_agent
|
66 |
+
from langchain.agents.tools import Tool
|
67 |
+
from langchain.chains.conversation.memory import ConversationBufferMemory
|
68 |
+
from langchain.llms.openai import OpenAI
|
69 |
+
from langchain.vectorstores import Weaviate
|
70 |
+
|
71 |
+
|
72 |
+
def cut_dialogue_history(history_memory, keep_last_n_words=500):
|
73 |
+
tokens = history_memory.split()
|
74 |
+
n_tokens = len(tokens)
|
75 |
+
print(f"hitory_memory:{history_memory}, n_tokens: {n_tokens}")
|
76 |
+
if n_tokens < keep_last_n_words:
|
77 |
+
return history_memory
|
78 |
+
else:
|
79 |
+
paragraphs = history_memory.split('\n')
|
80 |
+
last_n_tokens = n_tokens
|
81 |
+
while last_n_tokens >= keep_last_n_words:
|
82 |
+
last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))
|
83 |
+
paragraphs = paragraphs[1:]
|
84 |
+
return '\n' + '\n'.join(paragraphs)
|
85 |
+
|
86 |
+
def get_new_image_name(org_img_name, func_name="update"):
|
87 |
+
head_tail = os.path.split(org_img_name)
|
88 |
+
head = head_tail[0]
|
89 |
+
tail = head_tail[1]
|
90 |
+
name_split = tail.split('.')[0].split('_')
|
91 |
+
this_new_uuid = str(uuid.uuid4())[0:4]
|
92 |
+
if len(name_split) == 1:
|
93 |
+
most_org_file_name = name_split[0]
|
94 |
+
recent_prev_file_name = name_split[0]
|
95 |
+
new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
|
96 |
+
else:
|
97 |
+
assert len(name_split) == 4
|
98 |
+
most_org_file_name = name_split[3]
|
99 |
+
recent_prev_file_name = name_split[0]
|
100 |
+
new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
|
101 |
+
return os.path.join(head, new_file_name)
|
102 |
+
|
103 |
+
def ade_palette():
|
104 |
+
return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
|
105 |
+
[4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
|
106 |
+
[230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
|
107 |
+
[150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
|
108 |
+
[143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
|
109 |
+
[0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
|
110 |
+
[255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
|
111 |
+
[255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
|
112 |
+
[255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
|
113 |
+
[224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
|
114 |
+
[255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
|
115 |
+
[6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
|
116 |
+
[140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
|
117 |
+
[255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
|
118 |
+
[255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
|
119 |
+
[11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
|
120 |
+
[0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
|
121 |
+
[255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
|
122 |
+
[0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
|
123 |
+
[173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
|
124 |
+
[255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
|
125 |
+
[255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
|
126 |
+
[255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
|
127 |
+
[0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
|
128 |
+
[0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
|
129 |
+
[143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
|
130 |
+
[8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
|
131 |
+
[255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
|
132 |
+
[92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
|
133 |
+
[163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
|
134 |
+
[255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
|
135 |
+
[255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
|
136 |
+
[10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
|
137 |
+
[255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
|
138 |
+
[41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
|
139 |
+
[71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
|
140 |
+
[184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
|
141 |
+
[102, 255, 0], [92, 0, 255]]
|
142 |
+
|
143 |
+
def HWC3(x):
|
144 |
+
assert x.dtype == np.uint8
|
145 |
+
if x.ndim == 2:
|
146 |
+
x = x[:, :, None]
|
147 |
+
assert x.ndim == 3
|
148 |
+
H, W, C = x.shape
|
149 |
+
assert C == 1 or C == 3 or C == 4
|
150 |
+
if C == 3:
|
151 |
+
return x
|
152 |
+
if C == 1:
|
153 |
+
return np.concatenate([x, x, x], axis=2)
|
154 |
+
if C == 4:
|
155 |
+
color = x[:, :, 0:3].astype(np.float32)
|
156 |
+
alpha = x[:, :, 3:4].astype(np.float32) / 255.0
|
157 |
+
y = color * alpha + 255.0 * (1.0 - alpha)
|
158 |
+
y = y.clip(0, 255).astype(np.uint8)
|
159 |
+
return y
|
160 |
+
|
161 |
+
def resize_image(input_image, resolution):
|
162 |
+
H, W, C = input_image.shape
|
163 |
+
H = float(H)
|
164 |
+
W = float(W)
|
165 |
+
k = float(resolution) / min(H, W)
|
166 |
+
H *= k
|
167 |
+
W *= k
|
168 |
+
H = int(np.round(H / 64.0)) * 64
|
169 |
+
W = int(np.round(W / 64.0)) * 64
|
170 |
+
img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
|
171 |
+
return img
|
172 |
+
|
173 |
+
class MaskFormer:
|
174 |
+
def __init__(self, device):
|
175 |
+
self.device = device
|
176 |
+
self.processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
|
177 |
+
self.model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device)
|
178 |
+
|
179 |
+
def inference(self, image_path, text):
|
180 |
+
threshold = 0.5
|
181 |
+
min_area = 0.02
|
182 |
+
padding = 20
|
183 |
+
original_image = Image.open(image_path)
|
184 |
+
image = original_image.resize((512, 512))
|
185 |
+
inputs = self.processor(text=text, images=image, padding="max_length", return_tensors="pt",).to(self.device)
|
186 |
+
with torch.no_grad():
|
187 |
+
outputs = self.model(**inputs)
|
188 |
+
mask = torch.sigmoid(outputs[0]).squeeze().cpu().numpy() > threshold
|
189 |
+
area_ratio = len(np.argwhere(mask)) / (mask.shape[0] * mask.shape[1])
|
190 |
+
if area_ratio < min_area:
|
191 |
+
return None
|
192 |
+
true_indices = np.argwhere(mask)
|
193 |
+
mask_array = np.zeros_like(mask, dtype=bool)
|
194 |
+
for idx in true_indices:
|
195 |
+
padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)
|
196 |
+
mask_array[padded_slice] = True
|
197 |
+
visual_mask = (mask_array * 255).astype(np.uint8)
|
198 |
+
image_mask = Image.fromarray(visual_mask)
|
199 |
+
return image_mask.resize(image.size)
|
200 |
+
|
201 |
+
class ImageEditing:
|
202 |
+
def __init__(self, device):
|
203 |
+
print("Initializing StableDiffusionInpaint to %s" % device)
|
204 |
+
self.device = device
|
205 |
+
self.mask_former = MaskFormer(device=self.device)
|
206 |
+
self.inpainting = StableDiffusionInpaintPipeline.from_pretrained( "runwayml/stable-diffusion-inpainting",).to(device)
|
207 |
+
|
208 |
+
def remove_part_of_image(self, input):
|
209 |
+
image_path, to_be_removed_txt = input.split(",")
|
210 |
+
print(f'remove_part_of_image: to_be_removed {to_be_removed_txt}')
|
211 |
+
return self.replace_part_of_image(f"{image_path},{to_be_removed_txt},background")
|
212 |
+
|
213 |
+
def replace_part_of_image(self, input):
|
214 |
+
image_path, to_be_replaced_txt, replace_with_txt = input.split(",")
|
215 |
+
print(f'replace_part_of_image: replace_with_txt {replace_with_txt}')
|
216 |
+
original_image = Image.open(image_path)
|
217 |
+
mask_image = self.mask_former.inference(image_path, to_be_replaced_txt)
|
218 |
+
updated_image = self.inpainting(prompt=replace_with_txt, image=original_image, mask_image=mask_image).images[0]
|
219 |
+
updated_image_path = get_new_image_name(image_path, func_name="replace-something")
|
220 |
+
updated_image.save(updated_image_path)
|
221 |
+
return updated_image_path
|
222 |
+
|
223 |
+
class Pix2Pix:
|
224 |
+
def __init__(self, device):
|
225 |
+
print("Initializing Pix2Pix to %s" % device)
|
226 |
+
self.device = device
|
227 |
+
self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix", torch_dtype=torch.float16, safety_checker=None).to(device)
|
228 |
+
self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
|
229 |
+
|
230 |
+
def inference(self, inputs):
|
231 |
+
"""Change style of image."""
|
232 |
+
print("===>Starting Pix2Pix Inference")
|
233 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
234 |
+
original_image = Image.open(image_path)
|
235 |
+
image = self.pipe(instruct_text,image=original_image,num_inference_steps=40,image_guidance_scale=1.2,).images[0]
|
236 |
+
updated_image_path = get_new_image_name(image_path, func_name="pix2pix")
|
237 |
+
image.save(updated_image_path)
|
238 |
+
return updated_image_path
|
239 |
+
|
240 |
+
class T2I:
|
241 |
+
def __init__(self, device):
|
242 |
+
print("Initializing T2I to %s" % device)
|
243 |
+
self.device = device
|
244 |
+
self.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
|
245 |
+
self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
|
246 |
+
self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
|
247 |
+
self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model, tokenizer=self.text_refine_tokenizer, device=self.device)
|
248 |
+
self.pipe.to(device)
|
249 |
+
|
250 |
+
def inference(self, text):
|
251 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
252 |
+
refined_text = self.text_refine_gpt2_pipe(text)[0]["generated_text"]
|
253 |
+
print(f'{text} refined to {refined_text}')
|
254 |
+
image = self.pipe(refined_text).images[0]
|
255 |
+
image.save(image_filename)
|
256 |
+
print(f"Processed T2I.run, text: {text}, image_filename: {image_filename}")
|
257 |
+
return image_filename
|
258 |
+
|
259 |
+
class ImageCaptioning:
|
260 |
+
def __init__(self, device):
|
261 |
+
print("Initializing ImageCaptioning to %s" % device)
|
262 |
+
self.device = device
|
263 |
+
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
264 |
+
self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(self.device)
|
265 |
+
|
266 |
+
def inference(self, image_path):
|
267 |
+
inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device)
|
268 |
+
out = self.model.generate(**inputs)
|
269 |
+
captions = self.processor.decode(out[0], skip_special_tokens=True)
|
270 |
+
return captions
|
271 |
+
|
272 |
+
class image2canny:
|
273 |
+
def __init__(self):
|
274 |
+
print("Direct detect canny.")
|
275 |
+
self.low_threshold = 100
|
276 |
+
self.high_threshold = 200
|
277 |
+
|
278 |
+
def inference(self, inputs):
|
279 |
+
print("===>Starting image2canny Inference")
|
280 |
+
image = Image.open(inputs)
|
281 |
+
image = np.array(image)
|
282 |
+
canny = cv2.Canny(image, self.low_threshold, self.high_threshold)
|
283 |
+
canny = canny[:, :, None]
|
284 |
+
canny = np.concatenate([canny, canny, canny], axis=2)
|
285 |
+
canny = 255 - canny
|
286 |
+
canny = Image.fromarray(canny)
|
287 |
+
updated_image_path = get_new_image_name(inputs, func_name="edge")
|
288 |
+
canny.save(updated_image_path)
|
289 |
+
return updated_image_path
|
290 |
+
|
291 |
+
class canny2image:
|
292 |
+
def __init__(self, device):
|
293 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
294 |
+
"fusing/stable-diffusion-v1-5-controlnet-canny"
|
295 |
+
)
|
296 |
+
|
297 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
298 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
299 |
+
)
|
300 |
+
|
301 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
302 |
+
self.pipe.to(device)
|
303 |
+
self.image_resolution = 512
|
304 |
+
self.num_inference_steps = 20
|
305 |
+
self.seed = -1
|
306 |
+
self.unconditional_guidance_scale = 9.0
|
307 |
+
self.a_prompt = 'best quality, extremely detailed'
|
308 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
309 |
+
|
310 |
+
def inference(self, inputs):
|
311 |
+
print("===>Starting canny2image Inference")
|
312 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
313 |
+
image = Image.open(image_path)
|
314 |
+
image = np.array(image)
|
315 |
+
image = 255 - image
|
316 |
+
prompt = instruct_text
|
317 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
318 |
+
img = Image.fromarray(img)
|
319 |
+
|
320 |
+
self.seed = random.randint(0, 65535)
|
321 |
+
seed_everything(self.seed)
|
322 |
+
prompt = prompt + ', ' + self.a_prompt
|
323 |
+
image = self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=self.unconditional_guidance_scale).images[0]
|
324 |
+
updated_image_path = get_new_image_name(image_path, func_name="canny2image")
|
325 |
+
image.save(updated_image_path)
|
326 |
+
return updated_image_path
|
327 |
+
|
328 |
+
class image2line:
|
329 |
+
def __init__(self):
|
330 |
+
self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')
|
331 |
+
self.value_thresh = 0.1
|
332 |
+
self.dis_thresh = 0.1
|
333 |
+
self.resolution = 512
|
334 |
+
|
335 |
+
def inference(self, inputs):
|
336 |
+
print("===>Starting image2line Inference")
|
337 |
+
image = Image.open(inputs)
|
338 |
+
image = np.array(image)
|
339 |
+
image = HWC3(image)
|
340 |
+
mlsd = self.detector(resize_image(image, self.resolution), thr_v=self.value_thresh, thr_d=self.dis_thresh)
|
341 |
+
mlsd = np.array(mlsd)
|
342 |
+
mlsd = 255 - mlsd
|
343 |
+
mlsd = Image.fromarray(mlsd)
|
344 |
+
updated_image_path = get_new_image_name(inputs, func_name="line-of")
|
345 |
+
mlsd.save(updated_image_path)
|
346 |
+
return updated_image_path
|
347 |
+
|
348 |
+
class line2image:
|
349 |
+
def __init__(self, device):
|
350 |
+
print("Initialize the line2image model...")
|
351 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
352 |
+
"fusing/stable-diffusion-v1-5-controlnet-mlsd"
|
353 |
+
)
|
354 |
+
|
355 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
356 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
357 |
+
)
|
358 |
+
|
359 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
360 |
+
self.pipe.to(device)
|
361 |
+
self.image_resolution = 512
|
362 |
+
self.num_inference_steps = 20
|
363 |
+
self.seed = -1
|
364 |
+
self.unconditional_guidance_scale = 9.0
|
365 |
+
self.a_prompt = 'best quality, extremely detailed'
|
366 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
367 |
+
|
368 |
+
def inference(self, inputs):
|
369 |
+
print("===>Starting line2image Inference")
|
370 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
371 |
+
image = Image.open(image_path)
|
372 |
+
image = np.array(image)
|
373 |
+
image = 255 - image
|
374 |
+
prompt = instruct_text
|
375 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
376 |
+
img = Image.fromarray(img)
|
377 |
+
|
378 |
+
self.seed = random.randint(0, 65535)
|
379 |
+
seed_everything(self.seed)
|
380 |
+
|
381 |
+
prompt = prompt + ', ' + self.a_prompt
|
382 |
+
image = self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=self.unconditional_guidance_scale).images[0]
|
383 |
+
updated_image_path = get_new_image_name(image_path, func_name="line2image")
|
384 |
+
image.save(updated_image_path)
|
385 |
+
return updated_image_path
|
386 |
+
|
387 |
+
class image2hed:
|
388 |
+
def __init__(self):
|
389 |
+
print("Direct detect soft HED boundary...")
|
390 |
+
self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
|
391 |
+
self.resolution = 512
|
392 |
+
|
393 |
+
def inference(self, inputs):
|
394 |
+
print("===>Starting image2hed Inference")
|
395 |
+
image = Image.open(inputs)
|
396 |
+
image = np.array(image)
|
397 |
+
image = HWC3(image)
|
398 |
+
image = Image.fromarray(resize_image(image, self.resolution))
|
399 |
+
hed = self.detector(image)
|
400 |
+
|
401 |
+
updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")
|
402 |
+
hed.save(updated_image_path)
|
403 |
+
return updated_image_path
|
404 |
+
|
405 |
+
class hed2image:
|
406 |
+
def __init__(self, device):
|
407 |
+
print("Initialize the hed2image model...")
|
408 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
409 |
+
"fusing/stable-diffusion-v1-5-controlnet-hed"
|
410 |
+
)
|
411 |
+
|
412 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
413 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
414 |
+
)
|
415 |
+
|
416 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
417 |
+
self.pipe.to(device)
|
418 |
+
self.image_resolution = 512
|
419 |
+
self.num_inference_steps = 20
|
420 |
+
self.seed = -1
|
421 |
+
self.unconditional_guidance_scale = 9.0
|
422 |
+
self.a_prompt = 'best quality, extremely detailed'
|
423 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
424 |
+
|
425 |
+
def inference(self, inputs):
|
426 |
+
print("===>Starting hed2image Inference")
|
427 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
428 |
+
image = Image.open(image_path)
|
429 |
+
image = np.array(image)
|
430 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
431 |
+
img = Image.fromarray(img)
|
432 |
+
|
433 |
+
self.seed = random.randint(0, 65535)
|
434 |
+
seed_everything(self.seed)
|
435 |
+
|
436 |
+
prompt = instruct_text
|
437 |
+
prompt = prompt + ', ' + self.a_prompt
|
438 |
+
image = \
|
439 |
+
self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt,
|
440 |
+
guidance_scale=self.unconditional_guidance_scale).images[0]
|
441 |
+
updated_image_path = get_new_image_name(image_path, func_name="hed2image")
|
442 |
+
image.save(updated_image_path)
|
443 |
+
return updated_image_path
|
444 |
+
|
445 |
+
class image2scribble:
|
446 |
+
def __init__(self):
|
447 |
+
print("Direct detect scribble.")
|
448 |
+
self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
|
449 |
+
self.resolution = 512
|
450 |
+
|
451 |
+
def inference(self, inputs):
|
452 |
+
print("===>Starting image2scribble Inference")
|
453 |
+
image = Image.open(inputs)
|
454 |
+
image = np.array(image)
|
455 |
+
image = HWC3(image)
|
456 |
+
image = resize_image(image, self.resolution)
|
457 |
+
image = Image.fromarray(image)
|
458 |
+
scribble = self.detector(image, scribble=True)
|
459 |
+
scribble = np.array(scribble)
|
460 |
+
scribble = 255 - scribble
|
461 |
+
scribble = Image.fromarray(scribble)
|
462 |
+
updated_image_path = get_new_image_name(inputs, func_name="scribble")
|
463 |
+
scribble.save(updated_image_path)
|
464 |
+
return updated_image_path
|
465 |
+
|
466 |
+
class scribble2image:
|
467 |
+
def __init__(self, device):
|
468 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
469 |
+
"fusing/stable-diffusion-v1-5-controlnet-scribble"
|
470 |
+
)
|
471 |
+
|
472 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
473 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
474 |
+
)
|
475 |
+
|
476 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
477 |
+
self.pipe.to(device)
|
478 |
+
self.image_resolution = 512
|
479 |
+
self.num_inference_steps = 20
|
480 |
+
self.seed = -1
|
481 |
+
self.unconditional_guidance_scale = 9.0
|
482 |
+
self.a_prompt = 'best quality, extremely detailed'
|
483 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
484 |
+
|
485 |
+
def inference(self, inputs):
|
486 |
+
print("===>Starting scribble2image Inference")
|
487 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
488 |
+
image = Image.open(image_path)
|
489 |
+
image = np.array(image)
|
490 |
+
image = 255 - image
|
491 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
492 |
+
img = Image.fromarray(img)
|
493 |
+
|
494 |
+
self.seed = random.randint(0, 65535)
|
495 |
+
seed_everything(self.seed)
|
496 |
+
|
497 |
+
prompt = instruct_text
|
498 |
+
prompt = prompt + ', ' + self.a_prompt
|
499 |
+
image = \
|
500 |
+
self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt,
|
501 |
+
guidance_scale=self.unconditional_guidance_scale).images[0]
|
502 |
+
updated_image_path = get_new_image_name(image_path, func_name="scribble2image")
|
503 |
+
image.save(updated_image_path)
|
504 |
+
return updated_image_path
|
505 |
+
|
506 |
+
class image2pose:
|
507 |
+
def __init__(self):
|
508 |
+
self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')
|
509 |
+
self.resolution = 512
|
510 |
+
|
511 |
+
def inference(self, inputs):
|
512 |
+
print("===>Starting image2pose Inference")
|
513 |
+
image = Image.open(inputs)
|
514 |
+
image = np.array(image)
|
515 |
+
image = HWC3(image)
|
516 |
+
image = resize_image(image, self.resolution)
|
517 |
+
image = Image.fromarray(image)
|
518 |
+
pose = self.detector(image)
|
519 |
+
|
520 |
+
updated_image_path = get_new_image_name(inputs, func_name="human-pose")
|
521 |
+
pose.save(updated_image_path)
|
522 |
+
return updated_image_path
|
523 |
+
|
524 |
+
class pose2image:
|
525 |
+
def __init__(self, device):
|
526 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
527 |
+
"fusing/stable-diffusion-v1-5-controlnet-openpose"
|
528 |
+
)
|
529 |
+
|
530 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
531 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
532 |
+
)
|
533 |
+
|
534 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
535 |
+
self.pipe.to(device)
|
536 |
+
self.image_resolution = 512
|
537 |
+
self.num_inference_steps = 20
|
538 |
+
self.seed = -1
|
539 |
+
self.unconditional_guidance_scale = 9.0
|
540 |
+
self.a_prompt = 'best quality, extremely detailed'
|
541 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
542 |
+
|
543 |
+
def inference(self, inputs):
|
544 |
+
print("===>Starting pose2image Inference")
|
545 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
546 |
+
image = Image.open(image_path)
|
547 |
+
image = np.array(image)
|
548 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
549 |
+
img = Image.fromarray(img)
|
550 |
+
|
551 |
+
self.seed = random.randint(0, 65535)
|
552 |
+
seed_everything(self.seed)
|
553 |
+
|
554 |
+
prompt = instruct_text
|
555 |
+
prompt = prompt + ', ' + self.a_prompt
|
556 |
+
image = \
|
557 |
+
self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt,
|
558 |
+
guidance_scale=self.unconditional_guidance_scale).images[0]
|
559 |
+
updated_image_path = get_new_image_name(image_path, func_name="pose2image")
|
560 |
+
image.save(updated_image_path)
|
561 |
+
return updated_image_path
|
562 |
+
|
563 |
+
class image2seg:
|
564 |
+
def __init__(self):
|
565 |
+
print("Initialize image2segmentation Inference")
|
566 |
+
self.image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
|
567 |
+
self.image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
|
568 |
+
self.resolution = 512
|
569 |
+
|
570 |
+
def inference(self, inputs):
|
571 |
+
image = Image.open(inputs)
|
572 |
+
image = np.array(image)
|
573 |
+
image = HWC3(image)
|
574 |
+
image = resize_image(image, self.resolution)
|
575 |
+
image = Image.fromarray(image)
|
576 |
+
pixel_values = self.image_processor(image, return_tensors="pt").pixel_values
|
577 |
+
|
578 |
+
with torch.no_grad():
|
579 |
+
outputs = self.image_segmentor(pixel_values)
|
580 |
+
|
581 |
+
seg = self.image_processor.post_process_semantic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]
|
582 |
+
|
583 |
+
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
|
584 |
+
|
585 |
+
palette = np.array(ade_palette())
|
586 |
+
|
587 |
+
for label, color in enumerate(palette):
|
588 |
+
color_seg[seg == label, :] = color
|
589 |
+
|
590 |
+
color_seg = color_seg.astype(np.uint8)
|
591 |
+
|
592 |
+
segmentation = Image.fromarray(color_seg)
|
593 |
+
updated_image_path = get_new_image_name(inputs, func_name="segmentation")
|
594 |
+
segmentation.save(updated_image_path)
|
595 |
+
return updated_image_path
|
596 |
+
|
597 |
+
class seg2image:
|
598 |
+
def __init__(self, device):
|
599 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
600 |
+
"fusing/stable-diffusion-v1-5-controlnet-seg"
|
601 |
+
)
|
602 |
+
|
603 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
604 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
605 |
+
)
|
606 |
+
|
607 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
608 |
+
self.pipe.to(device)
|
609 |
+
self.image_resolution = 512
|
610 |
+
self.num_inference_steps = 20
|
611 |
+
self.seed = -1
|
612 |
+
self.unconditional_guidance_scale = 9.0
|
613 |
+
self.a_prompt = 'best quality, extremely detailed'
|
614 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
615 |
+
|
616 |
+
def inference(self, inputs):
|
617 |
+
print("===>Starting seg2image Inference")
|
618 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
619 |
+
image = Image.open(image_path)
|
620 |
+
image = np.array(image)
|
621 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
622 |
+
img = Image.fromarray(img)
|
623 |
+
|
624 |
+
self.seed = random.randint(0, 65535)
|
625 |
+
seed_everything(self.seed)
|
626 |
+
|
627 |
+
prompt = instruct_text
|
628 |
+
prompt = prompt + ', ' + self.a_prompt
|
629 |
+
image = \
|
630 |
+
self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt,
|
631 |
+
guidance_scale=self.unconditional_guidance_scale).images[0]
|
632 |
+
updated_image_path = get_new_image_name(image_path, func_name="segment2image")
|
633 |
+
image.save(updated_image_path)
|
634 |
+
return updated_image_path
|
635 |
+
|
636 |
+
class image2depth:
|
637 |
+
def __init__(self):
|
638 |
+
print("initialize depth estimation")
|
639 |
+
self.depth_estimator = pipeline('depth-estimation')
|
640 |
+
self.resolution = 512
|
641 |
+
|
642 |
+
def inference(self, inputs):
|
643 |
+
image = Image.open(inputs)
|
644 |
+
image = np.array(image)
|
645 |
+
image = HWC3(image)
|
646 |
+
image = resize_image(image, self.resolution)
|
647 |
+
image = Image.fromarray(image)
|
648 |
+
depth = self.depth_estimator(image)['depth']
|
649 |
+
depth = np.array(depth)
|
650 |
+
depth = depth[:, :, None]
|
651 |
+
depth = np.concatenate([depth, depth, depth], axis=2)
|
652 |
+
depth = Image.fromarray(depth)
|
653 |
+
updated_image_path = get_new_image_name(inputs, func_name="depth")
|
654 |
+
depth.save(updated_image_path)
|
655 |
+
return updated_image_path
|
656 |
+
|
657 |
+
class depth2image:
|
658 |
+
def __init__(self, device):
|
659 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
660 |
+
"fusing/stable-diffusion-v1-5-controlnet-depth"
|
661 |
+
)
|
662 |
+
|
663 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
664 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
665 |
+
)
|
666 |
+
|
667 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
668 |
+
self.pipe.to(device)
|
669 |
+
self.image_resolution = 512
|
670 |
+
self.num_inference_steps = 20
|
671 |
+
self.seed = -1
|
672 |
+
self.unconditional_guidance_scale = 9.0
|
673 |
+
self.a_prompt = 'best quality, extremely detailed'
|
674 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
675 |
+
|
676 |
+
def inference(self, inputs):
|
677 |
+
print("===>Starting depth2image Inference")
|
678 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
679 |
+
image = Image.open(image_path)
|
680 |
+
image = np.array(image)
|
681 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
682 |
+
img = Image.fromarray(img)
|
683 |
+
|
684 |
+
self.seed = random.randint(0, 65535)
|
685 |
+
seed_everything(self.seed)
|
686 |
+
|
687 |
+
prompt = instruct_text
|
688 |
+
prompt = prompt + ', ' + self.a_prompt
|
689 |
+
image = \
|
690 |
+
self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt,
|
691 |
+
guidance_scale=self.unconditional_guidance_scale).images[0]
|
692 |
+
updated_image_path = get_new_image_name(image_path, func_name="depth2image")
|
693 |
+
image.save(updated_image_path)
|
694 |
+
return updated_image_path
|
695 |
+
|
696 |
+
class image2normal:
|
697 |
+
def __init__(self):
|
698 |
+
print("normal estimation")
|
699 |
+
self.depth_estimator = pipeline("depth-estimation", model="Intel/dpt-hybrid-midas")
|
700 |
+
self.resolution = 512
|
701 |
+
self.bg_threhold = 0.4
|
702 |
+
|
703 |
+
def inference(self, inputs):
|
704 |
+
image = Image.open(inputs)
|
705 |
+
image = np.array(image)
|
706 |
+
image = HWC3(image)
|
707 |
+
image = resize_image(image, self.resolution)
|
708 |
+
image = Image.fromarray(image)
|
709 |
+
image = self.depth_estimator(image)['predicted_depth'][0]
|
710 |
+
|
711 |
+
image = image.numpy()
|
712 |
+
|
713 |
+
image_depth = image.copy()
|
714 |
+
image_depth -= np.min(image_depth)
|
715 |
+
image_depth /= np.max(image_depth)
|
716 |
+
|
717 |
+
bg_threhold = 0.4
|
718 |
+
|
719 |
+
x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)
|
720 |
+
x[image_depth < bg_threhold] = 0
|
721 |
+
|
722 |
+
y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)
|
723 |
+
y[image_depth < bg_threhold] = 0
|
724 |
+
|
725 |
+
z = np.ones_like(x) * np.pi * 2.0
|
726 |
+
|
727 |
+
image = np.stack([x, y, z], axis=2)
|
728 |
+
image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5
|
729 |
+
image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)
|
730 |
+
image = Image.fromarray(image)
|
731 |
+
updated_image_path = get_new_image_name(inputs, func_name="normal-map")
|
732 |
+
image.save(updated_image_path)
|
733 |
+
return updated_image_path
|
734 |
+
|
735 |
+
class normal2image:
|
736 |
+
def __init__(self, device):
|
737 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
738 |
+
"fusing/stable-diffusion-v1-5-controlnet-normal"
|
739 |
+
)
|
740 |
+
|
741 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
742 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
|
743 |
+
)
|
744 |
+
|
745 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
746 |
+
self.pipe.to(device)
|
747 |
+
self.image_resolution = 512
|
748 |
+
self.num_inference_steps = 20
|
749 |
+
self.seed = -1
|
750 |
+
self.unconditional_guidance_scale = 9.0
|
751 |
+
self.a_prompt = 'best quality, extremely detailed'
|
752 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
753 |
+
|
754 |
+
def inference(self, inputs):
|
755 |
+
print("===>Starting normal2image Inference")
|
756 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
757 |
+
image = Image.open(image_path)
|
758 |
+
image = np.array(image)
|
759 |
+
img = resize_image(HWC3(image), self.image_resolution)
|
760 |
+
img = Image.fromarray(img)
|
761 |
+
|
762 |
+
self.seed = random.randint(0, 65535)
|
763 |
+
seed_everything(self.seed)
|
764 |
+
|
765 |
+
prompt = instruct_text
|
766 |
+
prompt = prompt + ', ' + self.a_prompt
|
767 |
+
image = \
|
768 |
+
self.pipe(prompt, img, num_inference_steps=self.num_inference_steps, eta=0.0, negative_prompt=self.n_prompt,
|
769 |
+
guidance_scale=self.unconditional_guidance_scale).images[0]
|
770 |
+
updated_image_path = get_new_image_name(image_path, func_name="normal2image")
|
771 |
+
image.save(updated_image_path)
|
772 |
+
return updated_image_path
|
773 |
+
|
774 |
+
class BLIPVQA:
|
775 |
+
def __init__(self, device):
|
776 |
+
print("Initializing BLIP VQA to %s" % device)
|
777 |
+
self.device = device
|
778 |
+
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
779 |
+
self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(self.device)
|
780 |
+
|
781 |
+
def get_answer_from_question_and_image(self, inputs):
|
782 |
+
image_path, question = inputs.split(",")
|
783 |
+
raw_image = Image.open(image_path).convert('RGB')
|
784 |
+
print(F'BLIPVQA :question :{question}')
|
785 |
+
inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device)
|
786 |
+
out = self.model.generate(**inputs)
|
787 |
+
answer = self.processor.decode(out[0], skip_special_tokens=True)
|
788 |
+
return answer
|
789 |
+
|
790 |
+
class ConversationBot:
|
791 |
+
def __init__(self):
|
792 |
+
print("Initializing VisualChatGPT")
|
793 |
+
self.llm = OpenAI(temperature=0)
|
794 |
+
self.edit = ImageEditing(device="cuda:0")
|
795 |
+
self.i2t = ImageCaptioning(device="cuda:0")
|
796 |
+
self.t2i = T2I(device="cuda:0")
|
797 |
+
self.image2canny = image2canny()
|
798 |
+
self.canny2image = canny2image(device="cuda:1")
|
799 |
+
self.image2line = image2line()
|
800 |
+
self.line2image = line2image(device="cuda:1")
|
801 |
+
self.image2hed = image2hed()
|
802 |
+
self.hed2image = hed2image(device="cuda:1")
|
803 |
+
self.image2scribble = image2scribble()
|
804 |
+
self.scribble2image = scribble2image(device="cuda:2")
|
805 |
+
self.image2pose = image2pose()
|
806 |
+
self.pose2image = pose2image(device="cuda:2")
|
807 |
+
self.BLIPVQA = BLIPVQA(device="cuda:2")
|
808 |
+
self.image2seg = image2seg()
|
809 |
+
self.seg2image = seg2image(device="cuda:3")
|
810 |
+
self.image2depth = image2depth()
|
811 |
+
self.depth2image = depth2image(device="cuda:3")
|
812 |
+
self.image2normal = image2normal()
|
813 |
+
self.normal2image = normal2image(device="cuda:3")
|
814 |
+
self.pix2pix = Pix2Pix(device="cuda:3")
|
815 |
+
self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
|
816 |
+
self.tools = [
|
817 |
+
Tool(name="Get Photo Description", func=self.i2t.inference,
|
818 |
+
description="useful for when you want to know what is inside the photo. receives image_path as input. "
|
819 |
+
"The input to this tool should be a string, representing the image_path. "),
|
820 |
+
Tool(name="Generate Image From User Input Text", func=self.t2i.inference,
|
821 |
+
description="useful for when you want to generate an image from a user input text and it saved it to a file. like: generate an image of an object or something, or generate an image that includes some objects. "
|
822 |
+
"The input to this tool should be a string, representing the text used to generate image. "),
|
823 |
+
Tool(name="Remove Something From The Photo", func=self.edit.remove_part_of_image,
|
824 |
+
description="useful for when you want to remove and object or something from the photo from its description or location. "
|
825 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the object need to be removed. "),
|
826 |
+
Tool(name="Replace Something From The Photo", func=self.edit.replace_part_of_image,
|
827 |
+
description="useful for when you want to replace an object from the object description or location with another object from its description. "
|
828 |
+
"The input to this tool should be a comma seperated string of three, representing the image_path, the object to be replaced, the object to be replaced with "),
|
829 |
+
Tool(name="Instruct Image Using Text", func=self.pix2pix.inference,
|
830 |
+
description="useful for when you want to the style of the image to be like the text. like: make it look like a painting. or make it like a robot. "
|
831 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the text. "),
|
832 |
+
Tool(name="Answer Question About The Image", func=self.BLIPVQA.get_answer_from_question_and_image,
|
833 |
+
description="useful for when you need an answer for a question based on an image. like: what is the background color of the last image, how many cats in this figure, what is in this figure. "
|
834 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the question"),
|
835 |
+
Tool(name="Edge Detection On Image", func=self.image2canny.inference,
|
836 |
+
description="useful for when you want to detect the edge of the image. like: detect the edges of this image, or canny detection on image, or peform edge detection on this image, or detect the canny image of this image. "
|
837 |
+
"The input to this tool should be a string, representing the image_path"),
|
838 |
+
Tool(name="Generate Image Condition On Canny Image", func=self.canny2image.inference,
|
839 |
+
description="useful for when you want to generate a new real image from both the user desciption and a canny image. like: generate a real image of a object or something from this canny image, or generate a new real image of a object or something from this edge image. "
|
840 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),
|
841 |
+
Tool(name="Line Detection On Image", func=self.image2line.inference,
|
842 |
+
description="useful for when you want to detect the straight line of the image. like: detect the straight lines of this image, or straight line detection on image, or peform straight line detection on this image, or detect the straight line image of this image. "
|
843 |
+
"The input to this tool should be a string, representing the image_path"),
|
844 |
+
Tool(name="Generate Image Condition On Line Image", func=self.line2image.inference,
|
845 |
+
description="useful for when you want to generate a new real image from both the user desciption and a straight line image. like: generate a real image of a object or something from this straight line image, or generate a new real image of a object or something from this straight lines. "
|
846 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),
|
847 |
+
Tool(name="Hed Detection On Image", func=self.image2hed.inference,
|
848 |
+
description="useful for when you want to detect the soft hed boundary of the image. like: detect the soft hed boundary of this image, or hed boundary detection on image, or peform hed boundary detection on this image, or detect soft hed boundary image of this image. "
|
849 |
+
"The input to this tool should be a string, representing the image_path"),
|
850 |
+
Tool(name="Generate Image Condition On Soft Hed Boundary Image", func=self.hed2image.inference,
|
851 |
+
description="useful for when you want to generate a new real image from both the user desciption and a soft hed boundary image. like: generate a real image of a object or something from this soft hed boundary image, or generate a new real image of a object or something from this hed boundary. "
|
852 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
|
853 |
+
Tool(name="Segmentation On Image", func=self.image2seg.inference,
|
854 |
+
description="useful for when you want to detect segmentations of the image. like: segment this image, or generate segmentations on this image, or peform segmentation on this image. "
|
855 |
+
"The input to this tool should be a string, representing the image_path"),
|
856 |
+
Tool(name="Generate Image Condition On Segmentations", func=self.seg2image.inference,
|
857 |
+
description="useful for when you want to generate a new real image from both the user desciption and segmentations. like: generate a real image of a object or something from this segmentation image, or generate a new real image of a object or something from these segmentations. "
|
858 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
|
859 |
+
Tool(name="Predict Depth On Image", func=self.image2depth.inference,
|
860 |
+
description="useful for when you want to detect depth of the image. like: generate the depth from this image, or detect the depth map on this image, or predict the depth for this image. "
|
861 |
+
"The input to this tool should be a string, representing the image_path"),
|
862 |
+
Tool(name="Generate Image Condition On Depth", func=self.depth2image.inference,
|
863 |
+
description="useful for when you want to generate a new real image from both the user desciption and depth image. like: generate a real image of a object or something from this depth image, or generate a new real image of a object or something from the depth map. "
|
864 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
|
865 |
+
Tool(name="Predict Normal Map On Image", func=self.image2normal.inference,
|
866 |
+
description="useful for when you want to detect norm map of the image. like: generate normal map from this image, or predict normal map of this image. "
|
867 |
+
"The input to this tool should be a string, representing the image_path"),
|
868 |
+
Tool(name="Generate Image Condition On Normal Map", func=self.normal2image.inference,
|
869 |
+
description="useful for when you want to generate a new real image from both the user desciption and normal map. like: generate a real image of a object or something from this normal map, or generate a new real image of a object or something from the normal map. "
|
870 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
|
871 |
+
Tool(name="Sketch Detection On Image", func=self.image2scribble.inference,
|
872 |
+
description="useful for when you want to generate a scribble of the image. like: generate a scribble of this image, or generate a sketch from this image, detect the sketch from this image. "
|
873 |
+
"The input to this tool should be a string, representing the image_path"),
|
874 |
+
Tool(name="Generate Image Condition On Sketch Image", func=self.scribble2image.inference,
|
875 |
+
description="useful for when you want to generate a new real image from both the user desciption and a scribble image or a sketch image. "
|
876 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
|
877 |
+
Tool(name="Pose Detection On Image", func=self.image2pose.inference,
|
878 |
+
description="useful for when you want to detect the human pose of the image. like: generate human poses of this image, or generate a pose image from this image. "
|
879 |
+
"The input to this tool should be a string, representing the image_path"),
|
880 |
+
Tool(name="Generate Image Condition On Pose Image", func=self.pose2image.inference,
|
881 |
+
description="useful for when you want to generate a new real image from both the user desciption and a human pose image. like: generate a real image of a human from this human pose image, or generate a new real image of a human from this pose. "
|
882 |
+
"The input to this tool should be a comma seperated string of two, representing the image_path and the user description")
|
883 |
+
]
|
884 |
+
self.agent = initialize_agent(
|
885 |
+
self.tools,
|
886 |
+
self.llm,
|
887 |
+
agent="conversational-react-description",
|
888 |
+
verbose=True,
|
889 |
+
memory=self.memory,
|
890 |
+
return_intermediate_steps=True,
|
891 |
+
agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}, )
|
892 |
+
|
893 |
+
def run_text(self, text, state):
|
894 |
+
print("===============Running run_text =============")
|
895 |
+
print("Inputs:", text, state)
|
896 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
897 |
+
self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
|
898 |
+
res = self.agent({"input": text})
|
899 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
900 |
+
response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
|
901 |
+
state = state + [(text, response)]
|
902 |
+
print("Outputs:", state)
|
903 |
+
return state, state
|
904 |
+
|
905 |
+
def run_image(self, image, state, txt):
|
906 |
+
print("===============Running run_image =============")
|
907 |
+
print("Inputs:", image, state)
|
908 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
909 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
910 |
+
print("======>Auto Resize Image...")
|
911 |
+
img = Image.open(image.name)
|
912 |
+
width, height = img.size
|
913 |
+
ratio = min(512 / width, 512 / height)
|
914 |
+
width_new, height_new = (round(width * ratio), round(height * ratio))
|
915 |
+
img = img.resize((width_new, height_new))
|
916 |
+
img = img.convert('RGB')
|
917 |
+
img.save(image_filename, "PNG")
|
918 |
+
print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
|
919 |
+
description = self.i2t.inference(image_filename)
|
920 |
+
Human_prompt = "\nHuman: provide a figure named {}. The description is: {}. This information helps you to understand this image, but you should use tools to finish following tasks, " \
|
921 |
+
"rather than directly imagine from my description. If you understand, say \"Received\". \n".format(image_filename, description)
|
922 |
+
AI_prompt = "Received. "
|
923 |
+
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
|
924 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
925 |
+
state = state + [(f"![](/file={image_filename})*{image_filename}*", AI_prompt)]
|
926 |
+
print("Outputs:", state)
|
927 |
+
return state, state, txt + ' ' + image_filename + ' '
|
928 |
+
|
929 |
+
bot = ConversationBot()
|
930 |
+
with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
|
931 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
|
932 |
+
state = gr.State([])
|
933 |
+
|
934 |
+
with gr.Row():
|
935 |
+
with gr.Column(scale=0.7):
|
936 |
+
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)
|
937 |
+
with gr.Column(scale=0.15, min_width=0):
|
938 |
+
clear = gr.Button("Clear️")
|
939 |
+
with gr.Column(scale=0.15, min_width=0):
|
940 |
+
btn = gr.UploadButton("Upload", file_types=["image"])
|
941 |
+
|
942 |
+
txt.submit(bot.run_text, [txt, state], [chatbot, state])
|
943 |
+
txt.submit(lambda: "", None, txt)
|
944 |
+
|
945 |
+
btn.upload(bot.run_image, [btn, state, txt], [chatbot, state, txt])
|
946 |
+
|
947 |
+
clear.click(bot.memory.clear)
|
948 |
+
clear.click(lambda: [], None, chatbot)
|
949 |
+
clear.click(lambda: [], None, state)
|
950 |
+
|
951 |
+
|
952 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|