generated from replicate/cog-comfyui
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpredict.py
348 lines (313 loc) · 12.2 KB
/
predict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import os
import mimetypes
import json
import shutil
import re
from typing import List
from cog import BasePredictor, Input, Path
from comfyui import ComfyUI
from cog_model_helpers import seed as seed_helper
from replicate_weights import download_replicate_weights
from dataclasses import dataclass
OUTPUT_DIR = "/tmp/outputs"
INPUT_DIR = "/tmp/inputs"
COMFYUI_TEMP_OUTPUT_DIR = "ComfyUI/temp"
COMFYUI_LORAS_DIR = "ComfyUI/models/loras"
ALL_DIRECTORIES = [OUTPUT_DIR, INPUT_DIR, COMFYUI_TEMP_OUTPUT_DIR]
mimetypes.add_type("image/webp", ".webp")
api_json_file = "workflow.json"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
@dataclass
class Inputs:
prompt = Input(description="Text prompt for video generation")
negative_prompt = Input(
description="Things you do not want to see in your video", default=""
)
aspect_ratio = Input(
description="The aspect ratio of the video. 16:9, 9:16, 1:1, etc.",
choices=["16:9", "9:16", "1:1"],
default="16:9",
)
frames = Input(
description="The number of frames to generate (1 to 5 seconds)",
choices=[17, 33, 49, 65, 81],
default=81,
)
model = Input(
description="The model to use. 1.3b is faster, but 14b is better quality. A LORA either works with 1.3b or 14b, depending on the version it was trained on.",
choices=["1.3b", "14b"],
default="14b",
)
lora_url = Input(description="Optional: The URL of a LORA to use", default=None)
lora_strength_model = Input(
description="Strength of the LORA applied to the model. 0.0 is no LORA.",
default=1.0,
)
lora_strength_clip = Input(
description="Strength of the LORA applied to the CLIP model. 0.0 is no LORA.",
default=1.0,
)
sample_shift = Input(
description="Sample shift factor", default=8.0, ge=0.0, le=10.0
)
sample_guide_scale = Input(
description="Higher guide scale makes prompt adherence better, but can reduce variation",
default=5.0,
ge=0.0,
le=10.0,
)
sample_steps = Input(
description="Number of generation steps. Fewer steps means faster generation, at the expensive of output quality. 30 steps is sufficient for most prompts",
default=30,
ge=1,
le=60,
)
seed = Input(default=seed_helper.predict_seed())
replicate_weights = Input(
description="Replicate LoRA weights to use. Leave blank to use the default weights.",
default=None,
)
fast_mode = Input(
description="Speed up generation with different levels of acceleration. Faster modes may degrade quality somewhat. The speedup is dependent on the content, so different videos may see different speedups.",
choices=["Off", "Balanced", "Fast"],
default="Balanced",
)
resolution = Input(
description="The resolution of the video. 720p is not supported for 1.3b.",
choices=["480p", "720p"],
default="480p",
)
class Predictor(BasePredictor):
def setup(self):
self.comfyUI = ComfyUI("127.0.0.1:8188")
self.comfyUI.start_server(OUTPUT_DIR, INPUT_DIR)
os.makedirs("ComfyUI/models/loras", exist_ok=True)
with open(api_json_file, "r") as file:
workflow = json.loads(file.read())
self.comfyUI.handle_weights(
workflow,
weights_to_download=[
"wan_2.1_vae.safetensors",
"umt5_xxl_fp16.safetensors",
],
)
def filename_with_extension(self, input_file, prefix):
extension = os.path.splitext(input_file.name)[1]
return f"{prefix}{extension}"
def handle_input_file(
self,
input_file: Path,
filename: str = "image.png",
):
shutil.copy(input_file, os.path.join(INPUT_DIR, filename))
def get_width_and_height(self, resolution: str, aspect_ratio: str):
sizes = {
"480p": {
"16:9": (832, 480),
"9:16": (480, 832),
"1:1": (644, 644),
},
"720p": {
"16:9": (1280, 720),
"9:16": (720, 1280),
"1:1": (980, 980),
},
}
return sizes[resolution][aspect_ratio]
def update_workflow(self, workflow, **kwargs):
model = kwargs["model"]
is_14b = model == "14b"
empty_latent_video = workflow["40"]["inputs"]
empty_latent_video["length"] = kwargs["frames"]
width, height = self.get_width_and_height(
kwargs["resolution"], kwargs["aspect_ratio"]
)
empty_latent_video["width"] = width
empty_latent_video["height"] = height
model_loader = workflow["37"]["inputs"]
if is_14b:
model_loader["unet_name"] = "wan2.1_t2v_14B_bf16.safetensors"
else:
model_loader["unet_name"] = "wan2.1_t2v_1.3B_bf16.safetensors"
positive_prompt = workflow["6"]["inputs"]
positive_prompt["text"] = kwargs["prompt"]
negative_prompt = workflow["7"]["inputs"]
negative_prompt["text"] = f"nsfw, {kwargs['negative_prompt']}"
sampler = workflow["3"]["inputs"]
sampler["seed"] = kwargs["seed"]
sampler["cfg"] = kwargs["sample_guide_scale"]
sampler["steps"] = kwargs["sample_steps"]
shift = workflow["48"]["inputs"]
shift["shift"] = kwargs["sample_shift"]
thresholds = {
"14b": {
"Balanced": 0.15,
"Fast": 0.2,
},
"1.3b": {
"Balanced": 0.07,
"Fast": 0.08,
},
}
fast_mode = kwargs["fast_mode"]
if fast_mode == "Off":
# Turn off tea cache
del workflow["54"]
workflow["49"]["inputs"]["model"] = ["53", 0]
else:
tea_cache = workflow["54"]["inputs"]
tea_cache["coefficients"] = "14B" if is_14b else "1.3B"
tea_cache["rel_l1_thresh"] = thresholds[model][fast_mode]
if kwargs["lora_url"] or kwargs["lora_filename"]:
lora_loader = workflow["49"]["inputs"]
if kwargs["lora_filename"]:
lora_loader["lora_name"] = kwargs["lora_filename"]
elif kwargs["lora_url"]:
lora_loader["lora_name"] = kwargs["lora_url"]
lora_loader["strength_model"] = kwargs["lora_strength_model"]
lora_loader["strength_clip"] = kwargs["lora_strength_clip"]
else:
del workflow["49"] # delete lora loader node
positive_prompt["clip"] = ["38", 0]
shift["model"] = ["53", 0] if fast_mode == "Off" else ["54", 0]
def generate(
self,
prompt: str,
negative_prompt: str | None = None,
aspect_ratio: str = "16:9",
frames: int = 81,
model: str | None = None,
lora_url: str | None = None,
lora_strength_model: float = 1.0,
lora_strength_clip: float = 1.0,
fast_mode: str = "Balanced",
sample_shift: float = 8.0,
sample_guide_scale: float = 5.0,
sample_steps: int = 30,
seed: int | None = None,
resolution: str = "480p",
replicate_weights: str | None = None,
) -> List[Path]:
self.comfyUI.cleanup(ALL_DIRECTORIES)
seed = seed_helper.generate(seed)
lora_filename = None
inferred_model_type = None
if replicate_weights:
lora_filename, inferred_model_type = download_replicate_weights(
replicate_weights, COMFYUI_LORAS_DIR
)
model = inferred_model_type
elif lora_url:
if m := re.match(
r"^(?:https?://replicate.com/)?([^/]+)/([^/]+)/?$", lora_url
):
owner, model_name = m.groups()
lora_filename, inferred_model_type = download_replicate_weights(
f"https://replicate.com/{owner}/{model_name}/_weights",
COMFYUI_LORAS_DIR,
)
elif lora_url.startswith("https://replicate.delivery"):
lora_filename, inferred_model_type = download_replicate_weights(
lora_url, COMFYUI_LORAS_DIR
)
if inferred_model_type and inferred_model_type != model:
print(
f"Warning: Model type mismatch between requested model ({model}) and inferred model type ({inferred_model_type}). Using {inferred_model_type}."
)
model = inferred_model_type
if resolution == "720p" and model == "1.3b":
print("Warning: 720p is not supported for 1.3b, using 480p instead")
resolution = "480p"
with open(api_json_file, "r") as file:
workflow = json.loads(file.read())
self.update_workflow(
workflow,
prompt=prompt,
negative_prompt=negative_prompt,
seed=seed,
fast_mode=fast_mode,
sample_shift=sample_shift,
sample_guide_scale=sample_guide_scale,
sample_steps=sample_steps,
model=model,
frames=frames,
aspect_ratio=aspect_ratio,
lora_filename=lora_filename,
lora_url=lora_url,
lora_strength_model=lora_strength_model,
lora_strength_clip=lora_strength_clip,
resolution=resolution,
)
wf = self.comfyUI.load_workflow(workflow)
self.comfyUI.connect()
self.comfyUI.run_workflow(wf)
return self.comfyUI.get_files(OUTPUT_DIR, file_extensions=["mp4"])
class StandaloneLoraPredictor(Predictor):
def predict(
self,
prompt: str = Inputs.prompt,
negative_prompt: str = Inputs.negative_prompt,
aspect_ratio: str = Inputs.aspect_ratio,
frames: int = Inputs.frames,
model: str = Inputs.model,
resolution: str = Inputs.resolution,
lora_url: str = Inputs.lora_url,
lora_strength_model: float = Inputs.lora_strength_model,
lora_strength_clip: float = Inputs.lora_strength_clip,
fast_mode: str = Inputs.fast_mode,
sample_steps: int = Inputs.sample_steps,
sample_guide_scale: float = Inputs.sample_guide_scale,
sample_shift: float = Inputs.sample_shift,
seed: int = seed_helper.predict_seed(),
) -> List[Path]:
return self.generate(
prompt=prompt,
negative_prompt=negative_prompt,
aspect_ratio=aspect_ratio,
frames=frames,
model=model,
resolution=resolution,
lora_url=lora_url,
lora_strength_model=lora_strength_model,
lora_strength_clip=lora_strength_clip,
fast_mode=fast_mode,
sample_shift=sample_shift,
sample_guide_scale=sample_guide_scale,
sample_steps=sample_steps,
seed=seed,
replicate_weights=None,
)
class TrainedLoraPredictor(Predictor):
def predict(
self,
prompt: str = Inputs.prompt,
negative_prompt: str = Inputs.negative_prompt,
aspect_ratio: str = Inputs.aspect_ratio,
frames: int = Inputs.frames,
resolution: str = Inputs.resolution,
lora_strength_model: float = Inputs.lora_strength_model,
lora_strength_clip: float = Inputs.lora_strength_clip,
fast_mode: str = Inputs.fast_mode,
sample_steps: int = Inputs.sample_steps,
sample_guide_scale: float = Inputs.sample_guide_scale,
sample_shift: float = Inputs.sample_shift,
seed: int = seed_helper.predict_seed(),
replicate_weights: str = Inputs.replicate_weights,
) -> List[Path]:
return self.generate(
prompt=prompt,
negative_prompt=negative_prompt,
aspect_ratio=aspect_ratio,
frames=frames,
model=None,
resolution=resolution,
lora_url=None,
lora_strength_model=lora_strength_model,
lora_strength_clip=lora_strength_clip,
fast_mode=fast_mode,
sample_shift=sample_shift,
sample_guide_scale=sample_guide_scale,
sample_steps=sample_steps,
seed=seed,
replicate_weights=replicate_weights,
)