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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding: utf-8
|
2 |
+
import os
|
3 |
+
import gradio as gr
|
4 |
+
import random
|
5 |
+
import torch
|
6 |
+
import cv2
|
7 |
+
import re
|
8 |
+
import uuid
|
9 |
+
from PIL import Image, ImageDraw, ImageOps, ImageFont
|
10 |
+
import math
|
11 |
+
import numpy as np
|
12 |
+
import argparse
|
13 |
+
import inspect
|
14 |
+
import tempfile
|
15 |
+
from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
|
16 |
+
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
|
17 |
+
from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
|
18 |
+
|
19 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline
|
20 |
+
from diffusers import EulerAncestralDiscreteScheduler
|
21 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
|
22 |
+
from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector
|
23 |
+
|
24 |
+
from langchain.agents.initialize import initialize_agent
|
25 |
+
from langchain.agents.tools import Tool
|
26 |
+
from langchain.chains.conversation.memory import ConversationBufferMemory
|
27 |
+
from langchain.llms.openai import OpenAI
|
28 |
+
|
29 |
+
# Grounding DINO
|
30 |
+
import groundingdino.datasets.transforms as T
|
31 |
+
from groundingdino.models import build_model
|
32 |
+
from groundingdino.util import box_ops
|
33 |
+
from groundingdino.util.slconfig import SLConfig
|
34 |
+
from groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
|
35 |
+
|
36 |
+
# segment anything
|
37 |
+
from segment_anything import build_sam, SamPredictor, SamAutomaticMaskGenerator
|
38 |
+
import cv2
|
39 |
+
import numpy as np
|
40 |
+
import matplotlib.pyplot as plt
|
41 |
+
import wget
|
42 |
+
|
43 |
+
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.
|
44 |
+
|
45 |
+
Visual ChatGPT is able to process and understand large amounts of text and images. 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 the 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.
|
46 |
+
|
47 |
+
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.
|
48 |
+
|
49 |
+
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.
|
50 |
+
|
51 |
+
|
52 |
+
TOOLS:
|
53 |
+
------
|
54 |
+
|
55 |
+
Visual ChatGPT has access to the following tools:"""
|
56 |
+
|
57 |
+
VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
|
58 |
+
|
59 |
+
```
|
60 |
+
Thought: Do I need to use a tool? Yes
|
61 |
+
Action: the action to take, should be one of [{tool_names}]
|
62 |
+
Action Input: the input to the action
|
63 |
+
Observation: the result of the action
|
64 |
+
```
|
65 |
+
|
66 |
+
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:
|
67 |
+
|
68 |
+
```
|
69 |
+
Thought: Do I need to use a tool? No
|
70 |
+
{ai_prefix}: [your response here]
|
71 |
+
```
|
72 |
+
"""
|
73 |
+
|
74 |
+
VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if it does not exist.
|
75 |
+
You will remember to provide the image file name loyally if it's provided in the last tool observation.
|
76 |
+
|
77 |
+
Begin!
|
78 |
+
|
79 |
+
Previous conversation history:
|
80 |
+
{chat_history}
|
81 |
+
|
82 |
+
New input: {input}
|
83 |
+
Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
|
84 |
+
The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human.
|
85 |
+
Thought: Do I need to use a tool? {agent_scratchpad} Let's think step by step.
|
86 |
+
"""
|
87 |
+
|
88 |
+
VISUAL_CHATGPT_PREFIX_CN = """Visual ChatGPT 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 Visual ChatGPT 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。
|
89 |
+
|
90 |
+
Visual ChatGPT 能够处理和理解大量文本和图像。作为一种语言模型,Visual ChatGPT 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,Visual ChatGPT可以调用不同的工具来间接理解图片。在谈论图片时,Visual ChatGPT 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,Visual ChatGPT也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 Visual ChatGPT 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。
|
91 |
+
|
92 |
+
Human 可能会向 Visual ChatGPT 提供带有描述的新图形。描述帮助 Visual ChatGPT 理解这个图像,但 Visual ChatGPT 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。
|
93 |
+
|
94 |
+
总的来说,Visual ChatGPT 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。
|
95 |
+
|
96 |
+
工具列表:
|
97 |
+
------
|
98 |
+
|
99 |
+
Visual ChatGPT 可以使用这些工具:"""
|
100 |
+
|
101 |
+
VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN = """用户使用中文和你进行聊天,但是工具的参数应当使用英文。如果要调用工具,你必须遵循如下格式:
|
102 |
+
|
103 |
+
```
|
104 |
+
Thought: Do I need to use a tool? Yes
|
105 |
+
Action: the action to take, should be one of [{tool_names}]
|
106 |
+
Action Input: the input to the action
|
107 |
+
Observation: the result of the action
|
108 |
+
```
|
109 |
+
|
110 |
+
当你不再需要继续调用工具,而是对观察结果进行总结回复时,你必须使用如下格式:
|
111 |
+
|
112 |
+
|
113 |
+
```
|
114 |
+
Thought: Do I need to use a tool? No
|
115 |
+
{ai_prefix}: [your response here]
|
116 |
+
```
|
117 |
+
"""
|
118 |
+
|
119 |
+
VISUAL_CHATGPT_SUFFIX_CN = """你对文件名的正确性非常严格,而且永远不会伪造不存在的文件。
|
120 |
+
|
121 |
+
开始!
|
122 |
+
|
123 |
+
因为Visual ChatGPT是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。
|
124 |
+
推理想法和观察结果只对Visual ChatGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。
|
125 |
+
|
126 |
+
聊天历史:
|
127 |
+
{chat_history}
|
128 |
+
|
129 |
+
新输入: {input}
|
130 |
+
Thought: Do I need to use a tool? {agent_scratchpad}
|
131 |
+
"""
|
132 |
+
|
133 |
+
os.makedirs('image', exist_ok=True)
|
134 |
+
|
135 |
+
|
136 |
+
def seed_everything(seed):
|
137 |
+
random.seed(seed)
|
138 |
+
np.random.seed(seed)
|
139 |
+
torch.manual_seed(seed)
|
140 |
+
torch.cuda.manual_seed_all(seed)
|
141 |
+
return seed
|
142 |
+
|
143 |
+
|
144 |
+
def prompts(name, description):
|
145 |
+
def decorator(func):
|
146 |
+
func.name = name
|
147 |
+
func.description = description
|
148 |
+
return func
|
149 |
+
|
150 |
+
return decorator
|
151 |
+
|
152 |
+
|
153 |
+
def blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):
|
154 |
+
new_size = new_image.size
|
155 |
+
old_size = old_image.size
|
156 |
+
easy_img = np.array(new_image)
|
157 |
+
gt_img_array = np.array(old_image)
|
158 |
+
pos_w = (new_size[0] - old_size[0]) // 2
|
159 |
+
pos_h = (new_size[1] - old_size[1]) // 2
|
160 |
+
|
161 |
+
kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)
|
162 |
+
kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)
|
163 |
+
kernel = np.multiply(kernel_h, np.transpose(kernel_w))
|
164 |
+
|
165 |
+
kernel[steps:-steps, steps:-steps] = 1
|
166 |
+
kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]
|
167 |
+
kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]
|
168 |
+
kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]
|
169 |
+
kernel[-steps:, -steps:] = kernel[-steps:, -steps:] / kernel[-steps, -steps]
|
170 |
+
kernel = np.expand_dims(kernel, 2)
|
171 |
+
kernel = np.repeat(kernel, 3, 2)
|
172 |
+
|
173 |
+
weight = np.linspace(0, 1, steps)
|
174 |
+
top = np.expand_dims(weight, 1)
|
175 |
+
top = np.repeat(top, old_size[0] - 2 * steps, 1)
|
176 |
+
top = np.expand_dims(top, 2)
|
177 |
+
top = np.repeat(top, 3, 2)
|
178 |
+
|
179 |
+
weight = np.linspace(1, 0, steps)
|
180 |
+
down = np.expand_dims(weight, 1)
|
181 |
+
down = np.repeat(down, old_size[0] - 2 * steps, 1)
|
182 |
+
down = np.expand_dims(down, 2)
|
183 |
+
down = np.repeat(down, 3, 2)
|
184 |
+
|
185 |
+
weight = np.linspace(0, 1, steps)
|
186 |
+
left = np.expand_dims(weight, 0)
|
187 |
+
left = np.repeat(left, old_size[1] - 2 * steps, 0)
|
188 |
+
left = np.expand_dims(left, 2)
|
189 |
+
left = np.repeat(left, 3, 2)
|
190 |
+
|
191 |
+
weight = np.linspace(1, 0, steps)
|
192 |
+
right = np.expand_dims(weight, 0)
|
193 |
+
right = np.repeat(right, old_size[1] - 2 * steps, 0)
|
194 |
+
right = np.expand_dims(right, 2)
|
195 |
+
right = np.repeat(right, 3, 2)
|
196 |
+
|
197 |
+
kernel[:steps, steps:-steps] = top
|
198 |
+
kernel[-steps:, steps:-steps] = down
|
199 |
+
kernel[steps:-steps, :steps] = left
|
200 |
+
kernel[steps:-steps, -steps:] = right
|
201 |
+
|
202 |
+
pt_gt_img = easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]]
|
203 |
+
gaussian_gt_img = kernel * gt_img_array + (1 - kernel) * pt_gt_img # gt img with blur img
|
204 |
+
gaussian_gt_img = gaussian_gt_img.astype(np.int64)
|
205 |
+
easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]] = gaussian_gt_img
|
206 |
+
gaussian_img = Image.fromarray(easy_img)
|
207 |
+
return gaussian_img
|
208 |
+
|
209 |
+
|
210 |
+
def cut_dialogue_history(history_memory, keep_last_n_words=500):
|
211 |
+
if history_memory is None or len(history_memory) == 0:
|
212 |
+
return history_memory
|
213 |
+
tokens = history_memory.split()
|
214 |
+
n_tokens = len(tokens)
|
215 |
+
print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")
|
216 |
+
if n_tokens < keep_last_n_words:
|
217 |
+
return history_memory
|
218 |
+
paragraphs = history_memory.split('\n')
|
219 |
+
last_n_tokens = n_tokens
|
220 |
+
while last_n_tokens >= keep_last_n_words:
|
221 |
+
last_n_tokens -= len(paragraphs[0].split(' '))
|
222 |
+
paragraphs = paragraphs[1:]
|
223 |
+
return '\n' + '\n'.join(paragraphs)
|
224 |
+
|
225 |
+
|
226 |
+
def get_new_image_name(org_img_name, func_name="update"):
|
227 |
+
head_tail = os.path.split(org_img_name)
|
228 |
+
head = head_tail[0]
|
229 |
+
tail = head_tail[1]
|
230 |
+
name_split = tail.split('.')[0].split('_')
|
231 |
+
this_new_uuid = str(uuid.uuid4())[:4]
|
232 |
+
if len(name_split) == 1:
|
233 |
+
most_org_file_name = name_split[0]
|
234 |
+
else:
|
235 |
+
assert len(name_split) == 4
|
236 |
+
most_org_file_name = name_split[3]
|
237 |
+
recent_prev_file_name = name_split[0]
|
238 |
+
new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'
|
239 |
+
return os.path.join(head, new_file_name)
|
240 |
+
|
241 |
+
class InstructPix2Pix:
|
242 |
+
def __init__(self, device):
|
243 |
+
print(f"Initializing InstructPix2Pix to {device}")
|
244 |
+
self.device = device
|
245 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
246 |
+
self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix",
|
247 |
+
safety_checker=None,
|
248 |
+
torch_dtype=self.torch_dtype).to(device)
|
249 |
+
self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
|
250 |
+
|
251 |
+
@prompts(name="Instruct Image Using Text",
|
252 |
+
description="useful when you want to the style of the image to be like the text. "
|
253 |
+
"like: make it look like a painting. or make it like a robot. "
|
254 |
+
"The input to this tool should be a comma separated string of two, "
|
255 |
+
"representing the image_path and the text. ")
|
256 |
+
def inference(self, inputs):
|
257 |
+
"""Change style of image."""
|
258 |
+
print("===>Starting InstructPix2Pix Inference")
|
259 |
+
image_path, text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
260 |
+
original_image = Image.open(image_path)
|
261 |
+
image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]
|
262 |
+
updated_image_path = get_new_image_name(image_path, func_name="pix2pix")
|
263 |
+
image.save(updated_image_path)
|
264 |
+
print(f"\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, "
|
265 |
+
f"Output Image: {updated_image_path}")
|
266 |
+
return updated_image_path
|
267 |
+
|
268 |
+
|
269 |
+
class Text2Image:
|
270 |
+
def __init__(self, device):
|
271 |
+
print(f"Initializing Text2Image to {device}")
|
272 |
+
self.device = device
|
273 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
274 |
+
self.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",
|
275 |
+
torch_dtype=self.torch_dtype)
|
276 |
+
self.pipe.to(device)
|
277 |
+
self.a_prompt = 'best quality, extremely detailed'
|
278 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
|
279 |
+
'fewer digits, cropped, worst quality, low quality'
|
280 |
+
|
281 |
+
@prompts(name="Generate Image From User Input Text",
|
282 |
+
description="useful when you want to generate an image from a user input text and save it to a file. "
|
283 |
+
"like: generate an image of an object or something, or generate an image that includes some objects. "
|
284 |
+
"The input to this tool should be a string, representing the text used to generate image. ")
|
285 |
+
def inference(self, text):
|
286 |
+
image_filename = os.path.join('image', f"{str(uuid.uuid4())[:8]}.png")
|
287 |
+
prompt = text + ', ' + self.a_prompt
|
288 |
+
image = self.pipe(prompt, negative_prompt=self.n_prompt).images[0]
|
289 |
+
image.save(image_filename)
|
290 |
+
print(
|
291 |
+
f"\nProcessed Text2Image, Input Text: {text}, Output Image: {image_filename}")
|
292 |
+
return image_filename
|
293 |
+
|
294 |
+
|
295 |
+
class ImageCaptioning:
|
296 |
+
def __init__(self, device):
|
297 |
+
print(f"Initializing ImageCaptioning to {device}")
|
298 |
+
self.device = device
|
299 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
300 |
+
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
301 |
+
self.model = BlipForConditionalGeneration.from_pretrained(
|
302 |
+
"Salesforce/blip-image-captioning-base", torch_dtype=self.torch_dtype).to(self.device)
|
303 |
+
|
304 |
+
@prompts(name="Get Photo Description",
|
305 |
+
description="useful when you want to know what is inside the photo. receives image_path as input. "
|
306 |
+
"The input to this tool should be a string, representing the image_path. ")
|
307 |
+
def inference(self, image_path):
|
308 |
+
inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device, self.torch_dtype)
|
309 |
+
out = self.model.generate(**inputs)
|
310 |
+
captions = self.processor.decode(out[0], skip_special_tokens=True)
|
311 |
+
print(f"\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}")
|
312 |
+
return captions
|
313 |
+
|
314 |
+
|
315 |
+
class Image2Canny:
|
316 |
+
def __init__(self, device):
|
317 |
+
print("Initializing Image2Canny")
|
318 |
+
self.low_threshold = 100
|
319 |
+
self.high_threshold = 200
|
320 |
+
|
321 |
+
@prompts(name="Edge Detection On Image",
|
322 |
+
description="useful when you want to detect the edge of the image. "
|
323 |
+
"like: detect the edges of this image, or canny detection on image, "
|
324 |
+
"or perform edge detection on this image, or detect the canny image of this image. "
|
325 |
+
"The input to this tool should be a string, representing the image_path")
|
326 |
+
def inference(self, inputs):
|
327 |
+
image = Image.open(inputs)
|
328 |
+
image = np.array(image)
|
329 |
+
canny = cv2.Canny(image, self.low_threshold, self.high_threshold)
|
330 |
+
canny = canny[:, :, None]
|
331 |
+
canny = np.concatenate([canny, canny, canny], axis=2)
|
332 |
+
canny = Image.fromarray(canny)
|
333 |
+
updated_image_path = get_new_image_name(inputs, func_name="edge")
|
334 |
+
canny.save(updated_image_path)
|
335 |
+
print(f"\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}")
|
336 |
+
return updated_image_path
|
337 |
+
|
338 |
+
|
339 |
+
class CannyText2Image:
|
340 |
+
def __init__(self, device):
|
341 |
+
print(f"Initializing CannyText2Image to {device}")
|
342 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
343 |
+
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-canny",
|
344 |
+
torch_dtype=self.torch_dtype)
|
345 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
346 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
347 |
+
torch_dtype=self.torch_dtype)
|
348 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
349 |
+
self.pipe.to(device)
|
350 |
+
self.seed = -1
|
351 |
+
self.a_prompt = 'best quality, extremely detailed'
|
352 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
|
353 |
+
'fewer digits, cropped, worst quality, low quality'
|
354 |
+
|
355 |
+
@prompts(name="Generate Image Condition On Canny Image",
|
356 |
+
description="useful when you want to generate a new real image from both the user description and a canny image."
|
357 |
+
" like: generate a real image of a object or something from this canny image,"
|
358 |
+
" or generate a new real image of a object or something from this edge image. "
|
359 |
+
"The input to this tool should be a comma separated string of two, "
|
360 |
+
"representing the image_path and the user description. ")
|
361 |
+
def inference(self, inputs):
|
362 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
363 |
+
image = Image.open(image_path)
|
364 |
+
self.seed = random.randint(0, 65535)
|
365 |
+
seed_everything(self.seed)
|
366 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
367 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
368 |
+
guidance_scale=9.0).images[0]
|
369 |
+
updated_image_path = get_new_image_name(image_path, func_name="canny2image")
|
370 |
+
image.save(updated_image_path)
|
371 |
+
print(f"\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, "
|
372 |
+
f"Output Text: {updated_image_path}")
|
373 |
+
return updated_image_path
|
374 |
+
|
375 |
+
|
376 |
+
class Image2Line:
|
377 |
+
def __init__(self, device):
|
378 |
+
print("Initializing Image2Line")
|
379 |
+
self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')
|
380 |
+
|
381 |
+
@prompts(name="Line Detection On Image",
|
382 |
+
description="useful when you want to detect the straight line of the image. "
|
383 |
+
"like: detect the straight lines of this image, or straight line detection on image, "
|
384 |
+
"or perform straight line detection on this image, or detect the straight line image of this image. "
|
385 |
+
"The input to this tool should be a string, representing the image_path")
|
386 |
+
def inference(self, inputs):
|
387 |
+
image = Image.open(inputs)
|
388 |
+
mlsd = self.detector(image)
|
389 |
+
updated_image_path = get_new_image_name(inputs, func_name="line-of")
|
390 |
+
mlsd.save(updated_image_path)
|
391 |
+
print(f"\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}")
|
392 |
+
return updated_image_path
|
393 |
+
|
394 |
+
|
395 |
+
class LineText2Image:
|
396 |
+
def __init__(self, device):
|
397 |
+
print(f"Initializing LineText2Image to {device}")
|
398 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
399 |
+
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-mlsd",
|
400 |
+
torch_dtype=self.torch_dtype)
|
401 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
402 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
403 |
+
torch_dtype=self.torch_dtype
|
404 |
+
)
|
405 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
406 |
+
self.pipe.to(device)
|
407 |
+
self.seed = -1
|
408 |
+
self.a_prompt = 'best quality, extremely detailed'
|
409 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
|
410 |
+
'fewer digits, cropped, worst quality, low quality'
|
411 |
+
|
412 |
+
@prompts(name="Generate Image Condition On Line Image",
|
413 |
+
description="useful when you want to generate a new real image from both the user description "
|
414 |
+
"and a straight line image. "
|
415 |
+
"like: generate a real image of a object or something from this straight line image, "
|
416 |
+
"or generate a new real image of a object or something from this straight lines. "
|
417 |
+
"The input to this tool should be a comma separated string of two, "
|
418 |
+
"representing the image_path and the user description. ")
|
419 |
+
def inference(self, inputs):
|
420 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
421 |
+
image = Image.open(image_path)
|
422 |
+
self.seed = random.randint(0, 65535)
|
423 |
+
seed_everything(self.seed)
|
424 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
425 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
426 |
+
guidance_scale=9.0).images[0]
|
427 |
+
updated_image_path = get_new_image_name(image_path, func_name="line2image")
|
428 |
+
image.save(updated_image_path)
|
429 |
+
print(f"\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, "
|
430 |
+
f"Output Text: {updated_image_path}")
|
431 |
+
return updated_image_path
|
432 |
+
|
433 |
+
|
434 |
+
class Image2Hed:
|
435 |
+
def __init__(self, device):
|
436 |
+
print("Initializing Image2Hed")
|
437 |
+
self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
|
438 |
+
|
439 |
+
@prompts(name="Hed Detection On Image",
|
440 |
+
description="useful when you want to detect the soft hed boundary of the image. "
|
441 |
+
"like: detect the soft hed boundary of this image, or hed boundary detection on image, "
|
442 |
+
"or perform hed boundary detection on this image, or detect soft hed boundary image of this image. "
|
443 |
+
"The input to this tool should be a string, representing the image_path")
|
444 |
+
def inference(self, inputs):
|
445 |
+
image = Image.open(inputs)
|
446 |
+
hed = self.detector(image)
|
447 |
+
updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")
|
448 |
+
hed.save(updated_image_path)
|
449 |
+
print(f"\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}")
|
450 |
+
return updated_image_path
|
451 |
+
|
452 |
+
|
453 |
+
class HedText2Image:
|
454 |
+
def __init__(self, device):
|
455 |
+
print(f"Initializing HedText2Image to {device}")
|
456 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
457 |
+
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-hed",
|
458 |
+
torch_dtype=self.torch_dtype)
|
459 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
460 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
461 |
+
torch_dtype=self.torch_dtype
|
462 |
+
)
|
463 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
464 |
+
self.pipe.to(device)
|
465 |
+
self.seed = -1
|
466 |
+
self.a_prompt = 'best quality, extremely detailed'
|
467 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
|
468 |
+
'fewer digits, cropped, worst quality, low quality'
|
469 |
+
|
470 |
+
@prompts(name="Generate Image Condition On Soft Hed Boundary Image",
|
471 |
+
description="useful when you want to generate a new real image from both the user description "
|
472 |
+
"and a soft hed boundary image. "
|
473 |
+
"like: generate a real image of a object or something from this soft hed boundary image, "
|
474 |
+
"or generate a new real image of a object or something from this hed boundary. "
|
475 |
+
"The input to this tool should be a comma separated string of two, "
|
476 |
+
"representing the image_path and the user description")
|
477 |
+
def inference(self, inputs):
|
478 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
479 |
+
image = Image.open(image_path)
|
480 |
+
self.seed = random.randint(0, 65535)
|
481 |
+
seed_everything(self.seed)
|
482 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
483 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
484 |
+
guidance_scale=9.0).images[0]
|
485 |
+
updated_image_path = get_new_image_name(image_path, func_name="hed2image")
|
486 |
+
image.save(updated_image_path)
|
487 |
+
print(f"\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, "
|
488 |
+
f"Output Image: {updated_image_path}")
|
489 |
+
return updated_image_path
|
490 |
+
|
491 |
+
|
492 |
+
class Image2Scribble:
|
493 |
+
def __init__(self, device):
|
494 |
+
print("Initializing Image2Scribble")
|
495 |
+
self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
|
496 |
+
|
497 |
+
@prompts(name="Sketch Detection On Image",
|
498 |
+
description="useful when you want to generate a scribble of the image. "
|
499 |
+
"like: generate a scribble of this image, or generate a sketch from this image, "
|
500 |
+
"detect the sketch from this image. "
|
501 |
+
"The input to this tool should be a string, representing the image_path")
|
502 |
+
def inference(self, inputs):
|
503 |
+
image = Image.open(inputs)
|
504 |
+
scribble = self.detector(image, scribble=True)
|
505 |
+
updated_image_path = get_new_image_name(inputs, func_name="scribble")
|
506 |
+
scribble.save(updated_image_path)
|
507 |
+
print(f"\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}")
|
508 |
+
return updated_image_path
|
509 |
+
|
510 |
+
|
511 |
+
class ScribbleText2Image:
|
512 |
+
def __init__(self, device):
|
513 |
+
print(f"Initializing ScribbleText2Image to {device}")
|
514 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
515 |
+
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-scribble",
|
516 |
+
torch_dtype=self.torch_dtype)
|
517 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
518 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
519 |
+
torch_dtype=self.torch_dtype
|
520 |
+
)
|
521 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
522 |
+
self.pipe.to(device)
|
523 |
+
self.seed = -1
|
524 |
+
self.a_prompt = 'best quality, extremely detailed'
|
525 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
|
526 |
+
'fewer digits, cropped, worst quality, low quality'
|
527 |
+
|
528 |
+
@prompts(name="Generate Image Condition On Sketch Image",
|
529 |
+
description="useful when you want to generate a new real image from both the user description and "
|
530 |
+
"a scribble image or a sketch image. "
|
531 |
+
"The input to this tool should be a comma separated string of two, "
|
532 |
+
"representing the image_path and the user description")
|
533 |
+
def inference(self, inputs):
|
534 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
535 |
+
image = Image.open(image_path)
|
536 |
+
self.seed = random.randint(0, 65535)
|
537 |
+
seed_everything(self.seed)
|
538 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
539 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
540 |
+
guidance_scale=9.0).images[0]
|
541 |
+
updated_image_path = get_new_image_name(image_path, func_name="scribble2image")
|
542 |
+
image.save(updated_image_path)
|
543 |
+
print(f"\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, "
|
544 |
+
f"Output Image: {updated_image_path}")
|
545 |
+
return updated_image_path
|
546 |
+
|
547 |
+
|
548 |
+
class Image2Pose:
|
549 |
+
def __init__(self, device):
|
550 |
+
print("Initializing Image2Pose")
|
551 |
+
self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')
|
552 |
+
|
553 |
+
@prompts(name="Pose Detection On Image",
|
554 |
+
description="useful when you want to detect the human pose of the image. "
|
555 |
+
"like: generate human poses of this image, or generate a pose image from this image. "
|
556 |
+
"The input to this tool should be a string, representing the image_path")
|
557 |
+
def inference(self, inputs):
|
558 |
+
image = Image.open(inputs)
|
559 |
+
pose = self.detector(image)
|
560 |
+
updated_image_path = get_new_image_name(inputs, func_name="human-pose")
|
561 |
+
pose.save(updated_image_path)
|
562 |
+
print(f"\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}")
|
563 |
+
return updated_image_path
|
564 |
+
|
565 |
+
|
566 |
+
class PoseText2Image:
|
567 |
+
def __init__(self, device):
|
568 |
+
print(f"Initializing PoseText2Image to {device}")
|
569 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
570 |
+
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose",
|
571 |
+
torch_dtype=self.torch_dtype)
|
572 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
573 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
574 |
+
torch_dtype=self.torch_dtype)
|
575 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
576 |
+
self.pipe.to(device)
|
577 |
+
self.num_inference_steps = 20
|
578 |
+
self.seed = -1
|
579 |
+
self.unconditional_guidance_scale = 9.0
|
580 |
+
self.a_prompt = 'best quality, extremely detailed'
|
581 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
|
582 |
+
' fewer digits, cropped, worst quality, low quality'
|
583 |
+
|
584 |
+
@prompts(name="Generate Image Condition On Pose Image",
|
585 |
+
description="useful when you want to generate a new real image from both the user description "
|
586 |
+
"and a human pose image. "
|
587 |
+
"like: generate a real image of a human from this human pose image, "
|
588 |
+
"or generate a new real image of a human from this pose. "
|
589 |
+
"The input to this tool should be a comma separated string of two, "
|
590 |
+
"representing the image_path and the user description")
|
591 |
+
def inference(self, inputs):
|
592 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
593 |
+
image = Image.open(image_path)
|
594 |
+
self.seed = random.randint(0, 65535)
|
595 |
+
seed_everything(self.seed)
|
596 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
597 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
598 |
+
guidance_scale=9.0).images[0]
|
599 |
+
updated_image_path = get_new_image_name(image_path, func_name="pose2image")
|
600 |
+
image.save(updated_image_path)
|
601 |
+
print(f"\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, "
|
602 |
+
f"Output Image: {updated_image_path}")
|
603 |
+
return updated_image_path
|
604 |
+
|
605 |
+
class SegText2Image:
|
606 |
+
def __init__(self, device):
|
607 |
+
print(f"Initializing SegText2Image to {device}")
|
608 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
609 |
+
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-seg",
|
610 |
+
torch_dtype=self.torch_dtype)
|
611 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
612 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
613 |
+
torch_dtype=self.torch_dtype)
|
614 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
615 |
+
self.pipe.to(device)
|
616 |
+
self.seed = -1
|
617 |
+
self.a_prompt = 'best quality, extremely detailed'
|
618 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
|
619 |
+
' fewer digits, cropped, worst quality, low quality'
|
620 |
+
|
621 |
+
@prompts(name="Generate Image Condition On Segmentations",
|
622 |
+
description="useful when you want to generate a new real image from both the user description and segmentations. "
|
623 |
+
"like: generate a real image of a object or something from this segmentation image, "
|
624 |
+
"or generate a new real image of a object or something from these segmentations. "
|
625 |
+
"The input to this tool should be a comma separated string of two, "
|
626 |
+
"representing the image_path and the user description")
|
627 |
+
def inference(self, inputs):
|
628 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
629 |
+
image = Image.open(image_path)
|
630 |
+
self.seed = random.randint(0, 65535)
|
631 |
+
seed_everything(self.seed)
|
632 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
633 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
634 |
+
guidance_scale=9.0).images[0]
|
635 |
+
updated_image_path = get_new_image_name(image_path, func_name="segment2image")
|
636 |
+
image.save(updated_image_path)
|
637 |
+
print(f"\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, "
|
638 |
+
f"Output Image: {updated_image_path}")
|
639 |
+
return updated_image_path
|
640 |
+
|
641 |
+
|
642 |
+
class Image2Depth:
|
643 |
+
def __init__(self, device):
|
644 |
+
print("Initializing Image2Depth")
|
645 |
+
self.depth_estimator = pipeline('depth-estimation')
|
646 |
+
|
647 |
+
@prompts(name="Predict Depth On Image",
|
648 |
+
description="useful when you want to detect depth of the image. like: generate the depth from this image, "
|
649 |
+
"or detect the depth map on this image, or predict the depth for this image. "
|
650 |
+
"The input to this tool should be a string, representing the image_path")
|
651 |
+
def inference(self, inputs):
|
652 |
+
image = Image.open(inputs)
|
653 |
+
depth = self.depth_estimator(image)['depth']
|
654 |
+
depth = np.array(depth)
|
655 |
+
depth = depth[:, :, None]
|
656 |
+
depth = np.concatenate([depth, depth, depth], axis=2)
|
657 |
+
depth = Image.fromarray(depth)
|
658 |
+
updated_image_path = get_new_image_name(inputs, func_name="depth")
|
659 |
+
depth.save(updated_image_path)
|
660 |
+
print(f"\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}")
|
661 |
+
return updated_image_path
|
662 |
+
|
663 |
+
|
664 |
+
class DepthText2Image:
|
665 |
+
def __init__(self, device):
|
666 |
+
print(f"Initializing DepthText2Image to {device}")
|
667 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
668 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
669 |
+
"fusing/stable-diffusion-v1-5-controlnet-depth", torch_dtype=self.torch_dtype)
|
670 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
671 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
672 |
+
torch_dtype=self.torch_dtype)
|
673 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
674 |
+
self.pipe.to(device)
|
675 |
+
self.seed = -1
|
676 |
+
self.a_prompt = 'best quality, extremely detailed'
|
677 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
|
678 |
+
' fewer digits, cropped, worst quality, low quality'
|
679 |
+
|
680 |
+
@prompts(name="Generate Image Condition On Depth",
|
681 |
+
description="useful when you want to generate a new real image from both the user description and depth image. "
|
682 |
+
"like: generate a real image of a object or something from this depth image, "
|
683 |
+
"or generate a new real image of a object or something from the depth map. "
|
684 |
+
"The input to this tool should be a comma separated string of two, "
|
685 |
+
"representing the image_path and the user description")
|
686 |
+
def inference(self, inputs):
|
687 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
688 |
+
image = Image.open(image_path)
|
689 |
+
self.seed = random.randint(0, 65535)
|
690 |
+
seed_everything(self.seed)
|
691 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
692 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
693 |
+
guidance_scale=9.0).images[0]
|
694 |
+
updated_image_path = get_new_image_name(image_path, func_name="depth2image")
|
695 |
+
image.save(updated_image_path)
|
696 |
+
print(f"\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, "
|
697 |
+
f"Output Image: {updated_image_path}")
|
698 |
+
return updated_image_path
|
699 |
+
|
700 |
+
|
701 |
+
class Image2Normal:
|
702 |
+
def __init__(self, device):
|
703 |
+
print("Initializing Image2Normal")
|
704 |
+
self.depth_estimator = pipeline("depth-estimation", model="Intel/dpt-hybrid-midas")
|
705 |
+
self.bg_threhold = 0.4
|
706 |
+
|
707 |
+
@prompts(name="Predict Normal Map On Image",
|
708 |
+
description="useful when you want to detect norm map of the image. "
|
709 |
+
"like: generate normal map from this image, or predict normal map of this image. "
|
710 |
+
"The input to this tool should be a string, representing the image_path")
|
711 |
+
def inference(self, inputs):
|
712 |
+
image = Image.open(inputs)
|
713 |
+
original_size = image.size
|
714 |
+
image = self.depth_estimator(image)['predicted_depth'][0]
|
715 |
+
image = image.numpy()
|
716 |
+
image_depth = image.copy()
|
717 |
+
image_depth -= np.min(image_depth)
|
718 |
+
image_depth /= np.max(image_depth)
|
719 |
+
x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)
|
720 |
+
x[image_depth < self.bg_threhold] = 0
|
721 |
+
y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)
|
722 |
+
y[image_depth < self.bg_threhold] = 0
|
723 |
+
z = np.ones_like(x) * np.pi * 2.0
|
724 |
+
image = np.stack([x, y, z], axis=2)
|
725 |
+
image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5
|
726 |
+
image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)
|
727 |
+
image = Image.fromarray(image)
|
728 |
+
image = image.resize(original_size)
|
729 |
+
updated_image_path = get_new_image_name(inputs, func_name="normal-map")
|
730 |
+
image.save(updated_image_path)
|
731 |
+
print(f"\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}")
|
732 |
+
return updated_image_path
|
733 |
+
|
734 |
+
|
735 |
+
class NormalText2Image:
|
736 |
+
def __init__(self, device):
|
737 |
+
print(f"Initializing NormalText2Image to {device}")
|
738 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
739 |
+
self.controlnet = ControlNetModel.from_pretrained(
|
740 |
+
"fusing/stable-diffusion-v1-5-controlnet-normal", torch_dtype=self.torch_dtype)
|
741 |
+
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
742 |
+
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None,
|
743 |
+
torch_dtype=self.torch_dtype)
|
744 |
+
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
|
745 |
+
self.pipe.to(device)
|
746 |
+
self.seed = -1
|
747 |
+
self.a_prompt = 'best quality, extremely detailed'
|
748 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
|
749 |
+
' fewer digits, cropped, worst quality, low quality'
|
750 |
+
|
751 |
+
@prompts(name="Generate Image Condition On Normal Map",
|
752 |
+
description="useful when you want to generate a new real image from both the user description and normal map. "
|
753 |
+
"like: generate a real image of a object or something from this normal map, "
|
754 |
+
"or generate a new real image of a object or something from the normal map. "
|
755 |
+
"The input to this tool should be a comma separated string of two, "
|
756 |
+
"representing the image_path and the user description")
|
757 |
+
def inference(self, inputs):
|
758 |
+
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
759 |
+
image = Image.open(image_path)
|
760 |
+
self.seed = random.randint(0, 65535)
|
761 |
+
seed_everything(self.seed)
|
762 |
+
prompt = f'{instruct_text}, {self.a_prompt}'
|
763 |
+
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
|
764 |
+
guidance_scale=9.0).images[0]
|
765 |
+
updated_image_path = get_new_image_name(image_path, func_name="normal2image")
|
766 |
+
image.save(updated_image_path)
|
767 |
+
print(f"\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, "
|
768 |
+
f"Output Image: {updated_image_path}")
|
769 |
+
return updated_image_path
|
770 |
+
|
771 |
+
|
772 |
+
class VisualQuestionAnswering:
|
773 |
+
def __init__(self, device):
|
774 |
+
print(f"Initializing VisualQuestionAnswering to {device}")
|
775 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
776 |
+
self.device = device
|
777 |
+
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
778 |
+
self.model = BlipForQuestionAnswering.from_pretrained(
|
779 |
+
"Salesforce/blip-vqa-base", torch_dtype=self.torch_dtype).to(self.device)
|
780 |
+
|
781 |
+
@prompts(name="Answer Question About The Image",
|
782 |
+
description="useful when you need an answer for a question based on an image. "
|
783 |
+
"like: what is the background color of the last image, how many cats in this figure, what is in this figure. "
|
784 |
+
"The input to this tool should be a comma separated string of two, representing the image_path and the question")
|
785 |
+
def inference(self, inputs):
|
786 |
+
image_path, question = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
787 |
+
raw_image = Image.open(image_path).convert('RGB')
|
788 |
+
inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device, self.torch_dtype)
|
789 |
+
out = self.model.generate(**inputs)
|
790 |
+
answer = self.processor.decode(out[0], skip_special_tokens=True)
|
791 |
+
print(f"\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, "
|
792 |
+
f"Output Answer: {answer}")
|
793 |
+
return answer
|
794 |
+
|
795 |
+
|
796 |
+
class Segmenting:
|
797 |
+
def __init__(self, device):
|
798 |
+
print(f"Inintializing Segmentation to {device}")
|
799 |
+
self.device = device
|
800 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
801 |
+
self.model_checkpoint_path = os.path.join("checkpoints","sam")
|
802 |
+
|
803 |
+
self.download_parameters()
|
804 |
+
self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)
|
805 |
+
self.sam_predictor = SamPredictor(self.sam)
|
806 |
+
self.mask_generator = SamAutomaticMaskGenerator(self.sam)
|
807 |
+
|
808 |
+
def download_parameters(self):
|
809 |
+
url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
|
810 |
+
if not os.path.exists(self.model_checkpoint_path):
|
811 |
+
wget.download(url,out=self.model_checkpoint_path)
|
812 |
+
|
813 |
+
def show_mask(self, mask, ax, random_color=False):
|
814 |
+
if random_color:
|
815 |
+
color = np.concatenate([np.random.random(3), np.array([1])], axis=0)
|
816 |
+
else:
|
817 |
+
color = np.array([30/255, 144/255, 255/255, 1])
|
818 |
+
h, w = mask.shape[-2:]
|
819 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
820 |
+
ax.imshow(mask_image)
|
821 |
+
|
822 |
+
def show_box(self, box, ax, label):
|
823 |
+
x0, y0 = box[0], box[1]
|
824 |
+
w, h = box[2] - box[0], box[3] - box[1]
|
825 |
+
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
|
826 |
+
ax.text(x0, y0, label)
|
827 |
+
|
828 |
+
|
829 |
+
def get_mask_with_boxes(self, image_pil, image, boxes_filt):
|
830 |
+
|
831 |
+
size = image_pil.size
|
832 |
+
H, W = size[1], size[0]
|
833 |
+
for i in range(boxes_filt.size(0)):
|
834 |
+
boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
|
835 |
+
boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
|
836 |
+
boxes_filt[i][2:] += boxes_filt[i][:2]
|
837 |
+
|
838 |
+
boxes_filt = boxes_filt.cpu()
|
839 |
+
transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)
|
840 |
+
|
841 |
+
masks, _, _ = self.sam_predictor.predict_torch(
|
842 |
+
point_coords = None,
|
843 |
+
point_labels = None,
|
844 |
+
boxes = transformed_boxes.to(self.device),
|
845 |
+
multimask_output = False,
|
846 |
+
)
|
847 |
+
return masks
|
848 |
+
|
849 |
+
def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):
|
850 |
+
|
851 |
+
image = cv2.imread(image_path)
|
852 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
853 |
+
self.sam_predictor.set_image(image)
|
854 |
+
|
855 |
+
masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)
|
856 |
+
|
857 |
+
# draw output image
|
858 |
+
plt.figure(figsize=(10, 10))
|
859 |
+
plt.imshow(image)
|
860 |
+
for mask in masks:
|
861 |
+
self.show_mask(mask.cpu().numpy(), plt.gca(), random_color=True)
|
862 |
+
|
863 |
+
updated_image_path = get_new_image_name(image_path, func_name="segmentation")
|
864 |
+
plt.axis('off')
|
865 |
+
plt.savefig(
|
866 |
+
updated_image_path,
|
867 |
+
bbox_inches="tight", dpi=300, pad_inches=0.0
|
868 |
+
)
|
869 |
+
return updated_image_path
|
870 |
+
|
871 |
+
|
872 |
+
@prompts(name="Segment the Image",
|
873 |
+
description="useful when you want to segment all the part of the image, but not segment a certain object."
|
874 |
+
"like: segment all the object in this image, or generate segmentations on this image, "
|
875 |
+
"or segment the image,"
|
876 |
+
"or perform segmentation on this image, "
|
877 |
+
"or segment all the object in this image."
|
878 |
+
"The input to this tool should be a string, representing the image_path")
|
879 |
+
def inference_all(self,image_path):
|
880 |
+
image = cv2.imread(image_path)
|
881 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
882 |
+
masks = self.mask_generator.generate(image)
|
883 |
+
plt.figure(figsize=(20,20))
|
884 |
+
plt.imshow(image)
|
885 |
+
if len(masks) == 0:
|
886 |
+
return
|
887 |
+
sorted_anns = sorted(masks, key=(lambda x: x['area']), reverse=True)
|
888 |
+
ax = plt.gca()
|
889 |
+
ax.set_autoscale_on(False)
|
890 |
+
polygons = []
|
891 |
+
color = []
|
892 |
+
for ann in sorted_anns:
|
893 |
+
m = ann['segmentation']
|
894 |
+
img = np.ones((m.shape[0], m.shape[1], 3))
|
895 |
+
color_mask = np.random.random((1, 3)).tolist()[0]
|
896 |
+
for i in range(3):
|
897 |
+
img[:,:,i] = color_mask[i]
|
898 |
+
ax.imshow(np.dstack((img, m)))
|
899 |
+
|
900 |
+
updated_image_path = get_new_image_name(image_path, func_name="segment-image")
|
901 |
+
plt.axis('off')
|
902 |
+
plt.savefig(
|
903 |
+
updated_image_path,
|
904 |
+
bbox_inches="tight", dpi=300, pad_inches=0.0
|
905 |
+
)
|
906 |
+
return updated_image_path
|
907 |
+
|
908 |
+
class Text2Box:
|
909 |
+
def __init__(self, device):
|
910 |
+
print(f"Initializing ObjectDetection to {device}")
|
911 |
+
self.device = device
|
912 |
+
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
|
913 |
+
self.model_checkpoint_path = os.path.join("checkpoints","groundingdino")
|
914 |
+
self.model_config_path = os.path.join("checkpoints","grounding_config.py")
|
915 |
+
self.download_parameters()
|
916 |
+
self.box_threshold = 0.3
|
917 |
+
self.text_threshold = 0.25
|
918 |
+
self.grounding = (self.load_model()).to(self.device)
|
919 |
+
|
920 |
+
def download_parameters(self):
|
921 |
+
url = "https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth"
|
922 |
+
if not os.path.exists(self.model_checkpoint_path):
|
923 |
+
wget.download(url,out=self.model_checkpoint_path)
|
924 |
+
config_url = "https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py"
|
925 |
+
if not os.path.exists(self.model_config_path):
|
926 |
+
wget.download(config_url,out=self.model_config_path)
|
927 |
+
def load_image(self,image_raw):
|
928 |
+
# load image
|
929 |
+
# image_pil = Image.open(image_path).convert("RGB") # load image
|
930 |
+
# import base64
|
931 |
+
# from io import BytesIO
|
932 |
+
# image_bytes=base64.b64decode(image_base64)
|
933 |
+
# image_pil=Image.open(BytesIO(image_bytes)).convert('RGB')
|
934 |
+
image_pil=image_raw
|
935 |
+
transform = T.Compose(
|
936 |
+
[
|
937 |
+
T.RandomResize([512], max_size=1333),
|
938 |
+
T.ToTensor(),
|
939 |
+
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
940 |
+
]
|
941 |
+
)
|
942 |
+
image, _ = transform(image_pil, None) # 3, h, w
|
943 |
+
return image_pil, image
|
944 |
+
|
945 |
+
def load_model(self):
|
946 |
+
args = SLConfig.fromfile(self.model_config_path)
|
947 |
+
args.device = self.device
|
948 |
+
model = build_model(args)
|
949 |
+
checkpoint = torch.load(self.model_checkpoint_path, map_location="cpu")
|
950 |
+
load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
|
951 |
+
print(load_res)
|
952 |
+
_ = model.eval()
|
953 |
+
return model
|
954 |
+
|
955 |
+
def get_grounding_boxes(self, image, caption, with_logits=True):
|
956 |
+
caption = caption.lower()
|
957 |
+
caption = caption.strip()
|
958 |
+
if not caption.endswith("."):
|
959 |
+
caption = caption + "."
|
960 |
+
image = image.to(self.device)
|
961 |
+
with torch.no_grad():
|
962 |
+
outputs = self.grounding(image[None], captions=[caption])
|
963 |
+
logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
|
964 |
+
boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
|
965 |
+
logits.shape[0]
|
966 |
+
|
967 |
+
# filter output
|
968 |
+
logits_filt = logits.clone()
|
969 |
+
boxes_filt = boxes.clone()
|
970 |
+
filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold
|
971 |
+
logits_filt = logits_filt[filt_mask] # num_filt, 256
|
972 |
+
boxes_filt = boxes_filt[filt_mask] # num_filt, 4
|
973 |
+
logits_filt.shape[0]
|
974 |
+
|
975 |
+
# get phrase
|
976 |
+
tokenlizer = self.grounding.tokenizer
|
977 |
+
tokenized = tokenlizer(caption)
|
978 |
+
# build pred
|
979 |
+
pred_phrases = []
|
980 |
+
for logit, box in zip(logits_filt, boxes_filt):
|
981 |
+
pred_phrase = get_phrases_from_posmap(logit > self.text_threshold, tokenized, tokenlizer)
|
982 |
+
if with_logits:
|
983 |
+
pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
|
984 |
+
else:
|
985 |
+
pred_phrases.append(pred_phrase)
|
986 |
+
|
987 |
+
return boxes_filt, pred_phrases
|
988 |
+
|
989 |
+
def plot_boxes_to_image(self, image_pil, tgt):
|
990 |
+
H, W = tgt["size"]
|
991 |
+
boxes = tgt["boxes"]
|
992 |
+
labels = tgt["labels"]
|
993 |
+
assert len(boxes) == len(labels), "boxes and labels must have same length"
|
994 |
+
|
995 |
+
draw = ImageDraw.Draw(image_pil)
|
996 |
+
mask = Image.new("L", image_pil.size, 0)
|
997 |
+
mask_draw = ImageDraw.Draw(mask)
|
998 |
+
|
999 |
+
# draw boxes and masks
|
1000 |
+
for box, label in zip(boxes, labels):
|
1001 |
+
# from 0..1 to 0..W, 0..H
|
1002 |
+
box = box * torch.Tensor([W, H, W, H])
|
1003 |
+
# from xywh to xyxy
|
1004 |
+
box[:2] -= box[2:] / 2
|
1005 |
+
box[2:] += box[:2]
|
1006 |
+
# random color
|
1007 |
+
color = tuple(np.random.randint(0, 255, size=3).tolist())
|
1008 |
+
# draw
|
1009 |
+
x0, y0, x1, y1 = box
|
1010 |
+
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
|
1011 |
+
|
1012 |
+
draw.rectangle([x0, y0, x1, y1], outline=color, width=6)
|
1013 |
+
# draw.text((x0, y0), str(label), fill=color)
|
1014 |
+
|
1015 |
+
font = ImageFont.load_default()
|
1016 |
+
if hasattr(font, "getbbox"):
|
1017 |
+
bbox = draw.textbbox((x0, y0), str(label), font)
|
1018 |
+
else:
|
1019 |
+
w, h = draw.textsize(str(label), font)
|
1020 |
+
bbox = (x0, y0, w + x0, y0 + h)
|
1021 |
+
# bbox = draw.textbbox((x0, y0), str(label))
|
1022 |
+
draw.rectangle(bbox, fill=color)
|
1023 |
+
draw.text((x0, y0), str(label), fill="white")
|
1024 |
+
|
1025 |
+
mask_draw.rectangle([x0, y0, x1, y1], fill=255, width=2)
|
1026 |
+
|
1027 |
+
return image_pil, mask
|
1028 |
+
|
1029 |
+
@prompts(name="Detect the Give Object",
|
1030 |
+
description="useful when you only want to detect or find out given objects in the picture"
|
1031 |
+
"The input to this tool should be a comma separated string of two, "
|
1032 |
+
"representing the image_path, the text description of the object to be found")
|
1033 |
+
def inference(self, inputs):
|
1034 |
+
image_path, det_prompt = inputs.split(",")
|
1035 |
+
print(f"image_path={image_path}, text_prompt={det_prompt}")
|
1036 |
+
image_pil, image = self.load_image(image_path)
|
1037 |
+
|
1038 |
+
boxes_filt, pred_phrases = self.get_grounding_boxes(image, det_prompt)
|
1039 |
+
|
1040 |
+
size = image_pil.size
|
1041 |
+
pred_dict = {
|
1042 |
+
"boxes": boxes_filt,
|
1043 |
+
"size": [size[1], size[0]], # H,W
|
1044 |
+
"labels": pred_phrases,}
|
1045 |
+
|
1046 |
+
image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]
|
1047 |
+
|
1048 |
+
updated_image_path = get_new_image_name(image_path, func_name="detect-something")
|
1049 |
+
updated_image = image_with_box.resize(size)
|
1050 |
+
updated_image.save(updated_image_path)
|
1051 |
+
print(
|
1052 |
+
f"\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, "
|
1053 |
+
f"Output Image: {updated_image_path}")
|
1054 |
+
return updated_image_path
|
1055 |
+
|
1056 |
+
|
1057 |
+
class Inpainting:
|
1058 |
+
def __init__(self, device):
|
1059 |
+
self.device = device
|
1060 |
+
self.revision = 'fp16' if 'cuda' in self.device else None
|
1061 |
+
self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32
|
1062 |
+
|
1063 |
+
self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(
|
1064 |
+
"runwayml/stable-diffusion-inpainting", revision=self.revision, torch_dtype=self.torch_dtype).to(device)
|
1065 |
+
def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):
|
1066 |
+
update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),
|
1067 |
+
mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]
|
1068 |
+
return update_image
|
1069 |
+
|
1070 |
+
class InfinityOutPainting:
|
1071 |
+
template_model = True # Add this line to show this is a template model.
|
1072 |
+
def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):
|
1073 |
+
self.llm = OpenAI(temperature=0)
|
1074 |
+
self.ImageCaption = ImageCaptioning
|
1075 |
+
self.inpaint = Inpainting
|
1076 |
+
self.ImageVQA = VisualQuestionAnswering
|
1077 |
+
self.a_prompt = 'best quality, extremely detailed'
|
1078 |
+
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
|
1079 |
+
'fewer digits, cropped, worst quality, low quality'
|
1080 |
+
|
1081 |
+
def get_BLIP_vqa(self, image, question):
|
1082 |
+
inputs = self.ImageVQA.processor(image, question, return_tensors="pt").to(self.ImageVQA.device,
|
1083 |
+
self.ImageVQA.torch_dtype)
|
1084 |
+
out = self.ImageVQA.model.generate(**inputs)
|
1085 |
+
answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)
|
1086 |
+
print(f"\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}")
|
1087 |
+
return answer
|
1088 |
+
|
1089 |
+
def get_BLIP_caption(self, image):
|
1090 |
+
inputs = self.ImageCaption.processor(image, return_tensors="pt").to(self.ImageCaption.device,
|
1091 |
+
self.ImageCaption.torch_dtype)
|
1092 |
+
out = self.ImageCaption.model.generate(**inputs)
|
1093 |
+
BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)
|
1094 |
+
return BLIP_caption
|
1095 |
+
|
1096 |
+
def check_prompt(self, prompt):
|
1097 |
+
check = f"Here is a paragraph with adjectives. " \
|
1098 |
+
f"{prompt} " \
|
1099 |
+
f"Please change all plural forms in the adjectives to singular forms. "
|
1100 |
+
return self.llm(check)
|
1101 |
+
|
1102 |
+
def get_imagine_caption(self, image, imagine):
|
1103 |
+
BLIP_caption = self.get_BLIP_caption(image)
|
1104 |
+
background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')
|
1105 |
+
style = self.get_BLIP_vqa(image, 'what is the style of this image')
|
1106 |
+
imagine_prompt = f"let's pretend you are an excellent painter and now " \
|
1107 |
+
f"there is an incomplete painting with {BLIP_caption} in the center, " \
|
1108 |
+
f"please imagine the complete painting and describe it" \
|
1109 |
+
f"you should consider the background color is {background_color}, the style is {style}" \
|
1110 |
+
f"You should make the painting as vivid and realistic as possible" \
|
1111 |
+
f"You can not use words like painting or picture" \
|
1112 |
+
f"and you should use no more than 50 words to describe it"
|
1113 |
+
caption = self.llm(imagine_prompt) if imagine else BLIP_caption
|
1114 |
+
caption = self.check_prompt(caption)
|
1115 |
+
print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(
|
1116 |
+
f'Prompt: {caption}')
|
1117 |
+
return caption
|
1118 |
+
|
1119 |
+
def resize_image(self, image, max_size=1000000, multiple=8):
|
1120 |
+
aspect_ratio = image.size[0] / image.size[1]
|
1121 |
+
new_width = int(math.sqrt(max_size * aspect_ratio))
|
1122 |
+
new_height = int(new_width / aspect_ratio)
|
1123 |
+
new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)
|
1124 |
+
return image.resize((new_width, new_height))
|
1125 |
+
|
1126 |
+
def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):
|
1127 |
+
old_img = original_img
|
1128 |
+
while (old_img.size != tosize):
|
1129 |
+
prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)
|
1130 |
+
crop_w = 15 if old_img.size[0] != tosize[0] else 0
|
1131 |
+
crop_h = 15 if old_img.size[1] != tosize[1] else 0
|
1132 |
+
old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))
|
1133 |
+
temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],
|
1134 |
+
expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[
|
1135 |
+
1])
|
1136 |
+
temp_canvas, temp_mask = Image.new("RGB", temp_canvas_size, color="white"), Image.new("L", temp_canvas_size,
|
1137 |
+
color="white")
|
1138 |
+
x, y = (temp_canvas.width - old_img.width) // 2, (temp_canvas.height - old_img.height) // 2
|
1139 |
+
temp_canvas.paste(old_img, (x, y))
|
1140 |
+
temp_mask.paste(0, (x, y, x + old_img.width, y + old_img.height))
|
1141 |
+
resized_temp_canvas, resized_temp_mask = self.resize_image(temp_canvas), self.resize_image(temp_mask)
|
1142 |
+
image = self.inpaint(prompt=prompt, image=resized_temp_canvas, mask_image=resized_temp_mask,
|
1143 |
+
height=resized_temp_canvas.height, width=resized_temp_canvas.width,
|
1144 |
+
num_inference_steps=50).resize(
|
1145 |
+
(temp_canvas.width, temp_canvas.height), Image.ANTIALIAS)
|
1146 |
+
image = blend_gt2pt(old_img, image)
|
1147 |
+
old_img = image
|
1148 |
+
return old_img
|
1149 |
+
|
1150 |
+
@prompts(name="Extend An Image",
|
1151 |
+
description="useful when you need to extend an image into a larger image."
|
1152 |
+
"like: extend the image into a resolution of 2048x1024, extend the image into 2048x1024. "
|
1153 |
+
"The input to this tool should be a comma separated string of two, representing the image_path and the resolution of widthxheight")
|
1154 |
+
def inference(self, inputs):
|
1155 |
+
image_path, resolution = inputs.split(',')
|
1156 |
+
width, height = resolution.split('x')
|
1157 |
+
tosize = (int(width), int(height))
|
1158 |
+
image = Image.open(image_path)
|
1159 |
+
image = ImageOps.crop(image, (10, 10, 10, 10))
|
1160 |
+
out_painted_image = self.dowhile(image, tosize, 4, True, False)
|
1161 |
+
updated_image_path = get_new_image_name(image_path, func_name="outpainting")
|
1162 |
+
out_painted_image.save(updated_image_path)
|
1163 |
+
print(f"\nProcessed InfinityOutPainting, Input Image: {image_path}, Input Resolution: {resolution}, "
|
1164 |
+
f"Output Image: {updated_image_path}")
|
1165 |
+
return updated_image_path
|
1166 |
+
|
1167 |
+
|
1168 |
+
class ObjectSegmenting:
|
1169 |
+
template_model = True # Add this line to show this is a template model.
|
1170 |
+
def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting):
|
1171 |
+
# self.llm = OpenAI(temperature=0)
|
1172 |
+
self.grounding = Text2Box
|
1173 |
+
self.sam = Segmenting
|
1174 |
+
|
1175 |
+
@prompts(name="Segment the given object",
|
1176 |
+
description="useful when you only want to segment the certain objects in the picture"
|
1177 |
+
"according to the given text"
|
1178 |
+
"like: segment the cat,"
|
1179 |
+
"or can you segment an obeject for me"
|
1180 |
+
"The input to this tool should be a comma separated string of two, "
|
1181 |
+
"representing the image_path, the text description of the object to be found")
|
1182 |
+
def inference(self, inputs):
|
1183 |
+
image_path, det_prompt = inputs.split(",")
|
1184 |
+
print(f"image_path={image_path}, text_prompt={det_prompt}")
|
1185 |
+
image_pil, image = self.grounding.load_image(image_path)
|
1186 |
+
boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, det_prompt)
|
1187 |
+
updated_image_path = self.sam.segment_image_with_boxes(image_pil,image_path,boxes_filt,pred_phrases)
|
1188 |
+
print(
|
1189 |
+
f"\nProcessed ObejectSegmenting, Input Image: {image_path}, Object to be Segment {det_prompt}, "
|
1190 |
+
f"Output Image: {updated_image_path}")
|
1191 |
+
return updated_image_path
|
1192 |
+
|
1193 |
+
|
1194 |
+
class ImageEditing:
|
1195 |
+
template_model = True
|
1196 |
+
def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpainting:Inpainting):
|
1197 |
+
print(f"Initializing ImageEditing")
|
1198 |
+
self.sam = Segmenting
|
1199 |
+
self.grounding = Text2Box
|
1200 |
+
self.inpaint = Inpainting
|
1201 |
+
|
1202 |
+
def pad_edge(self,mask,padding):
|
1203 |
+
#mask Tensor [H,W]
|
1204 |
+
mask = mask.numpy()
|
1205 |
+
true_indices = np.argwhere(mask)
|
1206 |
+
mask_array = np.zeros_like(mask, dtype=bool)
|
1207 |
+
for idx in true_indices:
|
1208 |
+
padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)
|
1209 |
+
mask_array[padded_slice] = True
|
1210 |
+
new_mask = (mask_array * 255).astype(np.uint8)
|
1211 |
+
#new_mask
|
1212 |
+
return new_mask
|
1213 |
+
|
1214 |
+
@prompts(name="Remove Something From The Photo",
|
1215 |
+
description="useful when you want to remove and object or something from the photo "
|
1216 |
+
"from its description or location. "
|
1217 |
+
"The input to this tool should be a comma separated string of two, "
|
1218 |
+
"representing the image_path and the object need to be removed. ")
|
1219 |
+
def inference_remove(self, image, target): #image格式为PIL
|
1220 |
+
# image_path, to_be_removed_txt = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
|
1221 |
+
# return self.inference_replace_sam(f"{},{to_be_removed_txt},background")
|
1222 |
+
return self.inference_replace_sam(image,target,"background")
|
1223 |
+
|
1224 |
+
@prompts(name="Replace Something From The Photo",
|
1225 |
+
description="useful when you want to replace an object from the object description or "
|
1226 |
+
"location with another object from its description. "
|
1227 |
+
"The input to this tool should be a comma separated string of three, "
|
1228 |
+
"representing the image_path, the object to be replaced, the object to be replaced with ")
|
1229 |
+
def inference_replace_sam(self,image_raw,target,replacement): #image_raw是一个PIL类型
|
1230 |
+
# image_base64, to_be_replaced_txt, replace_with_txt = inputs.split(",")
|
1231 |
+
to_be_replaced_txt=target
|
1232 |
+
replace_with_txt=replacement
|
1233 |
+
# print(f"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}")
|
1234 |
+
#主要是改下面这行
|
1235 |
+
image_pil, image = self.grounding.load_image(image_raw)
|
1236 |
+
boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, to_be_replaced_txt)
|
1237 |
+
# from io import BytesIO
|
1238 |
+
# import base64
|
1239 |
+
# image_bytes=base64.b64decode(image_base64)
|
1240 |
+
# image=Image.open(BytesIO(image_bytes)).convert('RGB')
|
1241 |
+
image = cv2.cvtColor(np.array(image_raw), cv2.COLOR_RGB2BGR)
|
1242 |
+
# image = cv2.imread(image_path)
|
1243 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
1244 |
+
self.sam.sam_predictor.set_image(image)
|
1245 |
+
masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)
|
1246 |
+
mask = torch.sum(masks, dim=0).unsqueeze(0)
|
1247 |
+
mask = torch.where(mask > 0, True, False)
|
1248 |
+
mask = mask.squeeze(0).squeeze(0).cpu() #tensor
|
1249 |
+
|
1250 |
+
mask = self.pad_edge(mask,padding=20) #numpy
|
1251 |
+
mask_image = Image.fromarray(mask)
|
1252 |
+
|
1253 |
+
updated_image = self.inpaint(prompt=replace_with_txt, image=image_pil,
|
1254 |
+
mask_image=mask_image)
|
1255 |
+
# updated_image_path = get_new_image_name(image_path, func_name="replace-something")
|
1256 |
+
updated_image = updated_image.resize(image_pil.size)
|
1257 |
+
# updated_image.save(updated_image_path)
|
1258 |
+
# print(
|
1259 |
+
# f"\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, "
|
1260 |
+
# f"Output Image: {updated_image_path}")
|
1261 |
+
# return updated_image_path
|
1262 |
+
return updated_image
|
1263 |
+
|
1264 |
+
|
1265 |
+
class ConversationBot:
|
1266 |
+
def __init__(self, load_dict):
|
1267 |
+
# load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}
|
1268 |
+
print(f"Initializing VisualChatGPT, load_dict={load_dict}")
|
1269 |
+
if 'ImageCaptioning' not in load_dict:
|
1270 |
+
raise ValueError("You have to load ImageCaptioning as a basic function for VisualChatGPT")
|
1271 |
+
|
1272 |
+
self.models = {}
|
1273 |
+
# Load Basic Foundation Models
|
1274 |
+
for class_name, device in load_dict.items():
|
1275 |
+
self.models[class_name] = globals()[class_name](device=device)
|
1276 |
+
|
1277 |
+
# Load Template Foundation Models
|
1278 |
+
for class_name, module in globals().items():
|
1279 |
+
if getattr(module, 'template_model', False):
|
1280 |
+
template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}
|
1281 |
+
loaded_names = set([type(e).__name__ for e in self.models.values()])
|
1282 |
+
if template_required_names.issubset(loaded_names):
|
1283 |
+
self.models[class_name] = globals()[class_name](
|
1284 |
+
**{name: self.models[name] for name in template_required_names})
|
1285 |
+
|
1286 |
+
print(f"All the Available Functions: {self.models}")
|
1287 |
+
|
1288 |
+
self.tools = []
|
1289 |
+
for instance in self.models.values():
|
1290 |
+
for e in dir(instance):
|
1291 |
+
if e.startswith('inference'):
|
1292 |
+
func = getattr(instance, e)
|
1293 |
+
self.tools.append(Tool(name=func.name, description=func.description, func=func))
|
1294 |
+
self.llm = OpenAI(temperature=0)
|
1295 |
+
self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
|
1296 |
+
|
1297 |
+
def init_agent(self, lang):
|
1298 |
+
self.memory.clear() #clear previous history
|
1299 |
+
if lang=='English':
|
1300 |
+
PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX
|
1301 |
+
place = "Enter text and press enter, or upload an image"
|
1302 |
+
label_clear = "Clear"
|
1303 |
+
else:
|
1304 |
+
PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN
|
1305 |
+
place = "输入文字并回车,或者上传图片"
|
1306 |
+
label_clear = "清除"
|
1307 |
+
self.agent = initialize_agent(
|
1308 |
+
self.tools,
|
1309 |
+
self.llm,
|
1310 |
+
agent="conversational-react-description",
|
1311 |
+
verbose=True,
|
1312 |
+
memory=self.memory,
|
1313 |
+
return_intermediate_steps=True,
|
1314 |
+
agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,
|
1315 |
+
'suffix': SUFFIX}, )
|
1316 |
+
return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)
|
1317 |
+
|
1318 |
+
def run_text(self, text, state):
|
1319 |
+
self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
|
1320 |
+
res = self.agent({"input": text.strip()})
|
1321 |
+
res['output'] = res['output'].replace("\\", "/")
|
1322 |
+
response = re.sub('(image/[-\w]*.png)', lambda m: f'![](file={m.group(0)})*{m.group(0)}*', res['output'])
|
1323 |
+
state = state + [(text, response)]
|
1324 |
+
print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"
|
1325 |
+
f"Current Memory: {self.agent.memory.buffer}")
|
1326 |
+
return state, state
|
1327 |
+
|
1328 |
+
def run_image(self, image, state, txt, lang):
|
1329 |
+
image_filename = os.path.join('image', f"{str(uuid.uuid4())[:8]}.png")
|
1330 |
+
print("======>Auto Resize Image...")
|
1331 |
+
img = Image.open(image.name)
|
1332 |
+
width, height = img.size
|
1333 |
+
ratio = min(512 / width, 512 / height)
|
1334 |
+
width_new, height_new = (round(width * ratio), round(height * ratio))
|
1335 |
+
width_new = int(np.round(width_new / 64.0)) * 64
|
1336 |
+
height_new = int(np.round(height_new / 64.0)) * 64
|
1337 |
+
img = img.resize((width_new, height_new))
|
1338 |
+
img = img.convert('RGB')
|
1339 |
+
img.save(image_filename, "PNG")
|
1340 |
+
print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
|
1341 |
+
description = self.models['ImageCaptioning'].inference(image_filename)
|
1342 |
+
if lang == 'Chinese':
|
1343 |
+
Human_prompt = f'\nHuman: 提供一张名为 {image_filename}的图片。它的描述是: {description}。 这些信息帮助你理解这个图像,但是你应该使用工具来完成下面的任务,而不是直接从我的描述中想象。 如果你明白了, 说 \"收到\". \n'
|
1344 |
+
AI_prompt = "收到。 "
|
1345 |
+
else:
|
1346 |
+
Human_prompt = f'\nHuman: provide a figure named {image_filename}. The description is: {description}. This information helps you to understand this image, but you should use tools to finish following tasks, rather than directly imagine from my description. If you understand, say \"Received\". \n'
|
1347 |
+
AI_prompt = "Received. "
|
1348 |
+
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
|
1349 |
+
state = state + [(f"![](file={image_filename})*{image_filename}*", AI_prompt)]
|
1350 |
+
print(f"\nProcessed run_image, Input image: {image_filename}\nCurrent state: {state}\n"
|
1351 |
+
f"Current Memory: {self.agent.memory.buffer}")
|
1352 |
+
return state, state, f'{txt} {image_filename} '
|
1353 |
+
|
1354 |
+
|
1355 |
+
if __name__ == '__main__':
|
1356 |
+
if not os.path.exists("checkpoints"):
|
1357 |
+
os.mkdir("checkpoints")
|
1358 |
+
parser = argparse.ArgumentParser()
|
1359 |
+
parser.add_argument('--load', type=str, default="ImageCaptioning_cuda:0,Text2Image_cuda:0")
|
1360 |
+
args = parser.parse_args()
|
1361 |
+
load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}
|
1362 |
+
bot = ConversationBot(load_dict=load_dict)
|
1363 |
+
with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
|
1364 |
+
lang = gr.Radio(choices = ['Chinese','English'], value=None, label='Language')
|
1365 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
|
1366 |
+
state = gr.State([])
|
1367 |
+
with gr.Row(visible=False) as input_raws:
|
1368 |
+
with gr.Column(scale=0.7):
|
1369 |
+
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(
|
1370 |
+
container=False)
|
1371 |
+
with gr.Column(scale=0.15, min_width=0):
|
1372 |
+
clear = gr.Button("Clear")
|
1373 |
+
with gr.Column(scale=0.15, min_width=0):
|
1374 |
+
btn = gr.UploadButton(label="🖼️",file_types=["image"])
|
1375 |
+
|
1376 |
+
lang.change(bot.init_agent, [lang], [input_raws, lang, txt, clear])
|
1377 |
+
txt.submit(bot.run_text, [txt, state], [chatbot, state])
|
1378 |
+
txt.submit(lambda: "", None, txt)
|
1379 |
+
btn.upload(bot.run_image, [btn, state, txt, lang], [chatbot, state, txt])
|
1380 |
+
clear.click(bot.memory.clear)
|
1381 |
+
clear.click(lambda: [], None, chatbot)
|
1382 |
+
clear.click(lambda: [], None, state)
|
1383 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|