ysharma HF staff yinshengming commited on
Commit
06df6bf
0 Parent(s):

Duplicate from microsoft/visual_chatgpt

Browse files

Co-authored-by: yinshengming <[email protected]>

.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Visual Chatgpt
3
+ emoji: 🎨
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 3.20.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: osl-3.0
11
+ duplicated_from: microsoft/visual_chatgpt
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 langchain.agents.initialize import initialize_agent
47
+ from langchain.agents.tools import Tool
48
+ from langchain.chains.conversation.memory import ConversationBufferMemory
49
+ from langchain.llms.openai import OpenAI
50
+ import re
51
+ import gradio as gr
52
+
53
+
54
+ def cut_dialogue_history(history_memory, keep_last_n_words=400):
55
+ tokens = history_memory.split()
56
+ n_tokens = len(tokens)
57
+ print(f"hitory_memory:{history_memory}, n_tokens: {n_tokens}")
58
+ if n_tokens < keep_last_n_words:
59
+ return history_memory
60
+ else:
61
+ paragraphs = history_memory.split('\n')
62
+ last_n_tokens = n_tokens
63
+ while last_n_tokens >= keep_last_n_words:
64
+ last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))
65
+ paragraphs = paragraphs[1:]
66
+ return '\n' + '\n'.join(paragraphs)
67
+
68
+
69
+ class ConversationBot:
70
+ def __init__(self, load_dict):
71
+ # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}
72
+ print(f"Initializing VisualChatGPT, load_dict={load_dict}")
73
+ if 'ImageCaptioning' not in load_dict:
74
+ raise ValueError("You have to load ImageCaptioning as a basic function for VisualChatGPT")
75
+
76
+ self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
77
+
78
+ self.models = dict()
79
+ for class_name, device in load_dict.items():
80
+ self.models[class_name] = globals()[class_name](device=device)
81
+
82
+ self.tools = []
83
+ for class_name, instance in self.models.items():
84
+ for e in dir(instance):
85
+ if e.startswith('inference'):
86
+ func = getattr(instance, e)
87
+ self.tools.append(Tool(name=func.name, description=func.description, func=func))
88
+
89
+
90
+ def run_text(self, text, state):
91
+ self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
92
+ res = self.agent({"input": text})
93
+ res['output'] = res['output'].replace("\\", "/")
94
+ response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
95
+ state = state + [(text, response)]
96
+ print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"
97
+ f"Current Memory: {self.agent.memory.buffer}")
98
+ return state, state
99
+
100
+ def run_image(self, image, state, txt):
101
+ image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
102
+ print("======>Auto Resize Image...")
103
+ img = Image.open(image.name)
104
+ width, height = img.size
105
+ ratio = min(512 / width, 512 / height)
106
+ width_new, height_new = (round(width * ratio), round(height * ratio))
107
+ width_new = int(np.round(width_new / 64.0)) * 64
108
+ height_new = int(np.round(height_new / 64.0)) * 64
109
+ img = img.resize((width_new, height_new))
110
+ img = img.convert('RGB')
111
+ img.save(image_filename, "PNG")
112
+ print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
113
+ description = self.models['ImageCaptioning'].inference(image_filename)
114
+ Human_prompt = "\nHuman: provide a figure named {}. The description is: {}. " \
115
+ "This information helps you to understand this image, " \
116
+ "but you should use tools to finish following tasks, " \
117
+ "rather than directly imagine from my description. If you understand, say \"Received\". \n".format(
118
+ image_filename, description)
119
+ AI_prompt = "Received. "
120
+ self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
121
+ state = state + [(f"![](/file={image_filename})*{image_filename}*", AI_prompt)]
122
+ print(f"\nProcessed run_image, Input image: {image_filename}\nCurrent state: {state}\n"
123
+ f"Current Memory: {self.agent.memory.buffer}")
124
+ return state, state, txt + ' ' + image_filename + ' '
125
+
126
+ def init_agent(self, openai_api_key):
127
+ self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
128
+ self.agent = initialize_agent(
129
+ self.tools,
130
+ self.llm,
131
+ agent="conversational-react-description",
132
+ verbose=True,
133
+ memory=self.memory,
134
+ return_intermediate_steps=True,
135
+ agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}, )
136
+
137
+ return gr.update(visible = True)
138
+
139
+ bot = ConversationBot({'Text2Image':'cuda:0',
140
+ 'ImageCaptioning':'cuda:0',
141
+ 'ImageEditing': 'cuda:0',
142
+ 'VisualQuestionAnswering': 'cuda:0',
143
+ 'Image2Canny':'cpu',
144
+ 'CannyText2Image':'cuda:0',
145
+ 'InstructPix2Pix':'cuda:0'})
146
+
147
+ with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
148
+ with gr.Row():
149
+ gr.Markdown("<h3><center>Visual ChatGPT</center></h3>")
150
+
151
+ with gr.Row():
152
+ openai_api_key_textbox = gr.Textbox(
153
+ placeholder="Paste your OpenAI API key here to start Visual ChatGPT(sk-...)",
154
+ show_label=False,
155
+ lines=1,
156
+ type="password",
157
+ )
158
+
159
+ chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
160
+ state = gr.State([])
161
+
162
+ with gr.Row(visible=False) as input_raws:
163
+ with gr.Column(scale=0.7):
164
+ txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)
165
+ with gr.Column(scale=0.15, min_width=0):
166
+ clear = gr.Button("Clear️")
167
+ with gr.Column(scale=0.15, min_width=0):
168
+ btn = gr.UploadButton("Upload", file_types=["image"])
169
+
170
+ gr.Examples(
171
+ examples=["Generate a figure of a cat running in the garden",
172
+ "Replace the cat with a dog",
173
+ "Remove the dog in this image",
174
+ "Can you detect the canny edge of this image?",
175
+ "Can you use this canny image to generate an oil painting of a dog",
176
+ "Make it like water-color painting",
177
+ "What is the background color",
178
+ "Describe this image"],
179
+ inputs=txt
180
+ )
181
+
182
+
183
+ openai_api_key_textbox.submit(bot.init_agent, [openai_api_key_textbox], [input_raws])
184
+ txt.submit(bot.run_text, [txt, state], [chatbot, state])
185
+ txt.submit(lambda: "", None, txt)
186
+ btn.upload(bot.run_image, [btn, state, txt], [chatbot, state, txt])
187
+ clear.click(bot.memory.clear)
188
+ clear.click(lambda: [], None, chatbot)
189
+ clear.click(lambda: [], None, state)
190
+
191
+ demo.launch(server_name="0.0.0.0", server_port=7860)
image/placeholder.txt ADDED
File without changes
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python3-opencv
requirements.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch==1.12.1
3
+ torchvision==0.13.1
4
+ numpy==1.23.1
5
+ transformers==4.26.1
6
+ albumentations==1.3.0
7
+ opencv-contrib-python==4.3.0.36
8
+ imageio==2.9.0
9
+ imageio-ffmpeg==0.4.2
10
+ pytorch-lightning==1.5.0
11
+ omegaconf==2.1.1
12
+ test-tube>=0.7.5
13
+ streamlit==1.12.1
14
+ einops==0.3.0
15
+ webdataset==0.2.5
16
+ kornia==0.6
17
+ open_clip_torch==2.0.2
18
+ invisible-watermark>=0.1.5
19
+ streamlit-drawable-canvas==0.8.0
20
+ torchmetrics==0.6.0
21
+ timm==0.6.12
22
+ addict==2.4.0
23
+ yapf==0.32.0
24
+ prettytable==3.6.0
25
+ safetensors==0.2.7
26
+ basicsr==1.4.2
27
+ langchain==0.0.101
28
+ diffusers==0.14.0
29
+ gradio
30
+ openai
31
+ accelerate
32
+ controlnet-aux==0.0.1
visual_foundation_models.py ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline
2
+ from diffusers import EulerAncestralDiscreteScheduler
3
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
4
+ from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector
5
+
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation
7
+ from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
8
+ from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
9
+
10
+ import os
11
+ import random
12
+ import torch
13
+ import cv2
14
+ import uuid
15
+ from PIL import Image
16
+ import numpy as np
17
+ from pytorch_lightning import seed_everything
18
+
19
+ def prompts(name, description):
20
+ def decorator(func):
21
+ func.name = name
22
+ func.description = description
23
+ return func
24
+
25
+ return decorator
26
+
27
+ def get_new_image_name(org_img_name, func_name="update"):
28
+ head_tail = os.path.split(org_img_name)
29
+ head = head_tail[0]
30
+ tail = head_tail[1]
31
+ name_split = tail.split('.')[0].split('_')
32
+ this_new_uuid = str(uuid.uuid4())[0:4]
33
+ if len(name_split) == 1:
34
+ most_org_file_name = name_split[0]
35
+ recent_prev_file_name = name_split[0]
36
+ new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
37
+ else:
38
+ assert len(name_split) == 4
39
+ most_org_file_name = name_split[3]
40
+ recent_prev_file_name = name_split[0]
41
+ new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
42
+ return os.path.join(head, new_file_name)
43
+
44
+
45
+ class MaskFormer:
46
+ def __init__(self, device):
47
+ print("Initializing MaskFormer to %s" % device)
48
+ self.device = device
49
+ self.processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
50
+ self.model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device)
51
+
52
+ def inference(self, image_path, text):
53
+ threshold = 0.5
54
+ min_area = 0.02
55
+ padding = 20
56
+ original_image = Image.open(image_path)
57
+ image = original_image.resize((512, 512))
58
+ inputs = self.processor(text=text, images=image, padding="max_length", return_tensors="pt").to(self.device)
59
+ with torch.no_grad():
60
+ outputs = self.model(**inputs)
61
+ mask = torch.sigmoid(outputs[0]).squeeze().cpu().numpy() > threshold
62
+ area_ratio = len(np.argwhere(mask)) / (mask.shape[0] * mask.shape[1])
63
+ if area_ratio < min_area:
64
+ return None
65
+ true_indices = np.argwhere(mask)
66
+ mask_array = np.zeros_like(mask, dtype=bool)
67
+ for idx in true_indices:
68
+ padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)
69
+ mask_array[padded_slice] = True
70
+ visual_mask = (mask_array * 255).astype(np.uint8)
71
+ image_mask = Image.fromarray(visual_mask)
72
+ return image_mask.resize(original_image.size)
73
+
74
+
75
+ class ImageEditing:
76
+ def __init__(self, device):
77
+ print("Initializing ImageEditing to %s" % device)
78
+ self.device = device
79
+ self.mask_former = MaskFormer(device=self.device)
80
+ self.inpaint = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting", revision="fp16", torch_dtype=torch.float16).to(device)
81
+
82
+ @prompts(name="Remove Something From The Photo",
83
+ description="useful when you want to remove and object or something from the photo "
84
+ "from its description or location. "
85
+ "The input to this tool should be a comma seperated string of two, "
86
+ "representing the image_path and the object need to be removed. ")
87
+ def inference_remove(self, inputs):
88
+ image_path, to_be_removed_txt = inputs.split(",")
89
+ return self.inference_replace(f"{image_path},{to_be_removed_txt},background")
90
+
91
+ @prompts(name="Replace Something From The Photo",
92
+ description="useful when you want to replace an object from the object description or "
93
+ "location with another object from its description. "
94
+ "The input to this tool should be a comma seperated string of three, "
95
+ "representing the image_path, the object to be replaced, the object to be replaced with ")
96
+ def inference_replace(self, inputs):
97
+ image_path, to_be_replaced_txt, replace_with_txt = inputs.split(",")
98
+ original_image = Image.open(image_path)
99
+ original_size = original_image.size
100
+ mask_image = self.mask_former.inference(image_path, to_be_replaced_txt)
101
+ updated_image = self.inpaint(prompt=replace_with_txt, image=original_image.resize((512, 512)),
102
+ mask_image=mask_image.resize((512, 512))).images[0]
103
+ updated_image_path = get_new_image_name(image_path, func_name="replace-something")
104
+ updated_image = updated_image.resize(original_size)
105
+ updated_image.save(updated_image_path)
106
+ print(
107
+ f"\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, "
108
+ f"Output Image: {updated_image_path}")
109
+ return updated_image_path
110
+
111
+
112
+ class InstructPix2Pix:
113
+ def __init__(self, device):
114
+ print("Initializing InstructPix2Pix to %s" % device)
115
+ self.device = device
116
+ self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix", torch_dtype=torch.float16,
117
+ safety_checker=None).to(device)
118
+ self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
119
+
120
+ @prompts(name="Instruct Image Using Text",
121
+ description="useful when you want to the style of the image to be like the text. "
122
+ "like: make it look like a painting. or make it like a robot. "
123
+ "The input to this tool should be a comma seperated string of two, "
124
+ "representing the image_path and the text. ")
125
+ def inference(self, inputs):
126
+ """Change style of image."""
127
+ print("===>Starting InstructPix2Pix Inference")
128
+ image_path, text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
129
+ original_image = Image.open(image_path)
130
+ image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]
131
+ updated_image_path = get_new_image_name(image_path, func_name="pix2pix")
132
+ image.save(updated_image_path)
133
+ print(f"\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, "
134
+ f"Output Image: {updated_image_path}")
135
+ return updated_image_path
136
+
137
+
138
+ class Text2Image:
139
+ def __init__(self, device):
140
+ print("Initializing Text2Image to %s" % device)
141
+ self.device = device
142
+ self.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",torch_dtype=torch.float16)
143
+ self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
144
+ self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
145
+ self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model,
146
+ tokenizer=self.text_refine_tokenizer, device=self.device)
147
+ self.pipe.to(device)
148
+
149
+ @prompts(name="Generate Image From User Input Text",
150
+ description="useful when you want to generate an image from a user input text and save it to a file. "
151
+ "like: generate an image of an object or something, or generate an image that includes some objects. "
152
+ "The input to this tool should be a string, representing the text used to generate image. ")
153
+ def inference(self, text):
154
+ image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
155
+ refined_text = self.text_refine_gpt2_pipe(text)[0]["generated_text"]
156
+ image = self.pipe(refined_text).images[0]
157
+ image.save(image_filename)
158
+ print(
159
+ f"\nProcessed Text2Image, Input Text: {text}, Refined Text: {refined_text}, Output Image: {image_filename}")
160
+ return image_filename
161
+
162
+
163
+ class ImageCaptioning:
164
+ def __init__(self, device):
165
+ print("Initializing ImageCaptioning to %s" % device)
166
+ self.device = device
167
+ self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
168
+ self.model = BlipForConditionalGeneration.from_pretrained(
169
+ "Salesforce/blip-image-captioning-base", torch_dtype=torch.float16).to(self.device)
170
+
171
+ @prompts(name="Get Photo Description",
172
+ description="useful when you want to know what is inside the photo. receives image_path as input. "
173
+ "The input to this tool should be a string, representing the image_path. ")
174
+ def inference(self, image_path):
175
+ inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device, torch.float16)
176
+ out = self.model.generate(**inputs)
177
+ captions = self.processor.decode(out[0], skip_special_tokens=True)
178
+ print(f"\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}")
179
+ return captions
180
+
181
+
182
+ class Image2Canny:
183
+ def __init__(self, device):
184
+ print("Initializing Image2Canny")
185
+ self.low_threshold = 100
186
+ self.high_threshold = 200
187
+
188
+ @prompts(name="Edge Detection On Image",
189
+ description="useful when you want to detect the edge of the image. "
190
+ "like: detect the edges of this image, or canny detection on image, "
191
+ "or perform edge detection on this image, or detect the canny image of this image. "
192
+ "The input to this tool should be a string, representing the image_path")
193
+ def inference(self, inputs):
194
+ image = Image.open(inputs)
195
+ image = np.array(image)
196
+ canny = cv2.Canny(image, self.low_threshold, self.high_threshold)
197
+ canny = canny[:, :, None]
198
+ canny = np.concatenate([canny, canny, canny], axis=2)
199
+ canny = Image.fromarray(canny)
200
+ updated_image_path = get_new_image_name(inputs, func_name="edge")
201
+ canny.save(updated_image_path)
202
+ print(f"\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}")
203
+ return updated_image_path
204
+
205
+
206
+ class CannyText2Image:
207
+ def __init__(self, device):
208
+ print("Initializing CannyText2Image to %s" % device)
209
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-canny", torch_dtype=torch.float16)
210
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
211
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)
212
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
213
+ self.pipe.to(device)
214
+ self.seed = -1
215
+ self.a_prompt = 'best quality, extremely detailed'
216
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
217
+ 'fewer digits, cropped, worst quality, low quality'
218
+
219
+ @prompts(name="Generate Image Condition On Canny Image",
220
+ description="useful when you want to generate a new real image from both the user desciption and a canny image."
221
+ " like: generate a real image of a object or something from this canny image,"
222
+ " or generate a new real image of a object or something from this edge image. "
223
+ "The input to this tool should be a comma seperated string of two, "
224
+ "representing the image_path and the user description. ")
225
+ def inference(self, inputs):
226
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
227
+ image = Image.open(image_path)
228
+ self.seed = random.randint(0, 65535)
229
+ seed_everything(self.seed)
230
+ prompt = instruct_text + ', ' + self.a_prompt
231
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
232
+ guidance_scale=9.0).images[0]
233
+ updated_image_path = get_new_image_name(image_path, func_name="canny2image")
234
+ image.save(updated_image_path)
235
+ print(f"\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, "
236
+ f"Output Text: {updated_image_path}")
237
+ return updated_image_path
238
+
239
+
240
+ class Image2Line:
241
+ def __init__(self, device):
242
+ print("Initializing Image2Line")
243
+ self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')
244
+
245
+ @prompts(name="Line Detection On Image",
246
+ description="useful when you want to detect the straight line of the image. "
247
+ "like: detect the straight lines of this image, or straight line detection on image, "
248
+ "or peform straight line detection on this image, or detect the straight line image of this image. "
249
+ "The input to this tool should be a string, representing the image_path")
250
+ def inference(self, inputs):
251
+ image = Image.open(inputs)
252
+ mlsd = self.detector(image)
253
+ updated_image_path = get_new_image_name(inputs, func_name="line-of")
254
+ mlsd.save(updated_image_path)
255
+ print(f"\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}")
256
+ return updated_image_path
257
+
258
+
259
+ class LineText2Image:
260
+ def __init__(self, device):
261
+ print("Initializing LineText2Image to %s" % device)
262
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-mlsd")
263
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
264
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
265
+ )
266
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
267
+ self.pipe.to(device)
268
+ self.seed = -1
269
+ self.a_prompt = 'best quality, extremely detailed'
270
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
271
+ 'fewer digits, cropped, worst quality, low quality'
272
+
273
+ @prompts(name="Generate Image Condition On Line Image",
274
+ description="useful when you want to generate a new real image from both the user desciption "
275
+ "and a straight line image. "
276
+ "like: generate a real image of a object or something from this straight line image, "
277
+ "or generate a new real image of a object or something from this straight lines. "
278
+ "The input to this tool should be a comma seperated string of two, "
279
+ "representing the image_path and the user description. ")
280
+ def inference(self, inputs):
281
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
282
+ image = Image.open(image_path)
283
+ self.seed = random.randint(0, 65535)
284
+ seed_everything(self.seed)
285
+ prompt = instruct_text + ', ' + self.a_prompt
286
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
287
+ guidance_scale=9.0).images[0]
288
+ updated_image_path = get_new_image_name(image_path, func_name="line2image")
289
+ image.save(updated_image_path)
290
+ print(f"\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, "
291
+ f"Output Text: {updated_image_path}")
292
+ return updated_image_path
293
+
294
+
295
+ class Image2Hed:
296
+ def __init__(self, device):
297
+ print("Initializing Image2Hed")
298
+ self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
299
+
300
+ @prompts(name="Hed Detection On Image",
301
+ description="useful when you want to detect the soft hed boundary of the image. "
302
+ "like: detect the soft hed boundary of this image, or hed boundary detection on image, "
303
+ "or peform hed boundary detection on this image, or detect soft hed boundary image of this image. "
304
+ "The input to this tool should be a string, representing the image_path")
305
+ def inference(self, inputs):
306
+ image = Image.open(inputs)
307
+ hed = self.detector(image)
308
+ updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")
309
+ hed.save(updated_image_path)
310
+ print(f"\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}")
311
+ return updated_image_path
312
+
313
+
314
+ class HedText2Image:
315
+ def __init__(self, device):
316
+ print("Initializing HedText2Image to %s" % device)
317
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-hed")
318
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
319
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
320
+ )
321
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
322
+ self.pipe.to(device)
323
+ self.seed = -1
324
+ self.a_prompt = 'best quality, extremely detailed'
325
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
326
+ 'fewer digits, cropped, worst quality, low quality'
327
+
328
+ @prompts(name="Generate Image Condition On Soft Hed Boundary Image",
329
+ description="useful when you want to generate a new real image from both the user desciption "
330
+ "and a soft hed boundary image. "
331
+ "like: generate a real image of a object or something from this soft hed boundary image, "
332
+ "or generate a new real image of a object or something from this hed boundary. "
333
+ "The input to this tool should be a comma seperated string of two, "
334
+ "representing the image_path and the user description")
335
+ def inference(self, inputs):
336
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
337
+ image = Image.open(image_path)
338
+ self.seed = random.randint(0, 65535)
339
+ seed_everything(self.seed)
340
+ prompt = instruct_text + ', ' + self.a_prompt
341
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
342
+ guidance_scale=9.0).images[0]
343
+ updated_image_path = get_new_image_name(image_path, func_name="hed2image")
344
+ image.save(updated_image_path)
345
+ print(f"\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, "
346
+ f"Output Image: {updated_image_path}")
347
+ return updated_image_path
348
+
349
+
350
+ class Image2Scribble:
351
+ def __init__(self, device):
352
+ print("Initializing Image2Scribble")
353
+ self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
354
+
355
+ @prompts(name="Sketch Detection On Image",
356
+ description="useful when you want to generate a scribble of the image. "
357
+ "like: generate a scribble of this image, or generate a sketch from this image, "
358
+ "detect the sketch from this image. "
359
+ "The input to this tool should be a string, representing the image_path")
360
+ def inference(self, inputs):
361
+ image = Image.open(inputs)
362
+ scribble = self.detector(image, scribble=True)
363
+ updated_image_path = get_new_image_name(inputs, func_name="scribble")
364
+ scribble.save(updated_image_path)
365
+ print(f"\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}")
366
+ return updated_image_path
367
+
368
+
369
+ class ScribbleText2Image:
370
+ def __init__(self, device):
371
+ print("Initializing ScribbleText2Image to %s" % device)
372
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-scribble")
373
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
374
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None
375
+ )
376
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
377
+ self.pipe.to(device)
378
+ self.seed = -1
379
+ self.a_prompt = 'best quality, extremely detailed'
380
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
381
+ 'fewer digits, cropped, worst quality, low quality'
382
+
383
+ @prompts(name="Generate Image Condition On Sketch Image",
384
+ description="useful when you want to generate a new real image from both the user desciption and "
385
+ "a scribble image or a sketch image. "
386
+ "The input to this tool should be a comma seperated string of two, "
387
+ "representing the image_path and the user description")
388
+ def inference(self, inputs):
389
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
390
+ image = Image.open(image_path)
391
+ self.seed = random.randint(0, 65535)
392
+ seed_everything(self.seed)
393
+ prompt = instruct_text + ', ' + self.a_prompt
394
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
395
+ guidance_scale=9.0).images[0]
396
+ updated_image_path = get_new_image_name(image_path, func_name="scribble2image")
397
+ image.save(updated_image_path)
398
+ print(f"\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, "
399
+ f"Output Image: {updated_image_path}")
400
+ return updated_image_path
401
+
402
+
403
+ class Image2Pose:
404
+ def __init__(self, device):
405
+ print("Initializing Image2Pose")
406
+ self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')
407
+
408
+ @prompts(name="Pose Detection On Image",
409
+ description="useful when you want to detect the human pose of the image. "
410
+ "like: generate human poses of this image, or generate a pose image from this image. "
411
+ "The input to this tool should be a string, representing the image_path")
412
+ def inference(self, inputs):
413
+ image = Image.open(inputs)
414
+ pose = self.detector(image)
415
+ updated_image_path = get_new_image_name(inputs, func_name="human-pose")
416
+ pose.save(updated_image_path)
417
+ print(f"\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}")
418
+ return updated_image_path
419
+
420
+
421
+ class PoseText2Image:
422
+ def __init__(self, device):
423
+ print("Initializing PoseText2Image to %s" % device)
424
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose")
425
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
426
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)
427
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
428
+ self.pipe.to(device)
429
+ self.num_inference_steps = 20
430
+ self.seed = -1
431
+ self.unconditional_guidance_scale = 9.0
432
+ self.a_prompt = 'best quality, extremely detailed'
433
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
434
+ ' fewer digits, cropped, worst quality, low quality'
435
+
436
+ @prompts(name="Generate Image Condition On Pose Image",
437
+ description="useful when you want to generate a new real image from both the user desciption "
438
+ "and a human pose image. "
439
+ "like: generate a real image of a human from this human pose image, "
440
+ "or generate a new real image of a human from this pose. "
441
+ "The input to this tool should be a comma seperated string of two, "
442
+ "representing the image_path and the user description")
443
+ def inference(self, inputs):
444
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
445
+ image = Image.open(image_path)
446
+ self.seed = random.randint(0, 65535)
447
+ seed_everything(self.seed)
448
+ prompt = instruct_text + ', ' + self.a_prompt
449
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
450
+ guidance_scale=9.0).images[0]
451
+ updated_image_path = get_new_image_name(image_path, func_name="pose2image")
452
+ image.save(updated_image_path)
453
+ print(f"\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, "
454
+ f"Output Image: {updated_image_path}")
455
+ return updated_image_path
456
+
457
+
458
+ class Image2Seg:
459
+ def __init__(self, device):
460
+ print("Initializing Image2Seg")
461
+ self.image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
462
+ self.image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
463
+ self.ade_palette = [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
464
+ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
465
+ [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
466
+ [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
467
+ [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
468
+ [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
469
+ [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
470
+ [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
471
+ [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
472
+ [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
473
+ [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
474
+ [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
475
+ [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
476
+ [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
477
+ [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
478
+ [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
479
+ [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
480
+ [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
481
+ [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
482
+ [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
483
+ [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
484
+ [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
485
+ [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
486
+ [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
487
+ [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
488
+ [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
489
+ [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
490
+ [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
491
+ [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
492
+ [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
493
+ [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
494
+ [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
495
+ [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
496
+ [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
497
+ [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
498
+ [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
499
+ [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
500
+ [102, 255, 0], [92, 0, 255]]
501
+
502
+ @prompts(name="Segmentation On Image",
503
+ description="useful when you want to detect segmentations of the image. "
504
+ "like: segment this image, or generate segmentations on this image, "
505
+ "or peform segmentation on this image. "
506
+ "The input to this tool should be a string, representing the image_path")
507
+ def inference(self, inputs):
508
+ image = Image.open(inputs)
509
+ pixel_values = self.image_processor(image, return_tensors="pt").pixel_values
510
+ with torch.no_grad():
511
+ outputs = self.image_segmentor(pixel_values)
512
+ seg = self.image_processor.post_process_semantic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]
513
+ color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
514
+ palette = np.array(self.ade_palette)
515
+ for label, color in enumerate(palette):
516
+ color_seg[seg == label, :] = color
517
+ color_seg = color_seg.astype(np.uint8)
518
+ segmentation = Image.fromarray(color_seg)
519
+ updated_image_path = get_new_image_name(inputs, func_name="segmentation")
520
+ segmentation.save(updated_image_path)
521
+ print(f"\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}")
522
+ return updated_image_path
523
+
524
+
525
+ class SegText2Image:
526
+ def __init__(self, device):
527
+ print("Initializing SegText2Image to %s" % device)
528
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-seg")
529
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
530
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)
531
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
532
+ self.pipe.to(device)
533
+ self.seed = -1
534
+ self.a_prompt = 'best quality, extremely detailed'
535
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
536
+ ' fewer digits, cropped, worst quality, low quality'
537
+
538
+ @prompts(name="Generate Image Condition On Segmentations",
539
+ description="useful when you want to generate a new real image from both the user desciption and segmentations. "
540
+ "like: generate a real image of a object or something from this segmentation image, "
541
+ "or generate a new real image of a object or something from these segmentations. "
542
+ "The input to this tool should be a comma seperated string of two, "
543
+ "representing the image_path and the user description")
544
+ def inference(self, inputs):
545
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
546
+ image = Image.open(image_path)
547
+ self.seed = random.randint(0, 65535)
548
+ seed_everything(self.seed)
549
+ prompt = instruct_text + ', ' + self.a_prompt
550
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
551
+ guidance_scale=9.0).images[0]
552
+ updated_image_path = get_new_image_name(image_path, func_name="segment2image")
553
+ image.save(updated_image_path)
554
+ print(f"\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, "
555
+ f"Output Image: {updated_image_path}")
556
+ return updated_image_path
557
+
558
+
559
+ class Image2Depth:
560
+ def __init__(self, device):
561
+ print("Initializing Image2Depth")
562
+ self.depth_estimator = pipeline('depth-estimation')
563
+
564
+ @prompts(name="Predict Depth On Image",
565
+ description="useful when you want to detect depth of the image. like: generate the depth from this image, "
566
+ "or detect the depth map on this image, or predict the depth for this image. "
567
+ "The input to this tool should be a string, representing the image_path")
568
+ def inference(self, inputs):
569
+ image = Image.open(inputs)
570
+ depth = self.depth_estimator(image)['depth']
571
+ depth = np.array(depth)
572
+ depth = depth[:, :, None]
573
+ depth = np.concatenate([depth, depth, depth], axis=2)
574
+ depth = Image.fromarray(depth)
575
+ updated_image_path = get_new_image_name(inputs, func_name="depth")
576
+ depth.save(updated_image_path)
577
+ print(f"\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}")
578
+ return updated_image_path
579
+
580
+
581
+ class DepthText2Image:
582
+ def __init__(self, device):
583
+ print("Initializing DepthText2Image to %s" % device)
584
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-depth")
585
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
586
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)
587
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
588
+ self.pipe.to(device)
589
+ self.seed = -1
590
+ self.a_prompt = 'best quality, extremely detailed'
591
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
592
+ ' fewer digits, cropped, worst quality, low quality'
593
+
594
+ @prompts(name="Generate Image Condition On Depth",
595
+ description="useful when you want to generate a new real image from both the user desciption and depth image. "
596
+ "like: generate a real image of a object or something from this depth image, "
597
+ "or generate a new real image of a object or something from the depth map. "
598
+ "The input to this tool should be a comma seperated string of two, "
599
+ "representing the image_path and the user description")
600
+ def inference(self, inputs):
601
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
602
+ image = Image.open(image_path)
603
+ self.seed = random.randint(0, 65535)
604
+ seed_everything(self.seed)
605
+ prompt = instruct_text + ', ' + self.a_prompt
606
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
607
+ guidance_scale=9.0).images[0]
608
+ updated_image_path = get_new_image_name(image_path, func_name="depth2image")
609
+ image.save(updated_image_path)
610
+ print(f"\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, "
611
+ f"Output Image: {updated_image_path}")
612
+ return updated_image_path
613
+
614
+
615
+ class Image2Normal:
616
+ def __init__(self, device):
617
+ print("Initializing Image2Normal")
618
+ self.depth_estimator = pipeline("depth-estimation", model="Intel/dpt-hybrid-midas")
619
+ self.bg_threhold = 0.4
620
+
621
+ @prompts(name="Predict Normal Map On Image",
622
+ description="useful when you want to detect norm map of the image. "
623
+ "like: generate normal map from this image, or predict normal map of this image. "
624
+ "The input to this tool should be a string, representing the image_path")
625
+ def inference(self, inputs):
626
+ image = Image.open(inputs)
627
+ original_size = image.size
628
+ image = self.depth_estimator(image)['predicted_depth'][0]
629
+ image = image.numpy()
630
+ image_depth = image.copy()
631
+ image_depth -= np.min(image_depth)
632
+ image_depth /= np.max(image_depth)
633
+ x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)
634
+ x[image_depth < self.bg_threhold] = 0
635
+ y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)
636
+ y[image_depth < self.bg_threhold] = 0
637
+ z = np.ones_like(x) * np.pi * 2.0
638
+ image = np.stack([x, y, z], axis=2)
639
+ image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5
640
+ image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)
641
+ image = Image.fromarray(image)
642
+ image = image.resize(original_size)
643
+ updated_image_path = get_new_image_name(inputs, func_name="normal-map")
644
+ image.save(updated_image_path)
645
+ print(f"\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}")
646
+ return updated_image_path
647
+
648
+
649
+ class NormalText2Image:
650
+ def __init__(self, device):
651
+ print("Initializing NormalText2Image to %s" % device)
652
+ self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-normal")
653
+ self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
654
+ "runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)
655
+ self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
656
+ self.pipe.to(device)
657
+ self.seed = -1
658
+ self.a_prompt = 'best quality, extremely detailed'
659
+ self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
660
+ ' fewer digits, cropped, worst quality, low quality'
661
+
662
+ @prompts(name="Generate Image Condition On Normal Map",
663
+ description="useful when you want to generate a new real image from both the user desciption and normal map. "
664
+ "like: generate a real image of a object or something from this normal map, "
665
+ "or generate a new real image of a object or something from the normal map. "
666
+ "The input to this tool should be a comma seperated string of two, "
667
+ "representing the image_path and the user description")
668
+ def inference(self, inputs):
669
+ image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
670
+ image = Image.open(image_path)
671
+ self.seed = random.randint(0, 65535)
672
+ seed_everything(self.seed)
673
+ prompt = instruct_text + ', ' + self.a_prompt
674
+ image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
675
+ guidance_scale=9.0).images[0]
676
+ updated_image_path = get_new_image_name(image_path, func_name="normal2image")
677
+ image.save(updated_image_path)
678
+ print(f"\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, "
679
+ f"Output Image: {updated_image_path}")
680
+ return updated_image_path
681
+
682
+
683
+ class VisualQuestionAnswering:
684
+ def __init__(self, device):
685
+ print("Initializing VisualQuestionAnswering to %s" % device)
686
+ self.device = device
687
+ self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
688
+ self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base", torch_dtype=torch.float16).to(self.device)
689
+
690
+ @prompts(name="Answer Question About The Image",
691
+ description="useful when you need an answer for a question based on an image. "
692
+ "like: what is the background color of the last image, how many cats in this figure, what is in this figure. "
693
+ "The input to this tool should be a comma seperated string of two, representing the image_path and the question")
694
+ def inference(self, inputs):
695
+ image_path, question = inputs.split(",")
696
+ raw_image = Image.open(image_path).convert('RGB')
697
+ inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device, torch.float16)
698
+ out = self.model.generate(**inputs)
699
+ answer = self.processor.decode(out[0], skip_special_tokens=True)
700
+ print(f"\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, "
701
+ f"Output Answer: {answer}")
702
+ return answer