visual_chatgpt.py 56 KB

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