Spaces:
Running
on
Zero
Running
on
Zero
Upload 26 files
Browse files- 1.py +157 -0
- 2.py +149 -0
- README.md +348 -14
- config.py +1 -0
- environment.yaml +35 -0
- gradio_Scene_Diffusion.py +102 -0
- gradio_annotator.py +160 -0
- gradio_canny2image.py +99 -0
- gradio_depth2image.py +98 -0
- gradio_fake_scribble2image.py +102 -0
- gradio_hed2image.py +98 -0
- gradio_hough2image.py +100 -0
- gradio_normal2image.py +99 -0
- gradio_pose2image.py +98 -0
- gradio_scribble2image.py +92 -0
- gradio_scribble2image_interactive.py +102 -0
- gradio_seg2image.py +97 -0
- requirements.txt +28 -0
- share.py +8 -0
- tool_add_control.py +50 -0
- tool_add_control_sd21.py +50 -0
- tool_transfer_control.py +59 -0
- tutorial_dataset.py +39 -0
- tutorial_dataset_test.py +12 -0
- tutorial_train.py +35 -0
- tutorial_train_sd21.py +35 -0
1.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import random
|
4 |
+
import multiprocessing
|
5 |
+
import subprocess
|
6 |
+
import sys
|
7 |
+
import time
|
8 |
+
import signal
|
9 |
+
import json
|
10 |
+
import os
|
11 |
+
import requests
|
12 |
+
|
13 |
+
from loguru import logger
|
14 |
+
from decouple import config
|
15 |
+
|
16 |
+
from pathlib import Path
|
17 |
+
from PIL import Image
|
18 |
+
import io
|
19 |
+
|
20 |
+
URL="http://127.0.0.1"
|
21 |
+
OUTPUT_DIR = config('OUTPUT_DIR')
|
22 |
+
INPUT_DIR = config('INPUT_DIR')
|
23 |
+
COMF_PATH = config('COMF_PATH')
|
24 |
+
|
25 |
+
import torch
|
26 |
+
|
27 |
+
import spaces
|
28 |
+
|
29 |
+
print(f"Is CUDA available: {torch.cuda.is_available()}")
|
30 |
+
print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
|
31 |
+
print(torch.version.cuda)
|
32 |
+
device = torch.cuda.get_device_name(torch.cuda.current_device())
|
33 |
+
print(device)
|
34 |
+
|
35 |
+
|
36 |
+
def wait_for_image_with_prefix(folder, prefix):
|
37 |
+
def is_file_ready(file_path):
|
38 |
+
initial_size = os.path.getsize(file_path)
|
39 |
+
time.sleep(1)
|
40 |
+
return initial_size == os.path.getsize(file_path)
|
41 |
+
|
42 |
+
|
43 |
+
files = os.listdir(folder)
|
44 |
+
image_files = [f for f in files if f.lower().startswith(prefix.lower()) and
|
45 |
+
f.lower().endswith(('.png', '.jpg', '.jpeg'))]
|
46 |
+
|
47 |
+
if image_files:
|
48 |
+
# Sort by modification time to get the latest file
|
49 |
+
image_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x)), reverse=True)
|
50 |
+
latest_image = os.path.join(folder, image_files[0])
|
51 |
+
|
52 |
+
if is_file_ready(latest_image):
|
53 |
+
# Wait a bit more to ensure the file is completely written
|
54 |
+
time.sleep(3)
|
55 |
+
return latest_image
|
56 |
+
|
57 |
+
|
58 |
+
return None
|
59 |
+
|
60 |
+
|
61 |
+
def delete_image_file(file_path):
|
62 |
+
try:
|
63 |
+
if os.path.exists(file_path):
|
64 |
+
os.remove(file_path)
|
65 |
+
logger.debug(f"file {file_path} deleted")
|
66 |
+
else:
|
67 |
+
logger.debug(f"file {file_path} is not exist")
|
68 |
+
except Exception as e:
|
69 |
+
logger.debug(f"error {file_path}: {str(e)}")
|
70 |
+
|
71 |
+
|
72 |
+
def start_queue(prompt_workflow, port):
|
73 |
+
p = {"prompt": prompt_workflow}
|
74 |
+
data = json.dumps(p).encode('utf-8')
|
75 |
+
requests.post(f"{URL}:{port}/prompt", data=data)
|
76 |
+
|
77 |
+
|
78 |
+
def check_server_ready(port):
|
79 |
+
try:
|
80 |
+
response = requests.get(f"{URL}:{port}/history/123", timeout=5)
|
81 |
+
return response.status_code == 200
|
82 |
+
except requests.RequestException:
|
83 |
+
return False
|
84 |
+
|
85 |
+
|
86 |
+
|
87 |
+
@spaces.GPU(duration=240)
|
88 |
+
def generate_image(prompt, image):
|
89 |
+
prefix_filename = str(random.randint(0, 999999))
|
90 |
+
prompt = prompt.replace('ComfyUI', prefix_filename)
|
91 |
+
prompt = json.loads(prompt)
|
92 |
+
|
93 |
+
image = Image.fromarray(image)
|
94 |
+
image.save(INPUT_DIR + '/input.png', format='PNG')
|
95 |
+
|
96 |
+
process = None
|
97 |
+
new_port = str(random.randint(8123, 8200))
|
98 |
+
|
99 |
+
try:
|
100 |
+
# Запускаем скрипт как подпроцесс
|
101 |
+
process = subprocess.Popen([sys.executable, COMF_PATH, "--listen", "127.0.0.1", "--port", new_port])
|
102 |
+
logger.debug(f'Subprocess started with PID: {process.pid}')
|
103 |
+
|
104 |
+
# Ожидание запуска сервера
|
105 |
+
for _ in range(30): # Максимум 20 секунд ожидания
|
106 |
+
if check_server_ready(new_port):
|
107 |
+
break
|
108 |
+
time.sleep(1)
|
109 |
+
else:
|
110 |
+
raise TimeoutError("Server did not start in time")
|
111 |
+
|
112 |
+
start_queue(prompt, new_port)
|
113 |
+
|
114 |
+
# Ожидание нового изображения
|
115 |
+
timeout = 240 # Максимальное время ожидания в секундах
|
116 |
+
start_time = time.time()
|
117 |
+
while time.time() - start_time < timeout:
|
118 |
+
latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
|
119 |
+
if latest_image:
|
120 |
+
logger.debug(f"file is: {latest_image}")
|
121 |
+
try:
|
122 |
+
return Image.open(latest_image)
|
123 |
+
finally:
|
124 |
+
delete_image_file(latest_image)
|
125 |
+
delete_image_file(INPUT_DIR + '/input.png')
|
126 |
+
time.sleep(1)
|
127 |
+
|
128 |
+
raise TimeoutError("New image was not generated in time")
|
129 |
+
|
130 |
+
except Exception as e:
|
131 |
+
logger.error(f"Error in generate_image: {e}")
|
132 |
+
|
133 |
+
finally:
|
134 |
+
if process and process.poll() is None:
|
135 |
+
process.terminate()
|
136 |
+
logger.debug("process.terminate()")
|
137 |
+
try:
|
138 |
+
logger.debug("process.wait(timeout=5)")
|
139 |
+
process.wait(timeout=5)
|
140 |
+
except subprocess.TimeoutExpired:
|
141 |
+
logger.debug("process.kill()")
|
142 |
+
process.kill()
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
if __name__ == "__main__":
|
147 |
+
demo = gr.Interface(fn=generate_image, inputs=[
|
148 |
+
"text",
|
149 |
+
gr.Image(image_mode='RGBA', type="numpy")
|
150 |
+
],
|
151 |
+
outputs=[
|
152 |
+
gr.Image(type="numpy", image_mode='RGBA')
|
153 |
+
])
|
154 |
+
demo.launch(debug=True)
|
155 |
+
logger.debug('demo.launch()')
|
156 |
+
|
157 |
+
logger.info("Основной скрипт завершил работу.")
|
2.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import random
|
4 |
+
import multiprocessing
|
5 |
+
import subprocess
|
6 |
+
import sys
|
7 |
+
import time
|
8 |
+
import signal
|
9 |
+
import json
|
10 |
+
import os
|
11 |
+
import requests
|
12 |
+
|
13 |
+
from loguru import logger
|
14 |
+
from decouple import config
|
15 |
+
|
16 |
+
from pathlib import Path
|
17 |
+
from PIL import Image
|
18 |
+
import io
|
19 |
+
|
20 |
+
URL="http://127.0.0.1"
|
21 |
+
OUTPUT_DIR="Backend/output"
|
22 |
+
INPUT_DIR="Backend/input"
|
23 |
+
BACKEND_PATH="Backend/main.py"
|
24 |
+
import torch
|
25 |
+
|
26 |
+
import spaces
|
27 |
+
|
28 |
+
print(f"Is CUDA available: {torch.cuda.is_available()}")
|
29 |
+
print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
|
30 |
+
print(torch.version.cuda)
|
31 |
+
device = torch.cuda.get_device_name(torch.cuda.current_device())
|
32 |
+
print(device)
|
33 |
+
|
34 |
+
|
35 |
+
def read_prompt_from_file(filename):
|
36 |
+
with open(filename, 'r', encoding='utf-8') as file:
|
37 |
+
return json.load(file)
|
38 |
+
|
39 |
+
def wait_for_image_with_prefix(folder, prefix):
|
40 |
+
def is_file_ready(file_path):
|
41 |
+
initial_size = os.path.getsize(file_path)
|
42 |
+
time.sleep(1)
|
43 |
+
return initial_size == os.path.getsize(file_path)
|
44 |
+
|
45 |
+
files = os.listdir(folder)
|
46 |
+
image_files = [f for f in files if f.lower().startswith(prefix.lower()) and
|
47 |
+
f.lower().endswith(('.png', '.jpg', '.jpeg'))]
|
48 |
+
|
49 |
+
if image_files:
|
50 |
+
# Sort by modification time to get the latest file
|
51 |
+
image_files.sort(key=lambda x: os.path.getmtime(os.path.join(folder, x)), reverse=True)
|
52 |
+
latest_image = os.path.join(folder, image_files[0])
|
53 |
+
|
54 |
+
if is_file_ready(latest_image):
|
55 |
+
# Wait a bit more to ensure the file is completely written
|
56 |
+
time.sleep(3)
|
57 |
+
return latest_image
|
58 |
+
|
59 |
+
return None
|
60 |
+
|
61 |
+
def delete_image_file(file_path):
|
62 |
+
try:
|
63 |
+
if os.path.exists(file_path):
|
64 |
+
os.remove(file_path)
|
65 |
+
logger.debug(f"file {file_path} deleted")
|
66 |
+
else:
|
67 |
+
logger.debug(f"file {file_path} is not exist")
|
68 |
+
except Exception as e:
|
69 |
+
logger.debug(f"error {file_path}: {str(e)}")
|
70 |
+
|
71 |
+
def start_queue(prompt_workflow, port):
|
72 |
+
p = {"prompt": prompt_workflow}
|
73 |
+
data = json.dumps(p).encode('utf-8')
|
74 |
+
requests.post(f"{URL}:{port}/prompt", data=data)
|
75 |
+
|
76 |
+
def check_server_ready(port):
|
77 |
+
try:
|
78 |
+
response = requests.get(f"{URL}:{port}/history/123", timeout=5)
|
79 |
+
return response.status_code == 200
|
80 |
+
except requests.RequestException:
|
81 |
+
return False
|
82 |
+
|
83 |
+
@spaces.GPU(duration=170)
|
84 |
+
def generate_image(image):
|
85 |
+
prefix_filename = str(random.randint(0, 999999))
|
86 |
+
prompt = read_prompt_from_file('good_upscaler.json')
|
87 |
+
prompt = json.dumps(prompt, ensure_ascii=False).replace('OutPutImage', prefix_filename)
|
88 |
+
prompt = json.loads(prompt)
|
89 |
+
|
90 |
+
image = Image.fromarray(image)
|
91 |
+
image.save(INPUT_DIR + '/input.png', format='PNG')
|
92 |
+
|
93 |
+
process = None
|
94 |
+
new_port = str(random.randint(8123, 8200))
|
95 |
+
|
96 |
+
try:
|
97 |
+
process = subprocess.Popen([sys.executable, BACKEND_PATH, "--listen", "127.0.0.1", "--port", new_port])
|
98 |
+
logger.debug(f'Subprocess started with PID: {process.pid}')
|
99 |
+
|
100 |
+
for _ in range(40):
|
101 |
+
if check_server_ready(new_port):
|
102 |
+
break
|
103 |
+
time.sleep(1)
|
104 |
+
else:
|
105 |
+
raise TimeoutError("Server did not start in time")
|
106 |
+
|
107 |
+
start_queue(prompt, new_port)
|
108 |
+
|
109 |
+
timeout = 240
|
110 |
+
start_time = time.time()
|
111 |
+
while time.time() - start_time < timeout:
|
112 |
+
latest_image = wait_for_image_with_prefix(OUTPUT_DIR, prefix_filename)
|
113 |
+
if latest_image:
|
114 |
+
logger.debug(f"file is: {latest_image}")
|
115 |
+
try:
|
116 |
+
return Image.open(latest_image)
|
117 |
+
finally:
|
118 |
+
delete_image_file(latest_image)
|
119 |
+
delete_image_file(INPUT_DIR + '/input.png')
|
120 |
+
time.sleep(1)
|
121 |
+
|
122 |
+
raise TimeoutError("New image was not generated in time")
|
123 |
+
|
124 |
+
except Exception as e:
|
125 |
+
logger.error(f"Error in generate_image: {e}")
|
126 |
+
|
127 |
+
finally:
|
128 |
+
if process and process.poll() is None:
|
129 |
+
process.terminate()
|
130 |
+
logger.debug("process.terminate()")
|
131 |
+
try:
|
132 |
+
logger.debug("process.wait(timeout=5)")
|
133 |
+
process.wait(timeout=5)
|
134 |
+
except subprocess.TimeoutExpired:
|
135 |
+
logger.debug("process.kill()")
|
136 |
+
process.kill()
|
137 |
+
|
138 |
+
if __name__ == "__main__":
|
139 |
+
demo = gr.Interface(
|
140 |
+
fn=generate_image,
|
141 |
+
inputs=[gr.Image(image_mode='RGBA', type="numpy")],
|
142 |
+
outputs=[gr.Image(type="numpy", image_mode='RGBA')],
|
143 |
+
title="Image Upscaler",
|
144 |
+
description="This is an upscaler that increases the resolution of your image to 16 megapixels. Upload an image to get started!"
|
145 |
+
)
|
146 |
+
demo.launch(debug=True)
|
147 |
+
logger.debug('demo.launch()')
|
148 |
+
|
149 |
+
logger.info("finish")
|
README.md
CHANGED
@@ -1,14 +1,348 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# News: A nightly version of ControlNet 1.1 is released!
|
2 |
+
|
3 |
+
[ControlNet 1.1](https://github.com/lllyasviel/ControlNet-v1-1-nightly) is released. Those new models will be merged to this repo after we make sure that everything is good.
|
4 |
+
|
5 |
+
# Below is ControlNet 1.0
|
6 |
+
|
7 |
+
Official implementation of [Adding Conditional Control to Text-to-Image Diffusion Models](https://arxiv.org/abs/2302.05543).
|
8 |
+
|
9 |
+
ControlNet is a neural network structure to control diffusion models by adding extra conditions.
|
10 |
+
|
11 |
+
![img](github_page/he.png)
|
12 |
+
|
13 |
+
It copys the weights of neural network blocks into a "locked" copy and a "trainable" copy.
|
14 |
+
|
15 |
+
The "trainable" one learns your condition. The "locked" one preserves your model.
|
16 |
+
|
17 |
+
Thanks to this, training with small dataset of image pairs will not destroy the production-ready diffusion models.
|
18 |
+
|
19 |
+
The "zero convolution" is 1×1 convolution with both weight and bias initialized as zeros.
|
20 |
+
|
21 |
+
Before training, all zero convolutions output zeros, and ControlNet will not cause any distortion.
|
22 |
+
|
23 |
+
No layer is trained from scratch. You are still fine-tuning. Your original model is safe.
|
24 |
+
|
25 |
+
This allows training on small-scale or even personal devices.
|
26 |
+
|
27 |
+
This is also friendly to merge/replacement/offsetting of models/weights/blocks/layers.
|
28 |
+
|
29 |
+
### FAQ
|
30 |
+
|
31 |
+
**Q:** But wait, if the weight of a conv layer is zero, the gradient will also be zero, and the network will not learn anything. Why "zero convolution" works?
|
32 |
+
|
33 |
+
**A:** This is not true. [See an explanation here](docs/faq.md).
|
34 |
+
|
35 |
+
# Stable Diffusion + ControlNet
|
36 |
+
|
37 |
+
By repeating the above simple structure 14 times, we can control stable diffusion in this way:
|
38 |
+
|
39 |
+
![img](github_page/sd.png)
|
40 |
+
|
41 |
+
In this way, the ControlNet can **reuse** the SD encoder as a **deep, strong, robust, and powerful backbone** to learn diverse controls. Many evidences (like [this](https://jerryxu.net/ODISE/) and [this](https://vpd.ivg-research.xyz/)) validate that the SD encoder is an excellent backbone.
|
42 |
+
|
43 |
+
Note that the way we connect layers is computational efficient. The original SD encoder does not need to store gradients (the locked original SD Encoder Block 1234 and Middle). The required GPU memory is not much larger than original SD, although many layers are added. Great!
|
44 |
+
|
45 |
+
# Features & News
|
46 |
+
|
47 |
+
2023/0/14 - We released [ControlNet 1.1](https://github.com/lllyasviel/ControlNet-v1-1-nightly). Those new models will be merged to this repo after we make sure that everything is good.
|
48 |
+
|
49 |
+
2023/03/03 - We released a discussion - [Precomputed ControlNet: Speed up ControlNet by 45%, but is it necessary?](https://github.com/lllyasviel/ControlNet/discussions/216)
|
50 |
+
|
51 |
+
2023/02/26 - We released a blog - [Ablation Study: Why ControlNets use deep encoder? What if it was lighter? Or even an MLP?](https://github.com/lllyasviel/ControlNet/discussions/188)
|
52 |
+
|
53 |
+
2023/02/20 - Implementation for non-prompt mode released. See also [Guess Mode / Non-Prompt Mode](#guess-anchor).
|
54 |
+
|
55 |
+
2023/02/12 - Now you can play with any community model by [Transferring the ControlNet](https://github.com/lllyasviel/ControlNet/discussions/12).
|
56 |
+
|
57 |
+
2023/02/11 - [Low VRAM mode](docs/low_vram.md) is added. Please use this mode if you are using 8GB GPU(s) or if you want larger batch size.
|
58 |
+
|
59 |
+
# Production-Ready Pretrained Models
|
60 |
+
|
61 |
+
First create a new conda environment
|
62 |
+
|
63 |
+
conda env create -f environment.yaml
|
64 |
+
conda activate control
|
65 |
+
|
66 |
+
All models and detectors can be downloaded from [our Hugging Face page](https://huggingface.co/lllyasviel/ControlNet). Make sure that SD models are put in "ControlNet/models" and detectors are put in "ControlNet/annotator/ckpts". Make sure that you download all necessary pretrained weights and detector models from that Hugging Face page, including HED edge detection model, Midas depth estimation model, Openpose, and so on.
|
67 |
+
|
68 |
+
We provide 9 Gradio apps with these models.
|
69 |
+
|
70 |
+
All test images can be found at the folder "test_imgs".
|
71 |
+
|
72 |
+
## ControlNet with Canny Edge
|
73 |
+
|
74 |
+
Stable Diffusion 1.5 + ControlNet (using simple Canny edge detection)
|
75 |
+
|
76 |
+
python gradio_canny2image.py
|
77 |
+
|
78 |
+
The Gradio app also allows you to change the Canny edge thresholds. Just try it for more details.
|
79 |
+
|
80 |
+
Prompt: "bird"
|
81 |
+
![p](github_page/p1.png)
|
82 |
+
|
83 |
+
Prompt: "cute dog"
|
84 |
+
![p](github_page/p2.png)
|
85 |
+
|
86 |
+
## ControlNet with M-LSD Lines
|
87 |
+
|
88 |
+
Stable Diffusion 1.5 + ControlNet (using simple M-LSD straight line detection)
|
89 |
+
|
90 |
+
python gradio_hough2image.py
|
91 |
+
|
92 |
+
The Gradio app also allows you to change the M-LSD thresholds. Just try it for more details.
|
93 |
+
|
94 |
+
Prompt: "room"
|
95 |
+
![p](github_page/p3.png)
|
96 |
+
|
97 |
+
Prompt: "building"
|
98 |
+
![p](github_page/p4.png)
|
99 |
+
|
100 |
+
## ControlNet with HED Boundary
|
101 |
+
|
102 |
+
Stable Diffusion 1.5 + ControlNet (using soft HED Boundary)
|
103 |
+
|
104 |
+
python gradio_hed2image.py
|
105 |
+
|
106 |
+
The soft HED Boundary will preserve many details in input images, making this app suitable for recoloring and stylizing. Just try it for more details.
|
107 |
+
|
108 |
+
Prompt: "oil painting of handsome old man, masterpiece"
|
109 |
+
![p](github_page/p5.png)
|
110 |
+
|
111 |
+
Prompt: "Cyberpunk robot"
|
112 |
+
![p](github_page/p6.png)
|
113 |
+
|
114 |
+
## ControlNet with User Scribbles
|
115 |
+
|
116 |
+
Stable Diffusion 1.5 + ControlNet (using Scribbles)
|
117 |
+
|
118 |
+
python gradio_scribble2image.py
|
119 |
+
|
120 |
+
Note that the UI is based on Gradio, and Gradio is somewhat difficult to customize. Right now you need to draw scribbles outside the UI (using your favorite drawing software, for example, MS Paint) and then import the scribble image to Gradio.
|
121 |
+
|
122 |
+
Prompt: "turtle"
|
123 |
+
![p](github_page/p7.png)
|
124 |
+
|
125 |
+
Prompt: "hot air balloon"
|
126 |
+
![p](github_page/p8.png)
|
127 |
+
|
128 |
+
### Interactive Interface
|
129 |
+
|
130 |
+
We actually provide an interactive interface
|
131 |
+
|
132 |
+
python gradio_scribble2image_interactive.py
|
133 |
+
|
134 |
+
~~However, because gradio is very [buggy](https://github.com/gradio-app/gradio/issues/3166) and difficult to customize, right now, user need to first set canvas width and heights and then click "Open drawing canvas" to get a drawing area. Please do not upload image to that drawing canvas. Also, the drawing area is very small; it should be bigger. But I failed to find out how to make it larger. Again, gradio is really buggy.~~ (Now fixed, will update asap)
|
135 |
+
|
136 |
+
The below dog sketch is drawn by me. Perhaps we should draw a better dog for showcase.
|
137 |
+
|
138 |
+
Prompt: "dog in a room"
|
139 |
+
![p](github_page/p20.png)
|
140 |
+
|
141 |
+
## ControlNet with Fake Scribbles
|
142 |
+
|
143 |
+
Stable Diffusion 1.5 + ControlNet (using fake scribbles)
|
144 |
+
|
145 |
+
python gradio_fake_scribble2image.py
|
146 |
+
|
147 |
+
Sometimes we are lazy, and we do not want to draw scribbles. This script use the exactly same scribble-based model but use a simple algorithm to synthesize scribbles from input images.
|
148 |
+
|
149 |
+
Prompt: "bag"
|
150 |
+
![p](github_page/p9.png)
|
151 |
+
|
152 |
+
Prompt: "shose" (Note that "shose" is a typo; it should be "shoes". But it still seems to work.)
|
153 |
+
![p](github_page/p10.png)
|
154 |
+
|
155 |
+
## ControlNet with Human Pose
|
156 |
+
|
157 |
+
Stable Diffusion 1.5 + ControlNet (using human pose)
|
158 |
+
|
159 |
+
python gradio_pose2image.py
|
160 |
+
|
161 |
+
Apparently, this model deserves a better UI to directly manipulate pose skeleton. However, again, Gradio is somewhat difficult to customize. Right now you need to input an image and then the Openpose will detect the pose for you.
|
162 |
+
|
163 |
+
Prompt: "Chief in the kitchen"
|
164 |
+
![p](github_page/p11.png)
|
165 |
+
|
166 |
+
Prompt: "An astronaut on the moon"
|
167 |
+
![p](github_page/p12.png)
|
168 |
+
|
169 |
+
## ControlNet with Semantic Segmentation
|
170 |
+
|
171 |
+
Stable Diffusion 1.5 + ControlNet (using semantic segmentation)
|
172 |
+
|
173 |
+
python gradio_seg2image.py
|
174 |
+
|
175 |
+
This model use ADE20K's segmentation protocol. Again, this model deserves a better UI to directly draw the segmentations. However, again, Gradio is somewhat difficult to customize. Right now you need to input an image and then a model called Uniformer will detect the segmentations for you. Just try it for more details.
|
176 |
+
|
177 |
+
Prompt: "House"
|
178 |
+
![p](github_page/p13.png)
|
179 |
+
|
180 |
+
Prompt: "River"
|
181 |
+
![p](github_page/p14.png)
|
182 |
+
|
183 |
+
## ControlNet with Depth
|
184 |
+
|
185 |
+
Stable Diffusion 1.5 + ControlNet (using depth map)
|
186 |
+
|
187 |
+
python gradio_depth2image.py
|
188 |
+
|
189 |
+
Great! Now SD 1.5 also have a depth control. FINALLY. So many possibilities (considering SD1.5 has much more community models than SD2).
|
190 |
+
|
191 |
+
Note that different from Stability's model, the ControlNet receive the full 512×512 depth map, rather than 64×64 depth. Note that Stability's SD2 depth model use 64*64 depth maps. This means that the ControlNet will preserve more details in the depth map.
|
192 |
+
|
193 |
+
This is always a strength because if users do not want to preserve more details, they can simply use another SD to post-process an i2i. But if they want to preserve more details, ControlNet becomes their only choice. Again, SD2 uses 64×64 depth, we use 512×512.
|
194 |
+
|
195 |
+
Prompt: "Stormtrooper's lecture"
|
196 |
+
![p](github_page/p15.png)
|
197 |
+
|
198 |
+
## ControlNet with Normal Map
|
199 |
+
|
200 |
+
Stable Diffusion 1.5 + ControlNet (using normal map)
|
201 |
+
|
202 |
+
python gradio_normal2image.py
|
203 |
+
|
204 |
+
This model use normal map. Rightnow in the APP, the normal is computed from the midas depth map and a user threshold (to determine how many area is background with identity normal face to viewer, tune the "Normal background threshold" in the gradio app to get a feeling).
|
205 |
+
|
206 |
+
Prompt: "Cute toy"
|
207 |
+
![p](github_page/p17.png)
|
208 |
+
|
209 |
+
Prompt: "Plaster statue of Abraham Lincoln"
|
210 |
+
![p](github_page/p18.png)
|
211 |
+
|
212 |
+
Compared to depth model, this model seems to be a bit better at preserving the geometry. This is intuitive: minor details are not salient in depth maps, but are salient in normal maps. Below is the depth result with same inputs. You can see that the hairstyle of the man in the input image is modified by depth model, but preserved by the normal model.
|
213 |
+
|
214 |
+
Prompt: "Plaster statue of Abraham Lincoln"
|
215 |
+
![p](github_page/p19.png)
|
216 |
+
|
217 |
+
## ControlNet with Anime Line Drawing
|
218 |
+
|
219 |
+
We also trained a relatively simple ControlNet for anime line drawings. This tool may be useful for artistic creations. (Although the image details in the results is a bit modified, since it still diffuse latent images.)
|
220 |
+
|
221 |
+
This model is not available right now. We need to evaluate the potential risks before releasing this model. Nevertheless, you may be interested in [transferring the ControlNet to any community model](https://github.com/lllyasviel/ControlNet/discussions/12).
|
222 |
+
|
223 |
+
![p](github_page/p21.png)
|
224 |
+
|
225 |
+
<a id="guess-anchor"></a>
|
226 |
+
|
227 |
+
# Guess Mode / Non-Prompt Mode
|
228 |
+
|
229 |
+
The "guess mode" (or called non-prompt mode) will completely unleash all the power of the very powerful ControlNet encoder.
|
230 |
+
|
231 |
+
See also the blog - [Ablation Study: Why ControlNets use deep encoder? What if it was lighter? Or even an MLP?](https://github.com/lllyasviel/ControlNet/discussions/188)
|
232 |
+
|
233 |
+
You need to manually check the "Guess Mode" toggle to enable this mode.
|
234 |
+
|
235 |
+
In this mode, the ControlNet encoder will try best to recognize the content of the input control map, like depth map, edge map, scribbles, etc, even if you remove all prompts.
|
236 |
+
|
237 |
+
**Let's have fun with some very challenging experimental settings!**
|
238 |
+
|
239 |
+
**No prompts. No "positive" prompts. No "negative" prompts. No extra caption detector. One single diffusion loop.**
|
240 |
+
|
241 |
+
For this mode, we recommend to use 50 steps and guidance scale between 3 and 5.
|
242 |
+
|
243 |
+
![p](github_page/uc2a.png)
|
244 |
+
|
245 |
+
No prompts:
|
246 |
+
|
247 |
+
![p](github_page/uc2b.png)
|
248 |
+
|
249 |
+
Note that the below example is 768×768. No prompts. No "positive" prompts. No "negative" prompts.
|
250 |
+
|
251 |
+
![p](github_page/uc1.png)
|
252 |
+
|
253 |
+
By tuning the parameters, you can get some very intereting results like below:
|
254 |
+
|
255 |
+
![p](github_page/uc3.png)
|
256 |
+
|
257 |
+
Because no prompt is available, the ControlNet encoder will "guess" what is in the control map. Sometimes the guess result is really interesting. Because diffusion algorithm can essentially give multiple results, the ControlNet seems able to give multiple guesses, like this:
|
258 |
+
|
259 |
+
![p](github_page/uc4.png)
|
260 |
+
|
261 |
+
Without prompt, the HED seems good at generating images look like paintings when the control strength is relatively low:
|
262 |
+
|
263 |
+
![p](github_page/uc6.png)
|
264 |
+
|
265 |
+
The Guess Mode is also supported in [WebUI Plugin](https://github.com/Mikubill/sd-webui-controlnet):
|
266 |
+
|
267 |
+
![p](github_page/uci1.png)
|
268 |
+
|
269 |
+
No prompts. Default WebUI parameters. Pure random results with the seed being 12345. Standard SD1.5. Input scribble is in "test_imgs" folder to reproduce.
|
270 |
+
|
271 |
+
![p](github_page/uci2.png)
|
272 |
+
|
273 |
+
Below is another challenging example:
|
274 |
+
|
275 |
+
![p](github_page/uci3.png)
|
276 |
+
|
277 |
+
No prompts. Default WebUI parameters. Pure random results with the seed being 12345. Standard SD1.5. Input scribble is in "test_imgs" folder to reproduce.
|
278 |
+
|
279 |
+
![p](github_page/uci4.png)
|
280 |
+
|
281 |
+
Note that in the guess mode, you will still be able to input prompts. The only difference is that the model will "try harder" to guess what is in the control map even if you do not provide the prompt. Just try it yourself!
|
282 |
+
|
283 |
+
Besides, if you write some scripts (like BLIP) to generate image captions from the "guess mode" images, and then use the generated captions as prompts to diffuse again, you will get a SOTA pipeline for fully automatic conditional image generating.
|
284 |
+
|
285 |
+
# Combining Multiple ControlNets
|
286 |
+
|
287 |
+
ControlNets are composable: more than one ControlNet can be easily composed to multi-condition control.
|
288 |
+
|
289 |
+
Right now this feature is in experimental stage in the [Mikubill' A1111 Webui Plugin](https://github.com/Mikubill/sd-webui-controlnet):
|
290 |
+
|
291 |
+
![p](github_page/multi2.png)
|
292 |
+
|
293 |
+
![p](github_page/multi.png)
|
294 |
+
|
295 |
+
As long as the models are controlling the same SD, the "boundary" between different research projects does not even exist. This plugin also allows different methods to work together!
|
296 |
+
|
297 |
+
# Use ControlNet in Any Community Model (SD1.X)
|
298 |
+
|
299 |
+
This is an experimental feature.
|
300 |
+
|
301 |
+
[See the steps here](https://github.com/lllyasviel/ControlNet/discussions/12).
|
302 |
+
|
303 |
+
Or you may want to use the [Mikubill' A1111 Webui Plugin](https://github.com/Mikubill/sd-webui-controlnet) which is plug-and-play and does not need manual merging.
|
304 |
+
|
305 |
+
# Annotate Your Own Data
|
306 |
+
|
307 |
+
We provide simple python scripts to process images.
|
308 |
+
|
309 |
+
[See a gradio example here](docs/annotator.md).
|
310 |
+
|
311 |
+
# Train with Your Own Data
|
312 |
+
|
313 |
+
Training a ControlNet is as easy as (or even easier than) training a simple pix2pix.
|
314 |
+
|
315 |
+
[See the steps here](docs/train.md).
|
316 |
+
|
317 |
+
# Related Resources
|
318 |
+
|
319 |
+
Special Thank to the great project - [Mikubill' A1111 Webui Plugin](https://github.com/Mikubill/sd-webui-controlnet) !
|
320 |
+
|
321 |
+
We also thank Hysts for making [Hugging Face Space](https://huggingface.co/spaces/hysts/ControlNet) as well as more than 65 models in that amazing [Colab list](https://github.com/camenduru/controlnet-colab)!
|
322 |
+
|
323 |
+
Thank haofanwang for making [ControlNet-for-Diffusers](https://github.com/haofanwang/ControlNet-for-Diffusers)!
|
324 |
+
|
325 |
+
We also thank all authors for making Controlnet DEMOs, including but not limited to [fffiloni](https://huggingface.co/spaces/fffiloni/ControlNet-Video), [other-model](https://huggingface.co/spaces/hysts/ControlNet-with-other-models), [ThereforeGames](https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions/7784), [RamAnanth1](https://huggingface.co/spaces/RamAnanth1/ControlNet), etc!
|
326 |
+
|
327 |
+
Besides, you may also want to read these amazing related works:
|
328 |
+
|
329 |
+
[Composer: Creative and Controllable Image Synthesis with Composable Conditions](https://github.com/damo-vilab/composer): A much bigger model to control diffusion!
|
330 |
+
|
331 |
+
[T2I-Adapter: Learning Adapters to Dig out More Controllable Ability for Text-to-Image Diffusion Models](https://github.com/TencentARC/T2I-Adapter): A much smaller model to control stable diffusion!
|
332 |
+
|
333 |
+
[ControlLoRA: A Light Neural Network To Control Stable Diffusion Spatial Information](https://github.com/HighCWu/ControlLoRA): Implement Controlnet using LORA!
|
334 |
+
|
335 |
+
And these amazing recent projects: [InstructPix2Pix Learning to Follow Image Editing Instructions](https://www.timothybrooks.com/instruct-pix2pix), [Pix2pix-zero: Zero-shot Image-to-Image Translation](https://github.com/pix2pixzero/pix2pix-zero), [Plug-and-Play Diffusion Features for Text-Driven Image-to-Image Translation](https://github.com/MichalGeyer/plug-and-play), [MaskSketch: Unpaired Structure-guided Masked Image Generation](https://arxiv.org/abs/2302.05496), [SEGA: Instructing Diffusion using Semantic Dimensions](https://arxiv.org/abs/2301.12247), [Universal Guidance for Diffusion Models](https://github.com/arpitbansal297/Universal-Guided-Diffusion), [Region-Aware Diffusion for Zero-shot Text-driven Image Editing](https://github.com/haha-lisa/RDM-Region-Aware-Diffusion-Model), [Domain Expansion of Image Generators](https://arxiv.org/abs/2301.05225), [Image Mixer](https://twitter.com/LambdaAPI/status/1626327289288957956), [MultiDiffusion: Fusing Diffusion Paths for Controlled Image Generation](https://multidiffusion.github.io/)
|
336 |
+
|
337 |
+
# Citation
|
338 |
+
|
339 |
+
@misc{zhang2023adding,
|
340 |
+
title={Adding Conditional Control to Text-to-Image Diffusion Models},
|
341 |
+
author={Lvmin Zhang and Anyi Rao and Maneesh Agrawala},
|
342 |
+
booktitle={IEEE International Conference on Computer Vision (ICCV)}
|
343 |
+
year={2023},
|
344 |
+
}
|
345 |
+
|
346 |
+
[Arxiv Link](https://arxiv.org/abs/2302.05543)
|
347 |
+
|
348 |
+
[Supplementary Materials](https://lllyasviel.github.io/misc/202309/cnet_supp.pdf)
|
config.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
save_memory = False
|
environment.yaml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: control
|
2 |
+
channels:
|
3 |
+
- pytorch
|
4 |
+
- defaults
|
5 |
+
dependencies:
|
6 |
+
- python=3.8.5
|
7 |
+
- pip=20.3
|
8 |
+
- cudatoolkit=11.3
|
9 |
+
- pytorch=1.12.1
|
10 |
+
- torchvision=0.13.1
|
11 |
+
- numpy=1.23.1
|
12 |
+
- pip:
|
13 |
+
- gradio==3.16.2
|
14 |
+
- albumentations==1.3.0
|
15 |
+
- opencv-contrib-python==4.3.0.36
|
16 |
+
- imageio==2.9.0
|
17 |
+
- imageio-ffmpeg==0.4.2
|
18 |
+
- pytorch-lightning==1.5.0
|
19 |
+
- omegaconf==2.1.1
|
20 |
+
- test-tube>=0.7.5
|
21 |
+
- streamlit==1.12.1
|
22 |
+
- einops==0.3.0
|
23 |
+
- transformers==4.19.2
|
24 |
+
- webdataset==0.2.5
|
25 |
+
- kornia==0.6
|
26 |
+
- open_clip_torch==2.0.2
|
27 |
+
- invisible-watermark>=0.1.5
|
28 |
+
- streamlit-drawable-canvas==0.8.0
|
29 |
+
- torchmetrics==0.6.0
|
30 |
+
- timm==0.6.12
|
31 |
+
- addict==2.4.0
|
32 |
+
- yapf==0.32.0
|
33 |
+
- prettytable==3.6.0
|
34 |
+
- safetensors==0.2.7
|
35 |
+
- basicsr==1.4.2
|
gradio_Scene_Diffusion.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.canny import CannyDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
from ldm.models.diffusion.ddpm import LatentDiffusion
|
17 |
+
|
18 |
+
|
19 |
+
apply_canny = CannyDetector()
|
20 |
+
|
21 |
+
model = create_model('./models/cldm_v21_512_latctrl_coltrans.yaml').cpu()
|
22 |
+
model.load_state_dict(load_state_dict('./checkpoints/epoch=25-step=112553.ckpt', location='cuda'),strict=False)
|
23 |
+
model = model.cuda()
|
24 |
+
ddim_sampler = DDIMSampler(model)
|
25 |
+
|
26 |
+
|
27 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold):
|
28 |
+
with torch.no_grad():
|
29 |
+
img = resize_image(HWC3(input_image), image_resolution)
|
30 |
+
H, W, C = img.shape
|
31 |
+
|
32 |
+
# detected_map = apply_canny(img, low_threshold, high_threshold)
|
33 |
+
# detected_map = HWC3(detected_map)
|
34 |
+
|
35 |
+
control = torch.from_numpy(img.copy()).float().cuda() / 255.0
|
36 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
37 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
38 |
+
control = control.to(memory_format=torch.contiguous_format).float()
|
39 |
+
control = (control * 2.0) - 1.0
|
40 |
+
control = model.encode_first_stage(control).mean
|
41 |
+
|
42 |
+
if seed == -1:
|
43 |
+
seed = random.randint(0, 65535)
|
44 |
+
seed_everything(seed)
|
45 |
+
|
46 |
+
if config.save_memory:
|
47 |
+
model.low_vram_shift(is_diffusing=False)
|
48 |
+
|
49 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
50 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
51 |
+
shape = (4, H // 8, W // 8)
|
52 |
+
|
53 |
+
if config.save_memory:
|
54 |
+
model.low_vram_shift(is_diffusing=True)
|
55 |
+
|
56 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
57 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
58 |
+
shape, cond, verbose=False, eta=eta,
|
59 |
+
unconditional_guidance_scale=scale,
|
60 |
+
unconditional_conditioning=un_cond)
|
61 |
+
|
62 |
+
if config.save_memory:
|
63 |
+
model.low_vram_shift(is_diffusing=False)
|
64 |
+
|
65 |
+
x_samples = model.decode_first_stage(samples)
|
66 |
+
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)
|
67 |
+
|
68 |
+
results = [x_samples[i] for i in range(num_samples)]
|
69 |
+
return [255 - img] + results
|
70 |
+
|
71 |
+
|
72 |
+
block = gr.Blocks().queue()
|
73 |
+
with block:
|
74 |
+
with gr.Row():
|
75 |
+
gr.Markdown("## Scene Diffusion")
|
76 |
+
with gr.Row():
|
77 |
+
with gr.Column():
|
78 |
+
input_image = gr.Image(sources='upload', type="numpy")
|
79 |
+
prompt = gr.Textbox(label="Prompt")
|
80 |
+
run_button = gr.Button(label="Run")
|
81 |
+
# run_button=gr.Button("Run")
|
82 |
+
with gr.Accordion("Advanced options", open=False):
|
83 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
84 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
85 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
86 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
87 |
+
low_threshold = gr.Slider(label="Canny low threshold", minimum=1, maximum=255, value=100, step=1)
|
88 |
+
high_threshold = gr.Slider(label="Canny high threshold", minimum=1, maximum=255, value=200, step=1)
|
89 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
90 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
91 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
92 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
93 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
94 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
95 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
96 |
+
with gr.Column():
|
97 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
98 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold]
|
99 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
100 |
+
|
101 |
+
|
102 |
+
block.launch(server_name='0.0.0.0',share=True)
|
gradio_annotator.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
from annotator.util import resize_image, HWC3
|
4 |
+
|
5 |
+
|
6 |
+
model_canny = None
|
7 |
+
|
8 |
+
|
9 |
+
def canny(img, res, l, h):
|
10 |
+
img = resize_image(HWC3(img), res)
|
11 |
+
global model_canny
|
12 |
+
if model_canny is None:
|
13 |
+
from annotator.canny import CannyDetector
|
14 |
+
model_canny = CannyDetector()
|
15 |
+
result = model_canny(img, l, h)
|
16 |
+
return [result]
|
17 |
+
|
18 |
+
|
19 |
+
model_hed = None
|
20 |
+
|
21 |
+
|
22 |
+
def hed(img, res):
|
23 |
+
img = resize_image(HWC3(img), res)
|
24 |
+
global model_hed
|
25 |
+
if model_hed is None:
|
26 |
+
from annotator.hed import HEDdetector
|
27 |
+
model_hed = HEDdetector()
|
28 |
+
result = model_hed(img)
|
29 |
+
return [result]
|
30 |
+
|
31 |
+
|
32 |
+
model_mlsd = None
|
33 |
+
|
34 |
+
|
35 |
+
def mlsd(img, res, thr_v, thr_d):
|
36 |
+
img = resize_image(HWC3(img), res)
|
37 |
+
global model_mlsd
|
38 |
+
if model_mlsd is None:
|
39 |
+
from annotator.mlsd import MLSDdetector
|
40 |
+
model_mlsd = MLSDdetector()
|
41 |
+
result = model_mlsd(img, thr_v, thr_d)
|
42 |
+
return [result]
|
43 |
+
|
44 |
+
|
45 |
+
model_midas = None
|
46 |
+
|
47 |
+
|
48 |
+
def midas(img, res, a):
|
49 |
+
img = resize_image(HWC3(img), res)
|
50 |
+
global model_midas
|
51 |
+
if model_midas is None:
|
52 |
+
from annotator.midas import MidasDetector
|
53 |
+
model_midas = MidasDetector()
|
54 |
+
results = model_midas(img, a)
|
55 |
+
return results
|
56 |
+
|
57 |
+
|
58 |
+
model_openpose = None
|
59 |
+
|
60 |
+
|
61 |
+
def openpose(img, res, has_hand):
|
62 |
+
img = resize_image(HWC3(img), res)
|
63 |
+
global model_openpose
|
64 |
+
if model_openpose is None:
|
65 |
+
from annotator.openpose import OpenposeDetector
|
66 |
+
model_openpose = OpenposeDetector()
|
67 |
+
result, _ = model_openpose(img, has_hand)
|
68 |
+
return [result]
|
69 |
+
|
70 |
+
|
71 |
+
model_uniformer = None
|
72 |
+
|
73 |
+
|
74 |
+
def uniformer(img, res):
|
75 |
+
img = resize_image(HWC3(img), res)
|
76 |
+
global model_uniformer
|
77 |
+
if model_uniformer is None:
|
78 |
+
from annotator.uniformer import UniformerDetector
|
79 |
+
model_uniformer = UniformerDetector()
|
80 |
+
result = model_uniformer(img)
|
81 |
+
return [result]
|
82 |
+
|
83 |
+
|
84 |
+
block = gr.Blocks().queue()
|
85 |
+
with block:
|
86 |
+
with gr.Row():
|
87 |
+
gr.Markdown("## Canny Edge")
|
88 |
+
with gr.Row():
|
89 |
+
with gr.Column():
|
90 |
+
input_image = gr.Image(source='upload', type="numpy")
|
91 |
+
low_threshold = gr.Slider(label="low_threshold", minimum=1, maximum=255, value=100, step=1)
|
92 |
+
high_threshold = gr.Slider(label="high_threshold", minimum=1, maximum=255, value=200, step=1)
|
93 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
94 |
+
run_button = gr.Button(label="Run")
|
95 |
+
with gr.Column():
|
96 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
97 |
+
run_button.click(fn=canny, inputs=[input_image, resolution, low_threshold, high_threshold], outputs=[gallery])
|
98 |
+
|
99 |
+
with gr.Row():
|
100 |
+
gr.Markdown("## HED Edge")
|
101 |
+
with gr.Row():
|
102 |
+
with gr.Column():
|
103 |
+
input_image = gr.Image(source='upload', type="numpy")
|
104 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
105 |
+
run_button = gr.Button(label="Run")
|
106 |
+
with gr.Column():
|
107 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
108 |
+
run_button.click(fn=hed, inputs=[input_image, resolution], outputs=[gallery])
|
109 |
+
|
110 |
+
with gr.Row():
|
111 |
+
gr.Markdown("## MLSD Edge")
|
112 |
+
with gr.Row():
|
113 |
+
with gr.Column():
|
114 |
+
input_image = gr.Image(source='upload', type="numpy")
|
115 |
+
value_threshold = gr.Slider(label="value_threshold", minimum=0.01, maximum=2.0, value=0.1, step=0.01)
|
116 |
+
distance_threshold = gr.Slider(label="distance_threshold", minimum=0.01, maximum=20.0, value=0.1, step=0.01)
|
117 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=384, step=64)
|
118 |
+
run_button = gr.Button(label="Run")
|
119 |
+
with gr.Column():
|
120 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
121 |
+
run_button.click(fn=mlsd, inputs=[input_image, resolution, value_threshold, distance_threshold], outputs=[gallery])
|
122 |
+
|
123 |
+
with gr.Row():
|
124 |
+
gr.Markdown("## MIDAS Depth and Normal")
|
125 |
+
with gr.Row():
|
126 |
+
with gr.Column():
|
127 |
+
input_image = gr.Image(source='upload', type="numpy")
|
128 |
+
alpha = gr.Slider(label="alpha", minimum=0.1, maximum=20.0, value=6.2, step=0.01)
|
129 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=384, step=64)
|
130 |
+
run_button = gr.Button(label="Run")
|
131 |
+
with gr.Column():
|
132 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
133 |
+
run_button.click(fn=midas, inputs=[input_image, resolution, alpha], outputs=[gallery])
|
134 |
+
|
135 |
+
with gr.Row():
|
136 |
+
gr.Markdown("## Openpose")
|
137 |
+
with gr.Row():
|
138 |
+
with gr.Column():
|
139 |
+
input_image = gr.Image(source='upload', type="numpy")
|
140 |
+
hand = gr.Checkbox(label='detect hand', value=False)
|
141 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
142 |
+
run_button = gr.Button(label="Run")
|
143 |
+
with gr.Column():
|
144 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
145 |
+
run_button.click(fn=openpose, inputs=[input_image, resolution, hand], outputs=[gallery])
|
146 |
+
|
147 |
+
|
148 |
+
with gr.Row():
|
149 |
+
gr.Markdown("## Uniformer Segmentation")
|
150 |
+
with gr.Row():
|
151 |
+
with gr.Column():
|
152 |
+
input_image = gr.Image(source='upload', type="numpy")
|
153 |
+
resolution = gr.Slider(label="resolution", minimum=256, maximum=1024, value=512, step=64)
|
154 |
+
run_button = gr.Button(label="Run")
|
155 |
+
with gr.Column():
|
156 |
+
gallery = gr.Gallery(label="Generated images", show_label=False).style(height="auto")
|
157 |
+
run_button.click(fn=uniformer, inputs=[input_image, resolution], outputs=[gallery])
|
158 |
+
|
159 |
+
|
160 |
+
block.launch(server_name='0.0.0.0')
|
gradio_canny2image.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.canny import CannyDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_canny = CannyDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_canny.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold):
|
27 |
+
|
28 |
+
with torch.no_grad():
|
29 |
+
img = resize_image(HWC3(input_image), image_resolution)
|
30 |
+
H, W, C = img.shape
|
31 |
+
|
32 |
+
detected_map = apply_canny(img, low_threshold, high_threshold)
|
33 |
+
detected_map = HWC3(detected_map)
|
34 |
+
|
35 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
36 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
37 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
38 |
+
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
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)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [255 - detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Canny Edge Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
low_threshold = gr.Slider(label="Canny low threshold", minimum=1, maximum=255, value=100, step=1)
|
85 |
+
high_threshold = gr.Slider(label="Canny high threshold", minimum=1, maximum=255, value=200, step=1)
|
86 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
87 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
88 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
89 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
90 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
91 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
92 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
93 |
+
with gr.Column():
|
94 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
95 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold]
|
96 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
97 |
+
|
98 |
+
|
99 |
+
block.launch(server_name='0.0.0.0',share=True)
|
gradio_depth2image.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.midas import MidasDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_midas = MidasDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_depth.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map, _ = apply_midas(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
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)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Depth Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="Depth Resolution", minimum=128, maximum=1024, value=384, step=1)
|
85 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
86 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
87 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
88 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
89 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
90 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
91 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
92 |
+
with gr.Column():
|
93 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
94 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
95 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
96 |
+
|
97 |
+
|
98 |
+
block.launch(server_name='0.0.0.0')
|
gradio_fake_scribble2image.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.hed import HEDdetector, nms
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_hed = HEDdetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_scribble.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_hed(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
detected_map = nms(detected_map, 127, 3.0)
|
36 |
+
detected_map = cv2.GaussianBlur(detected_map, (0, 0), 3.0)
|
37 |
+
detected_map[detected_map > 4] = 255
|
38 |
+
detected_map[detected_map < 255] = 0
|
39 |
+
|
40 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
41 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
42 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
43 |
+
|
44 |
+
if seed == -1:
|
45 |
+
seed = random.randint(0, 65535)
|
46 |
+
seed_everything(seed)
|
47 |
+
|
48 |
+
if config.save_memory:
|
49 |
+
model.low_vram_shift(is_diffusing=False)
|
50 |
+
|
51 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
52 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
53 |
+
shape = (4, H // 8, W // 8)
|
54 |
+
|
55 |
+
if config.save_memory:
|
56 |
+
model.low_vram_shift(is_diffusing=True)
|
57 |
+
|
58 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
59 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
60 |
+
shape, cond, verbose=False, eta=eta,
|
61 |
+
unconditional_guidance_scale=scale,
|
62 |
+
unconditional_conditioning=un_cond)
|
63 |
+
|
64 |
+
if config.save_memory:
|
65 |
+
model.low_vram_shift(is_diffusing=False)
|
66 |
+
|
67 |
+
x_samples = model.decode_first_stage(samples)
|
68 |
+
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)
|
69 |
+
|
70 |
+
results = [x_samples[i] for i in range(num_samples)]
|
71 |
+
return [255 - detected_map] + results
|
72 |
+
|
73 |
+
|
74 |
+
block = gr.Blocks().queue()
|
75 |
+
with block:
|
76 |
+
with gr.Row():
|
77 |
+
gr.Markdown("## Control Stable Diffusion with Fake Scribble Maps")
|
78 |
+
with gr.Row():
|
79 |
+
with gr.Column():
|
80 |
+
input_image = gr.Image(source='upload', type="numpy")
|
81 |
+
prompt = gr.Textbox(label="Prompt")
|
82 |
+
run_button = gr.Button(label="Run")
|
83 |
+
with gr.Accordion("Advanced options", open=False):
|
84 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
85 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
86 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
87 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
88 |
+
detect_resolution = gr.Slider(label="HED Resolution", minimum=128, maximum=1024, value=512, step=1)
|
89 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
90 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
91 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
92 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
93 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
94 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
95 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
96 |
+
with gr.Column():
|
97 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
98 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
99 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
100 |
+
|
101 |
+
|
102 |
+
block.launch(server_name='0.0.0.0')
|
gradio_hed2image.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.hed import HEDdetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_hed = HEDdetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_hed.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_hed(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
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)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with HED Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="HED Resolution", minimum=128, maximum=1024, value=512, step=1)
|
85 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
86 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
87 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
88 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
89 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
90 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
91 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
92 |
+
with gr.Column():
|
93 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
94 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
95 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
96 |
+
|
97 |
+
|
98 |
+
block.launch(server_name='0.0.0.0')
|
gradio_hough2image.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.mlsd import MLSDdetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_mlsd = MLSDdetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_mlsd.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, value_threshold, distance_threshold):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_mlsd(resize_image(input_image, detect_resolution), value_threshold, distance_threshold)
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
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)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [255 - cv2.dilate(detected_map, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Hough Line Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="Hough Resolution", minimum=128, maximum=1024, value=512, step=1)
|
85 |
+
value_threshold = gr.Slider(label="Hough value threshold (MLSD)", minimum=0.01, maximum=2.0, value=0.1, step=0.01)
|
86 |
+
distance_threshold = gr.Slider(label="Hough distance threshold (MLSD)", minimum=0.01, maximum=20.0, value=0.1, step=0.01)
|
87 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
88 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
89 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
90 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
91 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
92 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
93 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
94 |
+
with gr.Column():
|
95 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
96 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, value_threshold, distance_threshold]
|
97 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
98 |
+
|
99 |
+
|
100 |
+
block.launch(server_name='0.0.0.0')
|
gradio_normal2image.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.midas import MidasDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_midas = MidasDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_normal.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, bg_threshold):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
_, detected_map = apply_midas(resize_image(input_image, detect_resolution), bg_th=bg_threshold)
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map[:, :, ::-1].copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
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)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Normal Maps")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="Normal Resolution", minimum=128, maximum=1024, value=384, step=1)
|
85 |
+
bg_threshold = gr.Slider(label="Normal background threshold", minimum=0.0, maximum=1.0, value=0.4, step=0.01)
|
86 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
87 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
88 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
89 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
90 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
91 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
92 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
93 |
+
with gr.Column():
|
94 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
95 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, bg_threshold]
|
96 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
97 |
+
|
98 |
+
|
99 |
+
block.launch(server_name='0.0.0.0')
|
gradio_pose2image.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.openpose import OpenposeDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_openpose = OpenposeDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_openpose.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map, _ = apply_openpose(resize_image(input_image, detect_resolution))
|
30 |
+
detected_map = HWC3(detected_map)
|
31 |
+
img = resize_image(input_image, image_resolution)
|
32 |
+
H, W, C = img.shape
|
33 |
+
|
34 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
35 |
+
|
36 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
37 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
38 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
39 |
+
|
40 |
+
if seed == -1:
|
41 |
+
seed = random.randint(0, 65535)
|
42 |
+
seed_everything(seed)
|
43 |
+
|
44 |
+
if config.save_memory:
|
45 |
+
model.low_vram_shift(is_diffusing=False)
|
46 |
+
|
47 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
48 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
49 |
+
shape = (4, H // 8, W // 8)
|
50 |
+
|
51 |
+
if config.save_memory:
|
52 |
+
model.low_vram_shift(is_diffusing=True)
|
53 |
+
|
54 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
55 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
56 |
+
shape, cond, verbose=False, eta=eta,
|
57 |
+
unconditional_guidance_scale=scale,
|
58 |
+
unconditional_conditioning=un_cond)
|
59 |
+
|
60 |
+
if config.save_memory:
|
61 |
+
model.low_vram_shift(is_diffusing=False)
|
62 |
+
|
63 |
+
x_samples = model.decode_first_stage(samples)
|
64 |
+
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)
|
65 |
+
|
66 |
+
results = [x_samples[i] for i in range(num_samples)]
|
67 |
+
return [detected_map] + results
|
68 |
+
|
69 |
+
|
70 |
+
block = gr.Blocks().queue()
|
71 |
+
with block:
|
72 |
+
with gr.Row():
|
73 |
+
gr.Markdown("## Control Stable Diffusion with Human Pose")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
input_image = gr.Image(source='upload', type="numpy")
|
77 |
+
prompt = gr.Textbox(label="Prompt")
|
78 |
+
run_button = gr.Button(label="Run")
|
79 |
+
with gr.Accordion("Advanced options", open=False):
|
80 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
81 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
82 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
83 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
84 |
+
detect_resolution = gr.Slider(label="OpenPose Resolution", minimum=128, maximum=1024, value=512, step=1)
|
85 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
86 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
87 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
88 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
89 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
90 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
91 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
92 |
+
with gr.Column():
|
93 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
94 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
95 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
96 |
+
|
97 |
+
|
98 |
+
block.launch(server_name='0.0.0.0')
|
gradio_scribble2image.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from cldm.model import create_model, load_state_dict
|
14 |
+
from cldm.ddim_hacked import DDIMSampler
|
15 |
+
|
16 |
+
|
17 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
18 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_scribble.pth', location='cuda'))
|
19 |
+
model = model.cuda()
|
20 |
+
ddim_sampler = DDIMSampler(model)
|
21 |
+
|
22 |
+
|
23 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
24 |
+
with torch.no_grad():
|
25 |
+
img = resize_image(HWC3(input_image), image_resolution)
|
26 |
+
H, W, C = img.shape
|
27 |
+
|
28 |
+
detected_map = np.zeros_like(img, dtype=np.uint8)
|
29 |
+
detected_map[np.min(img, axis=2) < 127] = 255
|
30 |
+
|
31 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
32 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
33 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
34 |
+
|
35 |
+
if seed == -1:
|
36 |
+
seed = random.randint(0, 65535)
|
37 |
+
seed_everything(seed)
|
38 |
+
|
39 |
+
if config.save_memory:
|
40 |
+
model.low_vram_shift(is_diffusing=False)
|
41 |
+
|
42 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
43 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
44 |
+
shape = (4, H // 8, W // 8)
|
45 |
+
|
46 |
+
if config.save_memory:
|
47 |
+
model.low_vram_shift(is_diffusing=True)
|
48 |
+
|
49 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
50 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
51 |
+
shape, cond, verbose=False, eta=eta,
|
52 |
+
unconditional_guidance_scale=scale,
|
53 |
+
unconditional_conditioning=un_cond)
|
54 |
+
|
55 |
+
if config.save_memory:
|
56 |
+
model.low_vram_shift(is_diffusing=False)
|
57 |
+
|
58 |
+
x_samples = model.decode_first_stage(samples)
|
59 |
+
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)
|
60 |
+
|
61 |
+
results = [x_samples[i] for i in range(num_samples)]
|
62 |
+
return [255 - detected_map] + results
|
63 |
+
|
64 |
+
|
65 |
+
block = gr.Blocks().queue()
|
66 |
+
with block:
|
67 |
+
with gr.Row():
|
68 |
+
gr.Markdown("## Control Stable Diffusion with Scribble Maps")
|
69 |
+
with gr.Row():
|
70 |
+
with gr.Column():
|
71 |
+
input_image = gr.Image(source='upload', type="numpy")
|
72 |
+
prompt = gr.Textbox(label="Prompt")
|
73 |
+
run_button = gr.Button(label="Run")
|
74 |
+
with gr.Accordion("Advanced options", open=False):
|
75 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
76 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
77 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
78 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
79 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
80 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
81 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
82 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
83 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
84 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
85 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
86 |
+
with gr.Column():
|
87 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
88 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
89 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
90 |
+
|
91 |
+
|
92 |
+
block.launch(server_name='0.0.0.0')
|
gradio_scribble2image_interactive.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from cldm.model import create_model, load_state_dict
|
14 |
+
from cldm.ddim_hacked import DDIMSampler
|
15 |
+
|
16 |
+
|
17 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
18 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_scribble.pth', location='cuda'))
|
19 |
+
model = model.cuda()
|
20 |
+
ddim_sampler = DDIMSampler(model)
|
21 |
+
|
22 |
+
|
23 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
24 |
+
with torch.no_grad():
|
25 |
+
img = resize_image(HWC3(input_image['mask'][:, :, 0]), image_resolution)
|
26 |
+
H, W, C = img.shape
|
27 |
+
|
28 |
+
detected_map = np.zeros_like(img, dtype=np.uint8)
|
29 |
+
detected_map[np.min(img, axis=2) > 127] = 255
|
30 |
+
|
31 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
32 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
33 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
34 |
+
|
35 |
+
if seed == -1:
|
36 |
+
seed = random.randint(0, 65535)
|
37 |
+
seed_everything(seed)
|
38 |
+
|
39 |
+
if config.save_memory:
|
40 |
+
model.low_vram_shift(is_diffusing=False)
|
41 |
+
|
42 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
43 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
44 |
+
shape = (4, H // 8, W // 8)
|
45 |
+
|
46 |
+
if config.save_memory:
|
47 |
+
model.low_vram_shift(is_diffusing=True)
|
48 |
+
|
49 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
50 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
51 |
+
shape, cond, verbose=False, eta=eta,
|
52 |
+
unconditional_guidance_scale=scale,
|
53 |
+
unconditional_conditioning=un_cond)
|
54 |
+
|
55 |
+
if config.save_memory:
|
56 |
+
model.low_vram_shift(is_diffusing=False)
|
57 |
+
|
58 |
+
x_samples = model.decode_first_stage(samples)
|
59 |
+
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)
|
60 |
+
|
61 |
+
results = [x_samples[i] for i in range(num_samples)]
|
62 |
+
return [255 - detected_map] + results
|
63 |
+
|
64 |
+
|
65 |
+
def create_canvas(w, h):
|
66 |
+
return np.zeros(shape=(h, w, 3), dtype=np.uint8) + 255
|
67 |
+
|
68 |
+
|
69 |
+
block = gr.Blocks().queue()
|
70 |
+
with block:
|
71 |
+
with gr.Row():
|
72 |
+
gr.Markdown("## Control Stable Diffusion with Interactive Scribbles")
|
73 |
+
with gr.Row():
|
74 |
+
with gr.Column():
|
75 |
+
canvas_width = gr.Slider(label="Canvas Width", minimum=256, maximum=1024, value=512, step=1)
|
76 |
+
canvas_height = gr.Slider(label="Canvas Height", minimum=256, maximum=1024, value=512, step=1)
|
77 |
+
create_button = gr.Button(label="Start", value='Open drawing canvas!')
|
78 |
+
input_image = gr.Image(source='upload', type='numpy', tool='sketch')
|
79 |
+
gr.Markdown(value='Do not forget to change your brush width to make it thinner. (Gradio do not allow developers to set brush width so you need to do it manually.) '
|
80 |
+
'Just click on the small pencil icon in the upper right corner of the above block.')
|
81 |
+
create_button.click(fn=create_canvas, inputs=[canvas_width, canvas_height], outputs=[input_image])
|
82 |
+
prompt = gr.Textbox(label="Prompt")
|
83 |
+
run_button = gr.Button(label="Run")
|
84 |
+
with gr.Accordion("Advanced options", open=False):
|
85 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
86 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
87 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
88 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
89 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
90 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
91 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
92 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
93 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
94 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
95 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
96 |
+
with gr.Column():
|
97 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
98 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
99 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
100 |
+
|
101 |
+
|
102 |
+
block.launch(server_name='0.0.0.0')
|
gradio_seg2image.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from annotator.uniformer import UniformerDetector
|
14 |
+
from cldm.model import create_model, load_state_dict
|
15 |
+
from cldm.ddim_hacked import DDIMSampler
|
16 |
+
|
17 |
+
|
18 |
+
apply_uniformer = UniformerDetector()
|
19 |
+
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_seg.pth', location='cuda'))
|
22 |
+
model = model.cuda()
|
23 |
+
ddim_sampler = DDIMSampler(model)
|
24 |
+
|
25 |
+
|
26 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
|
27 |
+
with torch.no_grad():
|
28 |
+
input_image = HWC3(input_image)
|
29 |
+
detected_map = apply_uniformer(resize_image(input_image, detect_resolution))
|
30 |
+
img = resize_image(input_image, image_resolution)
|
31 |
+
H, W, C = img.shape
|
32 |
+
|
33 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
34 |
+
|
35 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
36 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
37 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
38 |
+
|
39 |
+
if seed == -1:
|
40 |
+
seed = random.randint(0, 65535)
|
41 |
+
seed_everything(seed)
|
42 |
+
|
43 |
+
if config.save_memory:
|
44 |
+
model.low_vram_shift(is_diffusing=False)
|
45 |
+
|
46 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
47 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
48 |
+
shape = (4, H // 8, W // 8)
|
49 |
+
|
50 |
+
if config.save_memory:
|
51 |
+
model.low_vram_shift(is_diffusing=True)
|
52 |
+
|
53 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
54 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
55 |
+
shape, cond, verbose=False, eta=eta,
|
56 |
+
unconditional_guidance_scale=scale,
|
57 |
+
unconditional_conditioning=un_cond)
|
58 |
+
|
59 |
+
if config.save_memory:
|
60 |
+
model.low_vram_shift(is_diffusing=False)
|
61 |
+
|
62 |
+
x_samples = model.decode_first_stage(samples)
|
63 |
+
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)
|
64 |
+
|
65 |
+
results = [x_samples[i] for i in range(num_samples)]
|
66 |
+
return [detected_map] + results
|
67 |
+
|
68 |
+
|
69 |
+
block = gr.Blocks().queue()
|
70 |
+
with block:
|
71 |
+
with gr.Row():
|
72 |
+
gr.Markdown("## Control Stable Diffusion with Segmentation Maps")
|
73 |
+
with gr.Row():
|
74 |
+
with gr.Column():
|
75 |
+
input_image = gr.Image(source='upload', type="numpy")
|
76 |
+
prompt = gr.Textbox(label="Prompt")
|
77 |
+
run_button = gr.Button(label="Run")
|
78 |
+
with gr.Accordion("Advanced options", open=False):
|
79 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
80 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
81 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
82 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
83 |
+
detect_resolution = gr.Slider(label="Segmentation Resolution", minimum=128, maximum=1024, value=512, step=1)
|
84 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
85 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
86 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
87 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
88 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
89 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
90 |
+
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
91 |
+
with gr.Column():
|
92 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
93 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
|
94 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
95 |
+
|
96 |
+
|
97 |
+
block.launch(server_name='0.0.0.0')
|
requirements.txt
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pip=20.3
|
2 |
+
cudatoolkit=11.3
|
3 |
+
pytorch=1.12.1
|
4 |
+
torchvision=0.13.1
|
5 |
+
numpy=1.23.1
|
6 |
+
gradio==3.16.2
|
7 |
+
albumentations==1.3.0
|
8 |
+
opencv-contrib-python==4.3.0.36
|
9 |
+
imageio==2.9.0
|
10 |
+
imageio-ffmpeg==0.4.2
|
11 |
+
pytorch-lightning==1.5.0
|
12 |
+
omegaconf==2.1.1
|
13 |
+
test-tube>=0.7.5
|
14 |
+
streamlit==1.12.1
|
15 |
+
einops==0.3.0
|
16 |
+
transformers==4.19.2
|
17 |
+
webdataset==0.2.5
|
18 |
+
kornia==0.6
|
19 |
+
open_clip_torch==2.0.2
|
20 |
+
invisible-watermark>=0.1.5
|
21 |
+
streamlit-drawable-canvas==0.8.0
|
22 |
+
torchmetrics==0.6.0
|
23 |
+
timm==0.6.12
|
24 |
+
addict==2.4.0
|
25 |
+
yapf==0.32.0
|
26 |
+
prettytable==3.6.0
|
27 |
+
safetensors==0.2.7
|
28 |
+
basicsr==1.4.2
|
share.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import config
|
2 |
+
from cldm.hack import disable_verbosity, enable_sliced_attention
|
3 |
+
|
4 |
+
|
5 |
+
disable_verbosity()
|
6 |
+
|
7 |
+
if config.save_memory:
|
8 |
+
enable_sliced_attention()
|
tool_add_control.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
|
4 |
+
assert len(sys.argv) == 3, 'Args are wrong.'
|
5 |
+
|
6 |
+
input_path = sys.argv[1]
|
7 |
+
output_path = sys.argv[2]
|
8 |
+
|
9 |
+
assert os.path.exists(input_path), 'Input model does not exist.'
|
10 |
+
assert not os.path.exists(output_path), 'Output filename already exists.'
|
11 |
+
assert os.path.exists(os.path.dirname(output_path)), 'Output path is not valid.'
|
12 |
+
|
13 |
+
import torch
|
14 |
+
from share import *
|
15 |
+
from cldm.model import create_model
|
16 |
+
|
17 |
+
|
18 |
+
def get_node_name(name, parent_name):
|
19 |
+
if len(name) <= len(parent_name):
|
20 |
+
return False, ''
|
21 |
+
p = name[:len(parent_name)]
|
22 |
+
if p != parent_name:
|
23 |
+
return False, ''
|
24 |
+
return True, name[len(parent_name):]
|
25 |
+
|
26 |
+
|
27 |
+
model = create_model(config_path='./models/cldm_v15.yaml')
|
28 |
+
|
29 |
+
pretrained_weights = torch.load(input_path)
|
30 |
+
if 'state_dict' in pretrained_weights:
|
31 |
+
pretrained_weights = pretrained_weights['state_dict']
|
32 |
+
|
33 |
+
scratch_dict = model.state_dict()
|
34 |
+
|
35 |
+
target_dict = {}
|
36 |
+
for k in scratch_dict.keys():
|
37 |
+
is_control, name = get_node_name(k, 'control_')
|
38 |
+
if is_control:
|
39 |
+
copy_k = 'model.diffusion_' + name
|
40 |
+
else:
|
41 |
+
copy_k = k
|
42 |
+
if copy_k in pretrained_weights:
|
43 |
+
target_dict[k] = pretrained_weights[copy_k].clone()
|
44 |
+
else:
|
45 |
+
target_dict[k] = scratch_dict[k].clone()
|
46 |
+
print(f'These weights are newly added: {k}')
|
47 |
+
|
48 |
+
model.load_state_dict(target_dict, strict=True)
|
49 |
+
torch.save(model.state_dict(), output_path)
|
50 |
+
print('Done.')
|
tool_add_control_sd21.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
|
4 |
+
assert len(sys.argv) == 3, 'Args are wrong.'
|
5 |
+
|
6 |
+
input_path = sys.argv[1]
|
7 |
+
output_path = sys.argv[2]
|
8 |
+
|
9 |
+
assert os.path.exists(input_path), 'Input model does not exist.'
|
10 |
+
assert not os.path.exists(output_path), 'Output filename already exists.'
|
11 |
+
assert os.path.exists(os.path.dirname(output_path)), 'Output path is not valid.'
|
12 |
+
|
13 |
+
import torch
|
14 |
+
from share import *
|
15 |
+
from cldm.model import create_model
|
16 |
+
|
17 |
+
|
18 |
+
def get_node_name(name, parent_name):
|
19 |
+
if len(name) <= len(parent_name):
|
20 |
+
return False, ''
|
21 |
+
p = name[:len(parent_name)]
|
22 |
+
if p != parent_name:
|
23 |
+
return False, ''
|
24 |
+
return True, name[len(parent_name):]
|
25 |
+
|
26 |
+
|
27 |
+
model = create_model(config_path='./models/cldm_v21.yaml')
|
28 |
+
|
29 |
+
pretrained_weights = torch.load(input_path)
|
30 |
+
if 'state_dict' in pretrained_weights:
|
31 |
+
pretrained_weights = pretrained_weights['state_dict']
|
32 |
+
|
33 |
+
scratch_dict = model.state_dict()
|
34 |
+
|
35 |
+
target_dict = {}
|
36 |
+
for k in scratch_dict.keys():
|
37 |
+
is_control, name = get_node_name(k, 'control_')
|
38 |
+
if is_control:
|
39 |
+
copy_k = 'model.diffusion_' + name
|
40 |
+
else:
|
41 |
+
copy_k = k
|
42 |
+
if copy_k in pretrained_weights:
|
43 |
+
target_dict[k] = pretrained_weights[copy_k].clone()
|
44 |
+
else:
|
45 |
+
target_dict[k] = scratch_dict[k].clone()
|
46 |
+
print(f'These weights are newly added: {k}')
|
47 |
+
|
48 |
+
model.load_state_dict(target_dict, strict=True)
|
49 |
+
torch.save(model.state_dict(), output_path)
|
50 |
+
print('Done.')
|
tool_transfer_control.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
path_sd15 = './models/v1-5-pruned.ckpt'
|
2 |
+
path_sd15_with_control = './models/control_sd15_openpose.pth'
|
3 |
+
path_input = './models/anything-v3-full.safetensors'
|
4 |
+
path_output = './models/control_any3_openpose.pth'
|
5 |
+
|
6 |
+
|
7 |
+
import os
|
8 |
+
|
9 |
+
|
10 |
+
assert os.path.exists(path_sd15), 'Input path_sd15 does not exists!'
|
11 |
+
assert os.path.exists(path_sd15_with_control), 'Input path_sd15_with_control does not exists!'
|
12 |
+
assert os.path.exists(path_input), 'Input path_input does not exists!'
|
13 |
+
assert os.path.exists(os.path.dirname(path_output)), 'Output folder not exists!'
|
14 |
+
|
15 |
+
|
16 |
+
import torch
|
17 |
+
from share import *
|
18 |
+
from cldm.model import load_state_dict
|
19 |
+
|
20 |
+
|
21 |
+
sd15_state_dict = load_state_dict(path_sd15)
|
22 |
+
sd15_with_control_state_dict = load_state_dict(path_sd15_with_control)
|
23 |
+
input_state_dict = load_state_dict(path_input)
|
24 |
+
|
25 |
+
|
26 |
+
def get_node_name(name, parent_name):
|
27 |
+
if len(name) <= len(parent_name):
|
28 |
+
return False, ''
|
29 |
+
p = name[:len(parent_name)]
|
30 |
+
if p != parent_name:
|
31 |
+
return False, ''
|
32 |
+
return True, name[len(parent_name):]
|
33 |
+
|
34 |
+
|
35 |
+
keys = sd15_with_control_state_dict.keys()
|
36 |
+
|
37 |
+
final_state_dict = {}
|
38 |
+
for key in keys:
|
39 |
+
is_first_stage, _ = get_node_name(key, 'first_stage_model')
|
40 |
+
is_cond_stage, _ = get_node_name(key, 'cond_stage_model')
|
41 |
+
if is_first_stage or is_cond_stage:
|
42 |
+
final_state_dict[key] = input_state_dict[key]
|
43 |
+
continue
|
44 |
+
p = sd15_with_control_state_dict[key]
|
45 |
+
is_control, node_name = get_node_name(key, 'control_')
|
46 |
+
if is_control:
|
47 |
+
sd15_key_name = 'model.diffusion_' + node_name
|
48 |
+
else:
|
49 |
+
sd15_key_name = key
|
50 |
+
if sd15_key_name in input_state_dict:
|
51 |
+
p_new = p + input_state_dict[sd15_key_name] - sd15_state_dict[sd15_key_name]
|
52 |
+
# print(f'Offset clone from [{sd15_key_name}] to [{key}]')
|
53 |
+
else:
|
54 |
+
p_new = p
|
55 |
+
# print(f'Direct clone to [{key}]')
|
56 |
+
final_state_dict[key] = p_new
|
57 |
+
|
58 |
+
torch.save(final_state_dict, path_output)
|
59 |
+
print('Transferred model saved at ' + path_output)
|
tutorial_dataset.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
from torch.utils.data import Dataset
|
6 |
+
|
7 |
+
|
8 |
+
class MyDataset(Dataset):
|
9 |
+
def __init__(self):
|
10 |
+
self.data = []
|
11 |
+
with open('./training/fill50k/prompt.json', 'rt') as f:
|
12 |
+
for line in f:
|
13 |
+
self.data.append(json.loads(line))
|
14 |
+
|
15 |
+
def __len__(self):
|
16 |
+
return len(self.data)
|
17 |
+
|
18 |
+
def __getitem__(self, idx):
|
19 |
+
item = self.data[idx]
|
20 |
+
|
21 |
+
source_filename = item['source']
|
22 |
+
target_filename = item['target']
|
23 |
+
prompt = item['prompt']
|
24 |
+
|
25 |
+
source = cv2.imread('./training/fill50k/' + source_filename)
|
26 |
+
target = cv2.imread('./training/fill50k/' + target_filename)
|
27 |
+
|
28 |
+
# Do not forget that OpenCV read images in BGR order.
|
29 |
+
source = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)
|
30 |
+
target = cv2.cvtColor(target, cv2.COLOR_BGR2RGB)
|
31 |
+
|
32 |
+
# Normalize source images to [0, 1].
|
33 |
+
source = source.astype(np.float32) / 255.0
|
34 |
+
|
35 |
+
# Normalize target images to [-1, 1].
|
36 |
+
target = (target.astype(np.float32) / 127.5) - 1.0
|
37 |
+
|
38 |
+
return dict(jpg=target, txt=prompt, hint=source)
|
39 |
+
|
tutorial_dataset_test.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from tutorial_dataset import MyDataset
|
2 |
+
|
3 |
+
dataset = MyDataset()
|
4 |
+
print(len(dataset))
|
5 |
+
|
6 |
+
item = dataset[1234]
|
7 |
+
jpg = item['jpg']
|
8 |
+
txt = item['txt']
|
9 |
+
hint = item['hint']
|
10 |
+
print(txt)
|
11 |
+
print(jpg.shape)
|
12 |
+
print(hint.shape)
|
tutorial_train.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
|
3 |
+
import pytorch_lightning as pl
|
4 |
+
from torch.utils.data import DataLoader
|
5 |
+
from tutorial_dataset import MyDataset
|
6 |
+
from cldm.logger import ImageLogger
|
7 |
+
from cldm.model import create_model, load_state_dict
|
8 |
+
|
9 |
+
|
10 |
+
# Configs
|
11 |
+
resume_path = './models/control_sd15_ini.ckpt'
|
12 |
+
batch_size = 4
|
13 |
+
logger_freq = 300
|
14 |
+
learning_rate = 1e-5
|
15 |
+
sd_locked = True
|
16 |
+
only_mid_control = False
|
17 |
+
|
18 |
+
|
19 |
+
# First use cpu to load models. Pytorch Lightning will automatically move it to GPUs.
|
20 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict(resume_path, location='cpu'))
|
22 |
+
model.learning_rate = learning_rate
|
23 |
+
model.sd_locked = sd_locked
|
24 |
+
model.only_mid_control = only_mid_control
|
25 |
+
|
26 |
+
|
27 |
+
# Misc
|
28 |
+
dataset = MyDataset()
|
29 |
+
dataloader = DataLoader(dataset, num_workers=0, batch_size=batch_size, shuffle=True)
|
30 |
+
logger = ImageLogger(batch_frequency=logger_freq)
|
31 |
+
trainer = pl.Trainer(gpus=1, precision=32, callbacks=[logger])
|
32 |
+
|
33 |
+
|
34 |
+
# Train!
|
35 |
+
trainer.fit(model, dataloader)
|
tutorial_train_sd21.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
|
3 |
+
import pytorch_lightning as pl
|
4 |
+
from torch.utils.data import DataLoader
|
5 |
+
from tutorial_dataset import MyDataset
|
6 |
+
from cldm.logger import ImageLogger
|
7 |
+
from cldm.model import create_model, load_state_dict
|
8 |
+
|
9 |
+
|
10 |
+
# Configs
|
11 |
+
resume_path = './models/control_sd21_ini.ckpt'
|
12 |
+
batch_size = 4
|
13 |
+
logger_freq = 300
|
14 |
+
learning_rate = 1e-5
|
15 |
+
sd_locked = True
|
16 |
+
only_mid_control = False
|
17 |
+
|
18 |
+
|
19 |
+
# First use cpu to load models. Pytorch Lightning will automatically move it to GPUs.
|
20 |
+
model = create_model('./models/cldm_v21.yaml').cpu()
|
21 |
+
model.load_state_dict(load_state_dict(resume_path, location='cpu'))
|
22 |
+
model.learning_rate = learning_rate
|
23 |
+
model.sd_locked = sd_locked
|
24 |
+
model.only_mid_control = only_mid_control
|
25 |
+
|
26 |
+
|
27 |
+
# Misc
|
28 |
+
dataset = MyDataset()
|
29 |
+
dataloader = DataLoader(dataset, num_workers=0, batch_size=batch_size, shuffle=True)
|
30 |
+
logger = ImageLogger(batch_frequency=logger_freq)
|
31 |
+
trainer = pl.Trainer(gpus=1, precision=32, callbacks=[logger])
|
32 |
+
|
33 |
+
|
34 |
+
# Train!
|
35 |
+
trainer.fit(model, dataloader)
|