经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
笔精墨妙,妙手丹青,微软开源可视化版本的ChatGPT:Visual ChatGPT,人工智能AI聊天发图片,Python3.10实现
来源:cnblogs  作者:刘悦的技术博客  时间:2023/3/14 8:48:11  对本文有异议

说时迟那时快,微软第一时间发布开源库Visual ChatGPT,把 ChatGPT 的人工智能AI能力和Stable Diffusion以及ControlNet进行了整合。常常被互联网人挂在嘴边的“赋能”一词,几乎已经变成了笑话,但这回,微软玩了一次真真正正的AI“赋能”,彻底打通了人工智能“闭环”。

配置Visual ChatGPT环境

老规矩,运行Git命令拉取Visual ChatGPT项目:

  1. git clone https://github.com/microsoft/visual-chatgpt.git

进入项目目录:

  1. cd visual-chatgpt

确保本机的Python版本不低于Python3.10.9

随后安装依赖文件:

  1. pip3 install -r requirement.txt

这里有几个问题,一个是官方的Pytorch版本不是最新的,这里推荐1.13.1:

  1. pip3 install torch==1.13.1

另外langchain的版本也推荐最新的107版本。

  1. pip3 install langchain==0.0.107

安装好依赖之后,官方要求运行项目中的download.sh文件:

  1. bash download.sh

这个shell脚本主要就是构建子项目ControlNet,同时下载所有的ControlNet模型,如果之前已经下载过相关模型,直接将模型文件拷贝到项目目录即可:

  1. .
  2. ├── cldm_v15.yaml
  3. ├── cldm_v21.yaml
  4. ├── control_sd15_canny.pth
  5. ├── control_sd15_depth.pth
  6. ├── control_sd15_hed.pth
  7. ├── control_sd15_mlsd.pth
  8. ├── control_sd15_normal.pth
  9. ├── control_sd15_openpose.pth
  10. ├── control_sd15_scribble.pth
  11. └── control_sd15_seg.pth

关于ControlNet,请移玉步至:登峰造极,师出造化,Pytorch人工智能AI图像增强框架ControlNet绘画实践,基于Python3.10, 这里不再赘述。

接着配置Openai的环境变量:

  1. export OPENAI_API_KEY={你的openaik key}

如果是Windows用户,遵循下列步骤,配置好OPENAI_API_KEY:

  1. 打开“控制面板”,然后选择“系统和安全”。
  2. 选择“系统”,然后点击“高级系统设置”。
  3. 在“高级”选项卡下,点击“环境变量”。
  4. 在“用户变量”或“系统变量”下,选择要配置的变量,然后点击“编辑”。
  5. 在“变量值”字段中,输入要配置的值。
  6. 点击“确定”保存更改。

至此,大体上环境就配置好了。

Visual ChatGPT部分代码修改:

和ControlNet一样,Visual ChatGPT将运行方式写死为cuda,这对于不支持cuda模式的电脑不太友好,比如苹果M系列芯片的Mac系统,如果我们直接运行程序:

  1. python3 visual_chatgpt.py

就会报这个错误:

  1. AssertionError: Torch not compiled with CUDA enabled

这里需要将visual-chatgpt.py文件中写死的cuda模式改写为mps模式:

  1. print("Initializing VisualChatGPT")
  2. self.llm = OpenAI(temperature=0)
  3. self.edit = ImageEditing(device="mps")
  4. self.i2t = ImageCaptioning(device="mps")
  5. self.t2i = T2I(device="mps")

关于MPS模式,请参照:闻其声而知雅意,M1 Mac基于PyTorch(mps/cpu/cuda)的人工智能AI本地语音识别库Whisper(Python3.10) ,这里不再赘述。

接着创建训练图片的文件夹:

  1. mkdir image

随后还可能触发langchain库的内存溢出问题,需要将这行代码屏蔽:

  1. # self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)

接着将内存缓冲区替换为保存上下文逻辑:

  1. self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
  2. self.agent.memory.save_context({"input": Human_prompt}, {"output": AI_prompt})

当我们以为万事俱备只欠东风的时候,发现每次运行都会内存溢出,对此,官方给出了解释:

  1. Here we list the GPU memory usage of each visual foundation model, one can modify self.tools with fewer visual foundation models to save your GPU memory:
  2. Foundation Model Memory Usage (MB)
  3. ImageEditing 6667
  4. ImageCaption 1755
  5. T2I 6677
  6. canny2image 5540
  7. line2image 6679
  8. hed2image 6679
  9. scribble2image 6679
  10. pose2image 6681
  11. BLIPVQA 2709
  12. seg2image 5540
  13. depth2image 6677
  14. normal2image 3974
  15. InstructPix2Pix 2795

