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