chatgpt.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. import os
  2. import re
  3. import uuid
  4. import cv2
  5. import torch
  6. import requests
  7. import io, base64
  8. import numpy as np
  9. import gradio as gr
  10. from PIL import Image
  11. from base64 import b64encode
  12. from omegaconf import OmegaConf
  13. from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
  14. from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation
  15. from langchain.agents.initialize import initialize_agent
  16. from langchain.agents.tools import Tool
  17. from langchain.chains.conversation.memory import ConversationBufferMemory
  18. from langchain.llms.openai import OpenAI
  19. 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.
  20. 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.
  21. 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.
  22. 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.
  23. TOOLS:
  24. ------
  25. Visual ChatGPT has access to the following tools:"""
  26. VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
  27. ```
  28. Thought: Do I need to use a tool? Yes
  29. Action: the action to take, should be one of [{tool_names}]
  30. Action Input: the input to the action
  31. Observation: the result of the action
  32. ```
  33. 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:
  34. ```
  35. Thought: Do I need to use a tool? No
  36. {ai_prefix}: [your response here]
  37. ```
  38. """
  39. VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if it does not exist.
  40. You will remember to provide the image file name loyally if it's provided in the last tool observation.
  41. Begin!
  42. Previous conversation history:
  43. {chat_history}
  44. New input: {input}
  45. Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
  46. The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human.
  47. Thought: Do I need to use a tool? {agent_scratchpad}"""
  48. ENDPOINT = "http://localhost:7860"
  49. T2IAPI = ENDPOINT + "/controlnet/txt2img"
  50. DETECTAPI = ENDPOINT + "/controlnet/detect"
  51. MODELLIST = ENDPOINT + "/controlnet/model_list"
  52. device = "cpu"
  53. if torch.cuda.is_available():
  54. device = "cuda"
  55. def readImage(path):
  56. img = cv2.imread(path)
  57. retval, buffer = cv2.imencode('.jpg', img)
  58. b64img = b64encode(buffer).decode("utf-8")
  59. return b64img
  60. def get_model(pattern='^control_canny.*'):
  61. r = requests.get(MODELLIST)
  62. result = r.json()["model_list"]
  63. for item in result:
  64. if re.match(pattern, item):
  65. return item
  66. def do_webui_request(url=T2IAPI, **kwargs):
  67. reqbody = {
  68. "prompt": "best quality, extremely detailed",
  69. "negative_prompt": "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality",
  70. "seed": -1,
  71. "subseed": -1,
  72. "subseed_strength": 0,
  73. "batch_size": 1,
  74. "n_iter": 1,
  75. "steps": 15,
  76. "cfg_scale": 7,
  77. "width": 512,
  78. "height": 768,
  79. "restore_faces": True,
  80. "eta": 0,
  81. "sampler_index": "Euler a",
  82. "controlnet_input_images": [],
  83. "controlnet_module": 'canny',
  84. "controlnet_model": 'control_canny-fp16 [e3fe7712]',
  85. "controlnet_guidance": 1.0,
  86. }
  87. reqbody.update(kwargs)
  88. r = requests.post(url, json=reqbody)
  89. return r.json()
  90. def cut_dialogue_history(history_memory, keep_last_n_words=500):
  91. tokens = history_memory.split()
  92. n_tokens = len(tokens)
  93. print(f"hitory_memory:{history_memory}, n_tokens: {n_tokens}")
  94. if n_tokens < keep_last_n_words:
  95. return history_memory
  96. else:
  97. paragraphs = history_memory.split('\n')
  98. last_n_tokens = n_tokens
  99. while last_n_tokens >= keep_last_n_words:
  100. last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))
  101. paragraphs = paragraphs[1:]
  102. return '\n' + '\n'.join(paragraphs)
  103. def get_new_image_name(org_img_name, func_name="update"):
  104. head_tail = os.path.split(org_img_name)
  105. head = head_tail[0]
  106. tail = head_tail[1]
  107. name_split = tail.split('.')[0].split('_')
  108. this_new_uuid = str(uuid.uuid4())[0:4]
  109. if len(name_split) == 1:
  110. most_org_file_name = name_split[0]
  111. recent_prev_file_name = name_split[0]
  112. new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
  113. else:
  114. assert len(name_split) == 4
  115. most_org_file_name = name_split[3]
  116. recent_prev_file_name = name_split[0]
  117. new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
  118. return os.path.join(head, new_file_name)
  119. class MaskFormer:
  120. def __init__(self, device):
  121. self.device = device
  122. self.processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
  123. self.model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device)
  124. def inference(self, image_path, text):
  125. threshold = 0.5
  126. min_area = 0.02
  127. padding = 20
  128. original_image = Image.open(image_path)
  129. image = original_image.resize((512, 512))
  130. inputs = self.processor(text=text, images=image, padding="max_length", return_tensors="pt",).to(self.device)
  131. with torch.no_grad():
  132. outputs = self.model(**inputs)
  133. mask = torch.sigmoid(outputs[0]).squeeze().cpu().numpy() > threshold
  134. area_ratio = len(np.argwhere(mask)) / (mask.shape[0] * mask.shape[1])
  135. if area_ratio < min_area:
  136. return None
  137. true_indices = np.argwhere(mask)
  138. mask_array = np.zeros_like(mask, dtype=bool)
  139. for idx in true_indices:
  140. padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)
  141. mask_array[padded_slice] = True
  142. visual_mask = (mask_array * 255).astype(np.uint8)
  143. image_mask = Image.fromarray(visual_mask)
  144. return image_mask.resize(image.size)
  145. # class ImageEditing:
  146. # def __init__(self, device):
  147. # print("Initializing StableDiffusionInpaint to %s" % device)
  148. # self.device = device
  149. # self.mask_former = MaskFormer(device=self.device)
  150. # # self.inpainting = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",).to(device)
  151. # def remove_part_of_image(self, input):
  152. # image_path, to_be_removed_txt = input.split(",")
  153. # print(f'remove_part_of_image: to_be_removed {to_be_removed_txt}')
  154. # return self.replace_part_of_image(f"{image_path},{to_be_removed_txt},background")
  155. # def replace_part_of_image(self, input):
  156. # image_path, to_be_replaced_txt, replace_with_txt = input.split(",")
  157. # print(f'replace_part_of_image: replace_with_txt {replace_with_txt}')
  158. # mask_image = self.mask_former.inference(image_path, to_be_replaced_txt)
  159. # buffered = io.BytesIO()
  160. # mask_image.save(buffered, format="JPEG")
  161. # resp = do_webui_request(
  162. # url=ENDPOINT + "/sdapi/v1/img2img",
  163. # init_images=[readImage(image_path)],
  164. # mask=b64encode(buffered.getvalue()).decode("utf-8"),
  165. # prompt=replace_with_txt,
  166. # )
  167. # image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  168. # updated_image_path = get_new_image_name(image_path, func_name="replace-something")
  169. # updated_image.save(updated_image_path)
  170. # return updated_image_path
  171. # class Pix2Pix:
  172. # def __init__(self, device):
  173. # print("Initializing Pix2Pix to %s" % device)
  174. # self.device = device
  175. # self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix", torch_dtype=torch.float16, safety_checker=None).to(device)
  176. # self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
  177. # def inference(self, inputs):
  178. # """Change style of image."""
  179. # print("===>Starting Pix2Pix Inference")
  180. # image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  181. # original_image = Image.open(image_path)
  182. # image = self.pipe(instruct_text,image=original_image,num_inference_steps=40,image_guidance_scale=1.2,).images[0]
  183. # updated_image_path = get_new_image_name(image_path, func_name="pix2pix")
  184. # image.save(updated_image_path)
  185. # return updated_image_path
  186. class T2I:
  187. def __init__(self, device):
  188. print("Initializing T2I to %s" % device)
  189. self.device = device
  190. self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
  191. self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
  192. self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model, tokenizer=self.text_refine_tokenizer, device=self.device)
  193. def inference(self, text):
  194. image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
  195. refined_text = self.text_refine_gpt2_pipe(text)[0]["generated_text"]
  196. print(f'{text} refined to {refined_text}')
  197. resp = do_webui_request(
  198. url=ENDPOINT + "/sdapi/v1/txt2img",
  199. prompt=refined_text,
  200. )
  201. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  202. image.save(image_filename)
  203. print(f"Processed T2I.run, text: {text}, image_filename: {image_filename}")
  204. return image_filename
  205. class ImageCaptioning:
  206. def __init__(self, device):
  207. print("Initializing ImageCaptioning to %s" % device)
  208. self.device = device
  209. self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
  210. self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(self.device)
  211. def inference(self, image_path):
  212. inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device)
  213. out = self.model.generate(**inputs)
  214. captions = self.processor.decode(out[0], skip_special_tokens=True)
  215. return captions
  216. class image2canny:
  217. def inference(self, inputs):
  218. print("===>Starting image2canny Inference")
  219. resp = do_webui_request(
  220. url=DETECTAPI,
  221. controlnet_input_images=[readImage(inputs)],
  222. controlnet_module="segmentation",
  223. )
  224. updated_image_path = get_new_image_name(inputs, func_name="edge")
  225. image.save(updated_image_path)
  226. return updated_image_path
  227. class canny2image:
  228. def inference(self, inputs):
  229. print("===>Starting canny2image Inference")
  230. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  231. resp = do_webui_request(
  232. prompt=instruct_text,
  233. controlnet_input_images=[readImage(image_path)],
  234. controlnet_module="none",
  235. controlnet_model=get_model(pattern='^control_canny.*'),
  236. )
  237. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  238. updated_image_path = get_new_image_name(image_path, func_name="canny2image")
  239. real_image = Image.fromarray(x_samples[0])
  240. real_image.save(updated_image_path)
  241. return updated_image_path
  242. class image2line:
  243. def inference(self, inputs):
  244. print("===>Starting image2hough Inference")
  245. resp = do_webui_request(
  246. url=DETECTAPI,
  247. controlnet_input_images=[readImage(inputs)],
  248. controlnet_module="mlsd",
  249. )
  250. updated_image_path = get_new_image_name(inputs, func_name="line-of")
  251. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  252. image.save(updated_image_path)
  253. return updated_image_path
  254. class line2image:
  255. def inference(self, inputs):
  256. print("===>Starting line2image Inference")
  257. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  258. resp = do_webui_request(
  259. prompt=instruct_text,
  260. controlnet_input_images=[readImage(image_path)],
  261. controlnet_module="none",
  262. controlnet_model=get_model(pattern='^control_mlsd.*'),
  263. )
  264. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  265. updated_image_path = get_new_image_name(image_path, func_name="line2image")
  266. real_image = Image.fromarray(x_samples[0]) # default the index0 image
  267. real_image.save(updated_image_path)
  268. return updated_image_path
  269. class image2hed:
  270. def inference(self, inputs):
  271. print("===>Starting image2hed Inference")
  272. resp = do_webui_request(
  273. url=DETECTAPI,
  274. controlnet_input_images=[readImage(inputs)],
  275. controlnet_module="hed",
  276. )
  277. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  278. updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")
  279. image.save(updated_image_path)
  280. return updated_image_path
  281. class hed2image:
  282. def inference(self, inputs):
  283. print("===>Starting hed2image Inference")
  284. resp = do_webui_request(
  285. prompt=instruct_text,
  286. controlnet_input_images=[readImage(image_path)],
  287. controlnet_module="none",
  288. controlnet_model=get_model(pattern='^control_hed.*'),
  289. )
  290. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  291. updated_image_path = get_new_image_name(image_path, func_name="hed2image")
  292. real_image = Image.fromarray(x_samples[0]) # default the index0 image
  293. real_image.save(updated_image_path)
  294. return updated_image_path
  295. class image2scribble:
  296. def inference(self, inputs):
  297. print("===>Starting image2scribble Inference")
  298. resp = do_webui_request(
  299. url=DETECTAPI,
  300. controlnet_input_images=[readImage(inputs)],
  301. controlnet_module="scribble",
  302. )
  303. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  304. updated_image_path = get_new_image_name(inputs, func_name="scribble")
  305. image.save(updated_image_path)
  306. return updated_image_path
  307. class scribble2image:
  308. def inference(self, inputs):
  309. print("===>Starting seg2image Inference")
  310. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  311. resp = do_webui_request(
  312. prompt=instruct_text,
  313. controlnet_input_images=[readImage(image_path)],
  314. controlnet_module="none",
  315. controlnet_model=get_model(pattern='^control_scribble.*'),
  316. )
  317. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  318. updated_image_path = get_new_image_name(image_path, func_name="scribble2image")
  319. real_image = Image.fromarray(x_samples[0])
  320. real_image.save(updated_image_path)
  321. return updated_image_path
  322. class image2pose:
  323. def inference(self, inputs):
  324. print("===>Starting image2pose Inference")
  325. resp = do_webui_request(
  326. url=DETECTAPI,
  327. controlnet_input_images=[readImage(inputs)],
  328. controlnet_module="openpose",
  329. )
  330. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  331. updated_image_path = get_new_image_name(inputs, func_name="human-pose")
  332. image.save(updated_image_path)
  333. return updated_image_path
  334. class pose2image:
  335. def inference(self, inputs):
  336. print("===>Starting pose2image Inference")
  337. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  338. resp = do_webui_request(
  339. prompt=instruct_text,
  340. controlnet_input_images=[readImage(image_path)],
  341. controlnet_module="none",
  342. controlnet_model=get_model(pattern='^control_openpose.*'),
  343. )
  344. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  345. updated_image_path = get_new_image_name(image_path, func_name="pose2image")
  346. real_image = Image.fromarray(x_samples[0]) # default the index0 image
  347. real_image.save(updated_image_path)
  348. return updated_image_path
  349. class image2seg:
  350. def inference(self, inputs):
  351. print("===>Starting image2seg Inference")
  352. resp = do_webui_request(
  353. url=DETECTAPI,
  354. controlnet_input_images=[readImage(inputs)],
  355. controlnet_module="segmentation",
  356. )
  357. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  358. updated_image_path = get_new_image_name(inputs, func_name="segmentation")
  359. image.save(updated_image_path)
  360. return updated_image_path
  361. class seg2image:
  362. def inference(self, inputs):
  363. print("===>Starting seg2image Inference")
  364. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  365. resp = do_webui_request(
  366. prompt=instruct_text,
  367. controlnet_input_images=[readImage(image_path)],
  368. controlnet_module="none",
  369. controlnet_model=get_model(pattern='^control_seg.*'),
  370. )
  371. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  372. updated_image_path = get_new_image_name(image_path, func_name="segment2image")
  373. real_image = Image.fromarray(x_samples[0])
  374. real_image.save(updated_image_path)
  375. return updated_image_path
  376. class image2depth:
  377. def inference(self, inputs):
  378. print("===>Starting image2depth Inference")
  379. resp = do_webui_request(
  380. url=DETECTAPI,
  381. controlnet_input_images=[readImage(inputs)],
  382. controlnet_module="depth",
  383. )
  384. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  385. updated_image_path = get_new_image_name(inputs, func_name="depth")
  386. image.save(updated_image_path)
  387. return updated_image_path
  388. class depth2image:
  389. def inference(self, inputs):
  390. print("===>Starting depth2image Inference")
  391. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  392. resp = do_webui_request(
  393. prompt=instruct_text,
  394. controlnet_input_images=[readImage(image_path)],
  395. controlnet_module="depth",
  396. controlnet_model=get_model(pattern='^control_depth.*'),
  397. )
  398. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  399. updated_image_path = get_new_image_name(image_path, func_name="depth2image")
  400. real_image = Image.fromarray(x_samples[0]) # default the index0 image
  401. real_image.save(updated_image_path)
  402. return updated_image_path
  403. class image2normal:
  404. def inference(self, inputs):
  405. print("===>Starting image2 normal Inference")
  406. resp = do_webui_request(
  407. url=DETECTAPI,
  408. controlnet_input_images=[readImage(inputs)],
  409. controlnet_module="normal",
  410. )
  411. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  412. updated_image_path = get_new_image_name(inputs, func_name="normal-map")
  413. image.save(updated_image_path)
  414. return updated_image_path
  415. class normal2image:
  416. def inference(self, inputs):
  417. print("===>Starting normal2image Inference")
  418. image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
  419. resp = do_webui_request(
  420. prompt=instruct_text,
  421. controlnet_input_images=[readImage(image_path)],
  422. controlnet_module="normal",
  423. controlnet_model=get_model(pattern='^control_normal.*'),
  424. )
  425. image = Image.open(io.BytesIO(base64.b64decode(resp["images"][0])))
  426. updated_image_path = get_new_image_name(image_path, func_name="normal2image")
  427. real_image = Image.fromarray(x_samples[0]) # default the index0 image
  428. real_image.save(updated_image_path)
  429. return updated_image_path
  430. class BLIPVQA:
  431. def __init__(self, device):
  432. print("Initializing BLIP VQA to %s" % device)
  433. self.device = device
  434. self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
  435. self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(self.device)
  436. def get_answer_from_question_and_image(self, inputs):
  437. image_path, question = inputs.split(",")
  438. raw_image = Image.open(image_path).convert('RGB')
  439. print(F'BLIPVQA :question :{question}')
  440. inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device)
  441. out = self.model.generate(**inputs)
  442. answer = self.processor.decode(out[0], skip_special_tokens=True)
  443. return answer
  444. class ConversationBot:
  445. def __init__(self):
  446. print("Initializing VisualChatGPT")
  447. # self.edit = ImageEditing(device=device)
  448. self.i2t = ImageCaptioning(device=device)
  449. self.t2i = T2I(device=device)
  450. self.image2canny = image2canny()
  451. self.canny2image = canny2image()
  452. self.image2line = image2line()
  453. self.line2image = line2image()
  454. self.image2hed = image2hed()
  455. self.hed2image = hed2image()
  456. self.image2scribble = image2scribble()
  457. self.scribble2image = scribble2image()
  458. self.image2pose = image2pose()
  459. self.pose2image = pose2image()
  460. self.BLIPVQA = BLIPVQA(device=device)
  461. self.image2seg = image2seg()
  462. self.seg2image = seg2image()
  463. self.image2depth = image2depth()
  464. self.depth2image = depth2image()
  465. self.image2normal = image2normal()
  466. self.normal2image = normal2image()
  467. # self.pix2pix = Pix2Pix(device="cuda:3")
  468. self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
  469. self.tools = [
  470. Tool(name="Get Photo Description", func=self.i2t.inference,
  471. description="useful when you want to know what is inside the photo. receives image_path as input. "
  472. "The input to this tool should be a string, representing the image_path. "),
  473. Tool(name="Generate Image From User Input Text", func=self.t2i.inference,
  474. 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. "
  475. "The input to this tool should be a string, representing the text used to generate image. "),
  476. # Tool(name="Remove Something From The Photo", func=self.edit.remove_part_of_image,
  477. # description="useful when you want to remove and object or something from the photo from its description or location. "
  478. # "The input to this tool should be a comma seperated string of two, representing the image_path and the object need to be removed. "),
  479. # Tool(name="Replace Something From The Photo", func=self.edit.replace_part_of_image,
  480. # description="useful when you want to replace an object from the object description or location with another object from its description. "
  481. # "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 "),
  482. # Tool(name="Instruct Image Using Text", func=self.pix2pix.inference,
  483. # 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. "
  484. # "The input to this tool should be a comma seperated string of two, representing the image_path and the text. "),
  485. Tool(name="Answer Question About The Image", func=self.BLIPVQA.get_answer_from_question_and_image,
  486. 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. "
  487. "The input to this tool should be a comma seperated string of two, representing the image_path and the question"),
  488. Tool(name="Edge Detection On Image", func=self.image2canny.inference,
  489. 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. "
  490. "The input to this tool should be a string, representing the image_path"),
  491. Tool(name="Generate Image Condition On Canny Image", func=self.canny2image.inference,
  492. 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. "
  493. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),
  494. Tool(name="Line Detection On Image", func=self.image2line.inference,
  495. 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. "
  496. "The input to this tool should be a string, representing the image_path"),
  497. Tool(name="Generate Image Condition On Line Image", func=self.line2image.inference,
  498. 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. "
  499. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),
  500. Tool(name="Hed Detection On Image", func=self.image2hed.inference,
  501. 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. "
  502. "The input to this tool should be a string, representing the image_path"),
  503. Tool(name="Generate Image Condition On Soft Hed Boundary Image", func=self.hed2image.inference,
  504. 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. "
  505. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
  506. Tool(name="Segmentation On Image", func=self.image2seg.inference,
  507. 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. "
  508. "The input to this tool should be a string, representing the image_path"),
  509. Tool(name="Generate Image Condition On Segmentations", func=self.seg2image.inference,
  510. 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. "
  511. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
  512. Tool(name="Predict Depth On Image", func=self.image2depth.inference,
  513. 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. "
  514. "The input to this tool should be a string, representing the image_path"),
  515. Tool(name="Generate Image Condition On Depth", func=self.depth2image.inference,
  516. 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. "
  517. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
  518. Tool(name="Predict Normal Map On Image", func=self.image2normal.inference,
  519. 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. "
  520. "The input to this tool should be a string, representing the image_path"),
  521. Tool(name="Generate Image Condition On Normal Map", func=self.normal2image.inference,
  522. 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. "
  523. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
  524. Tool(name="Sketch Detection On Image", func=self.image2scribble.inference,
  525. 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. "
  526. "The input to this tool should be a string, representing the image_path"),
  527. Tool(name="Generate Image Condition On Sketch Image", func=self.scribble2image.inference,
  528. description="useful when you want to generate a new real image from both the user desciption and a scribble image or a sketch image. "
  529. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
  530. Tool(name="Pose Detection On Image", func=self.image2pose.inference,
  531. 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. "
  532. "The input to this tool should be a string, representing the image_path"),
  533. Tool(name="Generate Image Condition On Pose Image", func=self.pose2image.inference,
  534. 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. "
  535. "The input to this tool should be a comma seperated string of two, representing the image_path and the user description")]
  536. def init_langchain(self, openai_api_key):
  537. self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
  538. self.agent = initialize_agent(
  539. self.tools,
  540. self.llm,
  541. agent="conversational-react-description",
  542. verbose=True,
  543. memory=self.memory,
  544. return_intermediate_steps=True,
  545. agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}
  546. )
  547. def run_text(self, openai_api_key, text, state):
  548. if not hasattr(self, "agent"):
  549. self.init_langchain(openai_api_key)
  550. print("===============Running run_text =============")
  551. print("Inputs:", text, state)
  552. print("======>Previous memory:\n %s" % self.agent.memory)
  553. self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
  554. res = self.agent({"input": text})
  555. print("======>Current memory:\n %s" % self.agent.memory)
  556. response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
  557. state = state + [(text, response)]
  558. print("Outputs:", state)
  559. return state, state
  560. def run_image(self, openai_api_key, image, state, txt):
  561. if not hasattr(self, "agent"):
  562. self.init_langchain(openai_api_key)
  563. print("===============Running run_image =============")
  564. print("Inputs:", image, state)
  565. print("======>Previous memory:\n %s" % self.agent.memory)
  566. image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
  567. print("======>Auto Resize Image...")
  568. img = Image.open(image.name)
  569. width, height = img.size
  570. ratio = min(512 / width, 512 / height)
  571. width_new, height_new = (round(width * ratio), round(height * ratio))
  572. img = img.resize((width_new, height_new))
  573. img = img.convert('RGB')
  574. img.save(image_filename, "PNG")
  575. print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
  576. description = self.i2t.inference(image_filename)
  577. 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, " \
  578. "rather than directly imagine from my description. If you understand, say \"Received\". \n".format(image_filename, description)
  579. AI_prompt = "Received. "
  580. self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
  581. print("======>Current memory:\n %s" % self.agent.memory)
  582. state = state + [(f"![](/file={image_filename})*{image_filename}*", AI_prompt)]
  583. print("Outputs:", state)
  584. return state, state, txt + ' ' + image_filename + ' '
  585. if __name__ == '__main__':
  586. os.makedirs("image/", exist_ok=True)
  587. bot = ConversationBot()
  588. with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
  589. openai_api_key = gr.Textbox(type="password", label="Enter your OpenAI API key here")
  590. chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
  591. state = gr.State([])
  592. with gr.Row():
  593. with gr.Column(scale=0.7):
  594. txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)
  595. with gr.Column(scale=0.15, min_width=0):
  596. clear = gr.Button("Clear️")
  597. with gr.Column(scale=0.15, min_width=0):
  598. btn = gr.UploadButton("Upload", file_types=["image"])
  599. txt.submit(bot.run_text, [openai_api_key, txt, state], [chatbot, state])
  600. txt.submit(lambda: "", None, txt)
  601. btn.upload(bot.run_image, [openai_api_key, btn, state, txt], [chatbot, state, txt])
  602. clear.click(bot.memory.clear)
  603. clear.click(lambda: [], None, chatbot)
  604. clear.click(lambda: [], None, state)
  605. demo.launch(server_name="0.0.0.0", server_port=7864)