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