ctankso_americas_corpdir_net commited on
Commit
a175ca4
1 Parent(s): 3358f08

feat: initial commit

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