Prateeknlp commited on
Commit
ac36014
1 Parent(s): 8b37bc3

Create visual_text_chat.py

Browse files

Visual text forked from visualgpt

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