Spaces:
Running
on
Zero
Running
on
Zero
<fix> remove pipe_lock
Browse files
app.py
CHANGED
@@ -47,8 +47,6 @@ there's no need to manually input edge maps, depth maps, or other condition imag
|
|
47 |
The corresponding condition images will be automatically extracted.
|
48 |
"""
|
49 |
|
50 |
-
pipe_lock = threading.Lock()
|
51 |
-
|
52 |
|
53 |
def init_basemodel():
|
54 |
global transformer, scheduler, vae, text_encoder, text_encoder_2, tokenizer, tokenizer_2, image_processor, pipe, current_task
|
@@ -105,201 +103,200 @@ def init_basemodel():
|
|
105 |
@spaces.GPU
|
106 |
def process_image_and_text(condition_image, target_prompt, condition_image_prompt, task, random_seed, num_steps, inpainting, fill_x1, fill_x2, fill_y1, fill_y2):
|
107 |
# set up the model
|
108 |
-
|
109 |
-
|
110 |
-
if current_task
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
def
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
for n, m in transformer.named_modules():
|
134 |
-
if isinstance(m, peft.tuners.lora.layer.Linear):
|
135 |
-
m.forward = restore_forward(m)
|
136 |
-
|
137 |
-
current_task = task
|
138 |
-
|
139 |
-
# hack LoRA forward
|
140 |
-
def create_hacked_forward(module):
|
141 |
-
if not hasattr(module, 'original_forward'):
|
142 |
-
module.original_forward = module.forward
|
143 |
-
lora_forward = module.forward
|
144 |
-
non_lora_forward = module.base_layer.forward
|
145 |
-
img_sequence_length = int((512 / 8 / 2) ** 2)
|
146 |
-
encoder_sequence_length = 144 + 252 # encoder sequence: 144 img 252 txt
|
147 |
-
num_imgs = 4
|
148 |
-
num_generated_imgs = 3
|
149 |
-
num_encoder_sequences = 2 if task in ['subject_driven', 'style_transfer'] else 1
|
150 |
-
|
151 |
-
def hacked_lora_forward(self, x, *args, **kwargs):
|
152 |
-
if x.shape[1] == img_sequence_length * num_imgs and len(x.shape) > 2:
|
153 |
-
return torch.cat((
|
154 |
-
lora_forward(x[:, :-img_sequence_length*num_generated_imgs], *args, **kwargs),
|
155 |
-
non_lora_forward(x[:, -img_sequence_length*num_generated_imgs:], *args, **kwargs)
|
156 |
-
), dim=1)
|
157 |
-
elif x.shape[1] == encoder_sequence_length * num_encoder_sequences or x.shape[1] == encoder_sequence_length:
|
158 |
-
return lora_forward(x, *args, **kwargs)
|
159 |
-
elif x.shape[1] == img_sequence_length * num_imgs + encoder_sequence_length * num_encoder_sequences:
|
160 |
-
return torch.cat((
|
161 |
-
lora_forward(x[:, :(num_imgs - num_generated_imgs)*img_sequence_length], *args, **kwargs),
|
162 |
-
non_lora_forward(x[:, (num_imgs - num_generated_imgs)*img_sequence_length:-num_encoder_sequences*encoder_sequence_length], *args, **kwargs),
|
163 |
-
lora_forward(x[:, -num_encoder_sequences*encoder_sequence_length:], *args, **kwargs)
|
164 |
-
), dim=1)
|
165 |
-
elif x.shape[1] == 3072:
|
166 |
-
return non_lora_forward(x, *args, **kwargs)
|
167 |
-
else:
|
168 |
-
raise ValueError(
|
169 |
-
f"hacked_lora_forward receives unexpected sequence length: {x.shape[1]}, input shape: {x.shape}!"
|
170 |
-
)
|
171 |
-
|
172 |
-
return hacked_lora_forward.__get__(module, type(module))
|
173 |
-
|
174 |
for n, m in transformer.named_modules():
|
175 |
if isinstance(m, peft.tuners.lora.layer.Linear):
|
176 |
-
m.forward =
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
return Image.fromarray(edges).convert("RGB")
|
212 |
-
c_img = get_canny_edge(c_img)
|
213 |
-
elif task == "coloring":
|
214 |
-
c_img = (
|
215 |
-
c_img.resize((512, 512))
|
216 |
-
.convert("L")
|
217 |
-
.convert("RGB")
|
218 |
-
)
|
219 |
-
elif task == "deblurring":
|
220 |
-
blur_radius = 10
|
221 |
-
c_img = (
|
222 |
-
c_img.convert("RGB")
|
223 |
-
.filter(ImageFilter.GaussianBlur(blur_radius))
|
224 |
-
.resize((512, 512))
|
225 |
-
.convert("RGB")
|
226 |
-
)
|
227 |
-
elif task == "depth":
|
228 |
-
def get_depth_map(img):
|
229 |
-
from transformers import pipeline
|
230 |
-
|
231 |
-
depth_pipe = pipeline(
|
232 |
-
task="depth-estimation",
|
233 |
-
model="LiheYoung/depth-anything-small-hf",
|
234 |
-
device="cpu",
|
235 |
)
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
261 |
)
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
303 |
|
304 |
def get_samples():
|
305 |
sample_list = [
|
|
|
47 |
The corresponding condition images will be automatically extracted.
|
48 |
"""
|
49 |
|
|
|
|
|
50 |
|
51 |
def init_basemodel():
|
52 |
global transformer, scheduler, vae, text_encoder, text_encoder_2, tokenizer, tokenizer_2, image_processor, pipe, current_task
|
|
|
103 |
@spaces.GPU
|
104 |
def process_image_and_text(condition_image, target_prompt, condition_image_prompt, task, random_seed, num_steps, inpainting, fill_x1, fill_x2, fill_y1, fill_y2):
|
105 |
# set up the model
|
106 |
+
global pipe, current_task, transformer
|
107 |
+
if current_task != task:
|
108 |
+
if current_task is None:
|
109 |
+
# insert LoRA
|
110 |
+
lora_config = LoraConfig(
|
111 |
+
r=16,
|
112 |
+
lora_alpha=16,
|
113 |
+
init_lora_weights="gaussian",
|
114 |
+
target_modules=[
|
115 |
+
'attn.to_k', 'attn.to_q', 'attn.to_v', 'attn.to_out.0',
|
116 |
+
'attn.add_k_proj', 'attn.add_q_proj', 'attn.add_v_proj', 'attn.to_add_out',
|
117 |
+
'ff.net.0.proj', 'ff.net.2',
|
118 |
+
'ff_context.net.0.proj', 'ff_context.net.2',
|
119 |
+
'norm1_context.linear', 'norm1.linear',
|
120 |
+
'norm.linear', 'proj_mlp', 'proj_out',
|
121 |
+
]
|
122 |
+
)
|
123 |
+
transformer.add_adapter(lora_config)
|
124 |
+
else:
|
125 |
+
def restore_forward(module):
|
126 |
+
def restored_forward(self, x, *args, **kwargs):
|
127 |
+
return module.original_forward(x, *args, **kwargs)
|
128 |
+
return restored_forward.__get__(module, type(module))
|
129 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
for n, m in transformer.named_modules():
|
131 |
if isinstance(m, peft.tuners.lora.layer.Linear):
|
132 |
+
m.forward = restore_forward(m)
|
133 |
+
|
134 |
+
current_task = task
|
135 |
+
|
136 |
+
# hack LoRA forward
|
137 |
+
def create_hacked_forward(module):
|
138 |
+
if not hasattr(module, 'original_forward'):
|
139 |
+
module.original_forward = module.forward
|
140 |
+
lora_forward = module.forward
|
141 |
+
non_lora_forward = module.base_layer.forward
|
142 |
+
img_sequence_length = int((512 / 8 / 2) ** 2)
|
143 |
+
encoder_sequence_length = 144 + 252 # encoder sequence: 144 img 252 txt
|
144 |
+
num_imgs = 4
|
145 |
+
num_generated_imgs = 3
|
146 |
+
num_encoder_sequences = 2 if task in ['subject_driven', 'style_transfer'] else 1
|
147 |
+
|
148 |
+
def hacked_lora_forward(self, x, *args, **kwargs):
|
149 |
+
if x.shape[1] == img_sequence_length * num_imgs and len(x.shape) > 2:
|
150 |
+
return torch.cat((
|
151 |
+
lora_forward(x[:, :-img_sequence_length*num_generated_imgs], *args, **kwargs),
|
152 |
+
non_lora_forward(x[:, -img_sequence_length*num_generated_imgs:], *args, **kwargs)
|
153 |
+
), dim=1)
|
154 |
+
elif x.shape[1] == encoder_sequence_length * num_encoder_sequences or x.shape[1] == encoder_sequence_length:
|
155 |
+
return lora_forward(x, *args, **kwargs)
|
156 |
+
elif x.shape[1] == img_sequence_length * num_imgs + encoder_sequence_length * num_encoder_sequences:
|
157 |
+
return torch.cat((
|
158 |
+
lora_forward(x[:, :(num_imgs - num_generated_imgs)*img_sequence_length], *args, **kwargs),
|
159 |
+
non_lora_forward(x[:, (num_imgs - num_generated_imgs)*img_sequence_length:-num_encoder_sequences*encoder_sequence_length], *args, **kwargs),
|
160 |
+
lora_forward(x[:, -num_encoder_sequences*encoder_sequence_length:], *args, **kwargs)
|
161 |
+
), dim=1)
|
162 |
+
elif x.shape[1] == 3072:
|
163 |
+
return non_lora_forward(x, *args, **kwargs)
|
164 |
+
else:
|
165 |
+
raise ValueError(
|
166 |
+
f"hacked_lora_forward receives unexpected sequence length: {x.shape[1]}, input shape: {x.shape}!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
)
|
168 |
+
|
169 |
+
return hacked_lora_forward.__get__(module, type(module))
|
170 |
+
|
171 |
+
for n, m in transformer.named_modules():
|
172 |
+
if isinstance(m, peft.tuners.lora.layer.Linear):
|
173 |
+
m.forward = create_hacked_forward(m)
|
174 |
+
|
175 |
+
# load LoRA weights
|
176 |
+
model_root = hf_hub_download(
|
177 |
+
repo_id="Kunbyte/DRA-Ctrl",
|
178 |
+
filename=f"{task}.safetensors",
|
179 |
+
resume_download=True)
|
180 |
+
|
181 |
+
try:
|
182 |
+
with safe_open(model_root, framework="pt") as f:
|
183 |
+
lora_weights = {}
|
184 |
+
for k in f.keys():
|
185 |
+
param = f.get_tensor(k)
|
186 |
+
if k.endswith(".weight"):
|
187 |
+
k = k.replace('.weight', '.default.weight')
|
188 |
+
lora_weights[k] = param
|
189 |
+
transformer.load_state_dict(lora_weights, strict=False)
|
190 |
+
except Exception as e:
|
191 |
+
raise ValueError(f'{e}')
|
192 |
+
|
193 |
+
transformer.requires_grad_(False)
|
194 |
+
|
195 |
+
# start generation
|
196 |
+
c_txt = None if condition_image_prompt == "" else condition_image_prompt
|
197 |
+
c_img = condition_image.resize((512, 512))
|
198 |
+
t_txt = target_prompt
|
199 |
+
|
200 |
+
if task not in ['subject_driven', 'style_transfer']:
|
201 |
+
if task == "canny":
|
202 |
+
def get_canny_edge(img):
|
203 |
+
img_np = np.array(img)
|
204 |
+
img_gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
|
205 |
+
edges = cv2.Canny(img_gray, 100, 200)
|
206 |
+
edges_tmp = Image.fromarray(edges).convert("RGB")
|
207 |
+
edges[edges == 0] = 128
|
208 |
+
return Image.fromarray(edges).convert("RGB")
|
209 |
+
c_img = get_canny_edge(c_img)
|
210 |
+
elif task == "coloring":
|
211 |
+
c_img = (
|
212 |
+
c_img.resize((512, 512))
|
213 |
+
.convert("L")
|
214 |
+
.convert("RGB")
|
215 |
+
)
|
216 |
+
elif task == "deblurring":
|
217 |
+
blur_radius = 10
|
218 |
+
c_img = (
|
219 |
+
c_img.convert("RGB")
|
220 |
+
.filter(ImageFilter.GaussianBlur(blur_radius))
|
221 |
+
.resize((512, 512))
|
222 |
+
.convert("RGB")
|
223 |
+
)
|
224 |
+
elif task == "depth":
|
225 |
+
def get_depth_map(img):
|
226 |
+
from transformers import pipeline
|
227 |
+
|
228 |
+
depth_pipe = pipeline(
|
229 |
+
task="depth-estimation",
|
230 |
+
model="LiheYoung/depth-anything-small-hf",
|
231 |
+
device="cpu",
|
232 |
)
|
233 |
+
return depth_pipe(img)["depth"].convert("RGB").resize((512, 512))
|
234 |
+
c_img = get_depth_map(c_img)
|
235 |
+
k = (255 - 128) / 255
|
236 |
+
b = 128
|
237 |
+
c_img = c_img.point(lambda x: k * x + b)
|
238 |
+
elif task == "depth_pred":
|
239 |
+
c_img = c_img
|
240 |
+
elif task == "fill":
|
241 |
+
c_img = c_img.resize((512, 512)).convert("RGB")
|
242 |
+
x1, x2 = fill_x1, fill_x2
|
243 |
+
y1, y2 = fill_y1, fill_y2
|
244 |
+
mask = Image.new("L", (512, 512), 0)
|
245 |
+
draw = ImageDraw.Draw(mask)
|
246 |
+
draw.rectangle((x1, y1, x2, y2), fill=255)
|
247 |
+
if inpainting:
|
248 |
+
mask = Image.eval(mask, lambda a: 255 - a)
|
249 |
+
c_img = Image.composite(
|
250 |
+
c_img,
|
251 |
+
Image.new("RGB", (512, 512), (255, 255, 255)),
|
252 |
+
mask
|
253 |
+
)
|
254 |
+
c_img = Image.composite(
|
255 |
+
c_img,
|
256 |
+
Image.new("RGB", (512, 512), (128, 128, 128)),
|
257 |
+
mask
|
258 |
+
)
|
259 |
+
elif task == "sr":
|
260 |
+
c_img = c_img.resize((int(512 / 4), int(512 / 4))).convert("RGB")
|
261 |
+
c_img = c_img.resize((512, 512))
|
262 |
+
|
263 |
+
gen_img = pipe(
|
264 |
+
image=c_img,
|
265 |
+
prompt=[t_txt.strip()],
|
266 |
+
prompt_condition=[c_txt.strip()] if c_txt is not None else None,
|
267 |
+
prompt_2=[t_txt],
|
268 |
+
height=512,
|
269 |
+
width=512,
|
270 |
+
num_frames=5,
|
271 |
+
num_inference_steps=num_steps,
|
272 |
+
guidance_scale=6.0,
|
273 |
+
num_videos_per_prompt=1,
|
274 |
+
generator=torch.Generator(device=pipe.transformer.device).manual_seed(random_seed),
|
275 |
+
output_type='pt',
|
276 |
+
image_embed_interleave=4,
|
277 |
+
frame_gap=48,
|
278 |
+
mixup=True,
|
279 |
+
mixup_num_imgs=2,
|
280 |
+
enhance_tp=task in ['subject_driven'],
|
281 |
+
).frames
|
282 |
+
|
283 |
+
output_images = []
|
284 |
+
for i in range(10):
|
285 |
+
out = gen_img[:, i:i+1, :, :, :]
|
286 |
+
out = out.squeeze(0).squeeze(0).cpu().to(torch.float32).numpy()
|
287 |
+
out = np.transpose(out, (1, 2, 0))
|
288 |
+
out = (out * 255).astype(np.uint8)
|
289 |
+
out = Image.fromarray(out)
|
290 |
+
output_images.append(out)
|
291 |
+
|
292 |
+
# video = [np.array(img.convert('RGB')) for img in output_images[1:] + [output_images[0]]]
|
293 |
+
# video = np.stack(video, axis=0)
|
294 |
+
|
295 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
|
296 |
+
video_path = f.name
|
297 |
+
imageio.mimsave(video_path, output_images[1:]+[output_images[0]], fps=5)
|
298 |
+
|
299 |
+
return output_images[0], video_path
|
300 |
|
301 |
def get_samples():
|
302 |
sample_list = [
|