这就是加载了所有模型之后的显存占用,整整70个G的显存占用,这是给人玩的吗?人们不禁要问。

没办法,只能另辟蹊径,将非必要的模型加载代码进行屏蔽操作,一顿修改,修改后的完整代码:

  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:

Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action

  1. 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:

Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]

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

注意,以上代码是修改了MPS模式、langchain库bug以及屏蔽了多个模型后的修改版本。

运行Visual ChatGPT

折腾了大半天,终于可以无错误运行了:

  1. python3 visual_chatgpt.py

程序返回:

  1. ? visual-chatgpt git:(main) ? python visual_chatgpt.py
  2. Initializing VisualChatGPT
  3. Initializing ImageCaptioning to mps
  4. Initializing T2I to mps
  5. /opt/homebrew/lib/python3.10/site-packages/transformers/models/clip/feature_extraction_clip.py:28: FutureWarning: The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use CLIPImageProcessor instead.
  6. warnings.warn(
  7. Running on local URL: http://0.0.0.0:7860

编程的乐趣就在于,当你为了运行某个程序经历了千难万险,甚至濒临绝望的时候,突然,程序调通了,此时大脑皮层会大量分泌多巴胺(dopamine),那感觉,就像突然领悟了人生妙谛,又像是终于明白了天人化生、万物滋长的要道,简而言之,白日飞升,快乐加倍,那种精神上的享受,绝对比玩电子游戏或者享受美食更加的高级。

随后访问http://localhost:7860:

直接用中文开聊即可,不需要ControlNet那些令人厌烦的引导词。

后台程序逻辑:

  1. Inputs: 给我一只大金毛 []
  2. ======>Previous memory:
  3. chat_memory=ChatMessageHistory(messages=[]) output_key='output' input_key=None return_messages=False human_prefix='Human' ai_prefix='AI' memory_key='chat_history'
  4. > Entering new AgentExecutor chain...
  5. Yes
  6. Action: Generate Image From User Input Text
  7. Action Input: A golden retrieverSetting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
  8. A golden retriever refined to A golden retriever,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
  9. 100%|█████████████████████████████████████████████████████████████████████████████████| 50/50 [00:47<00:00, 1.05it/s]
  10. Processed T2I.run, text: A golden retriever, image_filename: image/865c561f.png
  11. Observation: image/865c561f.png
  12. Thought: Do I need to use a tool? No
  13. AI: Here is a golden retriever for you: image/865c561f.png
  14. > Finished chain.
  15. ======>Current memory:
  16. chat_memory=ChatMessageHistory(messages=[HumanMessage(content='给我一只大金毛', additional_kwargs={}), AIMessage(content='Here is a golden retriever for you: image/865c561f.png', additional_kwargs={})]) output_key='output' input_key=None return_messages=False human_prefix='Human' ai_prefix='AI' memory_key='chat_history'
  17. Outputs: [('给我一只大金毛', 'Here is a golden retriever for you: ![](/file=image/865c561f.png)*image/865c561f.png*')]

通过观察,我们可以得知,虽然是中文聊天,但其实ChatGPT会把中文翻译为英文,将“给我一只大金毛”翻译为:“a golden retriever”。

随后通过模型训练生成图片,再将聊天记录添加到上下文列表中,关于ChatGPT的聊天上下文,请参照:重新定义性价比!人工智能AI聊天ChatGPT新接口模型gpt-3.5-turbo闪电更新,成本降90%,Python3.10接入

当然,为了可以线下单机环境将Visual ChatGPT成功跑起来,所以屏蔽了多个ControlNet图像模型,因此有些图片场景并不那么尽如人意:

结语

有的时候,当我们称赞一项技术的时候,我们会称其为这样或者那样的行业标杆、教科书之类,但是对于ChatGPT来说,它已经超越了所谓的什么标杆,或者说得更准确一些,它是标杆中的标杆,其他的所谓的类ChatGPT产品,别说望其项背了,就连ChatGPT的尾气也闻不到,说白了,想碰瓷都不知道该怎么碰,因为神明早已在ChatGPT的命格中写下八个大字:前无古人,后无来者!最后,奉上修改后的项目代码,与众乡亲同飨:github.com/zcxey2911/visual_chatgpt_mps_cut

原文链接:https://www.cnblogs.com/v3ucn/p/17210321.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号